반응형
JMenuBar, JMenu, JMenuItem 각각의 상관관계는 아래 링크를 따라가서 보길 바란다
출처 : SWING 메뉴 구성, 메뉴 만들기, 메뉴 아이템에 Action 이벤트 달기
소스
MenuEx.java
더보기
|
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
|
import javax.swing.*;
public class MenuEx extends JFrame {
MenuEx() {
setTitle("Menu 만들기 예제");
createMenu(); // 메뉴 생성, 프레임에 삽입
setSize(250, 200);
setVisible(true);
}
void createMenu() {
JMenuBar mb = new JMenuBar();
JMenu screenMenu = new JMenu("Screen");
screenMenu.add(new JMenuItem("Load"));
screenMenu.add(new JMenuItem("Hide"));
screenMenu.add(new JMenuItem("ReShow"));
screenMenu.addSeparator();
screenMenu.add(new JMenuItem("Exit"));
mb.add(screenMenu);
mb.add(new JMenu("Edit"));
mb.add(new JMenu("Source"));
mb.add(new JMenu("Project"));
mb.add(new JMenu("Run"));
setJMenuBar(mb);
}
public static void main(String[] args) {
new MenuEx();
}
}
|
cs |
다음은 Action 이벤트 소스
MenuActionEventEx.java
더보기
|
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
|
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MenuActionEventEx extends JFrame {
JLabel imgLabel = new JLabel(); // 빈 레이블
MenuActionEventEx() {
setTitle("Menu에 Action 리스너 만들기 예제");
createMenu();
getContentPane().add(imgLabel, BorderLayout.CENTER);
setSize(250, 200);
setVisible(true);
}
void createMenu() {
JMenuBar mb = new JMenuBar(); // 메뉴바 생성
JMenuItem[] menuItem = new JMenuItem[4];
String[] itemTitle = { "Load", "Hide", "ReShow", "Exit" };
JMenu screenMenu = new JMenu("Screen");
MenuActionListener listener = new MenuActionListener();
for (int i = 0; i < menuItem.length; i++) {
menuItem[i] = new JMenuItem(itemTitle[i]);
menuItem[i].addActionListener(listener);
screenMenu.add(menuItem[i]);
}
mb.add(screenMenu);
setJMenuBar(mb); // 메뉴바를 프레임에 부착
}
class MenuActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
switch (cmd) { // 메뉴 아이템의 종류 구분
case "Load":
if (imgLabel.getIcon() != null)
return;
// 이미 로딩되었으면 리턴
imgLabel.setIcon(new ImageIcon("img/Koala.jpg"));
break;
case "Hide":
imgLabel.setVisible(false);
break;
case "ReShow":
imgLabel.setVisible(true);
break;
case "Exit":
System.exit(0);
break;
}
}
}
public static void main(String[] args) {
new MenuActionEventEx();
}
}
|
cs |
출처 : SWING 메뉴 구성, 메뉴 만들기, 메뉴 아이템에 Action 이벤트 달기
반응형
'개발 실무' 카테고리의 다른 글
| 진행바,프로그레스바(JProgressBar) (5) | 2018.09.11 |
|---|---|
| [JAVA][SWING] 팝업 JOptionPane (showInputDialog, showConfirmDialog, showMessageDialog) (0) | 2018.09.11 |
| [JAVA][SWING] Drag-and-drop 파일선택시 드레그 앤 드롭 구현 (1) | 2018.09.10 |
| [JAVA][SWING]화면 중앙에 창 띄우기 (0) | 2018.09.10 |
| [JAVA][SWING]JPanel ( 2개의 패널 전환 ) (0) | 2018.09.10 |