Hey guys. Actually, the question is this: I have a small program in which I will press the 'start' button (b1 in the source) and the timer will start counting (say 10 seconds) after the 10 seconds have passed The window (which is currently attached to the b2 button), has so far done as it is, because I do not know what to do with this timer (in the end, b1 and b2 should be ONE BUTTON). About the shortcomings of the b3 button until I say. Here is the code itself:

import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.nio.file.*; @SuppressWarnings("serial") public class Oclicker extends JFrame{ JOptionPane op = new JOptionPane(); JButton b1, b2, b3, b4, b5; JLabel l1, l2, l3; int c, v; static String r, name; public Oclicker(String s) { super(s); setLayout(new GridLayout(0,1,5,5)); b1 = new JButton("Сюда жамкай"); b2 = new JButton("Счет"); b3 = new JButton("Рекорды"); b4 = new JButton("Правила"); b5 = new JButton("Выход"); add(b1); add(b2); add(b3); add(b4); add(b5); b1.addActionListener(al); b2.addActionListener(al); b3.addActionListener(al); b4.addActionListener(al); b5.addActionListener(al); b1.setBackground(Color.white); b1.setForeground(Color.BLACK); b2.setBackground(Color.blue); b2.setForeground(Color.ORANGE); b3.setBackground(Color.blue); b3.setForeground(Color.orange); b4.setBackground(Color.red); b4.setForeground(Color.black); b5.setBackground(Color.red); b5.setForeground(Color.black); } ActionListener al = new ActionListener(){ public void actionPerformed (ActionEvent a){ if(a.getSource() == b1){ c++; } if(a.getSource() == b2){ r = "" + c; name = JOptionPane.showInputDialog(b2, "Время вышло, твой счет - " + r + "\nВведи свое имя "); writeUsingFiles(name + " - " + r + " очка(ов)\n"); c = 0; } if(a.getSource() == b3){ if(r == null) JOptionPane.showMessageDialog(b3, "Таких не имеется" , "Рекорды",JOptionPane.WARNING_MESSAGE); else JOptionPane.showMessageDialog(b3, "Лучший игрок - "+ name + " - "+ r + " очка(ов)" , "Рекорды", JOptionPane.CLOSED_OPTION); } if(a.getSource() == b4){ JOptionPane.showMessageDialog(b4, "1. Отсчет времени начнется после нажатия первой кнопки" + "\n2. Попади в 10-ку лучших))" +"\nGlhf", "Правила", JOptionPane.CLOSED_OPTION); } if(a.getSource() == b5){ Object[] options = {"Да, не хочу", "Нет, не хочу"}; v = JOptionPane.showOptionDialog(b5, "Уверены, что не хотите выйти?", "Подтверждение выхода", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if(v == 0){System.exit(0);} } } }; public static void writeUsingFiles(String data) { try { Files.write(Paths.get("/Users/Alfa/desktop/files.txt"), data.getBytes()); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { Oclicker frame = new Oclicker("Я - кликер"); frame.setVisible(true); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 300); frame.setLocationRelativeTo(null); Timer timer = new Timer(al, 4000); timer.start(); } } 

The next question is: initially, when I declared the listener, I had written public class Deystvie implements ActionListener, and now, as you can see, ActionListener al = new ActionListener (). So, does this somehow affect the code, if so, how?

And finally: how can you implement a table of records? (What is now available is simply writing the variables to the .txt file, which is updated with each new record) I thought through the array (so that it was sorting from best to worst), but this later rolled up my lip) so that by pressing “Records” buttons in the window showed, say, the first 10.

PS I ask you not to throw stones, for I am learning only. If possible, then point out any errors or something like that unrelated to the issues , I will be very grateful)). Thanks in advance.

    2 answers 2

    1. Please look here: Timer in Java Swing . Very similar to your case.
    2. In your place in the actionPerformed method, I would use switch instead of a large number of if
    3. Look towards SQLite.
    4. Let the names of variables so that it is immediately clear why they exist.
    • What are you specifically talking about in the 4th paragraph? About some of the variables in the code or just a tip for the future? - Vlad
    • And about the timer, I also took examples from the same place, in the end you can see that I created an object and set the start and start. I certainly oooooooochen tried different methods and, most likely, simply did not use them correctly. That is why he turned here - Vlad
    • In the 4th paragraph, I talk about the way to save records. It is possible in the file, and it is possible in a DB. The advantage of SQLite is that the database can be part of your program. Regarding the second comment: You also need to do this by pressing a button. And your timer starts after creating the window. Something is wrong with logic. Transfer to a separate method and call from ActionListener. - user3841429
    • ))))) Now the timer is where it is because I didn’t know where to put it because I tried 10000000000000000000000 methods, but either a compiler error or something. Well, thanks anyway)))) - Vlad
     final ActionListener tenSecondsEnd = new ActionListener() { @Override public void actionPerformed(ActionEvent a){ System.out.println(a.getActionCommand()); } } ActionListener tenSecondsStart = new ActionListener() { int runCounter = 0; @Override public void actionPerformed(ActionEvent a) { // Создаем и запускаем новый поток, который ждет 10 секунд, // А потом передает потоку интерфейса команду вызвать слушатель tenSecondsEnd String command = "Событие создано фоновым потоком. Вызов номер " + String.valueOf(runCounter++); final ActionEvent tssae = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, command); Thread tenSecThread = new Thread() { @Overide public void run() { wait(10000L); // Формирование и передача команды для потока интерфейса // Через объект класса Runnable SwingUtilities.invokeLater( new Runnable() { @Overide public void run() { tenSecondsEnd.actionPerformed(tssae); } }); } }; tenSecThread.start(); } } b1.addListener(tenSecondsStart); b2.addListener(tenSecondsEnd); b2.setActionCommand("Событие создано нажатием кнопки");