我有一个看起来像这样的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
之后进行“换行”的最便捷方式是什么,以便JButton
出现在JLabel
下方,而不使用setSize()
?我希望自动确定大小,以便组件完全匹配,就像pack()
所做的那样。
2)当我设置自定义尺寸时,对话框会显示在我想要的位置:parent
和myDialog
的中间位置匹配。但是,如果我改为使用pack()
,则myDialog
的左上角位于父级的中间位置。让middles匹配的最佳方法是什么?
答案 0 :(得分: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());
}
}