【发布时间】:2015-11-08 03:42:38
【问题描述】:
我是 Java 初学者,尤其是 Java Swing。我要做的是创建随机生成的“建筑物”(我已经完成了),并在它们之上添加大小和间隔相同的行/列中的窗口。但是我想在循环中执行此操作(for 循环?)。我的最终目标是每次运行代码时也只有几个窗口亮起(这也是随机生成的)。这是我到目前为止所拥有的,我创建的窗口基本上是我想要的大小。我知道我的属性 maxX 没有被使用,但我创建它是为了提醒我最大 X 值,以防我以后需要它。
import java.awt.*;
import javax.swing.*;
public class JPanelExample extends JPanel
{
private int maxX = 784;
private int maxY = 712;
@Override
public void paint(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.WHITE);
g2d.fillRect(5, 5, 25, 25);
int width = (int)(Math.random()*100+100);
int height = (int)(Math.random()*350+100);
for (int i =10; i<634; i+=(width+10))
{
for (int j = 462 ; j>=462; j--)
{
g2d.setColor(Color.GRAY);
g2d.drawRect(i, maxY-height, width, height);
g2d.fillRect(i, maxY-height, width, height);
g2d.setColor(Color.YELLOW);
g2d.drawRect(i+5, (maxY-height)+5, width/6, width/6);
g2d.fillRect(i+5, (maxY-height)+5, width/6, width/6);
height = (int)(Math.random()*462+100);
while (width == i+(width+10))
{
width = (int)(Math.random()*100+100);
}
}
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Frame");
frame.add(new JPanelExample());
frame.setBackground(Color.BLACK);
frame.setSize(800, 750);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
【问题讨论】:
-
不要覆盖
paint,而是使用paintComponent,同时确保调用super.paintComponent以维护绘制链。请参阅Painting in AWT and Swing 和Performing Custom Painting 了解更多详情 -
@MadProgrammer 所以你的意思是我有
paint(Graphics g)而不是paintComponent(Graphics g)?,并删除覆盖?我应该在哪里打电话给super.paintComponent? -
paintComponent是在JPanel中定义的方法(实际上是它的父母),就像paint一样。所以是的,在上面写着public void paint(Graphics g)的地方,用protected void paintComponent(Graphics g)代替它。在进行任何自定义绘画之前调用super.paintComponent(在paintComponent内) -
@MadProgrammer 好的,谢谢,不再在我的电脑上,但明天会改变这个。您对如何实现“窗口”问题有任何想法吗?