[英]Swing: GlassPane prevents mouse pointer from changing
我有一個帶有一些標簽的JTabbedPane,標簽旁邊還有很多未使用的額外空間。 所以我正在嘗試使用它並在那里放置一些按鈕(就像在Eclipse中一樣)。 我把按鈕放在GlassPane上:
JPanel glasspane = getPanelWithButtons();
// panel with FlowLayout.RIGHT
frame.setGlassPane(glasspane);
glasspane.setOpaque(false);
glasspane.setVisible(true);
這是有效的,我仍然可以點擊我的gui的其他元素(我發現的大多數搜索結果都是關於如何防止這種情況)。 到目前為止唯一的問題是當鼠標懸停在JSplitPane的條上時,鼠標指針不會改變為該雙端水平箭頭。 我怎樣才能恢復這種行為?
編輯
我發現沒有顯示玻璃窗格下任何組件的鼠標更改事件。 這些組件會將鼠標光標更改為手形光標,變焦鏡頭等。 這些鼠標指針更改都不會產生任何影響。 我想這是因為在玻璃窗格中,需要對玻璃窗格進行鼠標指針更改,但我不想手動更改所有鼠標指針。
好。 我弄清楚該怎么做。
雖然我花了5個多小時來理解背后的所有事情,但解決方案非常簡單。
只需覆蓋玻璃面板的'public boolean contains(int x,int y)'方法。
public static void main(String[] args)
{
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(800, 600);
final JSplitPane panel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JPanel(), new JPanel());
frame.getContentPane().add(panel, BorderLayout.CENTER);
final JPanel glassPane = new JPanel(){
@Override
public boolean contains(int x, int y)
{
Component[] components = getComponents();
for(int i = 0; i < components.length; i++)
{
Component component = components[i];
Point containerPoint = SwingUtilities.convertPoint(
this,
x, y,
component);
if(component.contains(containerPoint))
{
return true;
}
}
return false;
}
};
glassPane.setOpaque(false);
JButton button = new JButton("haha");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("haha");
}
});
glassPane.add(button);
glassPane.setBorder(BorderFactory.createLineBorder(Color.red));
frame.setGlassPane(glassPane);
//try to comment out this line to see the difference.
glassPane.setVisible(true);
frame.setVisible(true);
}
好。 我找到了問題的解決方案“在標簽旁邊放置按鈕”。 我不再使用玻璃窗格,而是直接放置按鈕:
buttonpanel.setBounds(...);
frame.getLayeredPane().add(buttonpanel, 1);
這有效並解決了我的問題。 它有點復雜,但涉及手工布局和監聽幀大小調整事件。
由於我仍然想知道如何使用玻璃窗格來實現這一點,我不接受這個答案。 也許有人想出一個玻璃窗格的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.