第一次后无法更改窗口大小

时间:2014-03-11 07:41:53

标签: java swing jframe size preferredsize

为什么按下按钮时窗口/框架尺寸不会改变?

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

    }

}

1 个答案:

答案 0 :(得分:0)

进行如下更改:

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

setSize()和setPreferedSize()之间的区别是here