想要在标签中显示日期
你能帮我解决这个代码吗,我试图在标签中显示当前日期,但我使用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();
}
}
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:
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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于任何使用 netbeans 可视化构建器的人来说,我找到了一种更快的方法来做到这一点。
希望它对陷入困境的人有所帮助!:-)
To anyone using netbeans visual builder, I found a faster way to do this.
Hope it helps a stranded one!:-)
DateLabel
必须扩展JLabel
,否则setText
将无法正常工作,也无法将自定义标签添加到Container
。DateLabel
must extendJLabel
, otherwisesetText
won't work as well as adding the custom label to theContainer
.无需在 Swing1 构造函数中创建新的 JFrame。 Swing1 扩展了 JFrame,只需在 Swing1 实例本身上执行
getContentPane().add(myDate, BorderLayout.NORTH);
即可。确保调用super()
作为构造函数中的第一个语句,也许带有合适的参数集(例如,如果您需要双缓冲等)。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 callsuper()
as the first statement in your constructor, maybe with a suitable argument set (e.g. if you need double buffering or such).