我编写了一个简单的Timer类,我想将框架布局设置为Border布局,并将timer放置在北方。我是布局的新手,有人可以帮助我吗?
import java.awt.*;
import javax.swing.*;
public class TimerTest extends JFrame{
JButton timerLabel = null;
public TimerTest()
{
this.setTitle("Timer Test");
Container c = this.getContentPane();
c.setLayout(new FlowLayout());
timerLabel = new JButton("0");
timerLabel.setEnabled(false);
c.add(timerLabel);
this.setSize(150,150);
this.setVisible(true);
int k = 100;
while(true)
{
timerLabel.setText(k+" seconds left");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
k--;
}
}
public static void main(String[] args) {
new TimerTest();
}
}
Container c = this.getContentPane(); // has border layout by DEFAULT
c.setLayout(new FlowLayout()); // but now it has flow layout!
// ..
c.add(timerLabel);
因此将其更改为:
Container c = this.getContentPane(); // has border layout by DEFAULT
// ..
c.add(timerLabel, BorderLayout.PAGE_START); // PAGE_START is AKA 'NORTH'
JFrame
,仅使用一个实例。 JButton timerLabel
是一个令人困惑的名称,它应该是JButton timerButton
this.setTitle("Timer Test");
可以写为super("Timer Test");
,或者如果使用标准(非扩展)框架.. JFrame frame = new JFrame("Timer Test");
this.setSize(150,150);
那只是个猜测。最好是this.pack();
while(true) .. Thread.sleep(1000);
请勿阻止EDT(事件调度线程)。发生这种情况时,GUI将“冻结”。有关详细信息和修复方法,请参见Concurrency in Swing。public static void main(String[] args) { new TimerTest(); }
Swing和AWT的GUI。