0 java swing netbeans paint thread-sleep
我想创建一个小应用程序.在我的应用程序中,我有jLabel1和Jbutton1.我想jLabel1使用jButton点击从一侧到另一侧进行动画制作.我不知道如何在创建动画时调用它.我做了一个绘图应用程序代码,给出如下.jButton1ActionPerformedjLabel1
这是我的代码:
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2=(Graphics2D)g;
g2.drawString("ancd", x, y);
try {
Thread.sleep(10000);
} catch (Exception e) {
System.out.println(""+e);
}
x+=10;
if(x>this.getWidth())
{
x=0;
}
repaint();
}
Run Code Online (Sandbox Code Playgroud)
为简单起见,您可以使用Swing计时器进行动画制作.但是,如果我是你,我不会移动JLabel.但我会直接在JPanel上绘制并保留一组位置(图像的x和y).在计时器中,更新位置并重新绘制它.
由于您想在屏幕上移动JLabel,您可以执行以下操作:
class DrawingSpace extends JPanel{
private JLabel label;
private JButton button;
private Timer timer;
public DrawingSpace(){
setPreferredSize(new Dimension(200, 300));
initComponents();
add(label);
add(button);
}
public void initComponents(){
label = new JLabel("I am a JLabel !");
label.setBackground(Color.YELLOW);
label.setOpaque(true);
button = new JButton("Move");
//Move every (approx) 5 milliseconds
timer = new Timer(5, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
//Move 1 px everytime
label.setLocation(label.getLocation().x, label.getLocation().y+1);
}
});
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
if(!timer.isRunning())
timer.start();
else
timer.stop();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
然后是运行程序的类:
class Mover{
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() { // Run the GUI codes on the EDT
@Override
public void run() {
JFrame frame = new JFrame("Some Basic Animation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawingSpace());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
如果你计划实现使用paint(),我会说你可能应该覆盖paintComponents(Graphics g)而不是paint(Graphics g)Java组件.也不要混淆你的绘画方法,因为Thread.sleep()它可能会冻结你的UI.paint方法应该只包含绘画所需的代码而不包含任何其他代码.
| 归档时间: |
|
| 查看次数: |
1913 次 |
| 最近记录: |