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);
}}
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);
}}
//结果发现Frame大小变了,可是怎么让ContentPane大小也随之改变呢// 加一行
frame.validate();
frame.setSize(int,int); // 设置窗体大小
frame.setLocation(int,int); // 设置窗体位置
使用 validate 方法会使容器再次布置其子组件。已经布置容器后,在修改此容器的子组件的时候(在容器中添加或移除组件,或者更改与布局相关的信息),应该调用上述方法。