我需要调整 Java 中绘制的椭圆形的大小,我为其创建了以下代码:
FrameView.java
package tutorial;
import java.awt.*;
import javax.swing.*;
public class FrameView{
public static void main(String args[]){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BallCreation c = new BallCreation();
f.add(c);
f.setSize(500, 500);
f.setVisible(true);
}
}
BallCreation.java
package tutorial;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BallCreation extends JPanel{
private static final long serialVersionUID = 1L;
private int height = 10;
private int width = 10;
private JPanel panel;
private JButton button1;
public BallCreation(){
panel = new JPanel();
button1 = new JButton("Click");
add(button1);
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
height = height + 2;
width = width + 2;
}
});
}
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.WHITE);
g.setColor(Color.GREEN);
g.fillOval(10, 10, width, height);
}
}
问题是它不起作用,我不知道如何使椭圆刷新到新的大小。我认为它应该可以工作,但由于某种原因,按钮无法解析 paintComponent
上的新高度和宽度。
最佳答案
只需在 actionPerformed
方法末尾添加一个 repaint()
,否则您将看不到更改(除非您最小化然后恢复窗口,例如,强制重新绘制该区域)。
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
height = height + 2;
width = width + 2;
repaint();
}
});
关于java - 如何在Java中调整绘制的椭圆形的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39747521/