日期:2014-05-20  浏览次数:20675 次

jpanel设置大小问题,谢谢
我在jframe中添加一个jpanel,每次鼠标出了jpanel的时候设置一下jFrame和jPanel 的大小,然后在绘制jPanel, 但为什么外层的jframe和jpanel大小改变了。。但绘制出来的区域(gc.fillRect(。。))的大小不变啊。。快疯了。。求帮助。。 谢谢

代码如下:
public class FrameTest extends JFrame {
private JPanel panel;
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrameTest frame = new FrameTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
 
public FrameTest() {
super();
getContentPane().setLayout(null);
addMouseListener(new MouseAdapter() {
public void mouseClicked(final MouseEvent e) {
}
});
setBounds(100, 100, 500, 375);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(getPanel());
}
private void out(){
int width = this.getWidth()+20;
int height = this.getHeight()+20;
this.setSize(width,height);
this.setPreferredSize(new Dimension(width,height));
this.panel.setSize(width, height);
this.panel.setPreferredSize(new Dimension(width,height));
}
private void draw(Graphics gc){
gc.setColor(Color.RED);
gc.fillRect(0, 0, this.panel.getWidth(), this.panel.getHeight());
}
 
protected JPanel getPanel() {
if (panel == null) {
panel = new JPanel(){
public void paintComponent(Graphics gc) {
draw(gc);
}
};
panel.setBounds(0, 0, 492, 348);
panel.setLayout(null);
panel.addMouseListener(new MouseAdapter() {
public void mouseExited(final MouseEvent e) {
out();
}
});
final JButton button_1 = new JButton();
button_1.setBounds(137, 5, 106, 28);
button_1.setText("New JButton");
panel.add(button_1);
final JButton button = new JButton();
button.setBounds(248, 5, 106, 28);
button.setText("New JButton");
panel.add(button);
}
return panel;
}




------解决方案--------------------
在构造函数中添加下列事件就可以了,具体原因不祥:
this.addComponentListener(new ComponentAdapter() {
public void componentResized(final ComponentEvent e) {
super.componentResized(e);
}
});