无法在JFrame上绘制

问题描述

  • 。如果可以,请始终在JComponent替代paintComponent方法上进行操作。

  • 为此,请勿使用无限循环。有MouseMotionListener用于Mouse Motion收听的

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();
        }
    }
}

解决方法

我正在尝试制作一个在鼠标本地化处绘制一个圆的简单Java程序,它获取了鼠标的X和Y坐标,但是它没有绘制任何内容,我试图绘制一个String,一个圆和一条线,但是没有任何效果,我稍微修改了代码,但仍然无法正常工作

class Test4 {

public static String a;
public static JFrame frame = new JFrame();

 public static Point Gett(){
 PointerInfo h = MouseInfo.getPointerInfo();
 Point b = h.getLocation();
 return b;
 }

public void paintComponent(int x,int y,Graphics g) {
    g.drawOval(x,y,10,10);
}

public static void main(String[] args) throws InterruptedException {
    int h = 250;
    int f = 200;
    frame.setVisible(true);
    frame.setSize(h,f);
    frame.setLocationRelativeTo(null);
    while(true){
    Point b = Gett();
    int x = (int) b.getX();
    int y = (int) b.getY();
    System.out.println(x);
    System.out.println(y);
    frame.repaint();}}}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...