在 JPanel 调整大小时使用 GroupLayout 使 JButton 在 JPanel 中保持居中的最佳方法是什么



当对话框通过鼠标抓住右下角并拖动来重新调整大小时,我最初花了很多时间试图重新调整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(JFrame上的默认布局管理器)的BorderLayout.center中。现在,默认情况下,面板也将拉伸以适合框架,除非您还在BorderLayout的NORTH、SOUTH、EAST和/或WEST部分放置了一些东西。这是否对你有效取决于你在做什么。

我也知道你可以把面板放在GridBagLayout的中心,里面没有其他东西,这会使它居中。这不是我的方法,但我提到它是为了完整性。

如果你想让一组按钮保持居中,首先为一个面板选择一个布局管理器来放置按钮——只有当你想让按钮大小相同时,网格布局才能工作,你可以使用GropuLayout将它们放在行和列中,BoxLayout可以水平放一串按钮或垂直堆叠按钮。

然后,您可以将该面板放入另一个具有不同布局的面板中,例如,在BorderLayout的SOUTH部分,以水平居中,或在Border布局的WEST部分,以垂直居中。这就是rcamrick在提到"嵌套面板"时所说的。

相关内容

  • 没有找到相关文章

最新更新