This question already has answers here:
Java paint not drawing in Swing
                                
                                    (3个答案)
                                
                        
                                3年前关闭。
            
                    
我正在尝试使用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);
    }


}

最佳答案

您正在硬编码行参数10、10、100、100:

final Shape line = new Line2D.Double(10, 10, 100, 100);


建立一个非常不灵活的结构-当用户单击并拖动时,您的代码无法更改此设置。解决方案不是这样做,而不是使用硬编码的“魔术”数字,而不是使用int变量,即在代码的MouseListener中更改的变量。在同一个MouseListener内部,您可以在更改参数值之后调用repaint(),这将建议JVM重新绘制GUI,然后重新调用paintComponent方法。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class DrawPanel2 extends JPanel {
    private static final int PREF_W = 600;
    private static final int PREF_H = 300;
    private static final Color BG = Color.WHITE;

    // create fields that can be set in your mouse listeners
    // and used in the painting methods
    private Point p1 = null;
    private Point p2 = null;

    public DrawPanel2() {
        setBackground(BG);

        // create your mouse adapter and add as mouse and mouse motion listeners
        MyMouse myMouse = new MyMouse();
        addMouseListener(myMouse);
        addMouseMotionListener(myMouse);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // if your points have been set,.... draw them!
        if (p1 != null && p2 != null) {
            int x1 = p1.x;
            int y1 = p1.y;
            int x2 = p2.x;
            int y2 = p2.y;

            g2.drawLine(x1, y1, x2, y2);
        }
    }

    // to set the size of the GUI
    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    // my mouse adapter inner class
    private class MyMouse extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent e) {
            p1 = e.getPoint();
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            p2 = e.getPoint();
            repaint();
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            p2 = e.getPoint();
            repaint();
        }
    }

    private static void createAndShowGui() {
        DrawPanel2 mainPanel = new DrawPanel2();

        JFrame frame = new JFrame("Draw Panel 2");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}




关于您发布的代码:


让您的内部类扩展MouseAdapter。此类已经实现了MouseListener和MouseMotionListener以及Wheel侦听器,并且您只需要重写要更改的方法即可。
您的最新代码不应编译,因为它尝试使用尚未在任何地方声明的两个字段theX和theY。我猜测这只是草率的发布,您很快就将此代码投入到您的问题中,而不必费心尝试先进行编译。请不要这样做。我们是志愿服务于我们的业余时间的志愿者,而您这样做将使帮助变得更加困难。
您应该使用两个Point字段(如上所示)或两组x和y int字段,例如x1,y1,x2,y2,然后在鼠标侦听器代码中进行设置。
简单程序的mouseDragged和mouseReleased相同,只需要设置第二个Point(按照上面的示例)或第二对x和y int字段,然后调用repaint。
然后,paintComponent方法将使用两个Point值(按照上面的示例)或使用x和y int字段对来绘制直线。

关于java - 如何在JPanel上画线? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37095835/

10-11 00:24