使用swing
一:创建GUI的四个步骤
- 创建window(JFrame)
JFrame frame = new JFrame(); - 创建组件
JButton button = new JButton(“click me”); - 把组件加到frame上 frame.getContentPane().add(BorderLayout.EAST,button);
- 显示出来
frame.setSize(300,300);
frame.setVisible(true);
( 可能还有一行代码:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
在窗口关闭时结束程序)
二:监听
- 实现ActionListener这个接口
public class 类名 implements ActionListener {
......
......
......
public void go(){
button.addActionListener(this);
}
......
......
......
@Override
public void actionPerformed(ActionEvent e) {
//要改变的行为
}
}
- 向按钮注册(告诉它你要监听事件)
public void go(){
button.addActionListener(this);
}
- 定义事件处理的方法(实现接口上的方法)
重写actionPerformed方法
@Override
public void actionPerformed(ActionEvent e) {
//要改变的行为
}
三:图形实现
四:布局管理器
JPanel panelA = new JPanel();
JPanel panelB = new JPanel();
panelB.add(new Button("button 1"));
panelB.add(new Button("button 2"));
panelB.add(new Button("button 3"));
panelA.add(panelB);
三大首席管理器:
BorderLayout
FlowLayout
BoxLayout