我在寫一些Java代碼,允許用戶看到一個框架,其中JLabel
,JTextField
和JButton
。Java FlowLayout
我想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)'如[這個問題和答案]所述(http://stackoverflow.com/questions/7143287/how-to-best-position-swing-guis)。它也應該在'frame.setVisible(true)'之前。 – MasterBlaster
你應該總是把擺動方法放在事件派發線程中。看看[併發中的Swing - Java™教程](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html)。 – MasterBlaster