0

マウスのローカリゼーションで円を描画する単純な Java プログラムを作成しようとしています。マウスの X 座標と Y 座標を取得しますが、何も描画しません。文字列、円、線を描画しようとしましたが、何も機能しませんでした、コードを少し変更しましたが、まだ機能しません

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

1 に答える 1

0
  • でカスタム ペイントを直接実行しないでくださいJFrame。可能であれば、常にメソッドJComponentをオーバーライドしてください。paintComponent

  • この目的で無限ループを使用しないでください。MouseMotionListenerMouse 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();
        }
    }
}
于 2013-09-16T20:46:04.230 に答える