如何在我点击的地方画一个圆圈

时间:2018-05-12 02:45:49

标签: java swing paint

以下是实际绘制无法工作的圆的代码。

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

public class TestCode extends JFrame {

private JPanel mousepanel;
private JLabel statusbar;

public TestCode() {
    super("title");
    mousepanel = new JPanel();
    mousepanel.setBackground(Color.WHITE);
    add(mousepanel, BorderLayout.CENTER);

    statusbar = new JLabel("default");
    add(statusbar, BorderLayout.SOUTH);

    Handlerclass handler = new Handlerclass();
    mousepanel.addMouseListener(handler);
    mousepanel.addMouseMotionListener(handler);

}

private class Handlerclass extends JFrame implements ActionListener, MouseListener, MouseMotionListener {

    public void paint(int a, int b) {
        Graphics g = this.getGraphics();
        int r = 10;
        g.drawOval(a, b, r, r);
        g.setColor(Color.BLACK);
        g.fillOval(a, b, r, r);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub
        int x,y;
        statusbar.setText(String.format("clicked at %d, %d", e.getX(), e.getY()));
        x=e.getX();
        y=e.getY();
        //paint(x, y);
        repaint();
    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    public void mouseDragged(MouseEvent e) {

    }

    public void mouseMoved(MouseEvent e) {

    }

    @Override
    public void actionPerformed(ActionEvent ae) {

    }

    }

}

您好我正在尝试编写一个代码,我单击鼠标并绘制一个圆圈。我不知道为什么它不起作用。这是我的主要方法。当我运行我的代码时,它只是显示窗口,当我点击时,除了底部的坐标之外没有任何显示。

import java.awt.Graphics;

import javax.swing.JFrame;

public class Ahh {

public static void main(String[] args) {
    // TODO Auto-generated method stub
            TestCode qwerty = new TestCode();
            // qwerty.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            qwerty.setSize(300, 300);
            qwerty.setVisible(true);


    }

}

0 个答案:

没有答案