Question

I try to order my elements with Borderlayout since Gridlayout makes everything the same size.

What I see is this: what i see while manually resizing it, I can have the following what I want to see

Here's part of my code

public InputPanel() {

    tfield = new TextField("Search your terms here!");
    add(tfield, BorderLayout.PAGE_START);

    searchButton = new JButton("Search");
    searchButton.addActionListener(this);
    add(searchButton, BorderLayout.LINE_START);

    clearButton = new JButton("Clear Text");
    clearButton.addActionListener(this);
    add(clearButton, BorderLayout.LINE_END);

    resultsArea = new TextArea();
    add(resultsArea, BorderLayout.PAGE_END);
}

It seems like it does not help in arranging. It's just like I have used FlowLayout.

How can I format it properly?

Was it helpful?

Solution

For BorderLayout you should be using NORTH, SOUTH, EAST, WEST and CENTER to place your components. To achive the above layout, you should create one panel that has FLOWLAYOUT, where you add the textfield, seachbutton and clear button. This panel will then be placed inside BorderLayout.NORTH. After this you place the JTextArea inside BorderLayout.NORTH

public InputPanel() {

    JPanel topPanel = new JPanel(); // Create a new panel
    topPanel.setLayout(FlowLayout()); //Left to right alignment is default for FlowLayout

    //Add your textfield and buttons to the panel with flowlayout
    tfield = new TextField("Search your terms here!");  
    topPanel.add(tfield);

    searchButton = new JButton("Search");
    searchButton.addActionListener(this);
    topPanel.add(searchButton);

    clearButton = new JButton("Clear Text");
    clearButton.addActionListener(this);
    topPanel.add(clearButton);

    add(topPanel, BorderLayout.NORTH); // Add the panel containing the buttons and textfield in the north

    resultsArea = new TextArea();
    add(resultsArea, BorderLayout.CENTER); //Add the textarea in the Center

}

This gives me the below appearance: enter image description here

OTHER TIPS

Seems you have missed GridBagLayout, which is the number one choice for a truly flexible layout manager. With BorderLayout you can also achieve a lot, but only with many levels of nesting, and the code to build it is quite unmanageable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top