0

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();

    }

}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
ManInMoon
  • 6,795
  • 15
  • 70
  • 133

1 Answers1

0

Make the changes as below:

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

Difference between setSize() and setPreferedSize() is here

Community
  • 1
  • 1
Rahul
  • 3,479
  • 3
  • 16
  • 28
  • Great! BUT this is just my SSCCE. In my real App, my code is installed inside a larger App and I don't have a ref to the enclosing frame. Is there anyway to find that from the actionPerformed event? – ManInMoon Mar 11 '14 at 07:51
  • You can use e.getSource() that will return you the Jbutton object and from that you can use getParent(). May this help you. – Rahul Mar 11 '14 at 07:58
  • The object I have access to is a JPanel. But when I inspect it parent == null and there is no getSource() option. – ManInMoon Mar 11 '14 at 09:02