swing - Java: Ball Collision with Frame -


How to not know how to kill it I have to kill I currently have a ball that moves diagonally downwards and on the right, When it is collided with the edge of the frame, it needs to bounce.

Main:

  Class controlled bottle JPanel {Private int x = 70; Private int y = 30; Private bullion yes = true; Public Zero Paint Component (Graphics G) {SuperpactConant (G); Graphics 2DG2 = (Graphics 2D) G; G2.setColor (Color.BLUE); Oval 2D Double ball = new oval 2D Double (X, Y, 50,50); g2.draw (ball); g2.fill (ball); } Public Zero Step: Wright (int d) {x = x + d}} Public Zero Step Down (int d) {y = y + d;} public void gogo () {yes = true;} Public zero nono () {Yes = false;} public static zero main (string [] args) {JFrame frame = new viewer (); Frame.setSize (500, 500); Frame.setTitle ("bouncing ball"); Frame.setDefaultCloseOperation ((JFrame.EXIT_ON_CLOSE)); Frame.setVisible (true); }}   

Viewer category:

  public class viewer JFrame {JButton go = new JButton ("GO"); Jebton Stop = New Jebton ("Stop"); JPNL button = new zpn (); Timer timer; Controlled ball cbPanel = new controller (); Zeppel left = new zpn (); JPN = true zp = new; JPNext Top = New JPN (); The class implements the Googistowner Executioner {Executed Public Zero Action (Action Avenger E) {cbPanel.gogo (); timer.start (); }} Class nonoListener applies ActionListener {public zero action action (ActionEvent e) {cbPanel.nono (); timer.stop (); }} Class timer listener verifies Alicer {Public Zero ActionPerfed (Action Event E) {cbPanel.moveRight (5); CbPanel.moveDown (5); Repaint (); }} Public Viewer () {buttons.add (go); Buttons.add (off); This.add (Button, Border Layout. South); This.add (cbPanel, BorderLayout.CENTER); This.add (right, border layout .aast); This.add (Top, Border Layout. North); This.add (left, borderline. West); Timer = new timer (50, new timer listener ()); Go.addActionListener (new gogoListener ()); stop.addActionListener (new nonoListener ()); timer.start (); CbPanel.setBorder (BorderFactory.createLineBorder (Color.black)); }}    

You need some type of delta that determines the direction In the ball moves, instead of calling moveRight / movedown , you will simply ask the ball to update itself on the basis of this delta.

When called (update method), it will apply the current delta in the case of X / Y and will evaluate if the ball is crossed beyond the available range, if it is on the edge of the ball Should be replaced and delta flipped (multiplying -1), which changes in the direction of the delta.

For example, you will need delta for both horizontal and vertical positions;)

For example:

  • < / li>


  • Comments

    Popular posts from this blog

    Pass DB Connection parameters to a Kettle a.k.a PDI table Input step dynamically from Excel -

    multithreading - PhantomJS-Node in a for Loop -

    c++ - MATLAB .m file to .mex file using Matlab Compiler -