[英]Why won't my GUI work properly?
Why is it that when the GUI I can press A, B, and C but if I click A and then C it (the GUI) doesn't change and vice versa but if I click B it will work for all? 为什么当GUI我可以按A,B和C但是如果我单击A然后C它(GUI)不会改变,反之亦然但如果我点击B它将适用于所有人? I don't understand?
我不明白? Please if anyone notices any mistakes or something let me know.
如果有人注意到任何错误或某些事情让我知道。 And ps I'm a beginner so please if you can explain in layman's terms.
ps我是初学者,所以如果你能用外行的话来解释,请。 Thank you
谢谢
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();
}
}
Change your actionPerformed method into this: 将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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.