java 想要在标签中显示日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7892381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:51:47  来源:igfitidea点击:

Want to display date in a label

javaswing

提问by obi1kinobi

Can you please help me with this codes, I am trying to show the current date in a label, but am using 3 different class, ie, the main class(AppStart), the class which I create the label in ad it will display the label in the frame, thus the (Swing1) and then the date class it self (DateLabel). The code is shown below:

你能帮我这个代码吗,我试图在标签中显示当前日期,但我使用了 3 个不同的类,即主类(AppStart),我在广告中创建标签的类它将显示框架中的标签,因此是(Swing1),然后是它自己的日期类(DateLabel)。代码如下所示:

public DateLabel()
{
    Date today = new Date();

    //Date format
    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
    String strDate = df.format(today);
     setText( strDate);


}
}

import java.awt.*;//used for Gui Developement
import java.util.*;
import java.text.*;
import javax.swing.*;//Used for GUI development

public class Swing1 extends JFrame
{

JLabel lblWelcome;
DateLabel myDate;
Swing1()
{
    JFrame myJF = new JFrame();
    myJF.setTitle("CBT Tutorial");

    //JLabel Stuff
    myDate = new DateLabel();

    Container c = getContentPane();
    c.add(myDate, BorderLayout.NORTH);


    myJF.setSize(300,300);
    myJF.show();

}

}


public class AppStart {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) 
{
   new Swing1();
}
}

回答by Moses Kirathe

To anyone using netbeans visual builder, I found a faster way to do this.

对于使用 netbeans 可视化构建器的任何人,我找到了一种更快的方法来做到这一点。

public classname{
    Initcomponents();
    String date= new Date.toString();
    Yourlabelname.setText(date)}
   }

Hope it helps a stranded one!:-)

希望它可以帮助一个搁浅的人!:-)

回答by f4lco

DateLabelmust extend JLabel, otherwise setTextwon't work as well as adding the custom label to the Container.

DateLabel必须扩展JLabel,否则setText将无法像将自定义标签添加到Container.

回答by G_H

No need to create a new JFrame in your Swing1 constructor. Swing1 extends JFrame, just do getContentPane().add(myDate, BorderLayout.NORTH);on the Swing1 instance itself. Make sure to call super()as the first statement in your constructor, maybe with a suitable argument set (e.g. if you need double buffering or such).

无需在 Swing1 构造函数中创建新的 JFrame。Swing1 扩展了 JFrame,只需getContentPane().add(myDate, BorderLayout.NORTH);在 Swing1 实例本身上执行即可。确保super()作为构造函数中的第一条语句调用,可能使用合适的参数集(例如,如果您需要双缓冲等)。