我对这段代码的目标是提示用户输入任意数量的框,然后程序将绘制他们输入的框数量,但每个框都有不同的位置和不同的颜色。我不确定我是否正确地执行循环,我无法弄清楚如何获取我在paint方法中随机生成的颜色并在drawBlock方法中使用它。
import javax.swing.*;
import java.awt.*;
import java.util.*;
import javax.swing.JOptionPane;
public class Homework4 extends JPanel
{
public int numBlocks;
public static void main( String[] args )
{
JFrame ourFrame = new JFrame();
ourFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ourFrame.setSize(500,500);
ourFrame.setBackground( Color.white );
Homework4 ourHomework4 = new Homework4();
String numBlocksString=
JOptionPane.showInputDialog( "How many blocks would you like?" );
Integer.parseInt( numBlocksString );
ourFrame.add( ourHomework4 );
ourFrame.setVisible(true);
}
public void paint( Graphics canvas )
{
Random rand = new Random();
Color blockColor = new Color( rand.nextInt(255), rand.nextInt(255), rand.nextInt(255) );
if( numBlocks > 0)
{
{
for( int i = 0; i < numBlocks; i++)
{
this.drawBlock( canvas, rand.nextInt(500), rand.nextInt(500), blockColor );
}
}
}
}
public void drawBlock(Graphics g, int x, int y, Color blockColor )
{
g.setColor( blockColor );
g.fillRect( x, y, 150, 150);
//g.setColor( Color.white );
g.fillRect( x+20, y+20, 110, 110);
}
}
答案 0 :(得分:0)
您在问题中发布的源代码中存在一些问题。
以下是您正在寻找的完整更新代码:
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Homework4 extends JPanel {
public static int numBlocks;
public static void main(String[] args) {
JFrame ourFrame = new JFrame();
ourFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ourFrame.setSize(500, 500);
ourFrame.setBackground(Color.white);
Homework4 ourHomework4 = new Homework4();
String numBlocksString = JOptionPane.showInputDialog("How many blocks would you like?");
numBlocks = Integer.parseInt(numBlocksString);
ourFrame.add(ourHomework4);
ourFrame.setVisible(true);
}
public void paint(Graphics canvas) {
Random rand = new Random();
for (int i = 0; i < numBlocks; i++) {
Color blockColor = new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255));
this.drawBlock(canvas, rand.nextInt(500), rand.nextInt(500), blockColor);
}
}
public void drawBlock(Graphics g, int x, int y, Color blockColor) {
g.setColor(blockColor);
g.fillRect(x, y, 150, 150);
g.fillRect(x + 20, y + 20, 110, 110);
}
}
任何随机执行(具有多个块:7)的输出可能如下所示:
希望这个答案有所帮助,它可以清除你的疑虑并且你理解一切。