1

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);
      }
    }
juan perez
  • 323
  • 5
  • 14

2 Answers2

2

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

vlad1918
  • 338
  • 3
  • 15
  • thanks a lot viad1918. That is what I needed. It worked perfect – juan perez Jun 10 '15 at 06:10
  • viad and if I need to center the JoptionPane right in the center of the parent elemen. How can I do that? – juan perez Jun 10 '15 at 06:14
  • 2
    I don't understand the question. Isn't this what the original question was about? Isn't it already centered in the parent element with the use of getParent()? – vlad1918 Jun 10 '15 at 06:19
  • ok I am wrong. I need to put the Joption a little more up the of center of the frame. This is only a optional characteristic but the original problem is already resolved – juan perez Jun 10 '15 at 06:25
  • 2
    If you need a custom position for JOptionPane and not the center of another component then use the setLocation(x, y) method as suggested by Eddy. – vlad1918 Jun 10 '15 at 06:59
1

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

Community
  • 1
  • 1
Eddy
  • 76
  • 2