2012-03-18 7 views
0

J'ai essayé de faire un programme qui sur l'écran la balle se déplacerait d'elle-même. Mais le problème est qu'il ne fait pas repeindre();JAVA déplaçant une balle

Une suggestion comment y remédier?

(classe principale) Main.java:

import javax.swing.*; 
import java.awt.*; 

public class Main extends JFrame{ 
    static int x = 10; 


    public static void main(String[] args){ 
     JFrame f = new JFrame("title"); 
     f.setVisible(true); 
     f.setSize(300,250); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     sekon m = new sekon(); 
     f.add(m); 

     antr t = new antr(); 
     Thread th = new Thread(t); 
     th.start(); 
    } 
} 

(deuxième classe) sekon.java:

import javax.swing.*; 
import java.awt.*; 

public class sekon extends JPanel{ 
    int xiu = 10; 

    public void paintComponent(Graphics g){ 
     super.paintComponent(g); 
     g.setColor(Color.RED); 
     g.fillOval(xiu, 10, 20, 20); 

    } 


    public void changeX(int b){ 
     this.xiu = b; 
    } 



} 

    class antr extends JPanel implements Runnable{ 
     int xi = 10; 
     sekon s = new sekon(); 
     public void run(){ 

      xi += 1; 
      s.changeX(xi); 
      JPanel p = new JPanel(); 
      p.repaint(); 

      try{ 
       Thread.sleep(5); 
       }catch(Exception e){} 
     } 
    } 
+1

1) 'Thread.sleep (5)' Ne pas bloquer l'EDT. Appelez la méthode à partir d'un «temporisateur» Swing. 2) Pour une meilleure aide plus tôt, postez un [SSCCE] (http://sscce.org/). 3) Veuillez utiliser un retrait cohérent et logique pour les blocs de code. 4) S'il vous plaît, apprenez les conventions de dénomination Java courantes (http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#73307) (en particulier le cas utilisé pour les noms) pour la classe , méthode et noms d'attribut et l'utiliser de manière cohérente. –

Répondre

1

L'instance de sekon appartenant à l'objet antr est distinct de celui ajouté à l'interface graphique.

0

Votre classe antr et la classe principale utilisent différentes instances de sekon. Vous devriez probablement passer l'instance créée dans la méthode principale à la classe antr.

2

1) dans votre code est repaint() bloqué par la ligne de code Thread.sleep(5);

2) votre code ne fonctionne pas, parce que manquer ..., toutes les coordonnées pour déplacer Oval throught l'écran

3) conteneur Swing, Swing JComponent utiliser seulement pour Swing Timer dealying, en mouvement, repeindre,

est sûr possible en utilisant Runnable#Thread, mais pas de cette façon,

exemple à propos Swing Timer

import java.awt.*; 
    import java.awt.event.*; 
    import javax.swing.*; 

    public class AnimationJPanel extends JPanel { 

     private static final long serialVersionUID = 1L; 
     private int cx = 0; 
     private int cy = 150; 
     private int cw = 20; 
     private int ch = 20; 
     private int xinc = 1; 
     private int yinc = 1; 

     public static void main(String[] args) { 
      EventQueue.invokeLater(new Runnable() { 

       @Override 
       public void run() { 
        AnimationJPanel panel = new AnimationJPanel(); 
        panel.setPreferredSize(new Dimension(400, 300)); 
        panel.animate(); 
        JFrame frame = new JFrame("Test"); 
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
        frame.getContentPane().add(panel); 
        frame.pack(); 
        frame.setLocationRelativeTo(null); 
        frame.setVisible(true); 
       } 
      }); 
     } 

     public AnimationJPanel() { 
      setLayout(new BorderLayout()); 
      JLabel label = new JLabel("This is an AnimationJPanel"); 
      label.setForeground(Color.RED); 
      label.setHorizontalAlignment(SwingConstants.CENTER); 
      add(label); 
      setBackground(Color.BLACK); 
      setForeground(Color.RED); 
      setOpaque(true); 
     } 

     public void animate() { 
      new Timer(15, new ActionListener() { 

       @Override 
       public void actionPerformed(ActionEvent e) { 
        Rectangle oldCircle = new Rectangle(cx - 1, cy - 1, cw + 2, ch + 2); 
        cx += xinc; 
        cy += yinc; 
        if (cx >= getWidth() - cw || cx <= 0) { 
         xinc *= -1; 
        } 
        if (cy >= getHeight() - ch || cy <= 0) { 
         yinc *= -1; 
        } 
        repaint(oldCircle); 
        repaint(cx - 1, cy - 1, cw + 2, ch + 2); 
       } 
      }).start(); 
     } 

     @Override 
     public void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      g.drawOval(cx, cy, cw, ch); 
     } 
} 
1

étude l'exemple d'instruction suivante pour voir comment provoquer l'animation de repeindre.

public static void main(String args[]) throws Exception { 
new JFrame("AnimationStudy") { 
    int x = 0; 
    JPanel j = new JPanel() { 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.setColor(Color.RED); 
     g.fillOval(x, 10, 20, 20); 
     g.setColor(Color.BLACK); 
     g.drawChars(("" + x).toCharArray(), 0, ("" + x).length(), x, 10); 
    } 
    }; 
    { 
    setSize(300, 100); 
    setLocation(300, 300); 
    setVisible(true); 
    setLayout(new BorderLayout()); 
    add(j); 
    new Thread(new Runnable() { 
     public void run() { 
     int t = 250; 
     for (x = 10; x < t; x += 1) { 
      j.repaint(); 
      try { 
      Thread.sleep((t - x)/4); 
      } catch (Exception e) { 
      e.printStackTrace(); 
      } 
     } 
     System.exit(0); 
     } 
    }).start(); 
    } 
}; 
} 
+1

Considérez également 'javax.swing.Timer'; voir aussi [Initial Threads] (http://download.oracle.com/javase/tutorial/uiswing/concurrency/initial.html). – trashgod

Questions connexes