如何使用java中的链接更改JLABEL的颜色?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class XXX extends JFrame {
XXX(){
final JLabel lab1=new JLabel("Username:");
final JTextField text1=new JTextField(20);
lab1.setBounds(20,140,65,20);
text1.setBounds(85,141,185,20);
add(lab1);
add(text1);
lab1.setForeground(Color.white);
final JLabel lab2=new JLabel("Password:");
final JPasswordField text2=new JPasswordField(20);
lab2.setBounds(20,165,65,20);
text2.setBounds(85,166,185,20);
add(lab2);
add(text2);
lab2.setForeground(Color.white);
final JButton a=new JButton("Sign In");
a.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Code
}
});
a.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
a.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
public void mouseExited(MouseEvent me) {
a.setCursor(Cursor.getDefaultCursor());
}
public void mouseClicked(MouseEvent me)
{
a.setEnabled(false);
text1.setEditable(false);
text2.setEditable(false);
try {
}
catch(Exception e) {
System.out.println(e);
}
}
});
a.setBounds(85,192,80,20);
add(a);
final String strURL = "http://www.yahoo.com";
final JLabel lab3 = new JLabel("<html><a href=\" " + strURL + "\">Register</a></html>");
lab3.setBounds(170,192,52,20);
add(lab3);
lab3.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
lab3.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
public void mouseExited(MouseEvent me) {
lab3.setCursor(Cursor.getDefaultCursor());
}
public void mouseClicked(MouseEvent me)
{
text2.setEditable(false);
try {
}
catch(Exception e) {
System.out.println(e);
}
}
});
final JLabel map = new JLabel(new ImageIcon(getClass().getResource("XXXBG.png")));
map.setBounds(0,0,300,250);
add(map);
setTitle("XXX");
setSize(300,250);
setResizable(false);
setCursor(DEFAULT_CURSOR);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(8, 8);
setLayout(null);
toFront();
setVisible(true);
}
public static void main(String[] args)
{
new XXX();
}
}
如您所见,我无法更改JLABEL lab3的前景色。 如果可行,我也想改变jframe的边框颜色。 有人可以帮忙吗?
答案 0 :(得分:3)
是的,这是可能的。简单提供您想要使用的foreground
颜色......
lab3.setForeground(Color.BLUE);
您也不需要鼠标监听器。简单地使用lab3.setCursor(new Cursor(Cursor.HAND_CURSOR));
会在鼠标移动到标签上时自动更改鼠标光标...魔术:D
<强>更新强>
public class TestLabel01 {
public static void main(String[] args) {
new TestLabel01();
}
public TestLabel01() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JLabel link = new JLabel("Linked in");
link.setForeground(Color.BLUE);
link.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(link);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}