0

How to replace button shown on code with a filled circled.The circle (e.g. red) must move away from cursor just as same it was with button. Is it another possible way to implement this type of task?

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class NewSwingTemplate {
    private Random d = new Random();

    public NewSwingTemplate() {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        panel.add(createButton());
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private JButton createButton() {
        final JButton button = new JButton("Button");
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                int a = d.nextInt(200);
                int b = d.nextInt(200);
                button.setLocation(a, b);
            }
        });
        return button;
    }
    

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new NewSwingTemplate();
            }
        });
    }
}
camickr
  • 321,443
  • 19
  • 166
  • 288
  • 2
    You can do custom painting of a `Shape`. Check out: https://stackoverflow.com/a/67443344/131872. It shows how to paint and drag any `Shape`. You would just need to replace the "dragging" logic and handle the `mouseMoved` event. You would first need to check if the `Shape` contains the mouse point. If so, then you transform the Shape to another location. – camickr Jun 10 '21 at 22:04
  • 1
    Or you could actually create a [Round Button](https://stackoverflow.com/questions/24028358/change-jbutton-focus-area/24028405#24028405). – camickr Jun 10 '21 at 22:11
  • Well is your problem solved? You keep asking questions but you never accept an answer or comment on if the problem is solved. – camickr Jun 11 '21 at 03:07
  • Well is your problem solved? You keep asking questions but you never accept an answer or comment if the suggestion have helped solve the problem. – camickr Jun 11 '21 at 03:20

1 Answers1

0

Create your own button.

That is, you derive from JComponent and overwrite the paint method. It needs to render your circle - the way you want it. Add some keyboard/mouse handling and maybe an ActionListener to the circle can react similar to a JButton.

Finally you use it just like a JButton - I guess you have the code that makes your button move somewhere already.

Queeg
  • 7,748
  • 1
  • 16
  • 42