java - 如何将类实例放在边界布局的北部?
问题描述
我写了一个简单的 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 将“冻结”。有关详细信息和修复,请参阅Swing 中的并发。public static void main(String[] args) { new TimerTest(); }
应在 EDT 上创建和更新基于 Swing 和 AWT 的 GUI。
推荐阅读
- python - Django Rest API 端点显示意外的数值而不是字符串
- r - mutate_at 中的复合函数
- python - SQLite3 外键不匹配
- android - 如何在两个 android 活动之间创建幻灯片过渡动画并排除工具栏?
- node.js - 使用“npm 缓存验证”时出现“EOF 后的错误 stream.push()”
- scheduled-tasks - Laravel5.6.4 中的任务计划
- c# - TripleDES 解密有效,但中间有一些乱码
- php - 在 preg_replace() 中使用捕获组
- angular - 如何为网站中的所有表生成过滤器元素 wrt 表列定义 - Angular
- php - 防止来自不同浏览器的 Codeigniter 中的多个并发登录