下面的代码创建了一个框架,该框架在框架的 contentPane 中带有 JTabbedPane,并且将“帮助”按钮直接添加到框架的分层 Pane 中 - 索引比默认值更高,因此应始终将其绘制在选项卡式 Pane 的前面。但正如您所看到的,如果您运行它,只要您单击其中一个选项卡(或者,在 Mac 上,只要您将鼠标悬停在选项卡上),“帮助”按钮就会被覆盖 - 即消失。您必须调整框架大小才能重新显示“帮助”按钮。
这是 Java 错误还是我做错了什么?如果是后者,需要采取什么措施来解决问题?我咨询过https://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html和 https://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html .
请原谅“帮助”按钮位置不当。我只是想写一个快速测试来包含在这里。这个想法是在 JTabbedPane 的未使用空间中覆盖一个“帮助”图标按钮。
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
public class TabTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
JTabbedPane tp = new JTabbedPane();
tp.addTab("hello", new JPanel());
tp.addTab("there", new JPanel());
frame.getContentPane().add(tp, BorderLayout.CENTER);
JLayeredPane layeredPane = frame.getRootPane().getLayeredPane();
JButton helpButton = new JButton("Help");
helpButton.setBounds(800, 5, 50, 20);
layeredPane.add(helpButton, 400);
frame.setSize(new Dimension(900, 800));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
最佳答案
这是对 JLayeredPane
的常见误解。
如果您查看了 Container
的 JavaDocs,您会注意到(至少)有两个 add
方法
您需要回答的问题是,您实际上在调用哪一个?
两者都是JavaDocs for JLayeredPane
和 How to use JLayeredPane证明您应该调用第二个。
虽然第一个可能影响组件的 z 顺序,但不能保证组件位置不会更改。
而不是:
layeredPane.add(helpButton, 400);
您应该使用:
layeredPane.add(helpButton, new Integer(400));
它将把值作为约束传递给容器,而不是容器层次结构中所需的位置 - 是的,我知道合适
另一种解决方案可能是使用glassPane
,例如......
JFrame frame = new JFrame();
JTabbedPane tp = new JTabbedPane();
tp.addTab("hello", new JPanel());
tp.addTab("there", new JPanel());
frame.getContentPane().add(tp, BorderLayout.CENTER);
// Null layout used here for demonstration purposes only
JPanel glassPane = new JPanel(null);
glassPane.setOpaque(false);
frame.getRootPane().setGlassPane(glassPane);
// This is important, as setGlassPane makes it invisible
glassPane.setVisible(true);
JButton helpButton = new JButton("Help");
helpButton.setBounds(800, 5, 50, 20);
glassPane.add(helpButton);
frame.setSize(new Dimension(900, 800));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
关于java - 将 JButton 覆盖到 JFrame 中,并在其内容 Pane 中使用 JTabbedPane?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49265393/