首页 > 解决方案 > 如何将类实例放在边界布局的北部?

问题描述

我写了一个简单的 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();
    }
}

标签: javaswingjframelayout-managerborder-layout

解决方案


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 将“冻结”。有关详细信息和修复,请参阅Swing 中的并发。
  6. public static void main(String[] args) { new TimerTest(); }应在 EDT 上创建和更新基于 Swing 和 AWT 的 GUI。

推荐阅读