我想编写一个简单的十字路口交通灯系统。我想制作一个按钮来启动整个程序(打开交通灯系统的 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;
}
}
}
最佳答案
您的代码中有几个错误:
- 您不应该扩展
JFrame
,请参阅 Extends JFrame vs. creating it inside the program - 不要调用
setBounds(...)
Layout Managers将负责定位您的组件 - 不要在行与行之间或左大括号之后/之前留下太多额外空间
{}
这会变得难以阅读 - 不要将
Button
调用为类名,它可能会与java.awt.Button
类混淆。
It doesnt display its text and the action it should perform won't happen
在本类(class)中:
public class Button extends JButton {
private String actionName;
public Button(String actionName) {
this.actionName = actionName;
JButton button = new JButton();
button.setText(actionName);
button.setSize(30, 30);
button.setBounds(5, 5, 25, 25);
button.addActionListener(new Evt(this.actionName));
}
}
您从 JButton
扩展,然后在其中创建一个 JButton
!因此,您有 2 个 JButton,一个来自类(继承),一个是您在其中创建的。但是您将文本设置为内部创建的文本,但将另一个文本(没有文本)添加到您的 JFrame
中。
打个比喻,就像:
- 您在页面中写了一些内容
- 您会获得一个新的白页并将其添加到您的书中,而不是将您所写的内容添加到您的书中。
无需在当前程序中扩展 JButton
,因此只需创建一个新的 JButton
实例即可。
否则,如果您确实想使用自定义 JButton
类,请执行以下操作:
public class MyCustomButton extends JButton { // Change class name
private String actionName;
public MyCustomButton(String actionName) {
super(actionName); //Sets the text
this.actionName = actionName;
button.addActionListener(new Evt(this.actionName));
}
}
关于Java/Swing JButton 不显示其文本且不执行其操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56449917/