如何在Java Swing中在2点之间拖动和绘制线

时间:2019-05-14 06:19:31

标签: java swing awt drawing

我想用鼠标拖动在两个xy坐标之间画一条线,但是什么也没画

使用swing和awt的gui应用程序,我目前使用鼠标事件将鼠标事件的初始和最终xy位置记录为[x1,y1,x2,y2],但是无法在它们之间绘制线条

绘制线是调用主函数的自身功能

编辑: 说我有2节课;

public class mainApp extends JFrame implements ActionListener, Runnable {

    private JPanel jpanel = new JPanel();

    private mainApp(String title) throws HeadlessException {
        super(title);
    }

    private void createGUI() {
        // TODO
        // ...

        // cannot call unless is static
        drawStraightLine.drawLine(jpanel);

        this.pack();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {}

    @Override
    public void run() {createGUI();}

    public static void main(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        SwingUtilities.invokeLater(new mainApp("drawline"));
    }
}
public class drawStraightLine extends JPanel {

    public static void drawLine(JPanel jpanel) {
        // content which conceivably works
        // mouselisteners and repaint()

        public void paintComponent (Graphics g){
            super.paintComponent(g);
            if (check != null) {
                Color purple = new Color(128, 0, 128);
                g.setColor(purple);
                g.drawLine(x1, y1, x2, y2);
        }
    }
}

除非它是静态函数,否则我无法调用drawline(jpanel),但将其设为静态会导致鼠标侦听器和重新绘制无效。

只要Graphics g在函数内部而不是直接在类中,它将变为无效符号(忽略check和xy值作为占位符) enter image description here

1 个答案:

答案 0 :(得分:2)

您不需要数组甚至X&Y。您可以使用mouseEvent的getPoint()方法。 试试这个:

public static void main(String args[]) throws Exception {
    JFrame f = new JFrame("Draw a Line");
    f.setSize(300, 300);
    f.setLocation(300, 300);
    f.setResizable(false);
    JPanel p = new JPanel() {
        Point pointStart = null;
        Point pointEnd   = null;
        {
            addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    pointStart = e.getPoint();
                }

                public void mouseReleased(MouseEvent e) {
                    pointStart = null;
                }
            });
            addMouseMotionListener(new MouseMotionAdapter() {
                public void mouseMoved(MouseEvent e) {
                    pointEnd = e.getPoint();
                }

                public void mouseDragged(MouseEvent e) {
                    pointEnd = e.getPoint();
                    repaint();
                }
            });
        }
        public void paint(Graphics g) {
            super.paint(g);
            if (pointStart != null) {
                g.setColor("put your color here");
                g.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
            }
        }
    };
    f.add(p);
    f.setVisible(true); 
}