gpt4 book ai didi

java - 绘制一个大小可变的填充矩形

转载 作者:行者123 更新时间:2023-12-01 10:40:26 26 4
gpt4 key购买 nike

我正在尝试编写一段代码,在拖动鼠标时绘制一个大小可变的填充矩形。当我运行这段代码时,它给我一个空白窗口。每当我按下并拖动时它都不会绘制任何东西。这段代码有什么问题?

import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Rectangle2D;

public class pr2 extends JFrame implements MouseListener, MouseMotionListener
{
Container cp;

Point p1;
Point p2;

Rectangle2D rectangle;

public pr2 (String Name)
{
super (Name);
setLayout(new FlowLayout ());
setBackground(Color.LIGHT_GRAY);
setSize(500, 500);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);

cp = getContentPane ();

addMouseListener(this);
}

public boolean isPointTwoInQuadOne(Point p1, Point p2)
{
return p1.x >= p2.x && p1.y >= p2.y;
}

public boolean isPointTwoInQuadTwo (Point p1, Point p2)
{
return p1.x <= p2.x && p1.y >= p2.y;
}

public boolean isPointTwoInQuadThree(Point p1, Point p2)
{
return p1.x <= p2.x && p1.y <= p2.y;
}

public boolean isPointTwoInQuadFour (Point p1, Point p2)
{
return p1.x >= p2.x && p1.y <= p2.y;
}

public void paintComponent(Graphics g)
{
g.setColor(Color.BLACK);
super.paintComponents(g);
Graphics2D g2 = (Graphics2D)g;
if (rectangle != null)
{
g2.fill(rectangle);
}
}

@Override
public void mousePressed(MouseEvent e)
{
p1 = e.getPoint();
rectangle = new Rectangle2D.Double(p1.x, p1.y, p1.x - p1.x, p1.y - p1.y);
}

@Override
public void mouseDragged(MouseEvent e)
{
p2 = e.getPoint();
if (isPointTwoInQuadOne(p1, p2))
{
rectangle.setRect(p2.x, p2.y, p2.x, p1.y);
repaint();
}
else if (isPointTwoInQuadTwo(p1, p2))
{
rectangle.setRect(p1.x, p2.y, p2.x - p1.x, p1.y - p2.y);
repaint();
}
else if (isPointTwoInQuadThree(p1, p2))
{
rectangle.setRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
repaint();
}
else if (isPointTwoInQuadFour(p1, p2))
{
rectangle.setRect(p2.x, p1.y, p1.x, p2.y);
repaint();
}
}

@Override
public void mouseClicked(MouseEvent e) { }

@Override
public void mouseReleased(MouseEvent e) { }

@Override
public void mouseEntered(MouseEvent e) { }

@Override
public void mouseExited(MouseEvent e) { }

@Override
public void mouseMoved(MouseEvent e) { }
}

最佳答案

从显而易见的事情开始

  • JFrame 没有 paintComponent 方法(您正在调用 super.paintComponents <- 请注意“s”,这会通常是个坏主意
  • 您直接向框架添加一个 MouseListener,如果其上方的子组件也注册了一个 MouseListener,则该框架可能不会收到鼠标事件通知,此外,您还想添加一个 MouseMotionListener

建议:

  • 从自定义组件开始,从 JPanel 等扩展,覆盖它的 paintComponent 方法,确保添加 @Override 注释(如果您尝试重写父类未实现的方法并调用 super.paintComponent
  • ,则会引发编译器错误
  • 向其添加 MouseListenerMouseMotionListener
  • 将自定义组件的实例添加到 JFrame 的实例

关于java - 绘制一个大小可变的填充矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34451947/

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