Thread bolinha não mexe

4 respostas
T

gente,por favor, me ajudem estou tentando fazer a bolinha se mexer qnd o botão iniciar for pressionado mas não tá dando certo (a chamada tá funcionando pq to vendo verificando isso pelo j++)

import java.awt.*;

import javax.swing.JApplet;
import javax.swing.JFrame;


public class applet extends JApplet{
    DrawPanel panel;
    DrawControls controls;


    public void init() {
	setLayout(new BorderLayout());
	panel = new DrawPanel();
        controls = new DrawControls(panel);
	add("Center", panel);
	add("South",controls);
    }

    public void destroy() {
        remove(panel);
        remove(controls);
    }

    public static void main(String args[]) {

	JFrame f = new JFrame("Pêndulo tipo mola");
	 applet drawTest = new  applet();
	drawTest.init();
	drawTest.start();

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	f.add("Center", drawTest);
	f.setSize(500, 500);
	f.setVisible(true);
    }
}


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Panel;
import java.util.Random;
import javax.swing.JOptionPane;

class DrawPanel extends Panel implements Runnable{

   int j =0;
   boolean f = false;

int w =350;
    int h = 250;

    int ww =158, hh =105;

    public  DrawPanel() {
	setBackground(Color.white);
        
           }


   


 public void run ()
	{      f= true;


               while(f){

                    hh+=20;
                    ww+=20;
                    repaint();

                    try
			{
                        Thread.sleep (200);
			}
			catch (InterruptedException ex)
			{		}
                        System.out.println("j="+j++);

		}


               }


    
    public void paint(Graphics g) {
     
	g.setColor(Color.BLACK);
         g.drawLine(125, 0, 225,0);//apoio do pendulo
         g.drawLine(w/2, 0, w/2,10);//inicio do pendulo
          g.drawLine((w/2), (h/2)-30, w/2,(h/2)+10);// fim do pendulo
         for(int i = 0; i< 80; i+=5) //mola
          g.drawOval((w/2)-12, 10+i, (w/2)-150 , 10);

         g.setColor(Color.RED);
         g.fillOval(ww , hh,30, 30); // bolinha

       
    }
}

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import java.awt.Event.*;
import java.awt.event.ActionListener;



class DrawControls extends JPanel implements ActionListener {
    DrawPanel target;

    private JButton iniciar = new JButton("Iniciar");
   private JButton pausar = new JButton("Pausar");
   private JButton continuar = new JButton("Continuar");

   private JLabel massa = new JLabel("Massa:"); private JLabel kg = new JLabel("kg");
   private JLabel k = new JLabel("Constante da mola (k):");private JLabel nm = new JLabel("N/m");
   private JLabel a = new JLabel("Amplitude:");private JLabel m = new JLabel("m");
   private JLabel osc = new JLabel("Período de Oscilação:");private JTextField oscresp = new JTextField(3);
   private JLabel s = new JLabel("s");

   private JRadioButton e = new JRadioButton("Elongação");
   private JRadioButton et = new JRadioButton("Energia Total");

    JTextField txtmassa = new JTextField(3);
    private JTextField txtk = new JTextField(3);
     private JTextField txta = new JTextField(3);
     DrawPanel tread;
   






