问题描述
我认为我需要在注释所在的位置放置一些代码(或者可以使用非静态方法,但我不确定). main方法创建窗口,然后启动图形方法.我希望蓝色方块闪烁.
I think I need to put some code where the comment is (or maybe use non static method but I am not sure). The main method creates the window and then starts the graphics method. I would like the blue square to flash.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class paintTest extends JPanel{
private static JFrame theWindow = new JFrame("Window");
static boolean blueSqr = false;
public void paint(Graphics g) {
g.setColor(Color.RED);
g.fillRect(10, 10, 10, 10);
if(blueSqr){
g.setColor(Color.BLUE);
g.fillRect(10, 10, 10, 10);
}
}
public static void main(String[] args){
createWindow();
theWindow.getContentPane().add(new paintTest());
while(true){
blueSqr = false;
System.out.println("off");
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
blueSqr = true;
// Needs something here
System.out.println("on");
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
}
}
public static void createWindow(){
theWindow.setSize(500, 500);
theWindow.setLocationRelativeTo(null);
theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theWindow.setVisible(true);
}
}
任何帮助都是非常好的.
Any help would be really good.
推荐答案
使用Swing Timer
调用repaint()
.另外,在JPanel
中而不是paint()
中覆盖paintComponent()
.
Use a Swing Timer
to call repaint()
. Also, override paintComponent()
in a JPanel
, rather than paint()
.
类似这样的东西:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PaintTest extends JPanel{
boolean blueSqr = false;
PaintTest() {
setPreferredSize(new Dimension(100,25));
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
blueSqr = !blueSqr;
repaint();
}
};
Timer timer = new Timer(1000,al);
timer.start();
}
public void paintComponent(Graphics g) {
Color c = (blueSqr ? Color.BLUE : Color.RED);
g.setColor(c);
g.fillRect(10, 10, 10, 10);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame theWindow = new JFrame("Window");
theWindow.getContentPane().add(new PaintTest());
createWindow(theWindow);
}
});
}
public static void createWindow(JFrame theWindow){
theWindow.pack();
theWindow.setLocationByPlatform(true);
theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theWindow.setVisible(true);
}
}
还有其他我无法打扰的改进(代码胜于雄辩).如果您有任何疑问(请先检查文档,然后再问).
There were other improvements I could not be bothered documenting (code speaks louder than words). If you have any questions (check the docs first, then) ask.
这篇关于如何重新运行paint方法,使JPanel具有动画效果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!