我目前正在学习NetBeans中的Java动画和图形。
我决定从JPanel中的一个简单的球移动开始。
我在修复闪烁问题时遇到了一些问题。我看过很多论坛,但大多数都是使用双缓冲的AWT,但我知道SWING组件不需要双缓冲。我尝试过-使用repaint()
和.clearRect()
。
在这2个time.So中,我发现使用.clearRect()
给了我更好的效果,但不是无缝的无闪烁动画,所有我想知道的time.So是否有更好的方法来消除闪烁。
下面是我的代码:
public class NewJFrame extends javax.swing.JFrame {
int x;
int y;
int xspeed = 1;
int yspeed = 1;
int width;
int height;
Graphics g;
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
g = jp.getGraphics();
width = jp.getWidth();
height = jp.getHeight();
final Timer timerCHK = new Timer();
timerCHK.schedule(new TimerTask() {
public void run() {
move();
time();
}
}, 1000, 10);
}
void time() {
final Graphics g = jp.getGraphics();
final Timer timerCHK = new Timer();
timerCHK.schedule(new TimerTask() {
public void run() {
g.clearRect(0, 0, jp.getWidth() - 3, jp.getHeight() - 3);
}
}, 1000, 12);
}
void move() {
x = x + xspeed;
y = y + yspeed;
Graphics mk = jp.getGraphics();
if (x < 0) {
x = 0;
xspeed = -xspeed;
} else if (x > width - 20) {
x = width - 20;
xspeed = -xspeed;
}
if (y < 0) {
y = 0;
yspeed = -yspeed;
} else if (y == height - 20) {
y = height - 20;
yspeed = -yspeed;
}
mk.drawOval(x, y, 20, 20);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
}
发布于 2012-12-27 18:29:20
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class NewJFrame extends JFrame {
private JPanel jp;
private Timer timer;
public NewJFrame() {
initComponents();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setLocationByPlatform(true);
timer.start();
}
public void initComponents() {
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jp.repaint();
}
};
timer = new Timer(50,al);
jp = new JPanel() {
int x;
int y;
int xspeed = 1;
int yspeed = 1;
Dimension preferredSize = new Dimension(300, 100);
@Override
public Dimension getPreferredSize() {
return preferredSize;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.move();
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.drawOval(x, y, 20, 20);
}
void move() {
x = x + xspeed;
y = y + yspeed;
if (x < 0) {
x = 0;
xspeed = -xspeed;
} else if (x > getWidth() - 20) {
x = getWidth() - 20;
xspeed = -xspeed;
}
if (y < 0) {
y = 0;
yspeed = -yspeed;
} else if (y == getHeight() - 20) {
y = getHeight() - 20;
yspeed = -yspeed;
}
}
};
jp.setBackground(Color.ORANGE);
this.add(jp);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
}
发布于 2012-12-27 15:50:57
我有一个非常类似的闪烁问题,我用
contentPane.updateUI();
并解决了我所有的问题,如果updateUI()解决了您的问题,请让我知道
https://stackoverflow.com/questions/14037848
复制相似问题