Java: Changing jLabel foreground color

Martin Nemeth picture Martin Nemeth · Dec 24, 2012 · Viewed 29.4k times · Source

I am developing app in netbeans. I have some buttons which I want to change on mouse event (MouseEntered,...) On MouseEntered i have following code:

private void jButton5MouseEntered(java.awt.event.MouseEvent evt) {
      jButton5.setIcon(new ImageIcon(getClass().getResource("resources/menu2.png")));
       jLabel1.setForeground(Color.RED);
}

I want it to change icon of that button and I also want to change foreground color of my jLabel1. I have problem with that jLabel1. It wont change. Why? Thank you

Answer

Weibo picture Weibo · Dec 24, 2012
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class Main extends JFrame {
JLabel label1;
JLabel label2;
public Main() {
    super("JLabel Demo");
    setSize(600, 100);

    JPanel content = new JPanel(new BorderLayout());

    label1 = new JLabel("Java2s");
    label1.setFont(new Font("Helvetica", Font.BOLD, 18));
    label1.setOpaque(true);
    label1.setBackground(Color.white);
    content.add(label1, BorderLayout.WEST);

    ImageIcon image = new ImageIcon(getClass().getResource("items.gif"));
    label2 = new JLabel("Java2s", image, SwingConstants.RIGHT);
    label2.setVerticalTextPosition(SwingConstants.TOP);
    label2.setOpaque(true);
    label2.setBackground(Color.white);
    content.add(label2, BorderLayout.CENTER);

    JButton btn = new JButton("Change");
    btn.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {
            label1.setForeground(Color.RED);
            label2.setIcon(new ImageIcon(getClass().getResource("menu_arrow.gif")));
        }

    });
    content.add(btn, BorderLayout.EAST);

    getContentPane().add(content);
    setVisible(true);
}

public static void main(String args[]) {
    new Main();
}
}

please try above code, the layout is not good looking, but I think this can resolve your issue.