why does my java program freezes when i click a button?

Advertisements

so I’m trying to create a java program that you chose a version and clicks a button.

in my java program, I’m trying to use JPanels to make a type of "next page button" for my program. but whenever I run the program, and I click the button, it instantly crashes/freezes.

button code:

package main;

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener;
import javax.swing.*;

@SuppressWarnings({ "rawtypes", "unused" })
public class Mainframe implements ActionListener {
    
    private static JFrame f;
    private static JPanel p1;
    private static JComboBox option;
    private static JButton launch;
    private static JPanel p2;
    
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        
        f=new JFrame("game");
        
        p1=new JPanel();
        f.add(p1);
        
        String s1[]={"Alpha_V1"};
        
        option=new JComboBox(s1);
        option.setBounds(10, 10, 100, 35);
        p1.add(option);
        
        launch=new JButton("Launch");
        launch.setBounds(10, 50, 100, 35);
        launch.addActionListener(new mainframe());
        p1.add(launch);
        
        p1.setLayout(null);
        f.setVisible(true);
        f.setSize(700,400);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        p2=new JPanel();
        p2.setLayout(null);
        
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        
        if (option.getSelectedItem().toString() == "V1") {
            
            // close p1 and open p2
            f.remove(p1);
            f.add(p2);
            
        } else if (option.getSelectedItem().toString() == "") {
            
            // do nothing lol
            
        } else {
            
            // do nothing 
            
        }
        
    }

}

>Solution :

Your application isn’t "crashed" or "freezes", it just haven’t update the drawing. When you add or remove components to your JFrame (or other components), you have to call repaint() to inform the component that the content has been changed drastically and should be redrawn (now, or as soon as possible). Otherwise it would only redraw the GUI on other occasions like changing the size or when displayed initially. In fact, if you press the button and then change the size of the frame you will see that the GUI gets updated (with an empty space).

You can call the repaint() method like this:

 if (option.getSelectedItem().toString() == "V1") {
        
     // close p1 and open p2
     f.remove(p1);
     f.add(p2);
     f.repaint();
 }

Leave a ReplyCancel reply