Martin Nemeth
Martin Nemeth

Reputation: 679

Java: Changing jLabel foreground color

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

Upvotes: 3

Views: 32636

Answers (5)

Rodrigo Matias
Rodrigo Matias

Reputation: 430

I create a simple app to show the way to change the label components through the mouse event. In the button, I added a mouse listener which is a inner class that implements MouseListener interface. In complement to that, I implement two methods: mouseExited and mouseEntered. The first method, I use to show the initial state of the label come back the original state when the mouse exit the button area. The second method present the label changes when the mouse is on button area.

I hope it helps you or someone more.

public class MouseChangeLabel {

    private JFrame frame;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MouseChangeLabel window = new MouseChangeLabel();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public MouseChangeLabel() {
        initialize();
    }

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(0, 0, 200, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JLabel lblLabel1 = new JLabel("Label 1 without Panel");
        lblLabel1.setHorizontalAlignment(SwingConstants.CENTER);
        lblLabel1.setBounds(30, 10, 150, 30);
        lblLabel1.setForeground(Color.BLACK);
        frame.getContentPane().add(lblLabel1);

        JButton btnButton = new JButton("Button 1");
        btnButton.setBounds(30, 50, 150, 30);
        btnButton.addMouseListener(new MouseListener() {

            @Override
            public void mouseReleased(MouseEvent e) {
                // TODO Auto-generated method stub
            }

            @Override
            public void mousePressed(MouseEvent e) {
                // TODO Auto-generated method stub
            }

            @Override
            public void mouseExited(MouseEvent e) {
                // TODO Auto-generated method stub
                lblLabel1.setForeground(Color.BLACK);
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                // TODO Auto-generated method stub
                lblLabel1.setForeground(Color.RED);     
            }

            @Override
            public void mouseClicked(MouseEvent e) {
                // TODO Auto-generated method stub
            }
        });
        frame.getContentPane().add(btnButton);
    }
}

Upvotes: 0

Kishan Bheemajiyani
Kishan Bheemajiyani

Reputation: 3439

Well no need to do that much lengthy Code you have one simple and desired Option of using Mouse Entered event. as follows

private void jMenu1MouseEntered(java.awt.event.MouseEvent evt) {                                    


        this.jMenu1.setBackground(Color.red);
        this.jMenu1.setForeground(Color.red);
        System.out.println("Mouse Entered in Manu 1");
    }

this will help.

Upvotes: 0

Andrew Thompson
Andrew Thompson

Reputation: 168825

Seems to work just fine here.

Nimbus Label Color

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

public class NimbusLabelColor {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                try {
                    for ( UIManager.LookAndFeelInfo info : 
                            UIManager.getInstalledLookAndFeels()) {
                        if ("Nimbus".equals(info.getName())) {
                            System.out.println("Nimbus found!");
                            UIManager.setLookAndFeel(info.getClassName());
                            break;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                JPanel gui = new JPanel(new GridLayout(3,1,2,2));

                MouseAdapter adapter = new MouseAdapter() {
                    @Override
                    public void mouseEntered(MouseEvent me) {
                        Object c = me.getSource();
                        // do with extreme caution
                        JLabel l = (JLabel)c;
                        l.setForeground(Color.RED);
                    }

                    @Override
                    public void mouseExited(MouseEvent me) {
                        Object c = me.getSource();
                        // do with extreme caution
                        JLabel l = (JLabel)c;
                        l.setForeground(Color.BLUE);
                    }
                };

                for (int ii=0; ii<3; ii++) {
                    JLabel l = new JLabel("Float Me!");
                    l.addMouseListener(adapter);
                    gui.add(l);
                }

                JOptionPane.showMessageDialog(null, gui);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        SwingUtilities.invokeLater(r);
    }
}

Upvotes: 4

Martin Nemeth
Martin Nemeth

Reputation: 679

I am developing it in netbeans, which means, when I created my jFrame form, there already was some pre-generated code in there. Here it is:

import java.awt.Color;
import java.awt.Component;
import javax.swing.ImageIcon;
import javax.swing.JLabel;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
 *
 * @author Svist
 */
public class OsvetlenieForm extends javax.swing.JFrame {

/**
 * Creates new form OsvetlenieForm
 */
public OsvetlenieForm() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jLabel5 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jButton4 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jButton5 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Osvetlenie");
    setMinimumSize(new java.awt.Dimension(900, 600));
    setResizable(false);
    getContentPane().setLayout(null);

    jLabel5.setFont(new java.awt.Font("Tunga", 0, 18)); // NOI18N
    jLabel5.setForeground(new java.awt.Color(255, 255, 255));
    jLabel5.setText("Pohodlie");
    getContentPane().add(jLabel5);
    jLabel5.setBounds(10, 320, 60, 20);

    jLabel4.setFont(new java.awt.Font("Tunga", 0, 18)); // NOI18N
    jLabel4.setForeground(new java.awt.Color(255, 255, 255));
    jLabel4.setText("Bezpecnost");
    getContentPane().add(jLabel4);
    jLabel4.setBounds(10, 280, 90, 20);

