[英]Java: Drawing two rectangles breaks
首先,翻译是附加的。 因此,您的面板可能不够高,无法显示第二个矩形。 请参阅以下代码和注释。
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)
处理父方法 bookkeepinggetPreferredSize
被认为是标准做法,因此其他区域可能不会随意更改大小。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.