opu opu - 1 year ago 86
Java Question

How to add Components into a JPanel

I Just want to add few components into a panel and set the panel background color.But I can't make it. Can anyone suggest me , how to do it?? Here is my Code.

public Multiple2() {

JPanel p1 = new JPanel();

lb1 = new JLabel("Enter the First Number: ");
lb1.setBounds(10, 10, 250, 20);

tf1 = new JTextField(100);
tf1.setBounds(155, 10, 400, 20);

lb2 = new JLabel("Enter the Second Number: ");
lb2.setBounds(10, 35, 250, 20);

tf2 = new JTextField(100);
tf2.setBounds(155, 35, 400, 20);


setSize(600, 400);

Answer Source

You appear to be trying to add p to the contentPane's BorderLayout.SOUTH location, but you've removed the contentPane's layout manager, and so it has no SOUTH location, and so you never see p1 anywhere.

To add components to the p1 JPanel, you need to use the add(...) method just as you're doing with the JFrame's contentPane. So instead of


You'd do:

p1. add(foo);

Then you'd possibly need to add the p1 JPanel to the contentPane's BorderLayout.CENTER position, and not use null layout.

While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.

For example:

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;

public class Mult2 extends JPanel {
    private JTextField field1 = new JTextField(10);
    private JTextField field2 = new JTextField(10);

    public Mult2() {
        setLayout(new GridBagLayout());

        add(new JLabel("Enter the First Number:"), createGbc(0, 0));
        add(field1, createGbc(1, 0));
        add(new JLabel("Enter the Second Number:"), createGbc(0, 1));
        add(field2, createGbc(1, 1));

        setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    private static GridBagConstraints createGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridheight = 1;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        int right = x % 2 == 0 ? 15 : 5;
        gbc.insets = new Insets(5, 5, 5, right);
        return gbc;

    private static void createAndShowGui() {
        Mult2 mainPanel = new Mult2();

        JFrame frame = new JFrame("Multiply");

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download