我有一个AbstractShape类,它向面板绘制一个形状(这个类是抽象的,并且有“Rect”和“Oval”类来扩展它)。 我正在尝试使用javax计时器以使形状闪烁(通过每隔2秒再次填充和绘制它)。 当我运行该功能时,只有当我调整屏幕大小时,形状才会改变其“填充”,我不明白为什么:(
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public abstract class AbstractShape extends JPanel implements Shape{
private int x;
private int y;
private int width;
private int height;
private boolean isFilled;
private Color color;
public AbstractShape(int x, int y, int width, int height, boolean isFilled, Color color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.isFilled = isFilled;
this.color = color;
}
@Override
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
@Override
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
@Override
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
@Override
public boolean isFilled() {
return isFilled;
}
public void setFilled(boolean filled) {
isFilled = filled;
}
@Override
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
@Override
public boolean equals (Object O){
if (O instanceof AbstractShape){
if (this.getWidth() == ((AbstractShape) O).getWidth() && this.getHeight() == ((AbstractShape) O).getHeight()){
return true;
}
}
return false;
}
public void changeFill(){
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (isFilled() == true){
isFilled = false;
repaint();
}else{
isFilled = true;
repaint();
}
}
};
Timer timer = new Timer(2000,listener);
timer.setInitialDelay(0);
while(true){
timer.start();
}
}
@Override
public void paintComponent(Graphics g) {
}
public void draw(JPanel panel){
panel.add(this);
panel.setVisible(true);
}
}
这是“AbstractShape”类,里面的“changeFill”函数需要使形状闪现。
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(this.getColor());
if (this.isFilled()){
g.fillRect(0,0,this.getWidth(),this.getHeight());
}
else{
g.drawRect(0,0,this.getWidth(),this.getHeight());
}
}
这是绘制矩形的“Rect”paintComponent函数。
public static void main (String [] args){
// TODO: MAGIC NUMBERS!!!!
GuiManagement g = new GuiManagement();
JFrame frame = g.createScreen();
JPanel panel = new JPanel();
panel.setBounds(0,0,700,1000);
frame.add(panel);
Rect r = new Rect(20,20,300,300,false,Color.BLUE);
r.draw(panel);
frame.setLayout(new BorderLayout());
frame.setVisible(true);
r.changeFill();
}
这是创建框架,面板,矩形并调用ChangeFill函数的主要功能。 谢谢你的帮助:)