简体   繁体   English

Center JOptionPane图标

[英]Center JOptionPane icon

I have a JOptionPane with a lot of text on it... which stretches it taller than wide. 我有一个JOptionPane,上面有很多文字...延伸得比宽高。 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. 无需修改图像。

  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). 将图像包装在JLabel的图标上,然后使用GridBagLayout将标签包装在JPanel (此布局将使图像/标签居中)。

  2. Create another JPanel with a BorderLayout , adding the image panel to the WEST and the text component to the CENTER 使用BorderLayout创建另一个JPanel ,将图像面板添加到WEST并将文本组件添加到CENTER

  3. Add just that JPanel from 2 to to the JOptionPane. 只需将JPanel从2添加到JOptionPane.


Example

在此处输入图片说明

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM