Mail.ruПочтаМой МирОдноклассникиВКонтактеИгрыЗнакомстваНовостиКалендарьОблакоЗаметкиВсе проекты

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

pasha hockey Знаток (358), открыт 2 недели назад
у меня есть окно созданное с помощью JPanel, менеджер компановки BoxLayout
хочу добавить циферблат, который бы отображал текущее время в формате ЧЧ:ММ (ч - часы, м - минуты)
а ещё, если получится, разместить его снизу по центру
1 ответ
Рустам Абдрашитов Мудрец (12114) 1 неделю назад
На
 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);
});
}
}
Похожие вопросы