Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- public class Pong
- {
- public static void main(String args[])
- {
- JFrame frame1 = new Pong1();
- frame1.setVisible(true);
- }
- }
- class Pong1 extends JFrame
- {
- private JPanel panelArea;
- public Pong1()
- {
- JPanel panelInferior;
- setSize(300,300);
- setTitle("Exemplo Thread...");
- addWindowListener(
- new WindowAdapter()
- {
- public void windowClosing(WindowEvent we)
- { System.exit(0); }
- });
- Container contentPane = getContentPane();
- panelArea = new JPanel();
- contentPane.add(panelArea,"Center");
- panelInferior = new JPanel();
- addBtn(panelInferior,"Iniciar",
- new ActionListener()
- {
- public void actionPerformed(ActionEvent ae)
- {
- BolaThreadExemplo b = new BolaThreadExemplo(panelArea);
- b.start();
- }
- });
- addBtn(panelInferior,"Fechar",
- new ActionListener()
- {
- public void actionPerformed(ActionEvent ae)
- { System.exit(0); }
- });
- contentPane.add(panelInferior,"South");
- }
- public void addBtn(Container c, String tit, ActionListener a)
- {
- JButton btn = new JButton(tit);
- c.add(btn);
- btn.addActionListener(a);
- }
- }
- class BolaThreadExemplo extends Thread
- {
- private JPanel caixa;
- private static final int LARG = 10;
- private static final int ALT = 10;
- private int pos_x = 0;
- private int pos_y = 0;
- private int desloc_x = 2;
- private int desloc_y = 2;
- public BolaThreadExemplo(JPanel p)
- { caixa = p; }
- public void desenhar()
- {
- Graphics g = caixa.getGraphics();
- g.fillOval(pos_x,pos_y,LARG,ALT);
- g.dispose();
- }
- public void movimentar()
- {
- Graphics g = caixa.getGraphics();
- g.setColor(caixa.getBackground());
- g.fillOval(pos_x,pos_y,LARG,ALT);
- pos_x += desloc_x;
- pos_y += desloc_y;
- Dimension dim = caixa.getSize();
- if (pos_x < 0)
- {
- pos_x = 0;
- desloc_x = -desloc_x;
- }
- if (pos_x+LARG >= dim.width)
- {
- pos_x=dim.width-LARG;
- desloc_x = -desloc_x;
- }
- if (pos_y < 0)
- {
- pos_y = 0;
- desloc_y = -desloc_y;
- }
- if (pos_y+ALT >= dim.height)
- {
- pos_y=dim.height-ALT;
- desloc_y = -desloc_y;
- }
- g.setColor(Color.BLUE);
- g.fillOval(pos_x,pos_y,LARG,ALT);
- g.dispose();
- }
- public void run()
- {
- try
- {
- desenhar();
- while (true)
- {
- movimentar();
- sleep(10);
- }
- }
- catch (InterruptedException exc) {}
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment