//GUI.java
public class GUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 870343916997182570L;
private JPanel btmPanel;
public GUI(String arg0) throws HeadlessException {
super(arg0);
createGUI();
}
private void createGUI() {
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
//ResultPanel rslt = new ResultPanel();
//this.getContentPane().add(rslt.createPanel(), BorderLayout.CENTER);
btmPanel = new JPanel();
btmPanel.setBackground(Color.LIGHT_GRAY);
btmPanel.setLayout(new FlowLayout());
JButton blueSearch = new JButton("Search");
blueSearch.setBackground(Color.WHITE);
blueSearch.addActionListener(this);
btmPanel.add(blueSearch);
JButton blackChart = new JButton("Chart");
blackChart.setBackground(Color.WHITE);
blackChart.addActionListener(this);
btmPanel.add(blackChart);
this.getContentPane().add(btmPanel, BorderLayout.SOUTH);
}
@Override
public void actionPerformed(ActionEvent e) {
String buttonString = e.getActionCommand();
if (buttonString.equals("Search")) {
ResultPanel rslt = new ResultPanel();
this.getContentPane().add(rslt.createPanel(), BorderLayout.CENTER);
}
}
}
//ResultPanel.java
public class ResultPanel extends JPanel implements ActionListener {
private static final long serialVersionUID = -7851502165390304971L;
private JPanel textPanel;
private JTextArea textDisplay;
public ResultPanel() {
textPanel = new JPanel();
textDisplay = new JTextArea("Text Area:");
}
public JPanel createPanel() {
textDisplay.setEditable(true);
textPanel.setBackground(Color.LIGHT_GRAY);
textPanel.setLayout(new BorderLayout());
textPanel.add(textDisplay,BorderLayout.CENTER);
return textPanel;
}
@Override
public void actionPerformed(ActionEvent e) {
}
}
我的主机架上有两个按钮,我希望按下按钮时可以改变面板。
问题是“actionPerformed”中的代码不起作用,
但如果我把它们放在 creatGUI().... 中效果很好(见标记部分)。
那有什么问题吗?