我需要創建一個程序,在JFrame或JPanel上顯示多個矩形。這是我到目前爲止的代碼:JPanel/JPanel上的隨機矩形
import javax.swing.*;
import java.util.Random;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class RandomRectangles extends JFrame {
private static final int FRAME_HEIGHT = 300;
private static final int FRAME_WIDTH = 250;
private JButton fewer;
private JButton more;
private Random generator = new Random();
private int count;
private JPanel display;
private JPanel panel;
public RandomRectangles()
{
count = generator.nextInt(100);
setSize(FRAME_WIDTH, FRAME_HEIGHT);
this.setTitle("Random Rectangles");
display = new JPanel(new BorderLayout());
setLayout(new BorderLayout());
//display = new JPanel(new GridLayout(2,2));
JPanel buttons = new JPanel();
fewer = new JButton("Fewer");
more = new JButton("More");
buttons.add(fewer);
buttons.add(more);
class fewerNum implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
count = count/2;
}
}
ActionListener listener = new fewerNum();
fewer.addActionListener(listener);
class moreNum implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
count = count * 2;
}
}
ActionListener listener2 = new moreNum();
more.addActionListener(listener2);
for (int i = 0; i <= count; i++)
{
// display.add(new RectangleComponent());
add(new RectangleComponent());
}
//add(display, BorderLayout.CENTER);
add(buttons, BorderLayout.SOUTH);
}
}
上述代碼編譯但存在一些缺陷。單擊按鈕時不做任何事情,而不是向框架或面板添加RectangleComponent對象。 我還創建一個單獨的RectangleComponent類來繪製一個矩形對象
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.Random;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class RectangleComponent extends JComponent{
private Random generator = new Random();
private int xLeft;
private int yTop;
public RectangleComponent()
{
xLeft = generator.nextInt(100);
yTop = generator.nextInt(100);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Rectangle rec = new Rectangle(xLeft, yTop, 20, 40);
int amount = generator.nextInt(100);
g2.draw(rec);
}
}
什麼,我要做的是:編寫顯示在隨機位置的一些長方形的計劃。供應按鈕「更少」和「更多」可生成更少或更多的隨機矩形。每次用戶點擊「較少」時,計數應該減半。每次用戶點擊「更多」時,計數應該加倍。
你的具體問題是什麼? – jzd 2011-04-05 18:16:13
我需要知道如何顯示多個矩形的框架或面板 – carlly 2011-04-05 18:18:24
小的一點,但這是一個需求的聲明,而不是一個問題。問題以問號(?)結尾。 – 2011-04-05 18:28:30