    public DrawControls(DrawPanel target) {
        tread = new DrawPanel();
        boolean pause = true;

	 GridBagConstraints cons = new GridBagConstraints();
        GridBagLayout layout = new GridBagLayout();

        JPanel panel = new JPanel(layout);

        cons.fill = GridBagConstraints.BOTH;
        cons.gridy = 0;        cons.gridx = 0;

	   panel.setPreferredSize(new Dimension(450,125));
	setBackground(Color.lightGray);

          panel.add(massa, cons);
          cons.gridy = 0;        cons.gridx = 1;
          panel.add(txtmassa, cons);
          cons.gridy = 0;        cons.gridx = 2;
          panel.add(kg, cons);

          cons.gridx = 0; cons.gridy = 1;
       panel.add(k, cons);
       cons.gridy = 1;        cons.gridx = 1;
       panel.add(txtk, cons);
       cons.gridy = 1;        cons.gridx = 2;
       panel.add(nm, cons);

        cons.gridx = 0; cons.gridy = 2;
       panel.add(a, cons);
       cons.gridy = 2;        cons.gridx = 1;
       panel.add(txta, cons);
       cons.gridy = 2;        cons.gridx = 2;
       panel.add(m, cons);

        cons.gridx = 0; cons.gridy = 3;
      panel.add(osc, cons);
      cons.gridx = 1; cons.gridy = 3;
      panel.add(oscresp, cons);
      cons.gridx = 2; cons.gridy = 3;
      panel.add(s, cons);
					//botões
       cons.gridx = 0; cons.gridy = 4;
	iniciar.addActionListener(this);
      panel.add(iniciar, cons);

      cons.gridx = 1; cons.gridy = 4;
	pausar.addActionListener(this);
	panel.add(pausar, cons);


      cons.gridx = 2; cons.gridy = 4;
	continuar.addActionListener(this);
      panel.add(continuar, cons);

      ButtonGroup group = new ButtonGroup();

      cons.gridx = 3; cons.gridy = 0;
    JRadioButton RadioButton = new JRadioButton("Velocidade", true);
    RadioButton.setBackground(Color.lightGray);
    panel.add(RadioButton, cons);
    group.add(RadioButton);
    cons.gridx = 3; cons.gridy = 1;
    RadioButton = new JRadioButton("Elongação");
    RadioButton.setBackground(Color.lightGray);
    panel.add(RadioButton, cons);
    group.add(RadioButton);
    cons.gridx = 3; cons.gridy = 2;
    RadioButton = new JRadioButton("Energia total");
    RadioButton.setBackground(Color.lightGray);
    panel.add(RadioButton, cons);
    group.add(RadioButton);



     panel.setBackground(Color.lightGray);
          setLayout(new BorderLayout());
      add("South", panel);




      }

     public void actionPerformed(ActionEvent e) {

        if (e.getSource() == iniciar){
           Thread t = new Thread(tread);
           t.start();
              }}}

4 Respostas

JoaoBluSCBR

Legal,

A única coisa errada, é que a tua classe DrawControls tem painéis demais kkkkk

Teu código está assim:

