java - 在 JPanel 调整大小上使用 GroupLayout 将 JButtons 保持在 JPanel 中心的最佳方法是什么

标签 java swing grouplayout

我最初花了相当多的时间试图通过用鼠标捕获右下角并拖动来调整对话框大小时调整 JPanel 的大小。我想我已经解决了这个问题,但现在无法让按钮保持居中。我已经包含了一些精简的代码,并且拉出了其他面板(我使用 JLayeredPane 因为有 5 个面板,而不仅仅是显示的面板)。如果我在 StackOverFlow 上的其他地方使用 JLabel,我看到了对此的修复,但还无法解决这个问题。任何帮助,将不胜感激。看来我一定错过了一些非常简单的东西。这是我的第一篇文章,所以我希望您能容忍任何格式错误。谢谢....

import java.awt.Color;
import java.awt.Component;
import java.util.logging.Logger;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class mock2Dialog extends JDialog {


private static final long serialVersionUID = 1L;
public static int BUTTON_UNKNOWN = -1;
public static int BUTTON_NO = 1;
public static int BUTTON_YES = 0;

public static int DIALOG_TYPE_YES_NO = 1;

int buttonClicked = BUTTON_UNKNOWN;
int dialogType = 1;
Logger logger = null;

public mock2Dialog() {
    }

public mock2Dialog(java.awt.Frame parent, boolean modal, String title,
        int dialogType, Logger logger) {
    super(parent, modal);
    this.logger = logger;
    this.dialogType = dialogType;
    initComponents(); 
    this.setTitle(title);
    buttonClicked = BUTTON_UNKNOWN;

    getYesButton().setFocusTraversalKeysEnabled(false);
    getNoButton().setFocusTraversalKeysEnabled(false);

    getYesNoPanel().setVisible(false);

    getYesButton().setVisible(false);
    getNoButton().setVisible(false);

    onOpen(this); //this fakes out the system so I can execute from this file       

}//EOM

public void onOpen(Component caller) {
    setLocationRelativeTo(caller);
    prepareOnOpen();
}//EOM

public void prepareOnOpen() {
    getYesNoPanel().setVisible(false);
    getYesButton().setVisible(false);
    getNoButton().setVisible(false);

    if (dialogType == DIALOG_TYPE_YES_NO) {
        getYesNoPanel().setVisible(true);
        getYesButton().setVisible(true);
        getNoButton().setVisible(true);
    } 

    buttonClicked = BUTTON_UNKNOWN;
    if (dialogType == DIALOG_TYPE_YES_NO) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                yesButton.requestFocusInWindow();
            }
        });

    }
    this.setVisible(true);
} //EOM


private void initComponents() {

    msgScrollPane = new JScrollPane();
    msgTextArea = new JTextArea();
    jLayeredPane1 = new JLayeredPane(); //no LayoutManager specified by design of component
    yesNoPanel = new JPanel();
    yesButton = new JButton();
    noButton = new JButton();


    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Message");

    //msgScrollPane
    msgScrollPane.setBorder(null);

    //msgTextArea
    msgTextArea.setColumns(20);
    msgTextArea.setEditable(false);
    msgTextArea.setFont(new java.awt.Font("Verdana", 0, 14));
    msgTextArea.setRows(5);
    msgTextArea.setWrapStyleWord(true);
    msgTextArea.setBorder(javax.swing.BorderFactory.createEtchedBorder());
    msgTextArea.setOpaque(false);
    msgScrollPane.setViewportView(msgTextArea);

    //YesNoPanel
    yesNoPanel.setBackground(Color.BLUE);
    yesButton.setText("Yes");
    yesButton.setName("yesButton");
    //yesButton.setAlignmentX(CENTER_ALIGNMENT); //thought this might work to center the button within the panel

    noButton.setText("No");
    noButton.setName("noButton");
    //noButton.setAlignmentX(CENTER_ALIGNMENT); //thought this might work to center the button within the panel

    GroupLayout yesNoPanelLayout = new GroupLayout(
            yesNoPanel);
    yesNoPanel.setLayout(yesNoPanelLayout);
    yesNoPanelLayout
            .setHorizontalGroup(yesNoPanelLayout
                    .createParallelGroup(
                            javax.swing.GroupLayout.Alignment.LEADING) //Center doesn't seem to change behaviour
                    .addGroup(
                            yesNoPanelLayout
                                    .createSequentialGroup()
                                    .addGap(146, 146, 146)
                                    .addComponent(yesButton)
                                    .addPreferredGap(
                                            javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(noButton)
                                    .addContainerGap(147, Short.MAX_VALUE)));
    yesNoPanelLayout
            .setVerticalGroup(yesNoPanelLayout
                    .createParallelGroup(
                            javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(
                            yesNoPanelLayout
                                    .createSequentialGroup()
                                    .addContainerGap()
                                    .addGroup(
                                            yesNoPanelLayout
                                                    .createParallelGroup(
                                                            javax.swing.GroupLayout.Alignment.LEADING)
                                                    .addComponent(yesButton)
                                                    .addComponent(noButton))
                                    .addContainerGap(
                                            javax.swing.GroupLayout.DEFAULT_SIZE,
                                            Short.MAX_VALUE)));

    yesNoPanel.setBounds(0, 0, Short.MAX_VALUE, 50); //setting Short.MAX_VALUE will allow the panel to expand.
    jLayeredPane1.add(yesNoPanel, javax.swing.JLayeredPane.DEFAULT_LAYER);


    //main layout for the dialog
    GroupLayout layout = new GroupLayout(
            getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(layout
            .createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(
                    layout.createSequentialGroup()
                            .addComponent(jLayeredPane1,
                                    GroupLayout.DEFAULT_SIZE,
                                    GroupLayout.DEFAULT_SIZE, //400,
                                    Short.MAX_VALUE)
                            .addGap(0, 0, 0))
            .addGroup(
                    layout.createSequentialGroup()
                            .addGap(12, 12, 12)
                            .addComponent(msgScrollPane,
                                    GroupLayout.DEFAULT_SIZE,
                                    376, 
                                    Short.MAX_VALUE).addContainerGap()));
    layout.setVerticalGroup(layout
            .createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(
                    GroupLayout.Alignment.TRAILING,
                    layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(msgScrollPane,
                                    GroupLayout.DEFAULT_SIZE,
                                    106, Short.MAX_VALUE)
                            .addPreferredGap(
                                    javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jLayeredPane1,
                                    GroupLayout.PREFERRED_SIZE,
                                    50,
                                    GroupLayout.PREFERRED_SIZE)));

    pack();
} 

private JLayeredPane jLayeredPane1;
private JScrollPane msgScrollPane;
private JTextArea msgTextArea;
private JButton noButton;
private JButton yesButton;
private JPanel yesNoPanel;

public javax.swing.JScrollPane getMsgScrollPane() {
    return msgScrollPane;
}

public void setMsgScrollPane(javax.swing.JScrollPane msgScrollPane) {
    this.msgScrollPane = msgScrollPane;
}

public javax.swing.JTextArea getMsgTextArea() {
    return msgTextArea;
}

public void setMsgTextArea(javax.swing.JTextArea msgTextArea) {
    this.msgTextArea = msgTextArea;
}

public String getMsgText() {
    return this.msgTextArea.getText();
}

public void setMsgText(String msgText) {
    this.msgTextArea.setText(msgText);
    msgTextArea.setCaretPosition(0);
    msgScrollPane.getVerticalScrollBar().setValue(0);
}

public javax.swing.JButton getNoButton() {
    return noButton;
}

public void setNoButton(javax.swing.JButton noButton) {
    this.noButton = noButton;
}

public javax.swing.JButton getYesButton() {
    return yesButton;
}

public void setYesButton(javax.swing.JButton yesButton) {
    this.yesButton = yesButton;
}

public javax.swing.JPanel getYesNoPanel() {
    return yesNoPanel;
}

public void setYesNoPanel(javax.swing.JPanel yesNoPanel) {
    this.yesNoPanel = yesNoPanel;
}


public static void main(String args[]) {
    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            Logger logger = null;
            int dialogType = 1;
            String title = "Mock Dialog";
            mock2Dialog dialog = new mock2Dialog(
                    new javax.swing.JFrame(), false, title, dialogType,
                    logger);
            dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                @Override
                public void windowClosing(java.awt.event.WindowEvent e) {
                    System.exit(0);
                }
            }); //nested a method in another methods arguments                          

            dialog.setVisible(true);
            dialog.msgTextArea
                    .setText(" Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam sit amet fringilla nunc.\n "
                            + "Duis sem nulla, egestas vel elit vitae, pulvinar semper nunc. Nam in nisi quis turpis pellentesque pulvinar. \n"
                            + "Nulla facilisi. Pellentesque ac rhoncus ante. Mauris ut magna nibh. Ut eget dapibus diam, sed iaculis erat. "
                            + "Vestibulum faucibus neque nisl, non imperdiet libero elementum sed. Fusce molestie eros id ligula consectetur ultrices.");
        }
    });

}
} 

最佳答案

我发现 GroupLayout 适合手动编码,当然不比 GridBagLayout 难,尽管我当然可以理解为什么它会成为工具的最爱。但它的目的是将内容放入列和行中,而不是用于使按钮居中。您使用了错误的布局管理器。

要将面板放置在您希望用户能够调整大小的屏幕中央(这应该是默认布局),您可以将面板放置在 BorderLayout 的 BorderLayout.CENTER 中(这是默认布局) JFrame 上的管理器)。现在,默认情况下,面板也会拉伸(stretch)以适合框架,除非您还在 BorderLayout 的北、南、东和/或西部分中放置了一些内容。这是否适合您取决于您​​正在做什么。

我还了解您可以将要居中的面板放入 GridBagLayout 中,其中没有其他内容,这样就会使其居中。这不是我的方法,但为了完整性我提及它。

如果您希望一组按钮保持居中,请首先为面板选择一个布局管理器来容纳按钮 - 网格布局仅在您希望按钮大小相同时才有效,您可以使用 GropuLayout 来放置它们在行和列中,BoxLayout 可以水平放置一串按钮或垂直堆叠它们。

然后,您可以将该面板放入具有不同布局的另一个面板中 - 例如,在 BorderLayout 的南部分 - 以使它们水平居中,或将它们放在 BorderLayout 的西部分中以垂直居中。这就是 rcamrick 在提到“嵌套面板”时所谈论的内容。

关于java - 在 JPanel 调整大小上使用 GroupLayout 将 JButtons 保持在 JPanel 中心的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20557378/

相关文章:

Java GroupLayout 实现

java - 无法从 Mac OS X 上的后台 Java 应用程序监视系统剪贴板更改

java - 保留单词之间的空格java

java - HIbernate 搜索不返回主键搜索结果

java - Swing - 从面板内部调用事件

java - 如何在java中的jPanel中绘图时删除所有线条?

java - JFrame 重绘();如何使用线程信息更新 JFrame?

java - JFrame/JPanel 未以组布局显示

java - 如何使用 GroupLayout 组织 2x2 自动调整大小的网格

java - Android 收不到广播