【发布时间】:2016-07-31 15:45:33
【问题描述】:
我正在编写一些 Java 代码,允许用户查看带有 JLabel、JTextField 和 JButton 的框架。
我希望将JLabel 称为“计数”,但FlowLayout 有问题。
我希望界面看起来像这样:
相反,我有这个:
这是我的代码:
package modul1_Interfate_Grafice;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Exercitiu04 implements ActionListener {
private JFrame frame;
private JLabel labelCount;
private JTextField tfCount;
private JButton buttonCount;
private int count = 0;
public void go() {
frame = new JFrame("Java Counter");
labelCount = new JLabel("Counter");
labelCount.setLayout(new FlowLayout());
frame.getContentPane().add(BorderLayout.CENTER, labelCount);
tfCount = new JTextField(count + " ", 10);
tfCount.setEditable(false);
labelCount.add(tfCount);
buttonCount = new JButton("Count");
labelCount.add(buttonCount);
buttonCount.addActionListener(this);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(350, 150);
frame.setLocation(400, 200);
}
@Override
public void actionPerformed(ActionEvent event) {
count++;
tfCount.setText(count + "");
}
public static void main(String[] args) {
Exercitiu04 a = new Exercitiu04();
a.go();
}
}
【问题讨论】:
-
frame.setSize(350, 150);应该是frame.pack();.. -
frame.setLocation(400, 200)应为frame.setLocationByPlatform(true),如 this question and answer 所述。它也应该在frame.setVisible(true)之前。 -
您应该始终将 swing 方法放在事件调度线程中。看看Concurrency in Swing - The Java™ Tutorials。
标签: java swing layout-manager flowlayout