我的Java应用程序中有一个问题有很多工具提示。有时工具提示会覆盖按钮,因为它覆盖了我无法点击。
我们是否有办法让工具提示对鼠标事件透明?然后,即使工具提示覆盖它,我也可以单击该按钮。
答案 0 :(得分:1)
由于此源代码演示了如何为可以“点击”的按钮创建工具提示,我想问题的解决方案是“更改代码中的任何内容”。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class TooltipButtonClickTest {
private JComponent ui = null;
TooltipButtonClickTest() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridLayout(0,8,2,2));
ui.setBorder(new EmptyBorder(4,4,4,4));
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("action command: " + e.getActionCommand());
}
};
int sz = 15;
Insets pad = new Insets(sz,sz,sz,sz);
for (int i=1; i<65; i++) {
JButton b = new JButton(String.valueOf(i));
b.setMargin(pad);
b.setToolTipText("This is tool tip " +String.valueOf(i));
b.addActionListener(listener);
ui.add(b);
}
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
TooltipButtonClickTest o = new TooltipButtonClickTest();
JFrame f = new JFrame("???");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
答案 1 :(得分:0)
如果底部位置不够,工具尖端会向上移动一点。
public static Point getToolTipLocation(JComponent component)
{
Point point = component.getLocationOnScreen();
int componentHeight = component.getHeight();
int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
Insets scnMax = Toolkit.getDefaultToolkit().getScreenInsets(component.getGraphicsConfiguration());
int taskBarSize = scnMax.bottom;
FontMetrics metrics = component.getFontMetrics(component.getFont());
int height = metrics.getHeight();
int lines = 1;
//Tool tip location shifted to up if screen does not have space in the bottom.
if (point.y + componentHeight + taskBarSize + (height * lines) > screenHeight)
{
int xPos = component.getWidth() / 2;
return new Point(xPos, -((height * lines) + 25));
}
return null;
}
然后覆盖JButton中的 getToolTipLocation()方法,调用上面的方法对我来说很好。