【发布时间】:2014-03-07 08:22:06
【问题描述】:
我有以下工作代码,其中有两个按钮作为事件侦听器。一个按钮获取并显示一个面板panel1,另一个按钮获取并显示另一个面板panel2,删除现有的显示面板。我为每个按钮创建了两个 actionPerformed 方法来执行彼此的任务。我只想做一个来缩短代码,但我不知道如何检测面板中的哪个按钮在编译时显示。任何帮助将不胜感激。
//Switching between panels (screens)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ScreenDemo extends JFrame {
private JPanel panel1, panel2;
private JButton btn1, btn2;
JLabel label1 = new JLabel("Screen 1");
JLabel label2 = new JLabel("Screen 2");
public ScreenDemo() {
createPanel(); //Created at Line 14
addPanel(); //Created at Line 28
}
private void createPanel() {
//Panel for first screen
panel1 = new JPanel(new FlowLayout());
btn1 = new JButton("Move to Screen 2");
btn1.addActionListener(new addScreen1ButtonListener());
//Panel for second screen
panel2 = new JPanel(new FlowLayout());
btn2 = new JButton("Move to Screen 1");
btn2.addActionListener(new addScreen2ButtonListener());
}
private void addPanel() {
panel1.add(label1);
panel1.add(btn1);
panel2.add(label2);
panel2.add(btn2);
add(panel1); //Add the first screen panel
}
class addScreen1ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
getContentPane().removeAll();
getContentPane().add(panel2);
repaint();
printAll(getGraphics()); //Prints all content
}
}
class addScreen2ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ea) {
getContentPane().removeAll();
getContentPane().add(panel1);
repaint();
printAll(getGraphics()); //Prints all content
}
}
public static void main(String[] args) {
ScreenDemo screen = new ScreenDemo();
screen.setTitle("Switching Screens");
screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
screen.setSize(500, 500);
screen.setVisible(true);
}
}
【问题讨论】:
-
对于一个空间中的多个组件,请使用
CardLayout,如short example 所示。或者,考虑将组件放入JTabbedPane。
标签: java swing jbutton actionlistener