java可以面板重叠不,如何将两个对象放在同一个面板中,而又不影响彼此??...

已结贴√

问题点数:20 回复次数:3

ca56232b3bbedf9a539d07f37fffb99a.gif

3144d8b7615c79d9f638db40d5689d26.gif

a218af6549b45ee526caf607ebff1358.gif

0f8df0e29816ae721419de940fb833d1.gif

如何将两个对象放在同一个面板中,而又不影响彼此??

我希望的是,将小球和枪放在同一个面板中,小球的位置是随机出现在框架中的。此时,要得到框架的高度和宽度,要在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 编辑]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值