繁体   English   中英

Java:绘制两个矩形中断

[英]Java: Drawing two rectangles breaks

我用这种方式填充了两个矩形:

graphics.setColor(Color.RED);
graphics.translate(0, 150);
graphics.fillRect(0,0,65,65); // First rect
graphics.dispose(); // If remove this line, nothing will change
graphics.translate(0, 150);
graphics.fillRect(0,150,100,65); // Second rect

由于某种原因,只渲染了一个矩形:(

看截图

首先,翻译是附加的。 因此,您的面板可能不够高,无法显示第二个矩形。 请参阅以下代码和注释。

graphics.setColor(Color.RED);
graphics.translate(0, 150);         // 0,0 is now at 0,150
graphics.fillRect(0,0,65,65); 
graphics.translate(0, 150);         // 0,0, is now at 0,300
graphics.fillRect(0,150,100,65);    // 0,150 is drawing at 
                                    // 0,450 with a size of 100,65

由于您是绘画新手,我将提供更多可能有用的信息。

  • 不要JFrame 它是一个顶级 class,用于容纳其他组件。 子类 JPanel 并将其添加到其中。 或者创建另一个子类 JPanel 的 class。
  • 覆盖paintComponent(Graphics g)进行绘画。
  • 先调用super.paintComponent(g)处理父方法 bookkeeping
  • 作为一般规则,我发现先填充 object 然后做轮廓/边框会有所帮助。 它只会用轮廓覆盖原始图形。
  • 覆盖getPreferredSize被认为是标准做法,因此其他区域可能不会随意更改大小。
  • 调用frame.pack()来调整框架的大小和布局组件。
public class RectanglesExample extends JPanel {
    
    JFrame f = new JFrame("Rectangles");
    
    public static void main(String[] args) {

            SwingUtilities.invokeLater((()-> 
                    new RectanglesExample()));
           
        }
    
    public RectanglesExample() {
        
        setBackground(Color.WHITE);
        f.add(this);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
    
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(400, 700);
    }
    
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D graphics = (Graphics2D) g.create();
        graphics.setColor(Color.RED);
        graphics.translate(0, 150);
        graphics.fillRect(0,0,65,65); // First rect at 0,150
        graphics.translate(0, 150);
        graphics.fillRect(0,150,100,65); // Second rect at 0,450
        graphics.dispose(); 
        
    
}

我继续画了两个矩形。

在此处输入图像描述

和完整的代码:(注意,你不应该从 0 开始翻译,因为它会削减边缘。)

package firstProject;

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

import javax.swing.JFrame;

public class DrawRectangle extends JFrame {

  @Override
  public void paint(Graphics graphics) {
      graphics.setColor(Color.RED);
      graphics.translate(150, 150);
      
      graphics.fillRect(0,0,65,65);
      graphics.fillRect(100,0,65,65);
  }

  public static void main(String[] args) {
    DrawRectangle frame = new DrawRectangle();
    frame.setSize(500, 500);
    frame.setVisible(true);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM