我正在开发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的问题.它不会改变.为什么?谢谢
解决方法:
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();
}
}
请尝试上面的代码,布局不好看,但我认为这可以解决您的问题.