import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;public class Test { private JFrame frame;
public static void main(String args[]) {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public Test() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(new Color(255, 0, 0));
frame.setBackground(new Color(0, 0, 0));
frame.getContentPane().setLayout(null);
frame.setBounds(100, 100, 100, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //测试按扭
final JButton testButton = new JButton();
testButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(final MouseEvent e) {

frame.setBounds(100, 100, 200, 200);
//结果发现Frame大小变了,可是怎么让ContentPane大小也随之改变呢
}
});
testButton.setText("Test");
testButton.setBounds(10, 10, 70, 30);
frame.getContentPane().add(testButton);
}}

解决方案 »

  1.   

    frame.setBounds(100, 100, 200, 200);
    //结果发现Frame大小变了,可是怎么让ContentPane大小也随之改变呢// 加一行
    frame.validate();
      

  2.   

    不建议使用setBounds(int,int,int,int);方法
    frame.setSize(int,int); // 设置窗体大小
    frame.setLocation(int,int); // 设置窗体位置
      

  3.   

    请问frame.validate()方法什么意思啊
      

  4.   

    public void validate()验证此容器及其所有子组件。 
    使用 validate 方法会使容器再次布置其子组件。已经布置容器后,在修改此容器的子组件的时候(在容器中添加或移除组件,或者更改与布局相关的信息),应该调用上述方法。