【发布时间】:2014-11-18 00:53:01
【问题描述】:
无论出于何种原因,我的循环似乎都没有正确打印颜色。我在填充和绘制之前设置了颜色,但它根本没有显示 Color.white。它显示为白色。为了更好地解释我希望图片看起来像什么,请附上一张照片。感谢您的帮助!
这是我的 ExampleGUI.java 源代码
import javax.swing.*;
public class ExampleGUI {
public static void main(String args []) {
JFrame frame = new JFrame("Example Graphics");
ExamplePanel panel = new ExamplePanel();
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(3);
frame.pack();
frame.setVisible(true);
}
}
这是我的 ExamplePanel.java 源代码
import java.awt.*;
import javax.swing.*;
public class ExamplePanel extends JPanel{
public ExamplePanel() {
setPreferredSize(new Dimension (600, 600));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 0;
int x2 = 5;
int y = 500;
int y2 = 505;
int w = 100;
int w2 = 90;
int h = 100;
int h2 = 90;
int i, j;
for(j = 1; j < 7; j++) {
x = 0;
x2 = x + 5;
for(i = 1; i < 7; i++) {
if(i % 2 == 0) {
g.setColor(Color.white);
g.fillRect(x, y, w, h);
g.setColor(Color.black);
g.drawRect(x, y, w, h);
g.setColor(Color.green);
g.fillOval(x2, y2, w2, h2);
g.setColor(Color.black);
g.drawOval(x2, y2, w2, h2);
}else if (i % 2 == 1 && j % 2 == 1)
g.setColor(Color.yellow);
g.fillRect(x, y, w, h);
g.setColor(Color.black);
g.drawRect(x, y, w, h);
g.setColor(Color.green);
g.fillOval(x2, y2, w2, h2);
g.setColor(Color.black);
g.drawOval(x2, y2, w2, h2);
x = x + w;
x2 = x2 + w2 + 10;
}
x = x + w;
y = y - h;
y2 = (y2 - h2) - 10;
}
}
}
【问题讨论】:
-
你的逻辑无处不在。首先,使用
if语句来定义您要使用的颜色,如果可以,请不要复制绘制代码。其次使用if ((i + j) % 2 == 0) {代替if(i % 2 == 0) {并删除else if并将其替换为else,这应该更接近一步
标签: java swing loops paintcomponent