Question

I have a JOptionPane with a lot of text on it... which stretches it taller than wide. This causes the icon to appear to "float" up high in the window.

Is there a way to "center" the icon?

JOptionPane.showMessageDialog(ProgManager.getMainWindow(),
    ProgManager.getMainWindow().getAboutBoxPane(), 
        Res.getString("title.about"), JOptionPane.INFORMATION_MESSAGE, 
            ProgRes.getImageIcon(ProgRes.MAIN_IMAGE));

I'd like this:

To appear more like:

without having to modify the image.

Was it helpful?

Solution

  1. Wrap the image a icon in a JLabel and wrap that label in a JPanel with a GridBagLayout (this layout will keep the image/label centered).

  2. Create another JPanel with a BorderLayout, adding the image panel to the WEST and the text component to the CENTER

  3. Add just that JPanel from 2 to to the JOptionPane.


Example

enter image description here

import java.awt.*;
import javax.swing.*;

public class TestImageCenter {

    public static void main(String[] args) {
        ImageIcon icon = new ImageIcon(TestImageCenter.class.getResource("/resources/images/ooooo.png"));
        JLabel iconLabel = new JLabel(icon);
        JPanel iconPanel = new JPanel(new GridBagLayout());
        iconPanel.add(iconLabel);

        JPanel textPanel= new JPanel(new GridLayout(0, 1));
        for (int i = 0; i < 15; i++) {
            textPanel.add(new JLabel("Hello, StackOverfkow"));
        }

        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.add(textPanel);
        mainPanel.add(iconPanel, BorderLayout.WEST);
        JOptionPane.showMessageDialog(null, mainPanel, "Center Image Dialog", JOptionPane.PLAIN_MESSAGE);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top