我是一名大學生,我在分配任務時遇到了麻煩。通常情況下,我只想去實驗室時間詢問技術支持,但他整個星期都病了,所以我們沒有任何實驗時間,這項工作將在星期一開始!如何將同一類的多個對象繪製到一個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