DrawPanel target;   
  
     DrawPanel tread;   

  
    public DrawControls(DrawPanel target) {   
        tread = new DrawPanel();

ou seja, você passa para a tua classe o teu DrawPanel mas não o usa no teu panel tread,

Então apague teu atributo DrawPanel target dos atributos e no construtor faça:

DrawPanel tread;   
     
    public DrawControls(DrawPanel target) {   
        tread = target;

A tua classe DrawControls deveria ser assim:

import java.awt.BorderLayout;   
import java.awt.Color;   
import java.awt.Dimension;   
import java.awt.GridBagConstraints;   
import java.awt.GridBagLayout;   
import java.awt.event.ActionEvent;   
import javax.swing.ButtonGroup;   
import javax.swing.JButton;   
import javax.swing.JLabel;   
import javax.swing.JPanel;   
import javax.swing.JRadioButton;   
import javax.swing.JTextField;   
import java.awt.Event.*;   
import java.awt.event.ActionListener;   
  
  
  
class DrawControls extends JPanel implements ActionListener {

    private JButton iniciar = new JButton("Iniciar");
    private JButton pausar = new JButton("Pausar");
    private JButton continuar = new JButton("Continuar");
    private JLabel massa = new JLabel("Massa:");
    private JLabel kg = new JLabel("kg");
    private JLabel k = new JLabel("Constante da mola (k):");
    private JLabel nm = new JLabel("N/m");
    private JLabel a = new JLabel("Amplitude:");
    private JLabel m = new JLabel("m");
    private JLabel osc = new JLabel("Período de Oscilação:");
    private JTextField oscresp = new JTextField(3);
    private JLabel s = new JLabel("s");
    private JRadioButton e = new JRadioButton("Elongação");
    private JRadioButton et = new JRadioButton("Energia Total");
    JTextField txtmassa = new JTextField(3);
    private JTextField txtk = new JTextField(3);
    private JTextField txta = new JTextField(3);
    DrawPanel tread;
    private JPanel panel;

    public DrawControls(DrawPanel target) {
        
        tread = target;
        boolean pause = true;

        GridBagConstraints cons = new GridBagConstraints();
        GridBagLayout layout = new GridBagLayout();

        panel = new JPanel(layout);

        cons.fill = GridBagConstraints.BOTH;
        cons.gridy = 0;
        cons.gridx = 0;

        panel.setPreferredSize(new Dimension(450, 125));
        setBackground(Color.lightGray);

        panel.add(massa, cons);
        cons.gridy = 0;
        cons.gridx = 1;
        panel.add(txtmassa, cons);
        cons.gridy = 0;
        cons.gridx = 2;
        panel.add(kg, cons);

        cons.gridx = 0;
        cons.gridy = 1;
        panel.add(k, cons);
        cons.gridy = 1;
        cons.gridx = 1;
        panel.add(txtk, cons);
        cons.gridy = 1;
        cons.gridx = 2;
        panel.add(nm, cons);

        cons.gridx = 0;
        cons.gridy = 2;
        panel.add(a, cons);
        cons.gridy = 2;
        cons.gridx = 1;
        panel.add(txta, cons);
        cons.gridy = 2;
        cons.gridx = 2;
        panel.add(m, cons);

        cons.gridx = 0;
        cons.gridy = 3;
        panel.add(osc, cons);
        cons.gridx = 1;
        cons.gridy = 3;
        panel.add(oscresp, cons);
        cons.gridx = 2;
        cons.gridy = 3;
        panel.add(s, cons);
        //botões   
        cons.gridx = 0;
        cons.gridy = 4;
        iniciar.addActionListener(this);
        panel.add(iniciar, cons);

        cons.gridx = 1;
        cons.gridy = 4;
        pausar.addActionListener(this);
        panel.add(pausar, cons);


        cons.gridx = 2;
        cons.gridy = 4;
        continuar.addActionListener(this);
        panel.add(continuar, cons);

        ButtonGroup group = new ButtonGroup();

        cons.gridx = 3;
        cons.gridy = 0;
        JRadioButton RadioButton = new JRadioButton("Velocidade", true);
        RadioButton.setBackground(Color.lightGray);
        panel.add(RadioButton, cons);
        group.add(RadioButton);
        cons.gridx = 3;
        cons.gridy = 1;
        RadioButton = new JRadioButton("Elongação");
        RadioButton.setBackground(Color.lightGray);
        panel.add(RadioButton, cons);
        group.add(RadioButton);
        cons.gridx = 3;
        cons.gridy = 2;
        RadioButton = new JRadioButton("Energia total");
        RadioButton.setBackground(Color.lightGray);
        panel.add(RadioButton, cons);
        group.add(RadioButton);



        panel.setBackground(Color.lightGray);
        setLayout(new BorderLayout());
        add("South", panel);




    }

    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == iniciar) {
            Thread t = new Thread(tread);
            t.start();
        }
    }
}

Abraços

ViniGodoy

Eu recomendo fortemente que você siga os tutoriais de Java do Ponto V:
http://www.pontov.com.br/site/index.php/java

Leia todos (exceto os de Android), sem exceção. Não pule etapas.
Fazer animações é um pouco mais complexo do que parece.

T

mtooooooooo brigada JoaoBluSCBR!!! :smiley:

ViniGodoy vlw pela dica do site, procurei mas não tinha achado nenhum voltado p animação, vou seguir os tutoriais :wink:

ViniGodoy

tahinf:
mtooooooooo brigada JoaoBluSCBR!!! :smiley:

ViniGodoy vlw pela dica do site, procurei mas não tinha achado nenhum voltado p animação, vou seguir os tutoriais :wink:

Como assim?
http://www.pontov.com.br/site/index.php/java/48-java2d/121-o-loop-de-animacao
http://www.pontov.com.br/site/index.php/java/48-java2d/123-a-primeira-animacao
http://www.pontov.com.br/site/index.php/java/48-java2d/124-desenho-direto-active-rendering

Ainda assim, recomendo que você leia os tutoriais antes dessa. Há dicas preciosas de como organizar uma aplicação Java 2D para que ela funcione de maneira suave. E também de como organizar classes para o código não virar uma bagunça.

Criado 11 de julho de 2011
Ultima resposta 11 de jul. de 2011
Respostas 4
Participantes 3