本文實例為大家分享了java圖形用戶界面實現菜單功能的具體代碼,供大家參考,具體內容如下
題目:編寫一個圖形用戶界面,實現菜單的功能。有3個一級菜單項:file、edit和help。在file菜單項中,有3個二級菜單項:new、open和save。在edit菜單項中,有3個二級菜單項:copy、cut和paste。在help菜單項中,有一個二級菜單項about。對于每一個二級菜單項,不必真正實現其功能,只要演示它能響應鼠標單擊事件即可,如彈出一個對話框或打印一句話。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
import java.awt.*; import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.*; public class menudemo extends jframe implements actionlistener{ public static void main(string[] args){ menudemo demo = new menudemo(); demo.go(); } public void go(){ this .settitle( "圖形用戶界面" ); this .setbounds( 600 , 150 , 500 , 150 ); this .setvisible( true ); this .setdefaultcloseoperation(jframe.exit_on_close); this .setlocationrelativeto( null ); //創建菜單 jmenubar jmb = new jmenubar(); //不能設定位置,會自動放在最上部 this .setjmenubar(jmb); //添加菜單 jmenu menu1 = new jmenu( "file" ); jmenu menu2 = new jmenu( "edit" ); jmenu menu3 = new jmenu( "help" ); jmenuitem item1 = new jmenuitem( "new" ); jmenuitem item2 = new jmenuitem( "open" ); jmenuitem item3 = new jmenuitem( "save" ); jmenuitem item4 = new jmenuitem( "copy" ); jmenuitem item5 = new jmenuitem( "cut" ); jmenuitem item6 = new jmenuitem( "paste" ); jmenuitem item7 = new jmenuitem( "about" ); //添加菜單項至菜單上 menu1.add(item1); menu1.add(item2); menu1.add(item3); menu2.add(item4); menu2.add(item5); menu2.add(item6); menu3.add(item7); //將菜單加入至菜單條 jmb.add(menu1); jmb.add(menu2); jmb.add(menu3); item1.addactionlistener( this ); item2.addactionlistener( this ); item3.addactionlistener( this ); item4.addactionlistener( this ); item5.addactionlistener( this ); item6.addactionlistener( this ); item7.addactionlistener( this ); } public void actionperformed(actionevent e){ string str = e.getactioncommand(); if ( "new" .equals(str)) { system.out.println( "new正在被點擊" ); } else if ( "open" .equals(str)){ system.out.println( "open正在被點擊" ); } else if ( "save" .equals(str)){ system.out.println( "save正在被點擊" ); } else if ( "copy" .equals(str)){ system.out.println( "copy正在被點擊" ); } else if ( "cut" .equals(str)){ system.out.println( "cut正在被點擊" ); } else if ( "paste" .equals(str)){ system.out.println( "paste正在被點擊" ); } else { system.out.println( "about正在被點擊" ); } } } |
運行效果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/liangllhahaha/article/details/80297823