【发布时间】:2015-10-08 16:00:24
【问题描述】:
此代码应创建一个包含标签的框架,用于打印时钟。方法zeitLaeuft() 使时钟工作,并且使用按钮“开始”时钟开始运行。当我调用方法zeitLaeuft() 时,代码失败。我已经尝试了一些东西,现在我知道这是因为标签jLUhr。在zeitLaeuft() 方法中,调用jLUhr.setText() 方法的两个订单失败。我尝试设置标签文本并注释掉该方法,但它不起作用。
有什么问题?
package uhr;
import javax.swing.*;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.util.concurrent.TimeUnit;
public class Uhr1 extends javax.swing.JFrame {
public Uhr1() {
super();
initGUI();
}
private static JLabel jLUhr;
private static JButton jBtnStart;
private static int stunden = 0, minuten = 0;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Uhr1 uhr = new Uhr1();
uhr.setVisible(true);
uhr.setLocationRelativeTo(null);
}
});
}
public void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setTitle("Uhr");
getContentPane().setLayout(null);
{
JLabel jLUhr = new JLabel(); //Uhr = clock in german
add(jLUhr);
jLUhr.setBounds(49, 89, 300, 100);
jLUhr.setHorizontalAlignment(SwingConstants.CENTER);
jLUhr.setVerticalAlignment(SwingConstants.CENTER);
}
{
JButton jBtnStart = new JButton();
add(jBtnStart);
jBtnStart.setBounds(49, 219, 80, 30);
jBtnStart.setText("Start");
jBtnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
start(evt);
}
});
}
pack();
setSize(400,300);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void zeitLaeuft() {
while(true) {
if(minuten < 60) {
int i;
try {
for(i = 0; i < 60; i++){
jLUhr.setText(Integer.toString(stunden) + " : " + Integer.toString(minuten)); //this is where the code fails
TimeUnit.SECONDS.sleep(1);
jLUhr.setText(Integer.toString(stunden) + " " + Integer.toString(minuten)); //this is where the code fails
}
minuten++;
i = 0;
} catch (Exception e) {
e.printStackTrace();
}
}
else if(minuten == 60) {
minuten = 0;
if(stunden < 24) {
stunden ++;
}
else {
stunden = 0;
}
}
}
}
public void start(ActionEvent evt) {
zeitLaeuft(); //this is where the code fails
}
}
【问题讨论】:
-
1) "..代码失败.." 总是复制/粘贴错误和异常输出! 2) 见What is a stack trace, and how can I use it to debug my application errors? & What is a Null Pointer Exception, and how do I fix it?
-
3)
getContentPane().setLayout(null);Java GUI 必须在不同的语言环境中使用不同的 PLAF 在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。