如何将实时时间添加到JPanel以及如何将时间按下按钮添加到其他JPanel? [英] How can I add live time to a JPanel and when button pressed time to other JPanel?

查看:93
本文介绍了如何将实时时间添加到JPanel以及如何将时间按下按钮添加到其他JPanel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码的目的是使Tıme和毫秒始终运行.当按下按钮时,此时的当前时间将出现在绿色面板上.我做了截图.

The aim of code is that the Tıme and milliseconds wıll run always. When the button pressed the current time at that moment will appear on the greenPanel. I made a screenshot.

我的应用必须看起来像这样:

My app must look like this:

有帮助吗?

我的按钮没有将时间发送到greenPanel.

My button is not sending the time to greenPanel.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.*;

public class TimePanel {

    public static void main(String[] args) {
        
        Font timeFont = new Font("Helvetica", Font.BOLD, 50);
        Font msFont = new Font("Helvetica", Font.PLAIN, 72);
        
        Date dateNow = new Date(); // current date and time
        
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); // current time
        SimpleDateFormat msFormat = new SimpleDateFormat(".S"); // milliseconds
        SimpleDateFormat sendToGreenFormat = new SimpleDateFormat("HH:mm:ss.S");
        
        String timeString = timeFormat.format(dateNow);
        String msString = msFormat.format(dateNow);
        
        JLabel timeLabel = new JLabel(timeString, JLabel.CENTER);
        timeLabel.setFont(timeFont);
        timeLabel.setForeground(new Color(242, 242, 242));
        timeLabel.setBounds(0, 25, 240, 50);
        
        JLabel msLabel = new JLabel(msString, JLabel.CENTER);
        msLabel.setFont(msFont);
        msLabel.setForeground(new Color(242, 242, 242));
        msLabel.setBounds(0, 25, 240, 65);
        
        JButton sendButton = new JButton("Send to Green");
        sendButton.setBounds(585, 260, 150, 25);
        
        JFrame frame = new JFrame("Time Panel");
        frame.setLayout(null);
        
        JPanel greenPanel = new JPanel();
        greenPanel.setLayout(new GridLayout(10,1));
        greenPanel.setBackground(new Color(18, 64, 55, 255));
        greenPanel.setBounds(20, 20, 500, 500);
        
        JPanel timePanel = new JPanel();
        timePanel.setLayout(null);
        timePanel.setBackground(new Color(89, 21, 33, 255));
        timePanel.setBounds(540, 20, 240, 100);
        
        JPanel msPanel = new JPanel(); // milliseconds panel.
        msPanel.setLayout(null);
        msPanel.setBackground(new Color(38, 7, 15, 255));
        msPanel.setBounds(540, 140, 240, 100);
        
        sendButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                
                String timeToGreenString = sendToGreenFormat.format(dateNow);
                
                JLabel timeToGreenLabel = new JLabel(timeToGreenString);
                timeToGreenLabel.setFont(timeFont);
                timeToGreenLabel.setForeground(new Color(242, 242, 242));
                timeToGreenLabel.setBounds(0, 25, 240, 50);
                
                greenPanel.add(timeToGreenLabel);
            }
        });
                
        timePanel.add(timeLabel);
        msPanel.add(msLabel);
        
        frame.add(greenPanel);
        frame.add(timePanel);
        frame.add(msPanel);
        frame.add(sendButton);
        
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }

}

推荐答案

这是我想出的一个GUI.

Here's a GUI I came up with.

当我创建Swing GUI或大多数其他Java应用程序时,我使用

When I create a Swing GUI, or most any other Java application, I use the model / view / controller pattern. In short, this pattern using Swing means:

  1. 视图(Swing组件)将从模型中读取.

  1. The view (Swing components) will read from the model.

视图不会更改模型中的任何内容.

The view will not change anything in the model.

控制器将更新模型并更新视图.

The controller will update the model and update the view.

