我启动计时器并调用paintRect
重绘眼睛并创建闪烁效果,但它不起作用。我打电话给paintEye
再次画左眼,但是是黄色。
我还在尝试学习ActionListener
作品,因此我不确定我是否正确行事,无论如何都看起来不像。
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class Content extends JPanel {
public Content() {
}
@Override
public void paintComponent(Graphics g) {
//face
g.setColor(Color.yellow);
g.fillOval(10, 10, 200, 200);
//eyes
g.setColor(Color.black);
g.fillOval(55, 65, 30, 30);
g.fillOval(135, 65, 30, 30);
//mouth
g.setColor(Color.black);
g.fillOval(50, 110, 120, 60);
//touchUp
g.setColor(Color.YELLOW);
g.fillRect(50, 110, 120, 30);
g.fillOval(50, 120, 120, 40);
time.start();
paintEye(super.getComponentGraphics(g));
//eyesAgain
g.setColor(Color.black);
g.fillOval(55, 65, 30, 30);
}
public void paintEye(Graphics grphcs) {
grphcs.setColor(Color.yellow);
grphcs.fillOval(55, 65, 30, 30);
}
Timer time = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
});
}
答案 0 :(得分:2)
你有问题(如评论中所述)
blink
的布尔值。我只需切换其值:blink = !blink;
,然后调用repaint()
start()
一次。
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // ***** here
// .... rest of the code goes below
if (blink) {
// ....
} else {
// ....
}
}
例如,一个简单的切换程序
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
public class Foo01 extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private static final Color COLOR_1 = Color.RED;
private static final Color COLOR_2 = Color.BLUE;
private static final int TIMER_DELAY = 100;
private static final int RECT_X = 100;
private static final int RECT_W = 400;
private boolean blink = false;
public Foo01() {
setPreferredSize(new Dimension(PREF_W, PREF_H));
new Timer(TIMER_DELAY, e -> {
blink = !blink;
repaint();
}).start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (blink) {
g.setColor(COLOR_1);
} else {
g.setColor(COLOR_2);
}
g.fillRect(RECT_X, RECT_X, RECT_W, RECT_W);
}
private static void createAndShowGui() {
Foo01 mainPanel = new Foo01();
JFrame frame = new JFrame("Foo01");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}