【问题标题】:Issue with drawRect/fillRect from Swing Library (Images included)Swing 库中的 drawRect/fillRect 问题(包括图像)
【发布时间】:2014-11-10 03:32:49
【问题描述】:

刚开始为 Java 中的类项目 GUI 使用 Swing。我正在尝试画一个游戏板,但是,不是传统的。我正在尝试绘制一个更像parchessi board 的图形,因此每个板图块都需要有一个特定的位置而不是一个网格。

到目前为止,我遇到了这个问题。在 paint() 中,我尝试绘制 5 个矩形,奇数的为蓝色和空的,偶数的为红色并填充。但是,我得到的不是漂亮的方格图案,而是:

谁能帮我弄清楚为什么会这样?

代码:

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Rectangles extends JPanel {

   public static void main(String[] a) {
      JFrame f = new JFrame();
      f.setSize(800, 800);
      f.add(new Rectangles());
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setVisible(true);
   }

   public void paint(Graphics g) {
      int x = 15;
      int y = 15;
      int w = 15; 
      int h = 15;
      for(int i = 0; i < 5; i++){
          if(i%2==0){
              g.setColor(Color.RED);
              g.fillRect (x, y, x+w, y+h);
          }
          else{
              g.setColor(Color.BLUE);
              g.drawRect (x, y, x+w, y+h);
          }
          x+=15;
          System.out.println(Integer.toString(x) + ' ' + Integer.toString(y) + '|' + Integer.toString(w) + ' ' + Integer.toString(h));
      }
   }
}

Println 语句的输出(x,y,width,height):

30 15|15 15
45 15|15 15
60 15|15 15
75 15|15 15
90 15|15 15

第一张图片好像有重叠,所以我修改了代码并尝试了这个:

  for(int i = 0; i < 5; i++){
      g.setColor(Color.BLUE);
      g.drawRect (x, y, x+w, y+h);    
      x+=15;
   }

这段代码会发生以下情况:

为什么会有重叠?这是什么原因造成的?

另外,有没有人知道制作一个易于修改的矩形数组的好方法?或者有什么好的建议或工具来绘制这种类型的板?

【问题讨论】:

    标签: java swing rectangles


    【解决方案1】:

    欢迎你不应该打破油漆链的原因......

    首先调用super.paint(g) 作为paint 方法的第一行,然后再进行任何自定义绘制。

    更好的解决方案是覆盖 paintComponent 而不是 paint,但仍确保在执行任何自定义绘制之前调用 super.paintComponent...

    查看Performing Custom PaintingPainting in AWT and Swing 了解更多详情

    接下来开始阅读JavaDocs on Graphics#fillRect,你会看到最后两个参数代表的是宽和高,而不是底角的x/y位置

    public class Rectangles extends JPanel {
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            int x = 15;
            int y = 15;
            int w = 15;
            int h = 15;
            for (int i = 0; i < 5; i++) {
                if (i % 2 == 0) {
                    g.setColor(Color.RED);
                    g.fillRect(x, y, w, h);
                } else {
                    g.setColor(Color.BLUE);
                    g.drawRect(x, y, w, h);
                }
                x += 15;
                System.out.println(Integer.toString(x) + ' ' + Integer.toString(y) + '|' + Integer.toString(w) + ' ' + Integer.toString(h));
            }
        }
    }
    

    【讨论】:

    • 非常感谢!我去看看paint和paintcomponent的区别。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-14
    • 2013-06-21
    • 2011-01-21
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多