本例通过按钮实现背景颜色转换的简单功能,不过重要的是实现过程以及层级调用关系,比如colorTest类和ButtonFrame类在所有GUI设计中都能起到重用功能,而makeButton用一个方法代替了反复用同样方法添加组件和事件监听的过程,读者也可以从本例的ActionListener监听器调用中看到匿名类的方便之处。
package frameclass;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class colorTest {
public static void main(String[] args) {
ButtonFrame frame=new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class ButtonFrame extends JFrame{ //继承JFrame类,实现其框架功能
private int DEFAULT_WIDTH=300;
private int DEFAULT_HEIGHT=300;
public ButtonFrame(){
setTitle("ButtonTest");
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
ButtonPanel panel=new ButtonPanel();
add(panel);
}
}
class ButtonPanel extends JPanel{ //继承JPanel类,实现其面板功能
public ButtonPanel(){
makeButton("yellow",Color.yellow);
makeButton("blue",Color.blue);
makeButton("red",Color.red);
}
void makeButton(String name,final Color backgroundColor){ //实现添加组件和事件监听
JButton button=new JButton(name);
add(button);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
setBackground(backgroundColor);
}
});
}
}