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 77
|
package com.star;
import java.awt.Color; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame;
public class Main extends JFrame {
private JButton btBlue, btDialog;
public Main() { setTitle("Java GUI 事件监听处理"); setBounds(100, 100, 500, 350); setLayout(new FlowLayout()); btBlue = new JButton("蓝色"); btBlue.addActionListener(new ColorEventListener(this)); btDialog = new JButton("弹窗"); btDialog.addActionListener(new DialogEventListener()); add(btBlue); add(btDialog); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
public static void main(String[] args) { new Main(); } }
class ColorEventListener implements ActionListener { private Main el;
ColorEventListener(Main el) { this.el = el; }
@Override public void actionPerformed(ActionEvent e) { Container c = el.getContentPane(); c.setBackground(Color.BLUE); } }
class DialogEventListener implements ActionListener {
@Override public void actionPerformed(ActionEvent e) { JDialog dialog = new JDialog(); dialog.setBounds(300, 200, 400, 300); dialog.setVisible(true); } }
|