I'm currently working on a browser in Java. I want to have a back button on the top left and to its right a JTextfield with the URL. I want the button to always have the same size but the textfield to change it's width to match the JFrame's width. It doesn't work with BorderLayout and I've tried this:

SpringLayout sl = new SpringLayout();
setLayout(sl);
sl.putConstraint(SpringLayout.WEST, back, 5, SpringLayout.WEST, this);
sl.putConstraint(SpringLayout.NORTH, back, 5, SpringLayout.NORTH, this);
sl.putConstraint(SpringLayout.WEST, addressBar, 5, SpringLayout.EAST, back);
sl.putConstraint(SpringLayout.NORTH, addressBar, 5, SpringLayout.NORTH, this);
sl.putConstraint(SpringLayout.SOUTH, back, 25, SpringLayout.NORTH, this);
sl.putConstraint(SpringLayout.SOUTH, addressBar, 25, SpringLayout.NORTH, this);
sl.putConstraint(SpringLayout.EAST, addressBar, 5, SpringLayout.EAST, this);

add(back);
add(addressBar);

where "back" is a JButton and addressBar a JTextField. The button seems to work but the addressBar just doen't draw at all.

Any suggestions?

有帮助吗?

解决方案

There are many ways to solve this, and one in fact involves BorderLayout by nesting JPanels. Put the button into a BorderLayout.WEST position of a BorderLayout using container, but the JTextField BorderLayout.CENTER in the same container, and then put that container into the main container BorderLayout.CENTER.

GridBagLayout could also solve this, but again, often the best/simplest solution will involve nesting JPanels (for your containers), each with its own layout manager.


Edit
For example:

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.*;

public class BrowserFoo {

   private static void createAndShowGui() {
      JPanel topPanel = new JPanel(new BorderLayout(2, 2));
      topPanel.add(new JButton("Back"), BorderLayout.WEST);
      topPanel.add(new JTextField(20), BorderLayout.CENTER);

      JPanel mainPanel = new JPanel(new BorderLayout());
      mainPanel.add(topPanel, BorderLayout.NORTH);
      mainPanel.add(Box.createRigidArea(new Dimension(400, 400)));

      JFrame frame = new JFrame("BrowserFoo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Note that if you re-size this GUI, the textarea and button remain in proper location.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top