gpt4 book ai didi

java - JPanel/JPanel 上的随机矩形

转载 作者:行者123 更新时间:2023-11-29 03:57:22 30 4
gpt4 key购买 nike

我需要创建一个在 JFrame 或 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);
}

}

我要做的是:编写一个程序,在随机位置显示多个矩形。提供生成更少或更多随机矩形的按钮“更少”和“更多”。每次用户点击“更少”时,计数应该减半。每次用户点击“更多”时,计数都应该加倍。

最佳答案

你的 [更多] 和 [更少] 按钮只是设置矩形的数量,而不是添加或删除它们。你必须以某种方式重新创建它们。

如果您只想显示矩形,则不需要创建 RectangleComponent - 您可以覆盖 JFrame 的绘制调用 super.paint,然后放置和绘制矩形。在这种情况下,您必须在所有 ActionListener 的 jframe 上添加 repaint()。

编辑:更好的想法是添加一个 jpanel 并仅在此面板上绘制矩形,否则矩形将覆盖按钮并在单击按钮后“消失”,查看此 simple demo

关于java - JPanel/JPanel 上的随机矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5556454/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com