JDialog - 组件之间的“换行”

问题描述 投票:0回答:1

我有一个看起来像这样的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和JButtons彼此相邻。

1)在JLabel之后进行“换行”的最方便方法是什么,以便JButtons出现在JLabel下方,而不使用setSize()?我希望自动确定大小,以便组件完全匹配,就像pack()所做的那样。

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

java swing layout jpanel jdialog
1个回答
2
投票
  1. Nest JPanels,每个都使用自己的布局管理器
  2. 打电话给setLocationRelativeTo(parent)后打电话给pack()。您需要在渲染后定位窗口。

例如:

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());
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.