我想創建一個包含標籤和按鈕的Java GUI應用程序。點擊按鈕後,第一個面板的背景顏色會發生變化。我有標籤和按鈕,但每次點擊按鈕時都會出現錯誤。另外,我希望第一塊麪板原本有黃色背景,然後切換到任何顏色。這裏是我的代碼:改變背景與按鈕的GUI應用程序
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class ChangeDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 300;
public static final int HEIGHT= 200;
private JPanel biggerPanel;
public static void main(String[] args)
{
ChangeDemo gui = new ChangeDemo();
gui.setVisible(true);
}
public ChangeDemo()
{
super ("ChangeBackgroundDemo");
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2,3));
JPanel biggerPanel = new JPanel();
biggerPanel.setLayout(new BorderLayout());
biggerPanel.setBackground(Color.YELLOW);
JLabel namePanel = new JLabel("Click the button to change the background color");
biggerPanel.add(namePanel, BorderLayout.NORTH);
add(namePanel);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBackground(Color.LIGHT_GRAY);
JButton changeButton = new JButton("Change Color");
changeButton.addActionListener(this);
buttonPanel.add(changeButton);
add(buttonPanel);
}
public void actionPerformed(ActionEvent e)
{
String buttonString = e.getActionCommand();
if(buttonString.equals("Change Color"))
biggerPanel.setBackground(Color.RED);
else
System.out.println("Unexpected Error!");
}
}
我試過,但沒有工作。當我點擊按鈕時仍然出現錯誤。 – JavaBeginner 2014-12-02 17:22:51