gpt4 book ai didi

java - 如何在JPanel上拖拽画线?

转载 作者:行者123 更新时间:2023-11-30 08:37:34 26 4
gpt4 key购买 nike

<分区>

我正在尝试使用 MouseListeners 绘制一条线并覆盖 paintComponent 方法。我现在设置我的 paintComponent 在面板上自己绘制一条线。但现在我需要将其更改为当您单击面板并将鼠标拖动到另一点以创建一条线时。我一直在阅读所有这些教程,但我仍然很迷茫。谁能指导我?

到目前为止,这是我的代码:

package gui;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.Line2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class DrawPanel extends JPanel {

private static final long serialVersionUID = 1697489704611349844L;

/** The width of the panel. */
private static final int WIDTH = 600;

/** The height of the panel. */
private static final int HEIGHT = 300;

/** The stroke width in pixels. */
private static final int STROKE_WIDTH = 1;

/** The width for the rectangle. */
private static final int RECTANGLE_WIDTH = 50;

/** The height for the rectangle. */
private static final int RECTANGLE_HEIGHT = 50;

public DrawPanel() {
super();
setBackground(Color.WHITE);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
}

class LineListener implements MouseListener, MouseMotionListener {
@Override
public void mouseClicked(MouseEvent theEvent) {
theX = theEvent.getX();
theY = theEvent.getY();
}

@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mouseDragged(MouseEvent theEvent) {
// TODO Auto-generated method stub

}

@Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub

}


@Override
public void paintComponent(final Graphics theGraphics) {
super.paintComponent(theGraphics);
final Graphics2D g2d = (Graphics2D) theGraphics;

// for better graphics display
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);

final Shape line = new Line2D.Double(10, 10, 100, 100);
g2d.setPaint(Color.ORANGE);
g2d.setStroke(new BasicStroke(STROKE_WIDTH));
g2d.draw(line);
}


public static void main(final String[] theArgs) {
final DrawPanel panel = new DrawPanel();
final JFrame frame = new JFrame("Drawing Panel Demo");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}


}

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