【问题标题】:Java: Changing jLabel foreground colorJava:更改 jLabel 前景色
【发布时间】:2012-12-11 00:27:40
【问题描述】:

我正在用 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 有疑问。它不会改变。为什么?谢谢

【问题讨论】:

  • 首先检查这个方法是否被调用,通过把 System.out.println("Called");在里面。如果是这样,请尝试调用 repaint: (name of JFrame).repaint();
  • 你能展示更多相关的代码吗?很难看出只有这个有什么问题。
  • Javadocs:设置该组件的前景色。尊重此属性取决于外观和感觉,有些人可能会选择忽略它。
  • @JesusPlusPlus: repaint() 是不必要的。 JLabel 知道当它的前景发生变化时必须重新绘制它。

标签: java swing user-interface jlabel foreground


【解决方案1】:

我创建了一个简单的应用程序来展示如何通过鼠标事件更改标签组件。在按钮中,我添加了一个鼠标监听器,它是一个实现 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);
    }
}

【讨论】:

    【解决方案2】:

    无需编写那么冗长的代码,您就有一个简单且理想的使用鼠标输入事件的选项。如下

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

    这会有所帮助。

    【讨论】:

      【解决方案3】:

      似乎在这里工作得很好。

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

      【讨论】:

        【解决方案4】:

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

        我的按钮有一张“图标”图片。我希望这段代码在“MouseEntered”时更改按钮的“图标”图像(这很好用),同时更改我的“jLabel1”的文本颜色,即“foreground(color)”参数。 (这部分不起作用)。

        【讨论】:

        • 这不是答案,应该是edited 进入问题。
        • 我改变了主意。 1) 由于您想更改 any 标签的颜色,因此不需要其中的 5 个! ..或按钮。 2) 为了尽快获得更好的帮助,请发布SSCCE。 3) 作为一般提示。在您了解布局的工作原理之前不要使用 GUI 设计器,并且永远不要调用(或强制 IDE 编写调用代码)setBounds
        【解决方案5】:
        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();
        }
        }
        

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

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-20
        • 2012-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-30
        • 2011-06-15
        相关资源
        最近更新 更多