我需要在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
。
答案 0 :(得分:2)
只需在repaint()
方法的末尾添加actionPerformed
,否则您将无法看到更改(除非您最小化然后恢复您的窗口,例如强制重新绘制区域)。
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
height = height + 2;
width = width + 2;
repaint();
}
});