简体   繁体   中英

Java. Resize issue on a JPanel

The following code snippet allows me to place a JTextfield and 2 JButtons on a JPanel using BorderLayout Manager.

        JPanel strPanel = new ButtonPanel();
        strPanel.setLayout(new BorderLayout());
        setBorder( new EmptyBorder( 3, 3, 3, 3 ) );

        strfield = new JTextField("",70);
        strPanel.add("West", strfield);
        strPanel.add("Center", btnCopy);
        strPanel.add("East", btnPaste);
        add("North", strPanel);

Here is a screenshot

在此处输入图片说明

However, the kicker is that when I resize my JFrame the 'copy' button is enlarged but I would like the JTextField to be enlarged instead with the copy and paste buttons remaining the same size. Here is an updated screenshot:

在此处输入图片说明

To try and fix it I downloaded NetBeans etc and played with the GUI designer but I can't solve it, even using different layout managers.

Can someone shed some light? Thanks

BorderLayout isn't cut out for this task since it gives all the left over space to the CENTER component. If you can change layout to GridBagLayout it's simple to give the leftmost component all the left over space.

Example:

public static void main(String[] args) {

    JFrame frame = new JFrame("Test");
    frame.setLayout(new GridBagLayout());

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = GridBagConstraints.BOTH;
    gbc.weightx = 1;

    frame.add(new JTextArea("Hello World!"), gbc);

    gbc.weightx = 0;
    frame.add(new JButton("Copy"), gbc);
    frame.add(new JButton("Paste"), gbc);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

If you really want to use BorderLayout , you can group the buttons together and add them to the east, adding the text field to the center, do something like this:

public static void main(String[] args) {

    JFrame frame = new JFrame("Test");

    frame.add(new JTextArea("Hello World!"), BorderLayout.CENTER);
    frame.add(new JPanel(new GridLayout(1, 0)) {{
        add(new JButton("Copy"));
        add(new JButton("Paste"));
    }}, BorderLayout.EAST);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM