如何在jpanel中切换文本

时间:2019-03-06 05:07:11

标签: java swing jpanel

在我的JPanel中,我有两个JLabel。顶部标签显示时间,底部标签显示日期。

我正在尝试实现一个JToggleButton,它将时间从12小时格式切换为24小时格式,反之亦然。问题是,切换按钮没有更改时间。我应该怎么做才能解决这个问题?非常感谢!

完整代码:

package clock;
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;

public class ClockPanel extends JPanel {

    private Date getTime, getDate;
    private JToggleButton hourTypeButton;
    private JLabel timeLabel, dateLabel;
    private SimpleDateFormat timeFormat, dateFormat;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("Clock");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setResizable(false);
                frame.setSize(640, 360);

                ClockPanel clockPanel = new ClockPanel();
                frame.add(clockPanel);
                frame.setVisible(true);
            }
        });
    }

    public ClockPanel() {
        timeFormat = new SimpleDateFormat("hh:mm a");
        dateFormat = new SimpleDateFormat("EEEE, MMMM dd, yyyy");

        hourTypeButton = new JToggleButton("12-Hour");
        hourTypeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                timeFormat = new SimpleDateFormat((hourTypeButton.isSelected() ? "kk" : "hh") + ":mm a");
                hourTypeButton.setText((hourTypeButton.isSelected() ? "24" : "12") + "-hour");
            }
        });
        add(hourTypeButton);

        getTime = new Date();
        timeLabel = new JLabel(timeFormat.format(getTime));
        timeLabel.setFont(new Font("Segoe UI", Font.PLAIN, 140));
        add(timeLabel);

        getDate = new Date();
        dateLabel = new JLabel(dateFormat.format(getDate));
        dateLabel.setFont(new Font("Segoe UI", Font.PLAIN, 50));
        dateLabel.setForeground(Color.GRAY);
        add(dateLabel);
    }

}

0 个答案:

没有答案