JDialog - "line break" 在组件之间

JDialog - "line break" in between components

我有一个如下所示的 JDialog:

JDialog myDialog = new JDialog();

myDialog.setLocationRelativeTo(parent); 
// parent is a JPanel. 
// I want the Dialog to appear in the middle of the parent JPanel.

myDialog.setModal(true);
myDialog.setLayout(new FlowLayout());
myDialog.add(new JLabel("my text", SwingConstants.CENTER));
myDialog.add(new JButton("button 1"));
myDialog.add(new JButton("button 2"));
myDialog.pack();
myDialog.setVisible(true);

结果是一个对话框,其中 JLabel 和 JButton 彼此相邻显示。

1) 在 JLabel 后面做一个 "line break" 最方便的方法是什么,这样 JButton 出现在 JLabel 下面,而不用 [=] 15=]?我希望自动确定尺寸,以便组件完全适合,就像 pack().

所做的那样

2) 当我设置自定义大小时,对话框会出现在我想要的位置:parentmyDialog 的中间匹配。但是,如果我改用 pack(),则 myDialog 的左上角位于父级的中间。使中间匹配的最佳方法是什么?

  1. 嵌套 JPanel,每个都使用自己的布局管理器
  2. 在 调用 pack() 之后调用 setLocationRelativeTo(parent) 。您需要在渲染后定位 window。

例如:

import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class SimpleGuiPanel extends JPanel {
    private static final String TITLE = "This is my Dialog Title";

    public SimpleGuiPanel() {
        JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
        titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 16f));

        JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 5));
        buttonPanel.add(new JButton("Button 1"));
        buttonPanel.add(new JButton("Button 2"));

        setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        setLayout(new BorderLayout(5, 5));
        add(titleLabel, BorderLayout.PAGE_START);
        add(buttonPanel, BorderLayout.CENTER);
    }

    private static void createAndShowGui() {
        JPanel mainFramePanel = new JPanel();
        mainFramePanel.setPreferredSize(new Dimension(500, 400));
        final JFrame mainFrame = new JFrame("Main Frame");
        mainFrame.add(mainFramePanel);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        SimpleGuiPanel simpleGuiPanel = new SimpleGuiPanel();
        final JDialog myDialog = new JDialog(mainFrame, "Dialog", ModalityType.APPLICATION_MODAL);
        myDialog.getContentPane().add(simpleGuiPanel);
        myDialog.pack();

        mainFramePanel.add(new JButton(new AbstractAction("Show Dialog") {

            @Override
            public void actionPerformed(ActionEvent e) {
                myDialog.setLocationRelativeTo(mainFrame);
                myDialog.setVisible(true);
            }
        }));

        mainFrame.pack();
        mainFrame.setLocationRelativeTo(null);
        mainFrame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}