如何将类实例放在边框布局的北部?

问题描述 投票:0回答:1

我编写了一个简单的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();
    }
}
java swing jframe layout-manager border-layout
1个回答
0
投票
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'

其他提示:

  1. 不扩展JFrame,仅使用一个实例。
  2. JButton timerLabel是一个令人困惑的名称,它应该是JButton timerButton
  3. [this.setTitle("Timer Test");可以写为super("Timer Test");,或者如果使用标准(非扩展)框架.. JFrame frame = new JFrame("Timer Test");
  4. this.setSize(150,150);那只是个猜测。最好是this.pack();
  5. while(true) .. Thread.sleep(1000);请勿阻止EDT(事件调度线程)。发生这种情况时,GUI将“冻结”。有关详细信息和修复方法,请参见Concurrency in Swing
  6. 应在EDT上创建和更新基于public static void main(String[] args) { new TimerTest(); } Swing和AWT的GUI。
© www.soinside.com 2019 - 2024. All rights reserved.