    jLabel3.setFont(new java.awt.Font("Tunga", 0, 18)); // NOI18N
    jLabel3.setForeground(new java.awt.Color(255, 255, 255));
    jLabel3.setText("Kúrenie");
    getContentPane().add(jLabel3);
    jLabel3.setBounds(10, 240, 70, 20);

    jLabel2.setFont(new java.awt.Font("Tunga", 0, 18)); // NOI18N
    jLabel2.setForeground(new java.awt.Color(55, 117, 121));
    jLabel2.setText("Osvetlenie");
    getContentPane().add(jLabel2);
    jLabel2.setBounds(10, 200, 80, 14);

    jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/nic.png"))); // NOI18N
    jButton4.setBorder(null);
    jButton4.setBorderPainted(false);
    jButton4.setContentAreaFilled(false);
    jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseEntered(java.awt.event.MouseEvent evt) {
            jButton4MouseEntered(evt);
        }
        public void mouseExited(java.awt.event.MouseEvent evt) {
            jButton4MouseExited(evt);
        }
    });
    getContentPane().add(jButton4);
    jButton4.setBounds(0, 310, 180, 40);

    jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/nic.png"))); // NOI18N
    jButton3.setBorder(null);
    jButton3.setBorderPainted(false);
    jButton3.setContentAreaFilled(false);
    jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseEntered(java.awt.event.MouseEvent evt) {
            jButton3MouseEntered(evt);
        }
        public void mouseExited(java.awt.event.MouseEvent evt) {
            jButton3MouseExited(evt);
        }
    });
    getContentPane().add(jButton3);
    jButton3.setBounds(0, 270, 180, 40);

    jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/nic.png"))); // NOI18N
    jButton5.setBorder(null);
    jButton5.setBorderPainted(false);
    jButton5.setContentAreaFilled(false);
    jButton5.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseEntered(java.awt.event.MouseEvent evt) {
            jButton5MouseEntered(evt);
        }
        public void mouseExited(java.awt.event.MouseEvent evt) {
            jButton5MouseExited(evt);
        }
    });
    getContentPane().add(jButton5);
    jButton5.setBounds(0, 190, 177, 39);

    jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/nic.png"))); // NOI18N
    jButton2.setBorder(null);
    jButton2.setBorderPainted(false);
    jButton2.setContentAreaFilled(false);
    jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseEntered(java.awt.event.MouseEvent evt) {
            jButton2MouseEntered(evt);
        }
        public void mouseExited(java.awt.event.MouseEvent evt) {
            jButton2MouseExited(evt);
        }
    });
    getContentPane().add(jButton2);
    jButton2.setBounds(0, 230, 177, 39);

    jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/menu.jpg"))); // NOI18N
    getContentPane().add(jLabel1);
    jLabel1.setBounds(0, 0, 900, 600);

    pack();
    java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    java.awt.Dimension dialogSize = getSize();
    setLocation((screenSize.width-dialogSize.width)/2,(screenSize.height-dialogSize.height)/2);
}// </editor-fold>

private void jButton2MouseEntered(java.awt.event.MouseEvent evt) {
   jButton2.setIcon(new ImageIcon(getClass().getResource("resources/menu2.png")));


}

private void jButton2MouseExited(java.awt.event.MouseEvent evt) {
    jButton2.setIcon(new ImageIcon(getClass().getResource("resources/nic.png")));
}

private void jButton3MouseEntered(java.awt.event.MouseEvent evt) {
    jButton3.setIcon(new ImageIcon("src/menu_over.png"));
}

private void jButton3MouseExited(java.awt.event.MouseEvent evt) {
    jButton3.setIcon(new ImageIcon("src/menu2.png"));
}

private void jButton4MouseEntered(java.awt.event.MouseEvent evt) {
    jButton4.setIcon(new ImageIcon("src/menu_over.png"));
}

private void jButton4MouseExited(java.awt.event.MouseEvent evt) {
    jButton4.setIcon(new ImageIcon("src/menu2.png"));
}

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

private void jButton5MouseExited(java.awt.event.MouseEvent evt) {
     jButton5.setIcon(new ImageIcon(getClass().getResource("resources/nic.png")));
}

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /*
     * Set the Nimbus look and feel
     */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /*
     * If Nimbus (introduced in Java SE 6) is not available, stay with the
     * default look and feel. For details see
     * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(OsvetlenieForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(OsvetlenieForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(OsvetlenieForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(OsvetlenieForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /*
     * Create and display the form
     */
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new OsvetlenieForm().setVisible(true);
        }
    });
}
// Variables declaration - do not modify
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
// End of variables declaration

private static class ComponentImpl extends Component {

    public ComponentImpl() {
    }
}
}

I have one "icon" picture for my buttons. I want this code to change "icon" image of my buttons, when "MouseEntered" (this works nice), and in the same time change text color of my "jLabel1", which is "foreground(color)" parameter. (This part isnt working).

Upvotes: -1

Weibo
Weibo

Reputation: 1042

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.

Upvotes: 4

Related Questions