我是一名大学生,我在分配任务时遇到了麻烦。通常情况下,我只想去实验室时间询问技术支持,但他整个星期都病了,所以我们没有任何实验时间,这项工作将在星期一开始!如何将同一类的多个对象绘制到一个JPanel上?
我遇到的具体问题与创建Java应用程序有关,该应用程序显示带有按钮的框架,允许用户创建一个在屏幕上弹起并弹回框架边界的球。
以前任务中的一个练习是创建一个类似的程序,但运行时会立即显示ONE ball bouncing。 (我开始工作)现在,我们必须修改我们的代码并合并允许我们创建多个球的按钮。起初,我认为这将是一个简单的修改,但现在我对如何真正实例化Ball对象感到困惑。我的思考过程是我首先必须使ReboundPanel和按钮面板出现(工作),然后每当用户按下按钮时,一个新的Ball对象被实例化并显示在ReboundPanel上。 (目前无效)
感谢各位的帮忙!
主程序:
import java.awt.*;
public class Rebound {
public static void main(String[] args) {
JFrame frame = new JFrame ("Rebound");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
JPanel reboundPanel = new ReboundPanel();
JPanel buttonPanel = new ButtonPanel();
frame.getContentPane().add(reboundPanel);
frame.getContentPane().add(buttonPanel);
frame.pack();
frame.setVisible(true);
}
}
Panel让球应该出现:
import java.awt.*;
public class ReboundPanel extends JPanel {
private final int WIDTH = 400, HEIGHT = 300;
public ReboundPanel() {
setPreferredSize (new Dimension(WIDTH, HEIGHT));
setBackground (Color.black);
}
}
按钮面板:
import java.awt.*;
public class ButtonPanel extends JPanel {
private final int WIDTH = 400, HEIGHT = 35;
public ButtonPanel() {
setPreferredSize (new Dimension(WIDTH, HEIGHT));
setBackground (Color.GRAY);
JButton button = new JButton("New ball");
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
new Ball();
}
});
}
}
Ball类:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Ball extends JPanel {
private final int DELAY = 20, IMAGE_SIZE = 35;
private ImageIcon image;
private Timer timer;
private int x, y, moveX, moveY;
public Ball() {
timer = new Timer(DELAY, new ReboundListener());
image = new ImageIcon ("/src/pa1/images/earth.gif");
x = 0;
y = 40;
moveX = moveY = 3;
draw(null);
timer.start();
}
public void draw(Graphics page) {
super.paintComponent (page);
image.paintIcon (new ReboundPanel(), page, x, y);
}
private class ReboundListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
x += moveX;
y += moveY;
if (x <= 0 || x >= WIDTH-IMAGE_SIZE)
moveX = moveX * -1;
if (y <= 0 || x >= WIDTH-IMAGE_SIZE)
moveY = moveY * -1;
repaint();
}
}
}
按下按钮时,您调用Ball的构造函数,但不存储新对象的地址。你不应该保留对它的引用,以便垃圾收集器不会摆脱它吗?尝试制作一个球的矢量,并添加每个新的球。 – broncoAbierto 2012-02-17 11:46:01
不知道你的意思是由矢量... 我对类设计感到困惑......什么类应该做什么? – Wangagat 2012-02-17 11:51:47
[链接] http://docs.oracle.com/javase/6/docs/api/java/util/Vector.html矢量是一个动态的对象数组。它没有规定的大小限制(除了你的可用内存,我认为)。在ButtonPanel中创建这个Vector vectorOfBalls = new Vector ;并用vectorOfBalls.add(new Ball())添加球; –
broncoAbierto
2012-02-17 12:06:25