0

This is my code:

package saaaaaaaaaa;

public class xd {
    public static JFrame frame = new JFrame("Halo");
    public static JLabel lab = new JLabel("learning ",JLabel.CENTER);
    public static JButton but = new JButton("but");
    public static JButton but1 = new JButton("butt");
    public static CustomAct act = new CustomAct(lab);

    public static void main(String[] args) {
        but.addMouseListener(act);
        but1.addMouseListener(act);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(640, 480);
        frame.setLayout(new BorderLayout());
        frame.setResizable(false);
        frame.add(lab, BorderLayout.CENTER);
        frame.add(but, BorderLayout.SOUTH);
        frame.add(but1, BorderLayout.NORTH);
    }
}

This is extra class for mouse click, I need 2x mouse click for 2 buttons.

package saaaaaaaaaa;

public class CustomAct implements MouseListener {
    private static final long serialVersionUID = 1L;
    private String halo = "this is ";
    private int getClickCount = 1;
    private JLabel lab;
    private JLabel lab1;

    public CustomAct(JLabel lab) {
        this.lab = lab;
    }

    public void mouseClicked(MouseEvent e) {
        if(e.getSource()==but) {
            lab.setText("cau"+getClickCount++);
        }
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

    @Override
    public void mousePressed(MouseEvent e) {
    }

    @Override
    public void mouseReleased(MouseEvent e) {
    }
}

How can I do a multiple buttons for each different mouse click action?

How can I get ID of button, which is used?

This is if(e.getSource()==but) --- but cannot be resolved to a variable

I really don't know how to do it.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

1 Answers1

0

First of all you don't use a MouseListener to listen for clicks on a button.

Instead you should be using an ActionListener.

If the Action for each button is unrelated, then you need to create a separate ActionListener for each button with each ActionListener containing the specific code for the button. For example the "Add" and "Subtract" methods of a simple calculator would require a separate Action.

If the Action is related, then you would create a generic ActionListener that can be shared by the buttons. For example, entering digits 0, 1, 2, ... could be a shared ActionListener. For a working example of this approach check out: How to add a shortcut key for a jbutton in java?

Also, you should NOT be using static variables. Instead you should be create a class that extends a JPanel where you define all your variables and Swing components. The ActionListeners would also be defined in that class so they can update the labels as required.

camickr
  • 321,443
  • 19
  • 166
  • 288