定义了一个TimerUtil类,为窗体上的JLabel赋值,但是在Timer方法中调用JLabel.setText()不管用,换到一个按钮单击事件中去赋值就管用,求解释!!!!!
代码:public void setTimer() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = new Date();
String currentDate = sdf.format(date);
this.jLabel5.setText(currentDate); <--这段不管用
}
java swing
------解决方案--------------------
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Maze{
public static void main(String[] a) throws ParseException{
DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
@SuppressWarnings("deprecation")
Date date=new Date();
String outputText = outputFormat.format(date);
System.out.println(outputText);
JLabel jLabel=new JLabel();
jLabel.setText(outputText);
JFrame frame = new JFrame("Frame With Panel");
Container contentPane = frame.getContentPane();
contentPane.setBackground(Color.CYAN); // 将JFrame实例背景设置为蓝绿色
JPanel panel = new JPanel(); // 创建一个JPanel的实例
panel.setBackground(Color.yellow); // 将JPanel的实例背景设置为黄色
JButton button = new JButton("Press me");
panel.add(button); // 将JButton实例添加到JPanel中
//contentPane.add(panel, BorderLayout.SOUTH); // 将JPanel实例添加到JFrame的南侧
contentPane.add(jLabel,BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
第一次写java 完全没问题
------解决方案--------------------
final JLabel label = ...;
final SimpleDateFormat formatter = ...;
new javax.swing.Timer(1000, new ActionListener(){
public void actionPerformed(ActionEvent e){
label.setText(formatter.format(new Date()));