我使用一个或多个简单的Java getter/setter类创建一个应用程序模型.我通过使用Swing组件和 Swing布局管理器来创建视图.最后,我使用 Swing监听器创建一个或多个控制器.控制器是您似乎最难以理解的地方.

I create an application model using one or more plain Java getter / setter classes. I create a view by using Swing components and Swing layout managers. Finally, I create one or more controllers by using Swing listeners. Controllers are where you seem to have the most difficulty understanding.

这是我要您从我将要发布的代码中删除的最重要的要点.

Here are the most important points I want you to take away from the code I will post.

  1. 始终通过调用 SwingUtilities invokeLater 方法来启动Swing应用程序.此方法确保将在事件调度上创建并执行您的Swing组件.线程.

  1. Always start a Swing application with a call to the SwingUtilities invokeLater method. This method ensures that your Swing components will be created and executed on the Event Dispatch Thread.

摆脱静态代码,然后将代码分组为Java方法.您可以在我的代码中看到,唯一的静态方法是启动应用程序的 main 方法.我的主要方法只有一行代码.该应用程序的其余部分使用方法和类.

Get out of static code and group your code into Java methods. You can see in my code that the only static method is the main method which starts the application. My main method has one line of code. The rest of the application uses methods and classes.

请勿使用绝对定位( setBounds ).使用 Swing布局管理器.您可以在我的整个代码中看到Swing布局管理器的示例.

Do not use absolute positioning (setBounds). Use Swing layout managers. You can see examples of Swing layout managers throughout my code.

为一个JFrame创建多个JPanel.用单独的方法创建每个主JPanel.这使您可以在应用程序中组合Swing布局管理器.

Create multiple JPanels for one JFrame. Create each main JPanel in a separate method. This allows you to combine Swing layout managers in an application.

在这个特定的应用程序中,控制器是如此简单,以至于我使它们成为匿名类.我创建了两个匿名类,一个用于更新左侧的时间面板,另一个用于运行控制面板中的两个时钟.控制器应该始终是模型和视图的单独类.

In this particular application, the controllers were so simple that I made them anonymous classes. I created two anonymous classes, one to update the time panel on the left, and one to run the two clocks in the control panel. Controllers should always be separate classes from your model and your view.

下次您发布问题时,我不想在main方法中看到所有代码.我不想看到绝对定位.我希望您花时间学习此答案中概述的概念,否则您将永远无法创建复杂的Swing应用程序.最后,您应该阅读Oracle的完整 Swing教程.您可以跳过"Netbeans"部分.

The next time you post a question, I don't want to see all your code in the main method. I don't want to see absolute positioning. I want you to take the time to learn the concepts I've outlined in this answer, or you will never be able to create complex Swing applications. Finally, you should go through Oracle's complete Swing tutorial. You can skip the Netbeans section.

这是代码.我没有打扰在左侧时间面板中居中显示时间.

