public class StatsGUI extends JFrame implements ActionListener {
JLabel label;
JLabel label2;
JTextField input;
JTextField output;
JButton getButton;
JButton exitButton;
public StatsGUI()
{
JPanel panel = new JPanel();
label = new JLabel("Enter number");
panel.add(label);
input = new JTextField(10);
input.addActionListener(this);
panel.add(input);
label2 = new JLabel("Statistics");
output = new JTextField(10);
output.setEditable(false);
panel.add(output);
getButton = new JButton("Go");
getButton.addActionListener(this);
panel.add(getButton);
exitButton = new JButton("Exit");
exitButton.addActionListener(this);
panel.add(exitButton);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == exitButton)
{
System.exit(0);
}
else
{
String text = input.getText();
output.setText(text + "COUNTER");
}
}
public static void main(String[] args)
{
}
这是我的简单 GUI 程序。我已将所有按钮和其他小工具放置在构造函数中。但是,我不确定应该在 main 中放入什么以使 GUI 真正显示出来。我确信我在这里遗漏了一些非常简单的东西,但我不确定是什么。非常感谢您的帮助。
最佳答案
您离让事情正常运转已经不远了。只需了解几件事:
- 您的 UI 应在事件调度线程 (EDT) 上启动
- 您实际上需要将面板/组件添加到框架中
- 您需要
pack()
您的窗口/框架 - 您需要使其可见
- (设计内容,可选,但当您使用它时,为什么不直接修复它),不需要扩展
JFrame
,所以让我们放弃它。
所以最终,考虑这些建议会让你得到这样的结果:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class StatsGUI implements ActionListener {
JLabel label;
JLabel label2;
JTextField input;
JTextField output;
JButton getButton;
JButton exitButton;
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == exitButton) {
System.exit(0);
} else {
String text = input.getText();
output.setText(text + "COUNTER");
}
}
public void initUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
label = new JLabel("Enter number");
panel.add(label);
input = new JTextField(10);
input.addActionListener(this);
panel.add(input);
label2 = new JLabel("Statistics");
output = new JTextField(10);
output.setEditable(false);
panel.add(output);
getButton = new JButton("Go");
getButton.addActionListener(this);
panel.add(getButton);
exitButton = new JButton("Exit");
exitButton.addActionListener(this);
panel.add(exitButton);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new StatsGUI().initUI();
}
});
}
}
关于java - 我该如何运行我的 GUI?或者更准确地说,我在 main 中放了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21892526/