好吧,我正在关注这个tutorial创建我自己的动画,当我运行它时,一切在 Windows 上运行良好,但在 Ubuntu 17.04 中,只有当鼠标在应用程序窗口上移动时,动画才会平滑。如果不这样做,它就像“断断续续”(我认为这是一个很好的翻译)。 这是我的代码:
import javax.swing.Box;
import javax.swing.BoxLayout;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Window extends JFrame {
private Panel pan = new Panel();
private JButton play = new JButton("play");
private JButton pause = new JButton("pause");
public Window(String titre) {
this.setTitle(titre);
this.setSize(900, 600);
this.setLocationRelativeTo(null);
this.setAlwaysOnTop(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box b1 = Box.createHorizontalBox();
b1.add(play);
b1.add(pause);
Box b2 = Box.createVerticalBox();
b2.add(b1);
this.setContentPane(pan);
this.getContentPane().add(b2);
this.setVisible(true);
this.go();
}
private void go() {
// Les coordonnées de départ de notre rond
int x = pan.getPosX(), y = pan.getPosY();
// Le booléen pour savoir si l'on recule ou non sur l'axe x
boolean backX = false;
// Le booléen pour savoir si l'on recule ou non sur l'axe y
boolean backY = false;
// Dans cet exemple, j'utilise une boucle while
// Vous verrez qu'elle fonctionne très bien
while (true) {
// Si la coordonnée x est inférieure à 1, on avance
if (x < 1)
backX = false;
// Si la coordonnée x est supérieure à la taille du Panneau moins la taille du
// rond, on recule
if (x > pan.getWidth() - 50)
backX = true;
// Idem pour l'axe y
if (y < 1)
backY = false;
if (y > pan.getHeight() - 50)
backY = true;
// Si on avance, on incrémente la coordonnée
// backX est un booléen, donc !backX revient à écrire
// if (backX == false)
if (!backX)
pan.setPosX(++x);
// Sinon, on décrémente
else
pan.setPosX(--x);
// Idem pour l'axe Y
if (!backY)
pan.setPosY(++y);
else
pan.setPosY(--y);
// On redessine notre Panneau
pan.repaint();
// Comme on dit : la pause s'impose ! Ici, trois millièmes de seconde
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
第二类:
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class Panel extends JPanel {
private int posX = -50;
private int posY = -50;
public void paintComponent(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.red);
g.fillOval(posX, posY, 50, 50);
}
public int getPosX() {
return posX;
}
public void setPosX(int posX) {
this.posX = posX;
}
public int getPosY() {
return posY;
}
public void setPosY(int posY) {
this.posY = posY;
}
}
主要内容:
import javax.swing.JFrame;
public class test {
public static void main(String [] args) {
Window window = new Window("Animation");
}
}
提前感谢任何能给我一些想法的人:)
最佳答案
尝试打电话
Toolkit.getDefaultToolkit().sync();
完成后
pan.repaint();
关于java - 让我的 java swing 动画在 Linux 中更流畅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46580889/