简体   繁体   English

用Java制作数字时钟

[英]Making a digital clock in Java

I'm making a digital clock for a project and I have four classes: DigitalTimeUI , which is the JFrame class, TitlePanel , DigitPanel , and ColonPanel , which are JPanels for the item stated.我正在为一个项目制作一个数字时钟,我有四个类: DigitalTimeUI ,它是 JFrame 类, TitlePanelDigitPanelColonPanel ,它们是所述项目的 JPanel 。 When it is finished, it should look like this:完成后,它应该是这样的:

在此处输入图片说明

The part I am stuck on is adding the DigitPanel s to the frame in the UI class.我坚持的部分是将DigitPanel s 添加到 UI 类中的框架中。 Here's what I have in the main class right now:这是我现在在主课上的内容:

public class DigitalTimeUI extends JFrame {

public static GregorianCalendar currentDate;
final static int CLOCKWIDTH = 605;
final static int CLOCKHEIGHT = 200;

public static void main(String[] args) {
    int numOfDigits = 6;
    int startingX = 0;
    int startingY = 0;

    Font clockFont = new Font("Tahoma", Font.BOLD, 72);
    JFrame clock = new JFrame();

    clock.setSize(CLOCKWIDTH, CLOCKHEIGHT);
    clock.setVisible(true);
    clock.setResizable(false);
    clock.setDefaultCloseOperation(EXIT_ON_CLOSE);

    TitlePanel titlePanel = new TitlePanel();
    JLabel title = new JLabel("DIGITAL CLOCK");
    title.setFont(clockFont);
    title.setForeground(Color.BLACK);
    titlePanel.add(title);
    clock.add(titlePanel);

    DigitPanel digitPanel = new DigitPanel();
    JLabel digit;
    startingY = 115;
    while (numOfDigits > 0) {
        if ((numOfDigits % 2) == 0) {
            startingX += 5;
            digit = new JLabel(String.valueOf(0));

        }

    }
  }
}

The code is kind of a mess right now, I've still got some cleaning up to do after I get that last part figured out.代码现在有点乱,在弄清楚最后一部分之后我还有一些清理工作要做。 That bottom part is just some scrap from my attempts to display the 6 digit fields.底部部分只是我尝试显示 6 位字段时的一些碎片。 I think the main problem I'm having is finding a way to split up the time returned from GregorianCalendar and put them into 6 different boxes, then an efficient way to put them into the frame using a while loop or whatnot.我认为我遇到的主要问题是找到一种方法来分割从GregorianCalendar返回的时间并将它们放入 6 个不同的框中,然后使用 while 循环或诸如此类的有效方法将它们放入框架中。

To clarify: The above picture was given to me by the instructor as a guideline to go by when formatting my clock.澄清一下上图是老师给我的,作为格式化我的时钟时的指导方针。 It also has 9 panels in it.它还有9个面板。 The "DIGITAL TIME" is a panel of the TitlePanel class. “数字时间”是TitlePanel类的一个面板。 The digit boxes are of the DigitPanel class and there are 6 of them.数字框属于DigitPanel类,共有 6 个。 The colon boxes are of the ColonPanel class and there are two of them.冒号框属于ColonPanel类,其中有两个。 The issue I am having is with splitting up the time into 6 different boxes.我遇到的问题是将时间分成 6 个不同的框。 Like, where the picture shows "48", I need a way to take the value from GregorianCalendar.MINUTE or whatever and split it into a 4 and an 8 to put into each of those boxes.比如,在图片显示“48”的地方,我需要一种方法来从GregorianCalendar.MINUTE或其他任何东西中获取值,并将其分成 4 和 8 以放入每个盒子中。 Thanks.谢谢。

If I understand the question correctly...如果我正确理解问题...

You're working in a OO environment.您在面向对象的环境中工作。 You should break your design down to the smallest manageable units of work as you can.您应该尽可能将设计分解为最小的可管理工作单元。

For me, this means that each digit (or time unit) is the smallest unit of work.对我来说,这意味着每个数字(或时间单位)都是最小的工作单位。 This would require a component that was simply capable of displaying a 0 padded int value.这将需要一个能够显示 0 填充 int 值的组件。

From there, you could build it up a clock pane, using 3 digit panes as so on.从那里,您可以构建一个时钟窗格,使用 3 位数字窗格等。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class DigitalClock {

    public static void main(String[] args) {
        new DigitalClock();
    }

    public DigitalClock() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class TestPane extends JPanel {

        private DigitPane hour;
        private DigitPane min;
        private DigitPane second;
        private JLabel[] seperator;

        private int tick = 0;

        public TestPane() {
            setLayout(new GridBagLayout());

            hour = new DigitPane();
            min = new DigitPane();
            second = new DigitPane();
            seperator = new JLabel[]{new JLabel(":"), new JLabel(":")};

            add(hour);
            add(seperator[0]);
            add(min);
            add(seperator[1]);
            add(second);

            Timer timer = new Timer(500, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Calendar cal = Calendar.getInstance();
                    hour.setValue(cal.get(Calendar.HOUR_OF_DAY));
                    min.setValue(cal.get(Calendar.MINUTE));
                    second.setValue(cal.get(Calendar.SECOND));

                    if (tick % 2 == 1) {
                        seperator[0].setText(" ");
                        seperator[1].setText(" ");
                    } else {
                        seperator[0].setText(":");
                        seperator[1].setText(":");
                    }
                    tick++;
                }
            });
            timer.setRepeats(true);
            timer.setCoalesce(true);
            timer.start();
        }

    }

    public class DigitPane extends JPanel {

        private int value;

        @Override
        public Dimension getPreferredSize() {
            FontMetrics fm = getFontMetrics(getFont());
            return new Dimension(fm.stringWidth("00"), fm.getHeight());
        }

        public void setValue(int aValue) {
            if (value != aValue) {
                int old = value;
                value = aValue;
                firePropertyChange("value", old, value);
                repaint();
            }
        }

        public int getValue() {
            return value;
        }

        protected String pad(int value) {
            StringBuilder sb = new StringBuilder(String.valueOf(value));
            while (sb.length() < 2) {
                sb.insert(0, "0");
            }
            return sb.toString();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g); 
            String text = pad(getValue());
            FontMetrics fm = getFontMetrics(g.getFont());
            int x = (getWidth() - fm.stringWidth(text)) / 2;
            int y = ((getHeight()- fm.getHeight()) / 2) + fm.getAscent();
            g.drawString(text, x, y);
        }        
    }    
}

Updated更新

Basically you can do something like...基本上你可以做一些像......

String min = String.valueOf(Calendar.getInstance().get(Calendar.MINUTE));
char[] digits = min.toCharArray();

As shown here , use SimpleDateFormat to format your time.如图所示这里,使用SimpleDateFormat格式化你的时间。 This will give you a formatted string that you can index to get the text for your components.这将为您提供一个格式化的字符串,您可以对其进行索引以获取组件的文本。

This related example uses the following formatter:此相关示例使用以下格式化程序:

private static final SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
private final Date now = new Date();
...
String s = df.format(now);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM