Top.Mail.Ru
Ответы

Как сделать циферблат на Java+JPanel

у меня есть окно созданное с помощью JPanel, менеджер компановки BoxLayout
хочу добавить циферблат, который бы отображал текущее время в формате ЧЧ:ММ (ч - часы, м - минуты)
а ещё, если получится, разместить его снизу по центру

По дате
По рейтингу
Аватар пользователя
Мастер

На

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
 import javax.swing.*; 
import java.awt.*; 
import java.time.LocalTime; 
import java.time.format.DateTimeFormatter; 
 
class ClockPanel extends JPanel { 
    private JLabel timeLabel; 
     
    public ClockPanel() { 
        setLayout(new BorderLayout()); 
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); 
        setBackground(new Color(240, 240, 240)); 
         
        timeLabel = new JLabel(); 
        timeLabel.setFont(new Font("Arial", Font.BOLD, 32)); 
        timeLabel.setForeground(new Color(50, 50, 50)); 
        timeLabel.setHorizontalAlignment(SwingConstants.CENTER); 
        timeLabel.setBorder(BorderFactory.createCompoundBorder( 
            BorderFactory.createLineBorder(new Color(200, 200, 200), 2, true), 
            BorderFactory.createEmptyBorder(15, 25, 15, 25) 
        )); 
         
        add(timeLabel, BorderLayout.SOUTH); 
         
        Timer timer = new Timer(1000, e -> updateTime()); 
        timer.start(); 
        updateTime(); 
    } 
     
    private void updateTime() { 
        LocalTime currentTime = LocalTime.now(); 
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm"); 
        timeLabel.setText(currentTime.format(formatter)); 
    } 
} 
 
public class MainWindow extends JFrame { 
    public MainWindow() { 
        setTitle("Digital Clock"); 
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        setSize(400, 300); 
         
        JPanel mainPanel = new JPanel(); 
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); 
        mainPanel.setBackground(new Color(240, 240, 240)); 
         
        mainPanel.add(Box.createVerticalGlue()); 
        ClockPanel clockPanel = new ClockPanel(); 
        mainPanel.add(clockPanel); 
        mainPanel.add(Box.createVerticalStrut(20)); 
         
        add(mainPanel); 
        setLocationRelativeTo(null); 
    } 
     
    public static void main(String[] args) { 
        SwingUtilities.invokeLater(() -> { 
            MainWindow window = new MainWindow(); 
            window.setVisible(true); 
        }); 
    } 
} 
 


Видео по теме