nooby nooby - 4 months ago 10
Java Question

Java How to thread a GUI

So I have a button that opens a while loop, then my whole GUI freezes until the while loop is over, with that being said how would I thread my GUI to update every second or so?

JButton Test= new JButton();
Test.setText("Test");
Test.setSize(230, 40);
Test.setVisible(true);
Test.setLocation(15, 290);

Test.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e){
int x = 0;
while(x<500){
x++
});

Answer

Use ExecutorService class

Test.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            ExecutorService es = Executors.newCachedThreadPool();
            es.submit(new Runnable() {
                @Override
                public void run() {
                    int x = 0;
                    while (x < 500) {
                        x++;
                    }
                }
            });
        }
 });