Question

Why does the window/frame size NOT change when I press the button?

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class TestSize {


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        final JFrame frame = new JFrame();
        frame.setPreferredSize(new Dimension(300,300));

        JButton help2Button = new JButton("PRESS");
        help2Button.setMaximumSize(new Dimension(40, 30));
        help2Button.setMinimumSize(new Dimension(40, 30));
        help2Button.setPreferredSize(new Dimension(40, 30));
        help2Button.setOpaque(true);
        help2Button.setVisible(true);
        help2Button.setBackground(Color.GREEN);
        help2Button.addActionListener(new ActionListener() {             
            public void actionPerformed(ActionEvent e)
            {
                frame.setPreferredSize(new Dimension(800,800));
            }
        }); 
        frame.add(help2Button);
        frame.setVisible(true);
        frame.pack();

    }

}
Was it helpful?

Solution

Make the changes as below:

public void actionPerformed(ActionEvent e)
{
   frame.setSize(new Dimension(800,800));
}

Difference between setSize() and setPreferedSize() is here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top