Adding components into JPanel inside a JFrame

42,810

Again, don't use null layout since it makes updating and maintaining your GUI much more difficult than it should be, and can lead to ugly GUI's if you plan on having them run on multiple platforms. Instead

  • Use several JPanels, each one holding a core group of components and each using its best layout manager
  • Nest these JPanels in other JPanels that use the best layout manager to display them
  • and that will allow your GUI to be resizeable without need of extra code.
  • Put your JTextAreas in JScrollPanes so that you can see all text even if it goes beyond the text area.
  • Never set the size of the JTextArea as that will not allow it to scroll. Instead set its columns and rows.

As a very simple example, run this to see what I mean:

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

public class FooSwing2 {
   public static void main(String[] args) {
      JTextArea chatArea = new JTextArea(8, 40);
      chatArea.setEditable(false);
      chatArea.setFocusable(false);
      JScrollPane chatScroll = new JScrollPane(chatArea);
      JPanel chatPanel = new JPanel(new BorderLayout());
      chatPanel.add(new JLabel("Chat:", SwingConstants.LEFT), BorderLayout.PAGE_START);
      chatPanel.add(chatScroll);

      JTextField inputField = new JTextField(40);
      JButton sendBtn = new JButton("Send");
      JPanel inputPanel = new JPanel();
      inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.LINE_AXIS));
      inputPanel.add(inputField);
      inputPanel.add(sendBtn);

      JPanel youLabelPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
      youLabelPanel.add(new JLabel("You:"));

      JPanel mainPanel = new JPanel();
      mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
      mainPanel.add(chatPanel);
      mainPanel.add(Box.createVerticalStrut(10));
      mainPanel.add(youLabelPanel);
      mainPanel.add(inputPanel);

      JFrame frame = new JFrame("Foo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.add(mainPanel);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}

This would result in a simple (non-functioning) GUI that looked like this:
enter image description here

Now say you want to change this and add another button, an "exit" JButton to the right of the send JButton. If you used null layout, you'd have to resize your GUI, you'd have to move the send button over to the left and make sure that your math was without error, etc. If you used layout managers, you'd need just two new lines of code (to change the display, not the functionality of course):

  JTextField inputField = new JTextField(40);
  JButton sendBtn = new JButton("Send");
  JButton exitBtn = new JButton("Exit"); // ***** added
  JPanel inputPanel = new JPanel();
  inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.LINE_AXIS));
  inputPanel.add(inputField);
  inputPanel.add(sendBtn);
  inputPanel.add(exitBtn);  // ***** added

That's it, and this would display:
enter image description here

Share:
42,810
Barışcan Kayaoğlu
Author by

Barışcan Kayaoğlu

Updated on July 09, 2022

Comments

  • Barışcan Kayaoğlu
    Barışcan Kayaoğlu almost 2 years

    Since im a beginner and i don't want to get involved with the layout managers, i was simply adding a JPanel into my main JFrame and giving spesific location to each component in the panel. But somehow the output appears way too wrong..

    frame = new JFrame(email + " (Offline)");
        frame.setSize(400, 400);
        frame.setLocation(0, 0);
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        frame.setLayout(new FlowLayout());
        frame.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                // out.println("BYE");
                // out.flush();
                frame.dispose();
                thread.stop();
            }
        });
        panel = new JPanel();
        frame.add(panel);
        chat = new JTextArea();
        chat.setSize(400, 200);
        chat.setLocation(0, 0);
        chat.setEditable(false);
        panel.add(chat);
        panel.validate();
        JLabel you = new JLabel("You:");
        you.setSize(you.getPreferredSize());
        you.setLocation(0, 210);
        panel.add(you);
        panel.validate();
        input = new JTextArea();
        input.setSize(200, 200);
        input.setLocation(0, 220 + chat.getSize().height);
        panel.add(input);
        panel.validate();
        send = new JButton("Send");
        send.setSize(send.getPreferredSize());
        send.setLocation(210, 220 + chat.getSize().height);
        panel.add(send);
        panel.validate();
        frame.setVisible(true);
    

    The outcome of this frame is that text areas are invisible, a You: label in the middle and next to the right of it the button.. What am i missing here?