2013年11月19日星期二

Find Daniel explained , the program can not run , in the panel to achieve three button, click the corresponding color

transform
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;
}





I did not run properly for anonymous class before then streamlined , set up a method makeButton, set up anonymous class to die , seeking Daniel explains , Jia
------ Solution --------------------------------------------


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);
}
});
}

}

------ For reference only -------------------------------------- -
landlord is beginner java bar , this problem will be very common in the future , I hope to learn and progress landlord

没有评论:

发表评论