Here's the code. I didn't bother centering the times in the time panel on the left.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class TimePanel implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new TimePanel());
    }
    
    private JLabel timeLabel;
    private JLabel msLabel;
    
    private JTextArea textArea;
    
    private TimeModel model;
    
    public TimePanel() {
        this.model = new TimeModel();
    }
    
    @Override
    public void run() {
        JFrame frame = new JFrame("Time Panel");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        frame.add(createTextPanel(), BorderLayout.CENTER);
        frame.add(createControlPanel(), BorderLayout.AFTER_LINE_ENDS);
        
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        
        Timer timer = new Timer(50, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                updateControlPanel();
            }
        });
        timer.start();
    }   
    
    private JPanel createTextPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        JPanel innerPanel = new JPanel(new BorderLayout());
        innerPanel.setBackground(model.getBackgroundTextColor());
        innerPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        textArea = new JTextArea(8, 10);
        textArea.setBackground(model.getBackgroundTextColor());
        textArea.setForeground(model.getForegroundColor());
        textArea.setFont(model.getTimeFont());
        innerPanel.add(textArea, BorderLayout.CENTER);
        
        JScrollPane scrollPane = new JScrollPane(innerPanel);
        panel.add(scrollPane);
        return panel;
    }   

    private JPanel createControlPanel() {
        JPanel panel = new JPanel(new FlowLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        JPanel innerPanel = new JPanel(new GridBagLayout());
        
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(0, 5, 10, 5);
        gbc.gridx = 0;
        gbc.gridy = 0;
        
        JPanel timePanel = new JPanel(new BorderLayout());
        timePanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
        timePanel.setBackground(model.getBackgroundControlColor());
        
        timeLabel = new JLabel(model.getTime());
        timeLabel.setBackground(model.getBackgroundControlColor());
        timeLabel.setFont(model.getTimeFont());
        timeLabel.setForeground(model.getForegroundColor());
        timePanel.add(timeLabel, BorderLayout.CENTER);

        JPanel msPanel = new JPanel();
        msPanel.setBackground(model.getBackgroundControlColor());
        
        msLabel = new JLabel(model.getMSTime());
        msLabel.setBackground(model.getBackgroundControlColor());
        msLabel.setFont(model.getMSFont());
        msLabel.setForeground(model.getForegroundColor());
        msPanel.add(msLabel);
        
        Dimension t = timePanel.getPreferredSize();
        Dimension m = msPanel.getPreferredSize();
        int width = Math.max(t.width, m.width);
        int height = Math.max(t.height, m.height);
        Dimension a = new Dimension(width, height);
        
        timePanel.setPreferredSize(a);
        msPanel.setPreferredSize(a);
        
        innerPanel.add(timePanel, gbc);
        
        gbc.gridy++;
        innerPanel.add(msPanel, gbc);

        gbc.gridy++;
        JButton sendButton = new JButton("Send to Green");
        sendButton.setFont(model.getButtonFont());
        innerPanel.add(sendButton, gbc);
        
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                textArea.append(model.getDisplayTime());
                textArea.append(System.lineSeparator());
            }
        });
        
        panel.add(innerPanel);
                    
        return panel;
    }
    
    public void updateControlPanel() {
        timeLabel.setText(model.getTime());
        msLabel.setText(model.getMSTime());
    }
    
    public class TimeModel {
        
        private final Color foregroundColor;
        private final Color backgroundTextColor;
        private final Color backgroundControlColor;
        
        private final DateTimeFormatter timeFormat;
        private final DateTimeFormatter msFormat;
        private final DateTimeFormatter displayFormat;
        
        private final Font timeFont;
        private final Font msFont;
        private final Font buttonFont;
        
        public TimeModel() {
            this.foregroundColor = new Color(242, 242, 242);
            this.backgroundTextColor = new Color(18, 64, 55);
            this.backgroundControlColor = new Color(89, 21, 33);
            
            this.timeFormat = DateTimeFormatter.ofPattern("HH:mm:ss");
            this.msFormat = DateTimeFormatter.ofPattern(".SSS");
            this.displayFormat = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
            
            String fontName = "Helvetica";
            this.msFont = new Font(fontName, Font.PLAIN, 72);
            this.timeFont = new Font(fontName, Font.BOLD, 48);
            this.buttonFont = new Font(fontName, Font.PLAIN, 16);   
        }
        
        public String getTime() {
            return timeFormat.format(getCurrentTime());
        }
        
        public String getMSTime() {
            return msFormat.format(getCurrentTime());
        }
        
        public String getDisplayTime() {
            return displayFormat.format(getCurrentTime());
        }
        
        public Color getForegroundColor() {
            return foregroundColor;
        }

        public Color getBackgroundTextColor() {
            return backgroundTextColor;
        }

        public Color getBackgroundControlColor() {
            return backgroundControlColor;
        }

        public Font getTimeFont() {
            return timeFont;
        }

        public Font getMSFont() {
            return msFont;
        }

        public Font getButtonFont() {
            return buttonFont;
        }

        private LocalDateTime getCurrentTime() {
            return LocalDateTime.now();
        }
        
    }

}
 

这篇关于如何将实时时间添加到JPanel以及如何将时间按下按钮添加到其他JPanel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