我的表单上有一个按钮,我想检测鼠标是否位于该按钮上。如果按钮位于表单上方,我想闪烁一个具有完全红色背景颜色的 JLabel,以指示停止或警告或类似的内容。
e.getComponent() 返回调用组件,因此在本例中应该是 Save Jbutton。但名称为空?
当我有名称时,我检查 source.equals(myButton) 是否应该将标签放在 JFrame 上
代码:
@Override
public void mouseEntered(MouseEvent e) {
final Component source = e.getComponent();
final JFrame frame = (JFrame) SwingUtilities.getRoot(source);
System.out.println("entered:" + source.getName());
if (source.equals("btnSave")) {
System.out.println("save button");
JLabel StopLabel = new JLabel("test");
StopLabel.setOpaque(true);
StopLabel.setEnabled(true);
StopLabel.setBackground(Color.RED);
StopLabel.setBounds(10, 203, 150, 23);
frame.add(StopLabel);
}
}
最佳答案
getName()
不是按钮的标签,您需要调用 getText()
来代替。
例如
JButton randomButton = new JButton("I'm a label!");
System.out.println(randomButton.getName()); // prints null
System.out.println(randomButton.getText()); // prints the label
此外,您要将标签文本与按钮本身进行比较,您需要与标签进行比较:
// wrong
System.out.println("entered:" + source.getName());
if (source.equals("btnSave")) {
// right
System.out.println("entered:" + source.getText());
if (source.getText().equals("btnSave")) {
编辑
我错过了你没有转换你的来源。在源对象上运行 JButton
特定方法之前,您需要将其显式转换为正确的类,如下所示:
final JButton source = (JButton) e.getComponent();
关于java - 为什么我无法在 mouseEntered 方法中获取 JButton 的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23684228/