jpanel设置大小问题,谢谢

scljfh scljfh 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我在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;
}
}

...全文
评论 15
收藏 已收藏
分享
返回顶部
scljfh
Java SE 62,620 成员 307,251 内容