【发布时间】:2020-11-20 07:17:53
【问题描述】:
我正在尝试根据由 for 循环确定的坐标在按钮内为矩形设置动画。这是我的JComponent 班级:
public class Rect extends JComponent {
public int x;
public int y;
public int w;
public int h;
public Rect (int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
repaint();
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g);
g2.setColor(Color.green);
g2.drawRect(x+15, y+15, w, h);
}
}
这是我的按钮和button 在JFrame 类中:
public class MainFrame extends JFrame {
Rect R = new Rect(15, 15, 50, 50);
JPanel lm = new JPanel();
LayoutManager lay = new OverlayLayout(lm);
JButton animate = new JButton("animate");
public MainFrame () {
setSize(1200, 700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
lm.setLayout(lay);
lm.add(R);
}
animate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int k = 0; k < 500; k+=50) {
R = new Rect(k, k, 50, 50);
validate();
repaint();
}
}
});
}
但是当我运行代码并单击按钮时,什么也没有发生。怎么了?
编辑:我像这样在我的主类中运行框架:
public class OrImage {
public static void main(String[] args) throws Exception
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MainFrame mf = new MainFrame();
mf.setVisible(true);
}
});
}
}
【问题讨论】:
-
类
MainFrame无法编译。sg是什么? -
@Abra 我已经更新了代码。我在其他类中使用 main 方法运行
MainFrame。我已经删除了sg -
我不确定,但看起来你的
MainFrame类仍然无法编译,即使在你编辑之后。 -
Swing 中的动画类似于手动动画。您创建了一系列可以快速更改(重新绘制)的静止图像。您的绘图 JPanel 应根据逻辑模型的内容绘制图像。逻辑模型中的值使用 Swing Timer 更改。