我想写一个简单的过马路红绿灯系统。我想制作一个按钮来启动整个程序(打开交通灯系统的 GUI)。但是我的第一个按钮已经开始出问题了。它不显示其文本,它应该执行的操作也不会发生。我真的是一个初学者所以它可能是一些愚蠢和明显的错误但是请看看我会很高兴^^
package kreuzung;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JFrame;
public class HomeFrame extends JFrame{
public HomeFrame(String title) {
super(title);
this.setLayout(new FlowLayout(FlowLayout.CENTER));
Button test = new Button("noAction");
Container cont = getContentPane();
cont.add(test, BorderLayout.CENTER);
}
}
这将是生成的按钮,它不做它应该做的事情
package kreuzung;
import javax.swing.Action;
import javax.swing.JButton;
public class Button extends JButton{
private String actionName;
public Button(String actionName) {
this.actionName = actionName; //set the Action name of this button
JButton button = new JButton(); //instantiate this Button
button.setText(actionName); //set the Action Name as Button Text
button.setSize(30, 30);
button.setBounds(5, 5, 25, 25);
button.addActionListener(new Evt(this.actionName)); //add an Action Listener to the button
//and gets the Action from the Evt Class
}
}
最后但并非最不重要的是 Evt 类,它应该负责执行动作
package kreuzung;
import java.awt.event.*;
import javax.swing.JFrame;
public class Evt implements ActionListener {
private String actionName;
public Evt(String actName) {
this.actionName = actName;
}
@Override
public void actionPerformed(ActionEvent e) {
switch(actionName) {
case "noAction":
JFrame frame = new HomeFrame("Home");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 400);
frame.setVisible(true);
break;
}
}
}
HUH函数
阿波罗的战车
相关分类