java - 为什么我的 GUI 不能正常工作?

标签 java swing user-interface awt

为什么在 GUI 时我可以按 A、B 和 C 但如果我单击 A 然后 C (GUI)不会改变,反之亦然,但如果我单击 B,它会适用于所有人吗?我不明白?请如果有人注意到任何错误或什么让我知道。 ps 我是初学者,如果您能用通俗易懂的语言解释一下,请多多指教。谢谢

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();
    }

}

最佳答案

将您的 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);
}

关于java - 为什么我的 GUI 不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31631129/

相关文章:

java - 图像调整大小以适应 JPanel

java - 如何在 Java 中正确实现自定义加载屏幕

java - ScrolledComposite 内大量复合 Material 的 SWT 性能

python - 向图中添加导航工具栏(matplotlib 和 PyQt4)

java - 无法在调用拦截 Android 应用程序中阻止号码不以“+91”开头的联系人

java - Java 中的基元与对象

java - Recyclerview 持有者在滚动上混合

java - 在 JList 中显示使用不同对象加载 JList 数据的 ImageIcon

ios - UICollectionView 多个单元格选择 Swift iOS

java - 如何知道 Java 中 GeoTIFF/TIFF 文件的波段序列/名称?