首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

关于jlabel赋值有关问题

2013-06-19 
关于jlabel赋值问题定义了一个TimerUtil类,为窗体上的JLabel赋值,但是在Timer方法中调用JLabel.setText()

关于jlabel赋值问题
定义了一个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()));


    }
}).start();

热点排行
Bad Request.