什么是在JPanel调整大小时使用GroupLayout将JButton置于JPanel中心的最佳方法

时间:2013-12-13 01:08:34

标签: 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.");
        }
    });

}
} 

1 个答案:

答案 0 :(得分:1)

我发现GroupLayout可以手工编写代码,当然不会比GridBagLayout更难,但我当然可以理解为什么它会成为使用工具的最爱。但它用于将事物放入列和行中,而不是用于居中按钮。你有错误的布局管理器。

要将面板放在您希望用户能够调整大小的屏幕中央(这应该是默认值),您可以将面板放在BorderLayout的BorderLayout.CENTER中(这是默认布局) jFrame经理)。现在,默认情况下,除非您还在BorderLayout的NORTH,SOUTH,EAST和/或WEST部分放置了一些内容,否则面板也会拉伸以适合框架。这对你有用取决于你正在做什么。

我也理解你可以将面板置于GridBagLayout中心,其中没有任何其他东西,并且它将使其居中。这不是我的方法,但我提到它是完整的。

如果你想让一组按钮保持居中,首先选择面板的布局管理器来保持按钮 - 网格布局只有在你想要按钮尺寸相同的情况下才有效,你可以使用GropuLayout来放置它们在行和列中,BoxLayout可以水平放置一串按钮或垂直堆叠。

然后你可以把THAT面板放到另一个具有不同布局的面板中 - 例如,在BorderLayout的SOUTH部分 - 将它们水平居中,或者将BorderLayout的WEST部分垂直居中。这就是rcamrick在提到“嵌套面板”时所说的话。