Is there a way to repaint a JPanel constantly on loop without Java stopping?

twitter logo github logo ・1 min read

I am making a program that displays the time in a JPanel and it makes Java "stop" when I do:

while(true) {
    timeWindow.removeAll();
    timeWindow.revalidate();
    timeWindow.repaint();
}

and when Java "stops" it will stop updating the main JFrame and when I expand it, it becomes glitchy, but when I remove the while loop above and do:

//This is a different method, mind you....
while(true) {
    now = LocalDateTime.now();
    framesCounted++;
    machineWindow.invalidate();
    machineWindow.validate();
    machineWindow.repaint();
}

the program works perfectly fine! So 2 questions, 1) How can I keep my JPanel on a loop? 2) Why does my program work just fine in the second case, but not in the first?

twitter logo DISCUSS (8)
markdown guide
 

It is not clear to me the difference between the first and the second code. However the java painting is done in one MAIN AWT thread and for not block it you should use SwingUtilities.invokeLater. Take a look on it.

 

Any specific source (if so can you send a link?), Thanks.

 

You can try to wrap you loop and painting logic into an Runnable and fire it using the invokeLater.

Check this out docs.oracle.com/javase/tutorial/ui...

:/ What do I try now, I have tried invokeLater(...), still the program crashes...
maybe there is no way around this...
Have any other ideas?

Can you provide a minimal working example that show the problem?

Come again? Like what exactly are you looking for? The method, The class, The file> please specify. Thanks!

Original code:

import java.io.BufferedReader;
import javax.swing.event.*;

import java.time.format.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
import java.util.*;
import java.time.*;
import java.awt.*;
import java.net.*;
import java.io.*;

/*

MADE BY:

CCCCCCCCCC AAAAAAA L        IIIII N    N
C        C A     A L          I   NN   N
C          A     A L          I   N N  N
C          AAAAAAA L          I   N  N N
C        C A     A L          I   N   NN
CCCCCCCCCC A     A LLLLLLLL IIIII N    N

*/
public class JavaMacroComputer {
    public static void main(String[] args) {
        VirtualMachine.load();
    }
}
class VirtualMachine extends MouseAdapter {
    public static VirtualMachine vmCommand = new VirtualMachine();
    public static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
    public static File configSettings = new File("system/files/config/settings.txt");
    public static File configOrder = new File("system/files/config/refrence.txt");
    public static Color systemColor = Color.CYAN;
    public static String systemUser;
    public static String systemLocation;
    public static String systemPassword = null;
    public static LocalDateTime now = LocalDateTime.now();
    public static int framesCounted = 0;
    public static JLabel settingsApp;
    public static JLabel foldersApp;
    public static JLabel webApp;
    public static JLabel timeApp;
    public static JFrame machineWindow;

