我正在创建一种待办事项列表应用程序。一方面,您有待办事项列表应用程序,其中包含可以添加任务的框,另一方面,您有一个数字时钟。待办事项清单可以正常工作并完美显示。另一方面,时钟根本不显示。当我在测试程序中自己实例化一个 Clock 对象时,它运行得很好,但是当我尝试在 JFrame 中用待办事项列表实例化它时,它根本不显示。我已经检查了我的驱动程序,并且我有我的时钟对象的实例化和声明。我究竟做错了什么?
时钟面板对象:
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.Timer;
public class ClockPanel extends javax.swing.JPanel implements ActionListener{
private SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
private Timer timer;
private javax.swing.JLabel clockLabel = new javax.swing.JLabel();
public ClockPanel() {
super();
clockLabel.setText(sdf.format(new Date(System.currentTimeMillis())));
clockLabel.setFont(new Font("Monospaced", Font.BOLD, 100));
clockLabel.setOpaque(true);
clockLabel.setBackground(Color.black);
clockLabel.setForeground(Color.white);
timer = new Timer(500, this);
timer.setRepeats(true);
timer.start();
clockLabel.setVisible(true);
initComponents();
}
@Override
public void actionPerformed(ActionEvent e){
if(e.getSource().equals(timer))
clockLabel.setText(sdf.format(new Date(System.currentTimeMillis())));
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
时钟对象本身:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Clock extends JLabel implements ActionListener{
private SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
private Timer timer;
public Clock(){
super();
setText(sdf.format(new Date(System.currentTimeMillis())));
setFont(new Font("Monospaced", Font.BOLD, 100));
setOpaque(true);
setBackground(Color.black);
setForeground(Color.white);
timer = new Timer(500, this);
timer.setRepeats(true);
timer.start();
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource().equals(timer))
setText(sdf.format(new Date(System.currentTimeMillis())));
}
}