2

I'm learning how to create application in Java.

I'm having trouble getting the JLabel to have a background color whilst the JPanel is white, behind it. Also, is there a way to resize the JPanel to half of what the JFrame is?

Any help would be very much appreciated. Thank you.


   package PracticeOne;

    import java.awt.BorderLayout;

    public class PracticeOne {

        public static void main(String[] args) {


            Frame container = new Frame();
            Panel box = new Panel();
            Label txt = new Label();

            box.add(txt);

            container.add(box, BorderLayout.CENTER);


        }

    }

package PracticeOne;

import javax.swing.JFrame;

public class Frame extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    Frame(){        
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.setSize(500, 500);

        this.setVisible(true);

        this.setLocationRelativeTo(null);

        this.setTitle("Testing this out");
    }

}

package PracticeOne;

import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;

public class Panel extends JPanel {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    public Dimension d = new Dimension(100,100);

    Panel(){
        this.setSize(d);
        this.setAlignmentX(CENTER_ALIGNMENT);
        this.setBackground(Color.WHITE);

    }



}

package PracticeOne;

import java.awt.Color;

import javax.swing.JLabel;

public class Label extends JLabel {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;



    Label(){
        this.setSize(50, 50);


        this.setText("ya boy is working here");
        this.setForeground(Color.BLACK);
        this.setBackground(Color.ORANGE);

    }
}
Abdirizak Obsiye
  • 265
  • 5
  • 7
  • 29
  • How big the JPanel is, is determined by two things 1) What layout manager you are using 2) What you have passed to panel.setPreferredSize. In some cases the preferred size won't effect anything depending on the layout in force. the use of setSize when a layout manager is in play does nothing. in your case since you are using BorderLayout, and only putting something in the CENTER, the JPanel will grow to the full size of the window. You might want to consider using JFrame.pack rather than setSize if you want the frame to be the size of the preferred size of the panel. – MeBigFatGuy Apr 03 '17 at 17:49

1 Answers1

5

I'm having trouble getting the JLabel to have a background color whilst the JPanel is white

You need to call setOpaque(true); in your JLabel

Also, is there a way to resize the JPanel to half of what the JFrame is?

You could use a GridLayout, and place 2 JPanels in it, that way, you're going to have 2 JPanels using half the size of your JFrame each.

Also, rename your classes, Panel belongs to the name of a class in AWT, same for Frame and Label, this might confuse your (and whoever reads your code).

Never extend JFrame, instead build your GUI based on JPanels. See extends JFrame vs creating it inside of class and The use of multiple JFrames, Good / Bad practice? The general consensus says it's bad.

Also you should also check Should I avoid the use of setPreferred|Maximum|MinimumSize() in Swing? Again, yes, you should and instead override the getPreferredSize() method.

Don't forget to place your program on the Event Dispatch Thread (EDT) by changing your main() method as follows:

public static void main(String[] args) {
    //Java 8 with lambda expressions
    SwingUtilities.invokeLater(() -> 
        //Your code here
    );
    //Java 7 and below (Or 8 without lambda expressions)
    SwingUtilities.invokeLater(new Runnable() {
        //Your code here
    });
}

Now, with all the above recommendations, your code should now look like this:

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class HalfSizePanelWithLabelInDifferentColor {

    private JFrame frame;
    private Container contentPane;
    private JPanel pane;
    private JPanel pane2;
    private JLabel label;

    private static final Dimension dim = new Dimension(100, 100);

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new HalfSizePanelWithLabelInDifferentColor().createAndShowGui());
    }

    public void createAndShowGui() {
        frame = new JFrame(getClass().getSimpleName());

        contentPane = frame.getContentPane();
        pane = new JPanel() {
            @Override
            public Dimension getPreferredSize() {
                return dim;
            }
        };

        pane2 = new JPanel();

        pane.setOpaque(false);
        pane2.setOpaque(false);

        pane.setBorder(BorderFactory.createLineBorder(Color.RED));
        pane2.setBorder(BorderFactory.createLineBorder(Color.BLUE));

        label = new JLabel("Hello World!");
        label.setBackground(Color.GREEN);
        label.setOpaque(true);

        contentPane.setLayout(new GridLayout(2, 1));

        pane.add(label);

        contentPane.add(pane);
        contentPane.add(pane2);

        contentPane.setBackground(Color.WHITE);

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

And your output would be like this:

enter image description here

Note that I added some colored borders to show where a pane starts and ends and where the other one starts and ends

Community
  • 1
  • 1
Frakcool
  • 10,915
  • 9
  • 50
  • 89