How to click buttons by dragging mouse over them in swing?

63 Views Asked by At

I want to be able to click multiple JButtons with one mouse drag, but I can't seem to find any built in functionality to do this. I was considering just checking if the mouse drag crossed the coordinates of the buttons, but it seems like there should be a better way to do this. I am trying to make a program for designing poker charts where if you click on one of the buttons on the grid, they cycle between fold, call, raise, and all-in. The problem is that this is quite slow to do clicking one by one (since there's 169 possible hand combinations), and it would be nice to be able to click multiple at a time by dragging the mouse over them.

1

There are 1 best solutions below

0
Grinding For Reputation On

You could add a mouse listener which checks if the mouse is dragged across the buttons and then use button.doClick to execute the button function or do a custom action.

Here's a simple program to demonstrate this

public class Main {

    private static final MouseAdapter adapter = new MouseAdapter() {

        boolean mouseDown = false;

        @Override
        public void mouseEntered(MouseEvent e) {
            if(mouseDown)
                ((JButton) e.getSource()).doClick();
        }

        @Override
        public void mousePressed(MouseEvent e) {
            ((JButton) e.getSource()).doClick(); // Click the initial button
            mouseDown = true;
        }

        public void mouseReleased(MouseEvent e) {
            mouseDown = false;
        }
    };

    public static void main(String[] args) {

        JButton b1 = new JButton("Button 1");
        JButton b2 = new JButton("Button 2");
        JButton b3 = new JButton("Button 3");

        b1.addMouseListener(adapter);
        b2.addMouseListener(adapter);
        b3.addMouseListener(adapter);

        b1.addActionListener(e -> System.out.println(((JButton) e.getSource()).getText()));
        b2.addActionListener(e -> System.out.println(((JButton) e.getSource()).getText()));
        b3.addActionListener(e -> System.out.println(((JButton) e.getSource()).getText()));

        JFrame jf = new JFrame();

        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        jf.add(b1);
        jf.add(b2);
        jf.add(b3);

        jf.setLayout(new GridLayout(0, 3));
        jf.pack();
        jf.setVisible(true);
    }
}