我们可以通过 Java Swing 来改变光标吗?
是的,我们可以更改 Java 中的默认光标表示。我们首先创建一个按钮组件 -
JButton button = new JButton("Button with two borders");
每当用户将鼠标光标停留在上述按钮组件上时,光标就会更改为手形光标 -
Cursor cursor = button.getCursor(); button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
以下是一个更改光标的示例 -
示例
package my; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Cursor; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.border.Border; import javax.swing.border.EtchedBorder; import javax.swing.border.LineBorder; import javax.swing.border.TitledBorder; public class SwingDemo { public static void main(String args[]) { JFrame frame = new JFrame("Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Border raisedBorder = new EtchedBorder(EtchedBorder.RAISED); LineBorder lineBorder = new LineBorder(Color.red); TitledBorder titleBorder = new TitledBorder("Demo Title"); Border border = BorderFactory.createCompoundBorder(lineBorder, titleBorder); JButton raisedButton = new JButton("Raised Border"); raisedButton.setBorder(raisedBorder); JButton button = new JButton("Button with two borders"); button.setBorder(border); Cursor cursor = button.getCursor(); button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); Container contentPane = frame.getContentPane(); contentPane.add(raisedButton,BorderLayout.WEST); contentPane.add(button,BorderLayout.EAST); frame.setSize(600, 300); frame.setVisible(true); } }
输出
输出如下。当您将光标停留在具有两个边框的按钮上时,则手形光标将如下所示可见 -
广告