gpt4 book ai didi

java - 更改 Graphic2D 形状

转载 作者:行者123 更新时间:2023-12-02 09:27:19 25 4
gpt4 key购买 nike

嘿,我想创建一个程序,你可以在其中绘制圆形、矩形、直线等多种形状。当我单击圆形按钮并绘制圆形(1)时,然后当我单击矩形时,它应该只绘制矩形,而不是圆形和矩形(2) ) ,当我单击“直线”时,它应该只绘制直线而不是“圆形”、“矩形”和“直线”(3)。

enter image description here

public class Images extends JComponent {


private Image image;

private Graphics2D g2;

private int currentX, currentY, oldX, oldY;

public Images() {
setDoubleBuffered(false);
}

protected void paintComponent(Graphics g) {
if (image == null) {

image = createImage(getSize().width, getSize().height);
g2 = (Graphics2D) image.getGraphics();

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

clear();
}
g.drawImage(image, 0, 0, null);
}


public void line() {
currentX = 0;
currentY = 0;
oldX = 0;
oldY = 0;

addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
oldX = e.getX();
oldY = e.getY();
}
});

addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
currentX = e.getX();
currentY = e.getY();
g2.draw(new Line2D.Double(oldX, oldY, currentX, currentY));
repaint();
}
});
}

public void rectangle() {
currentX = 0;
currentY = 0;
oldX = 0;
oldY = 0;
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
oldX = e.getX();
oldY = e.getY();
}
});
addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
currentX = e.getX();
currentY = e.getY();
g2.draw(new Rectangle2D.Double(oldX, oldY, currentX - oldX, currentY - oldY));
repaint();
}
});
}
public void circle() {
currentX = 0;
currentY = 0;
oldX = 0;
oldY = 0;
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
oldX = e.getX();
oldY = e.getY();
}
});
addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
currentX = e.getX();
currentY = e.getY();
g2.draw(new Ellipse2D.Double(oldX, oldY, (currentX - oldX), (currentX - oldX)));
repaint();
}});}}

最佳答案

您将获得所有以前选择的形状,因为它们的 mousedown/mouseup 事件仍然绑定(bind)。

解决此问题的一个简单方法是跟踪您的 MouseAdapter(在绑定(bind)它们时将它们添加到列表中)并在切换工具时将其删除(随后清除列表)。

关于java - 更改 Graphic2D 形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58257339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com