所以我正在进行Java分配,我必须创建一个Rectangle类,该类在绘制重叠矩形的程序中使用,并且矩形重叠,绘制一个新的矩形,使用新颜色。我已经包含了一个指向硬件描述的链接,因为我认为最简单的方法是让你看一下,而不是我试图解释它。http://myslu.stlawu.edu/~ltorrey/courses/spring13/cs219/hw/hw6.html
我目前停留在创建getOverlap方法,该方法绘制新的重叠矩形。我必须创建一个显然绘制矩形的绘制方法,并且对于getOverlap方法是否为先前定义的变量定义新参数然后重新路由到draw方法感到困惑?任何帮助将不胜感激。
答案 0 :(得分:4)
通过巧妙地使用Area
,您可以获得Graphics2D
API来为您完成。
基本上,我创建了一个Area
,它是对两个矩形进行异或运算的结果。然后我从Area
中减去这个,这是将两个矩形加在一起的结果
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Area;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class OverlappingRectangles {
public static void main(String[] args) {
new OverlappingRectangles();
}
public OverlappingRectangles() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Rectangle r1 = new Rectangle(0, 0, 150, 150);
Rectangle r2 = new Rectangle(50, 50, 150, 150);
g2d.setColor(Color.RED);
g2d.fill(r1);
g2d.setColor(Color.BLUE);
g2d.fill(r2);
Area a1 = new Area(r1);
a1.exclusiveOr(new Area(r2));
Area a2 = new Area(r2);
a2.add(new Area(r1));
a2.subtract(a1);
g2d.setColor(Color.GREEN);
g2d.fill(a2);
g2d.dispose();
}
}
}
答案 1 :(得分:3)
使用MadProgrammer的代码我发现了几种更简单的方法:
使用区域:
Area yellow = new Area(r1);
yellow.intersect( new Area(r2) );
g2d.setColor(Color.YELLOW);
g2d.fill(yellow);
或者使用另一个Rectangle:
Rectangle green = r1.intersection(r2);
g2d.setColor(Color.GREEN);
g2d.fill(green);
答案 2 :(得分:2)
如果允许java.awt.Rectangle
,请在此处概述如何在实施中使用它:
private static class Rectangle {
private int x1, y1, x2, y2, r, g, b;
private java.awt.Rectangle r1 = new java.awt.Rectangle();
private java.awt.Rectangle r2 = new java.awt.Rectangle();
private java.awt.Rectangle r3;
public Rectangle(int x1, int y1, int x2, int y2, int r, int g, int b) {
...
}
private void draw(Graphics page) {
...
}
private boolean overlapsWith(Rectangle r) {
r1.setBounds(...);
r2.setBounds(...);
return r1.intersects(r2);
}
private Rectangle getOverlap(Rectangle r) {
r1.setBounds(...);
r2.setBounds(...);
r3 = r1.intersection(r2);
return new Rectangle(...);
}