Home > Software engineering >  Can't click on a button, while an other button is active
Can't click on a button, while an other button is active

Time:02-23

I made a button, when you click on, it calls a function, which has a big for loop. While the for is active, you can't click any other thing in the window. I want to make a STOP/EXIT button, when you click on, it exits the program (System.exit(0)). But while the for is active, you cant click on them, so basically it is useless.

How can I solve this problem?

CodePudding user response:

Put your function with a big for loop inside a thread and kill the thread it when the button is pressed.

CodePudding user response:

So I read every link, but I don't get it. I made an example code, my program do almost this just bigger. Can somebody edit this code, to see what do I need to do?

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class stackoverflow 
{
    private static JTextField txtNumber;
    public static void loop (int number)
    {
        for(int i = 0;i<number;i  )
        {
            txtNumber.setText(i "");
        }
    }
    
    public static void main(String[] args) 
    {
        JFrame frm = new JFrame();
        frm.setBounds(100,100,409,274);
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frm.getContentPane().setLayout(null);
        
        JButton btnStart = new JButton("START");
        btnStart.setBounds(50, 171, 89, 23);
        frm.getContentPane().add(btnStart);
        
        JButton btnSTOP = new JButton("STOP");
        btnSTOP.setBounds(227, 171, 89, 23);
        frm.getContentPane().add(btnSTOP);
        
        txtNumber = new JTextField();
        txtNumber.setEditable(false);
        txtNumber.setBounds(143, 91, 86, 20);
        frm.getContentPane().add(txtNumber);
        txtNumber.setColumns(10);
        
        btnStart.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent e) 
            {
                loop(100000);
            }
        });
        
        frm.setVisible(true);
        
        
    }
}

  • Related