日期:2014-05-20 浏览次数:20678 次
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable()
{
public void run()
{
TestFrame frame = new TestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class TestFrame extends JFrame
{
public TestFrame()
{
setTitle("First Swing Test");
setSize(FRAME_WIDTH,FRAME_HEIGHT);
makeButton("yellow",Color.YELLOW);
makeButton("pink",Color.PINK);
makeButton("red",Color.RED);
}
public void makeButton (String name,final Color backgroundColor)
{
JButton button = new JButton(name);
buttonPanel.add(button);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
buttonPanel.setBackground(backgroundColor);
}
});
}
private JPanel buttonPanel;
private static int FRAME_WIDTH = 350;
private static int FRAME_HEIGHT = 500;
}
class TestFrame extends JFrame {
private JPanel buttonPanel;
private static int FRAME_WIDTH = 350;
private static int FRAME_HEIGHT = 500;
/**
*
*/
private static final long serialVersionUID = 1L;
public TestFrame() {
setTitle("First Swing Test");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
/**
* 你写了一个 buttonPanel 变量,但是却没有给它赋值,所以出现了空指针的问题。 下面我给它进行了赋值,问题就解决了。
*/
buttonPanel = new JPanel();
add(buttonPanel);
makeButton("yellow", Color.YELLOW);
makeButton("pink", Color.PINK);
makeButton("red", Color.RED);
}
public void makeButton(String name, final Color backgroundColor) {
JButton button = new JButton(name);
buttonPanel.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
buttonPanel.setBackground(backgroundColor);
}
});
}
}