[英]How to fix the output of a GUI application where multiple windows pop up infinitely and then abruptly terminates program?
我尝试运行的这个 GUI 应用程序有问题。 它将英尺转换为英寸。 但由于某种原因,它似乎不起作用。 当我运行它时,会弹出多个窗口,并且这些窗口的数量不断增加,直到它突然停止运行。 请帮忙! 我也使用netbeans。
简单gui的代码:
package converter;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Converter{
JFrame f;
JTextField t1, t2;
public Converter() {
f = new JFrame("Converter");
f.setSize(250, 200);
f.setLayout(new FlowLayout());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p1 = new JPanel();
JLabel foot = new JLabel("Foot");
t1 = new JTextField(12);
p1.add(foot);p1.add(t1);
JPanel p2 = new JPanel();
JButton btn = new JButton("Convert to Inch");
p2.add(btn);
JPanel p3 = new JPanel();
JLabel inch = new JLabel("Inch");
t2 = new JTextField(12);
p3.add(inch);p3.add(t2);
ButtonListener o = new ButtonListener();
btn.addActionListener(o);
f.add(p1);
f.add(p2);
f.add(p3);
f.setVisible(true);
}
class ButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
String t = t1.getText();
int a = Integer.parseInt(t);
int y = a*12;
t1.setText(y+"");
}
}
public static void main(String[] args) {
new Converter();
}
}
尽管评论中已经回答了主要问题,但这是对评论中其他问题的回答。
如需进一步说明,请查看代码中的注释。
public class Converter implements ActionListener {
JFrame f;
JTextField t1, t2;
public Converter() {
f = new JFrame("Converter");
f.setSize(250, 200);
f.setLayout(new FlowLayout());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p1 = new JPanel();
JLabel foot = new JLabel("Foot");
t1 = new JTextField(12);
p1.add(foot);
p1.add(t1);
JPanel p2 = new JPanel();
JButton btn = new JButton("Convert to Inch");
p2.add(btn);
JPanel p3 = new JPanel();
JLabel inch = new JLabel("Inch");
t2 = new JTextField(12);
p3.add(inch);
p3.add(t2);
// Here add the action listener to you button
// In this case "this" because your "Converter" is your ActionListener
btn.addActionListener(this);
f.add(p1);
f.add(p2);
f.add(p3);
f.setVisible(true);
}
// Override the actionPerformed method in your Converter Class (as it now
// implements ActionListener)
@Override
public void actionPerformed(ActionEvent e) {
String t = t1.getText();
int a = Integer.parseInt(t);
int y = a * 12;
t2.setText(y + "");
}
public static void main(String[] args) {
new Converter();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.