can't draw on JFrame

前端 未结 1 679
忘掉有多难
忘掉有多难 2021-01-28 10:14

I\'m trying to make a simle java program that draws a circle at the mouse localization, it gets the mouse X and Y coordinates but it doesn\'t draw anything, i tried to draw a St

相关标签:
1条回答
  • 2021-01-28 10:28
    • Don't perform custom painting directly on a JFrame. Always do it on a JComponent overriding the paintComponent method if you can.

    • Don't use an infinite loop for this purpose. There is the MouseMotionListener for Mouse Motion listening


    public class Test4 {
    
        public static String a;
        public static CustomDrawingPanel content;
        public static JFrame frame = new JFrame();
        final static int OVAL_WIDTH = 10;
        final static int OVAL_HEIGHT = 10;
        static int x = -20, y = -20;
        public static MouseMotionListener listener = new ContentListener();
    
        public static void main(String[] args) throws InterruptedException {
            int h = 250;
            int f = 200;
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            content = new CustomDrawingPanel();
            content.addMouseMotionListener(listener);
            frame.add(content);
    
            frame.getContentPane().setPreferredSize(new Dimension(h, f));
            frame.pack();
            frame.setLocationRelativeTo(null);
    
            frame.setVisible(true);
        }
    
        //class that performs custom drawing
        static class CustomDrawingPanel extends JPanel {
    
            public void paintComponent(Graphics g) {
                super.paintComponent(g);  //Always call this
                g.drawOval(x, y, 10, 10);
            }
        }
    
        //listener to the mouse motion
        static class ContentListener implements MouseMotionListener {
    
            @Override
            public void mouseDragged(MouseEvent e) {
                mouseMoved(e); //if you delete this line, when you drag your circle will hang
            }
    
            @Override
            public void mouseMoved(MouseEvent e) {
                x = e.getX() - OVAL_WIDTH / 2;
                y = e.getY() - OVAL_HEIGHT / 2;
                content.repaint();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题