在java中怎么实现一个按钮对两个事件监听
1个回答
展开全部
你问的是JAVASE么?
使用Button的addActionListener就好了
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
JFrame frame = new JFrame();
frame.setTitle("my frame");
frame.setBounds(0, 0, 200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btn1 = new JButton("OpenBrowser");
JButton btn2 = new JButton("OpenNotepad");
JPanel panel = new JPanel(new FlowLayout(4));
btn1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("OpenBrowser")) {
try {
Process p = Runtime.getRuntime().exec("explorer http://www.qq.com");
p.destroy();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}) ;
btn2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Process p = Runtime.getRuntime().exec("notepad");
p.destroy();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
panel.add(btn1);
panel.add(btn2);
frame.add(panel);
frame.setVisible(true);
使用Button的addActionListener就好了
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
JFrame frame = new JFrame();
frame.setTitle("my frame");
frame.setBounds(0, 0, 200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btn1 = new JButton("OpenBrowser");
JButton btn2 = new JButton("OpenNotepad");
JPanel panel = new JPanel(new FlowLayout(4));
btn1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("OpenBrowser")) {
try {
Process p = Runtime.getRuntime().exec("explorer http://www.qq.com");
p.destroy();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}) ;
btn2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Process p = Runtime.getRuntime().exec("notepad");
p.destroy();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
panel.add(btn1);
panel.add(btn2);
frame.add(panel);
frame.setVisible(true);
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询