如何申报一个

时间:2014-03-07 08:22:06

标签: java swing jbutton actionlistener

我有以下工作代码,两个按钮作为事件监听器。获取并显示面板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);
}
} 

2 个答案:

答案 0 :(得分:4)

为您的类实现ActionListener,并尝试使用此代码

       ScreenDemo extends JFrame implements ActionListener
    ...
        btn1.addActionListener(this);
        btn2.addActionListener(this);
    ...
        @override
        public void actionPerformed(ActionEvent ae) {
            if(ae.getSource().equals(btn1)) {
            ...
            }
            else if(ae.getSource().equals(btn1)) {
            ...
            }
        }

答案 1 :(得分:0)

您必须implements来自ActionListener的课程 而不是注册JButton,如:btn.addActionListener(this);

现在如此接近,您只需捕获事件并从其所在的位置获取源:

 public void actionPerformed(ActionEvent ae) {
        if(ae.getSource == btn1){
            //shuffle panel from btn1
        }
        if(ae.getSource == btn2) {
            //shuffle panel from btn2               
        }
}