下記のプログラムはボールが直線運動をするものなのですが、ここからフレームの端に当たる度にボールの速さを変えたいです。当たり判定でgetWidth,getHeightを使えばよいと思うのですが、どこに挿入すればよいかわかりません。助けてください。
java
1import java.awt.Color; 2import java.awt.Font; 3import java.awt.Graphics; 4import java.awt.event.ActionEvent; 5import java.awt.event.ActionListener; 6import java.util.ArrayList; 7 8import javax.swing.JFrame; 9import javax.swing.JPanel; 10 11public class BALL extends JPanel { 12 ArrayList<Figure> figs = new ArrayList<Figure>(); 13 Circle c1 = new Circle(Color.BLUE, 100, 100, 30); 14 Text t1 = new Text(20, 40, "?", new Font("serif", Font.BOLD, 36)); 15 16 public BALL() { 17 setOpaque(false); 18 figs.add(t1); 19 figs.add(c1); 20 final long tm0 = System.currentTimeMillis(); 21 new javax.swing.Timer(50, new ActionListener() { 22 public void actionPerformed(ActionEvent evt) { 23 double tm = 0.001 * (System.currentTimeMillis() - tm0); 24 t1.setText(String.format("%4.2f", tm)); 25 c1.moveTo(20 + (int) (tm * 100) % 250, 100); 26 repaint(); 27 } 28 }).start(); 29 } 30 31 public void paintComponent(Graphics g) { 32 for (Figure f : figs) { 33 f.draw(g); 34 } 35 36 } 37 38 public static void main(String[] args) { 39 JFrame app = new JFrame(); 40 app.add(new BALL()); 41 app.setSize(400, 300); 42 app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 43 app.setVisible(true); 44 } 45 46 interface Figure { 47 public void draw(Graphics g); 48 } 49 50 static class Circle implements Figure { 51 Color col; 52 int xpos, ypos, rad; 53 54 public Circle(Color c, int x, int y, int r) { 55 col = c; 56 xpos = x; 57 ypos = y; 58 rad = r; 59 } 60 61 public boolean hit(int x, int y) { 62 return (xpos - x) * (xpos - x) + (ypos - y) * (ypos - y) <= rad 63 * rad; 64 } 65 66 public void setColor(Color c) { 67 col = c; 68 } 69 70 public void moveTo(int x, int y) { 71 xpos = x; 72 ypos = y; 73 } 74 75 public void draw(Graphics g) { 76 g.setColor(col); 77 g.fillOval(xpos - rad, ypos - rad, rad * 2, rad * 2); 78 79 } 80 } 81 82 static class Text implements Figure { 83 int xpos, ypos; 84 String txt; 85 Font fn; 86 87 public Text(int x, int y, String t, Font f) { 88 xpos = x; 89 ypos = y; 90 txt = t; 91 fn = f; 92 } 93 94 public void setText(String t) { 95 txt = t; 96 } 97 98 public void draw(Graphics g) { 99 g.setColor(Color.BLACK); 100 g.setFont(fn); 101 g.drawString(txt, xpos, ypos); 102 } 103 } 104}
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。