gpt4 book ai didi

java - 为什么jPanel不清除?

转载 作者:行者123 更新时间:2023-12-01 22:58:24 25 4
gpt4 key购买 nike

该程序在jPanel上绘制输入尺寸的椭圆形。当我改变绘制的圆圈的大小时,旧的圆圈不会消失。为什么?

代码:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {  

jPanel.Repaint();
try{
jLabel6.setText("");
int a=Integer.parseInt(jTextField1.getText());

Graphics2D gfx=(Graphics2D)jPanel1.getGraphics();
gfx.setColor(Color.red);
gfx.fillOval(100,50,a,a);
gfx.fillOval(400,50,a,a);

}catch(NumberFormatException e){
jLabel6.setText("Incorrect data");
}
}

最佳答案

使用覆盖的JPanel#paintComponent()方法而不是使用 JPanel#getGraphics() 方法。

不要忘记在重写的 paintComponent() 方法中调用 super.paintComponent(g);

JPanel jPanel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.fillOval(100, 50, c, c);
g.fillOval(400, 50, c, c);
}
};
<小时/>

--编辑--

代码中的更改:

// This is the code where you have create JPanel object
JPanel jPanel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);

try{
int c=Integer.parseInt(jTextField1.getText());//read the value

g.setColor(Color.red);
g.fillOval(100, 50, c, c);
g.fillOval(400, 50, c, c);

}catch(NumberFormatException e){//handle the exception}
}
};


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

try{
jLabel6.setText("");
jPanel.repaint(); // simply call repaint method
}catch(NumberFormatException e){
jLabel6.setText("Incorrect data");
}
}

关于java - 为什么jPanel不清除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23714245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com