我的GUI为什么无法正常工作?

4
为什么当我在GUI中按A、B和C时,如果我先点击A再点击C,GUI不会改变,反之亦然。但如果我点击B,它将对所有操作都有效?我不明白为什么会这样,请各位指正错误,同时请尽可能通俗易懂地解释,因为我是初学者。谢谢。
package Experimental;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class EventListener2 extends JFrame implements ActionListener{
    JButton a,b,c;
    JLabel aa,bb,cc;
    JPanel top, bottom;
    EventListener2(){
        super("Event Listener 2");
        setSize(300,300);
        setLayout(new FlowLayout());
        a=new JButton("A");
        aa = new JLabel("Button \"A\" was pressed");
        b=new JButton("B");
        bb = new JLabel("Button \"B\" was pressed");
        c=new JButton("C");
        cc = new JLabel("Button \"C\" was pressed");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        a.addActionListener(this);
        b.addActionListener(this);
        c.addActionListener(this);

        top=new JPanel();
        top.setLayout(new FlowLayout());
        top.add(a);
        top.add(b);
        top.add(c);
        bottom=new JPanel();

        this.add(top);
        this.add(bottom);

        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        // TODO Auto-generated method stub
        Object source = event.getSource();
        bottom.removeAll();
        if (source==a){
            bottom.add(aa);
            System.out.println("a was pressed");
        }
        else if (source==b){
            bottom.add(bb);
            System.out.println("b was pressed");
        }
        else{
            bottom.add(cc);
            System.out.println("c was pressed");
        }
        this.setVisible(true);

    }
    public static void main(String[] args) {
         EventListener2 a = new EventListener2();
    }

}

2
整个 actionPerformed(..) 方法表明 bottom 面板应该使用 CardLayout,如 这个答案 所示。 - Andrew Thompson
1个回答

5
将您的actionPerformed方法更改为以下内容:
public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();
    bottom.removeAll();
    if (source==a){
        bottom.add(aa);
        System.out.println("a was pressed");
    }
    else if (source==b){
        bottom.add(bb);
        System.out.println("b was pressed");
    }
    else{
        bottom.add(cc);
        System.out.println("c was pressed");
    }
    bottom.revalidate();
    bottom.repaint();
    this.setVisible(true);
}

2
@Override 是一个注解,用于检查我们是否真正重写了方法。将其添加到像 equalshashCode 这样的方法中是很好的,以确保我们使用了正确的参数并没有拼错方法名。将其添加到方法调用中是没有意义的。 - Pshemo
没问题 :) 你可以在这里阅读更多相关信息:Java中的@ Override注释何时使用以及为什么? - Pshemo
你的英语似乎还不错(至少对于我这个非英语为母语的人来说),所以不要太担心了。只要我们能够理解你想表达的意思,它不需要完美无瑕。 - Pshemo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接