    public static void load() {
        Dimension size = new Dimension(800,600);
        machineWindow = new JFrame("JavaMacroComputer (JMC) v0.1.0 - Made by Calin Z. Baenen.");
        machineWindow.setLayout(new FlowLayout());
        ImageIcon settingsImg = new ImageIcon("system/assets/icons/settings.png");
        ImageIcon foldersImg = new ImageIcon("system/assets/icons/folders.png");
        ImageIcon webImg = new ImageIcon("system/assets/icons/webbrowser.png");
        ImageIcon timeImg = new ImageIcon("system/assets/icons/time.png");
        ImageIcon appEmblem = new ImageIcon("system/assets/icons/ico.png");
        timeApp = new JLabel(timeImg);
        timeApp.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent me) {
                vmCommand.openTime();
            }
        });
        settingsApp = new JLabel(settingsImg);
        settingsApp.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent me) {
                vmCommand.openSettings();
            }
        });
        foldersApp = new JLabel(foldersImg);
        foldersApp.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent me) {
                vmCommand.openFolders();
            }
        });
        webApp = new JLabel(webImg);
        webApp.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent me) {
                vmCommand.openInternet();
            }
        });
        machineWindow.setPreferredSize(size);
        machineWindow.setMinimumSize(size);
        machineWindow.setMaximumSize(size);
        machineWindow.setLocationRelativeTo(null);
        machineWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        machineWindow.getContentPane().setBackground(systemColor);
        machineWindow.getContentPane().add(settingsApp);
        machineWindow.getContentPane().add(foldersApp);
        machineWindow.getContentPane().add(webApp);
        machineWindow.getContentPane().add(timeApp);
        // machineWindow.getContentPane().add();
        // machineWindow.getContentPane().add();
        // machineWindow.getContentPane().add();
        // machineWindow.getContentPane().add();
        // machineWindow.getContentPane().add();
        // machineWindow.getContentPane().add();
        // machineWindow.getContentPane().add();
        machineWindow.setIconImage(appEmblem.getImage());
        machineWindow.pack();
        machineWindow.setVisible(true);
        while(true) {
            now = LocalDateTime.now();
            framesCounted++;
            machineWindow.invalidate();
            machineWindow.validate();
            machineWindow.repaint();
        }
    }
    public static void openTime() {
        Dimension size = new Dimension(540,450);
        JPanel timeWindow = new JPanel();
        JLabel timeTicks = new JLabel("<html><br/><font size='+2' color='white'>Time spent on computer (in ticks): </font><br/></html>");
        JLabel timeCurrent = new JLabel("<html><br/><font size='+4' color='white'>Current time: </font><br/></html>");
        JButton exitButton = new JButton("X");
        exitButton.setBackground(Color.RED);
        exitButton.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                machineWindow.remove(timeWindow);
            }
        });
        exitButton.setLocation(0,0);
        machineWindow.remove(timeWindow);
        timeWindow.setLayout(new FlowLayout());
        timeWindow.setPreferredSize(size);
        timeWindow.setMinimumSize(size);
        timeWindow.setMaximumSize(size);
        timeWindow.setLocation(10, 100);
        timeWindow.setBackground(Color.BLUE);
        timeWindow.add(exitButton);
        timeWindow.add(timeTicks, SwingConstants.CENTER);
        timeWindow.add(timeCurrent, SwingConstants.CENTER);
        timeWindow.setVisible(true);
        machineWindow.add(timeWindow);
        timeTicks.setText("<html><br/><font size='+2' color='white'>Time spent on computer (in ticks): "+framesCounted+"</font><br/></html>");
        timeCurrent.setText("<html><br/><font size='+2' color='white'>Current time: "+dtf.format(now)+"</font><br/></html>");
        /*while(true) {
            timeWindow.removeAll();
            timeWindow.revalidate();
            timeWindow.repaint();
        }
        commented out bc it crashes Java
        */
    }
    public static void openSettings() {
        Dimension size = new Dimension(540,450);
        JPanel settingsWindow = new JPanel();
        JLabel personalizationOption = new JLabel("<html><br/><font size='+1' color='white'>PERSONALIZATION</font><br/></html>");
        JLabel miscOption = new JLabel("<html><br/><font size='+1' color='white'>???</font><br/></html>");
        JLabel helpOption = new JLabel("<html><br/><font size='+1' color='white'>HELP</font><br/></html>");
        JButton exitButton = new JButton("X");
        exitButton.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                machineWindow.remove(settingsWindow);
            }
        });
        exitButton.setBackground(Color.RED);
        settingsWindow.setLayout(new FlowLayout());
        settingsWindow.setPreferredSize(size);
        settingsWindow.setMinimumSize(size);
        settingsWindow.setMaximumSize(size);
        settingsWindow.setLocation(10, 100);
        settingsWindow.setBackground(Color.BLACK);
        settingsWindow.add(exitButton);
        settingsWindow.add(personalizationOption, SwingConstants.CENTER);
        settingsWindow.add(helpOption, SwingConstants.CENTER);
        settingsWindow.add(miscOption, SwingConstants.CENTER);
        machineWindow.add(settingsWindow);
        settingsWindow.setVisible(true);
    }
    public static void openFolders() {
        final File sysFolder = new File("system/files");
        Dimension size = new Dimension(550,350);
        JFrame foldersWindow = new JFrame("JavaMacroComputer (JMC) v0.1.0 - Made by Calin Z. Baenen.");
        JLabel systemFiles;
        try {
            systemFiles = FileTree.listFilesForFolder(sysFolder);
        } catch(Exception e) {
            systemFiles = new JLabel("Sorry, something went wrong! :(");
        }
        ImageIcon appEmblem = new ImageIcon("system/assets/icons/folders.png");
        foldersWindow.setLayout(new FlowLayout());
        foldersWindow.setPreferredSize(size);
        foldersWindow.setMinimumSize(size);
        foldersWindow.setMaximumSize(size);
        foldersWindow.setResizable(true);
        foldersWindow.setLocationRelativeTo(null);
        foldersWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        foldersWindow.setIconImage(appEmblem.getImage());
        foldersWindow.getContentPane().add(systemFiles, SwingConstants.CENTER);
        foldersWindow.getContentPane().setBackground(Color.BLACK);
        foldersWindow.pack();
        foldersWindow.setVisible(true);
    }
    public static void openInternet() {
        final AcceptString wbSI = new AcceptString("http://");
        Dimension size = new Dimension(600,400);
        JFrame webWindow = new JFrame("JavaMacroComputer (JMC) v0.1.0 - Made by Calin Z. Baenen.");
        ImageIcon appEmblem = new ImageIcon("system/assets/icons/webbrowser.png");
        JTextField textField = new JTextField();
        textField.setPreferredSize(new Dimension(150,25));
        Crawler webFinder = new Crawler();
        JLabel searchBar = new JLabel("");
        JLabel internetIcon = new JLabel("<html>");
        JButton searchButton = new JButton("Search");
        searchButton.addActionListener(e -> {
            textField.setText(textField.getText().replace("http://",""));
            wbSI.update("http://"+textField.getText());
            searchBar.setText(wbSI.string);
            openUrl(wbSI.string);
        });
        webWindow.setLayout(new FlowLayout());
        webWindow.setPreferredSize(size);
        webWindow.setMinimumSize(size);
        webWindow.setMaximumSize(size);
        webWindow.setResizable(true);
        webWindow.setLocationRelativeTo(null);
        webWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        webWindow.setIconImage(appEmblem.getImage());
        webWindow.getContentPane().setBackground(Color.WHITE);
        webWindow.getContentPane().add(textField);
        webWindow.getContentPane().add(searchButton);
        webWindow.getContentPane().add(internetIcon);
        webWindow.pack();
        webWindow.setVisible(true);
    }
    public static void openUrl(String givenUrl) {
        Dimension size = new Dimension(600,400);
        JFrame webWindow = new JFrame("JavaMacroComputer (JMC) v0.1.0 - Made by Calin Z. Baenen.");
        ImageIcon appEmblem = new ImageIcon("system/assets/icons/webbrowser.png");
        JLabel loadWebpage = new JLabel(Crawler.getHTML(givenUrl));
        webWindow.setLayout(new FlowLayout());
        webWindow.setPreferredSize(size);
        webWindow.setMinimumSize(size);
        webWindow.setMaximumSize(size);
        webWindow.setResizable(true);
        webWindow.setLocationRelativeTo(null);
        webWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        webWindow.setIconImage(appEmblem.getImage());
        webWindow.getContentPane().setBackground(Color.WHITE);
        webWindow.getContentPane().add(loadWebpage);
        webWindow.pack();
        webWindow.setVisible(true);
    }
}
class FileTree {
    public static int whitespaceLayers = 0;
    public static int removespaceAt = 0;
    public static int willRemove = 0;
    public static HashSet<File> filesInList = new HashSet<File>();
    public static JLabel fileList = new JLabel("<html><font color='white'>");
    public static JLabel listFilesForFolder(final File folder) {
        String currentFile = folder.getPath();
        try {
            for (final File fileEntry : folder.listFiles()) {
                removespaceAt = folder.listFiles().length;
                willRemove++;
                String whitespaceString = "";
                for(int i = 0; i < whitespaceLayers;) {
                    whitespaceString += "&#9";
                    i++;
                }
                if(!(filesInList.contains(fileEntry))) {
                    if (fileEntry.isDirectory()) {
                        if(!(filesInList.contains(fileEntry))) {
                            fileList.setText(fileList.getText()+whitespaceString+fileEntry+"<br/>");
                            whitespaceLayers++;
                            filesInList.add(fileEntry);
                            listFilesForFolder(fileEntry);
                        } else {
                            listFilesForFolder(new File("system/files"));
                            break;
                        }
                        if(willRemove >= removespaceAt) {
                            whitespaceLayers--;
                        }
                    } else {
                        if(!(filesInList.contains(fileEntry))) {
                            fileList.setText(fileList.getText()+fileEntry+whitespaceString+fileEntry+"<br/>");
                            filesInList.add(fileEntry);
                        } else {
                            listFilesForFolder(new File(currentFile));
                            break;
                        }
                        if(willRemove >= removespaceAt) {
                            whitespaceLayers--;
                        }
                    }
                }
            }
        } catch(Exception e) {
            //
        }
        fileList.setText(fileList.getText()+"</font></html>");
        return fileList;
    }
}
class AcceptString {
    public static String string = null;
    public AcceptString(String s) {
        string = s;
    }
    public static void update(String s) {
        string = s;
    }
}
class AcceptInt {
    public static Integer integer = 0;
    public AcceptInt(Integer s) {
        integer = s;
    }
    public static void update(Integer s) {
        integer = s;
    }
}
class Crawler {
    private static String htmlString = "";
    public static String getHTML(String websiteUrl) {
        String mainHtml = "<html>";
        try {
            URL google = new URL(websiteUrl);
            BufferedReader in = new BufferedReader(new InputStreamReader(google.openStream()));
            String inputLine; 
            while ((inputLine = in.readLine()) != null) {
                // Process each line.
                htmlString += inputLine;
            }
            mainHtml += htmlString;
            in.close(); 
        } catch (Exception me) {
            mainHtml += "<font color='black'>Sorry, but an error occured trying to load the requested webpage ("+websiteUrl+")<br/>Error:<br/>&#9"+me+"</font>";
        }
        mainHtml += "</html>";
        htmlString = "";
        return mainHtml;
    }
}
Classic DEV Post from Dec 27 '18

Ever been stumped by <E>, <T>, <K, V> in OO language documentation?

Over on the Reddit /r/dartlang group, an individual by the name of NFC_TagsForD...

PDS OWNER CALIN (Calin Baenen) profile image
I am a very interested in making games in Java and making programming languages in Python

dev.to now has dark theme. 🌝

Go to the "misc" section of your settings and select night theme

(You can also change font to sans serif, which a lot of folks prefer.) πŸ’–