Center JoptionPaneMessageDialog in parent element of the source element that generated the event

396 Views Asked by At

I need to center the JOptionPaneMessageDialog in the parent element of e.getSource. The problem is that I have two differents classes. One listener class and another class that use that listener this is the line that I need to change

JOptionPane.showMessageDialog((Component)e.getSource(), "pulsado");

    package excepciones;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;

    class ButtonListener  implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {

            JOptionPane.showMessageDialog((Component)e.getSource(), "pulsado");
        }

    }

    public class UseActionListener {
      public static void main(String[] args) {
          JFrame frame = new JFrame("Popup JComboBox");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            JButton source = new JButton("Ring the bell!");
            source.addActionListener(new ButtonListener());
            frame.add(source, BorderLayout.SOUTH);

            source.addActionListener(new ButtonListener());

            frame.setSize(300, 200);
            frame.setVisible(true);
      }
    }
2

There are 2 best solutions below

5
On BEST ANSWER

JOptionPane.showMessageDialog(((Component) e.getSource()).getParent(), "pulsado");

0
On

Have you tried setting the location through the setLocation(x, y) method? Check out How to set the location of “JOptionPane.showMessageDialog”