How do I set a JLabel's background color?
Use
label.setOpaque(true);
Otherwise the background is not painted, since the default of opaque
is false
for JLabel
.
From the JavaDocs:
If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.
For more information, read the Java Tutorial How to Use Labels.
JLabel.setBackground(Color color) doesn't work?
A component must be opaque for its background do be effective, a JLabel's default is false, so you have to set it:
label.setOpaque(true);
Java JLabel background color not working?
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 JPanel
s in it, that way, you're going to have 2 JPanel
s 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 JPanel
s. 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:
Note that I added some colored borders to show where a pane starts and ends and where the other one starts and ends
how to set color of multiple jlabel on click netbeans?
You could simply need to:
- Create 1 method which will handle what happens to a
JLabel
when clicked. - Use the
JPanel
's.getComponents()
to get all the components. - Use the
instance of
operator to ensure that the component is aJLabel
. - If the component is a
JLabel
, assign the method in1
as theclick
event handler.
In the event handler, then, simply do the same as above. The event itself should give you access to the source
, that is the component which triggered the event. You would simply need to do as follows:
- Iterate over the labels and set them to a green background.*
- Take the source of the event and set it to red.
*This can be improved by keeping a label which denotes the currently selected label. When a label is clicked, you would reset the background of that label and update it to show the new label which the user has clicked.
How to change JLabel background when I click the JLabel in Java
By default a JLabel is non-opaque so its background is not painted. You need to make the label opaque when you create it:
lblKembali = new JLabel("Kembali");
lblKembali.setOpaque( true );
Also you can make your listener more generic so it can be shared by multiple components by doing:
public void mouseClicked(MouseEvent e)
{
Component c = e.getComponent();
c.setBackground(Color.BLUE);
}
How to change JLabel's background color through mouse events?
e.getSource()
will return the label that is clicked, not the color of that label (in your example, anyway)
So, cast to a label:
JLabel theLabel = (JLabel) e.getSource();
then setBackground on it appropriately:
if (theLabel.getBackground().equals(Color.WHITE))
theLabel.setBackgound(...);
Java JLabel background color cant be changed using Netbeans
You'd need to set opaque to true
yourLabel.setOpaque(true);
(Or tick the opaque box in the label's properties in design view in NetBeans)
Cannot update JLabel background in Java
Here is a working demo that changes label color (also demonstrates what MCVE should look like):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class MainWindow extends JFrame {
private static final int WIDTH = 250, HEIGHT = 200;
private Color[] colors;
private int colorIndex = 0;
private JLabel redLabel;
public MainWindow() {
setSize(WIDTH, HEIGHT);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setColors();
JPanel mainPanel = new JPanel(new BorderLayout());
add(mainPanel);
redLabel = new JLabel("A Test Label");
redLabel.setBackground(colors[colorIndex]);
redLabel.setOpaque(true);
redLabel.setPreferredSize(new Dimension(100, 50));
mainPanel.add(redLabel, BorderLayout.NORTH);
JButton button = new JButton("Manual Color Change");
button.addActionListener( e-> changeColor() );
mainPanel.add(button, BorderLayout.SOUTH);
setVisible(true);
}
private void setColors() {
colors = new Color[] {
new Color(110, 110, 110),
Color.CYAN,
Color.RED,
Color.YELLOW
};
}
private void changeColor() {
colorIndex = ((colorIndex+1) >= colors.length) ? 0 : colorIndex+1;
redLabel.setBackground(colors[colorIndex]);
}
public static void main(String[] args) throws InterruptedException {
MainWindow win = new MainWindow();
//auto change color every 2 sec
new Timer(2000, e-> win.changeColor()).start();
}
}
Related Topics
Compare Two Objects in Java with Possible Null Values
Difference Between List and Array
"File Not Found" When Running New Libgdx Project
Does Java Support Inner/Local/Sub Methods
Which Artifacts Should I Use for Jaxb Ri in My Maven Project
How to See the Source Code of the Sun Jdk
Springboot - Making Jar Files - No Auto Configuration Classes Found in Meta-Inf/Spring.Factories
How to Find Out What Type Each Object Is in a Arraylist<Object>
Modifying Local Variable from Inside Lambda
Is This a Bug in Files.Lines(), or am I Misunderstanding Something About Parallel Streams
Java Outofmemoryerror Strange Behaviour
How to Stop a Scheduled Task That Was Started Using @Scheduled Annotation
Using Javafx in Jre 8, "Access Restriction" Error
Intellij Shows Method Parameter Hints on Usage - How to Disable It