如何将两个对象放在同一个面板中,而又不影响彼此??
我希望的是,将小球和枪放在同一个面板中,小球的位置是随机出现在框架中的。此时,要得到框架的高度和宽度,要在paintComponent方法中用getWidth啊。。但如果这样,当我移动枪时,小球的位置又发生了变化。。。现我把程序改成下面这样,但小球的位置就一直是0,0了。。。
谁知道怎么改啊???
谢谢了
如果用一个面板来装这两个,如下
gun.setFocusable(true);
p1.add(gun);
p1.add(ball);
add(p1);
那么枪的位置就不在最下面了。还是错的。。。
[attach]73718[/attach]
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class BallGame extends JFrame {
private Ball ball = new Ball();
Ball.Gun gun = ball.new Gun();
public BallGame(){
// add(ball);
add(gun);
gun.setFocusable(true);
}
public static void main (String[] args){
BallGame frame = new BallGame();
frame.setTitle("BallGame");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,200);
frame.setVisible(true);
}
public class Ball extends JPanel {
int xCoordinate ;
int yCoordinate ;
protected void paintComponent(Graphics g){
super.paintComponent(g);
xCoordinate = (int)(Math.random() * getWidth());
yCoordinate = (int)(Math.random() * getHeight());
g.drawOval(xCoordinate, yCoordinate, 10, 10);
}
// }
public class Gun extends JPanel {
private int x1 = 0;
private int x2 = 0;
private int y1 = 0;
private int y2 = 0;
private int arc = 0;
private int xBall = 0;
private int yBall = 0;
public Gun(){
xBall = xCoordinate;
yBall = yCoordinate;
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
switch(e.getKeyCode()){
case KeyEvent.VK_LEFT: if(arc > 90)
arc -= 90;
else if (arc < 0)
arc += 90;
else
arc++; break;
case KeyEvent.VK_RIGHT: if(arc > 90)
arc -= 90;
else if (arc < 0)
arc += 90;
else
arc--; break;
default: arc = getArc();
}
repaint();
}
});
}
public int getArc(){
return arc;
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
x1 = getWidth() / 2;
y1 = getHeight();
x2 = getWidth() / 2 + (int)((Math.cos(arc * (2 * Math.PI / 180))) * 50);
y2 = getHeight() - (int)((Math.sin(arc * (2 * Math.PI / 180))) * 50);
g.drawLine(x1, y1, x2, y2);
g.drawOval(xBall, yBall, 10, 10);
}
}
}
}
[ 本帖最后由 ilvhmfer 于 2013-11-24 08:38 编辑 ]