Java: 改变 jLabel 的前景色

3

我正在使用NetBeans开发应用程序。我有一些按钮,我希望在鼠标事件(MouseEntered,...)上更改它们。在MouseEntered事件中,我有以下代码:

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

我希望更改那个按钮的图标,同时也想要更改我的jLabel1的前景色。但是我遇到了jLabel1无法更改的问题。为什么呢?谢谢。


3
在进行下一步操作之前,首先检查该方法是否被调用,可以在方法中加入System.out.println("Called"); 进行输出验证。如果被调用了,尝试调用repaint方法:(JFrame的名称).repaint(); - Name
你能展示一些更相关的代码吗?仅凭这些很难看出问题所在。 - Name
2
Javadocs:设置此组件的前景色。这取决于外观和感觉是否尊重此属性,有些可能选择忽略它。 - Brian Roach
3
repaint()不必要。 JLabel知道当其前景色更改时必须进行重绘。 - JB Nizet
5个回答

4
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();
}
}

请尝试上述代码,布局可能看起来不太好,但我认为这可以解决您的问题。

1
+1 好的。必读 http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html - vels4j
@vels4j 还有关于 JFrame 的内容:http://docs.oracle.com/javase/tutorial/uiswing/components/frame.html - Branislav Lazic

4

这里似乎一切正常。

Nimbus标签颜色

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);
    }
}

0
我创建了一个简单的应用程序,展示如何通过鼠标事件更改标签组件。在按钮中,我添加了一个实现MouseListener接口的内部类作为鼠标监听器。除此之外,我还实现了两个方法:mouseExited和mouseEntered。第一个方法用于在鼠标退出按钮区域时将标签的初始状态恢复为原始状态。第二个方法在鼠标位于按钮区域时呈现标签的变化。
希望这能帮助你或其他人。
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);
    }
}

0

其实不需要写那么冗长的代码,你可以使用鼠标进入事件这个简单而又理想的选项。具体如下:

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");
    }

这会有所帮助。


-1

我正在使用NetBeans进行开发,这意味着当我创建我的jFrame表单时,其中已经有一些预生成的代码。以下是它:

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() {
    }
}
}

我有一个用于按钮的“图标”图片。当鼠标进入时,我想要这段代码更改按钮的“图标”图像(这部分可以正常工作),同时更改我的“jLabel1”的文本颜色,即“foreground(color)”参数(但这部分无法正常工作)。

1
这不是一个答案,应该被编辑到问题中。 - Andrew Thompson
我改变了主意。1)既然你想要改变任何标签的颜色,那么就不需要5个!或者按钮。2)为了更快地得到帮助,请发布一个SSCCE。3)作为一般提示。在理解布局如何工作之前,不要使用GUI设计器,并且永远不要调用(或强制IDE编写调用)setBounds - Andrew Thompson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接