【发布时间】:2021-11-24 16:34:07
【问题描述】:
我想在 JFrame 标题栏上放置一个按钮,如下图所示。
当我使用 button.setBounds() 设置按钮的边界时,按钮隐藏在标题栏下方,如下所示。
我在下面给出了我尝试过的代码。
public class SetBoundsTest {
public static void main(String arg[]) {
JFrame frame = new JFrame("Test Frame");
frame.setSize(500, 250);
// Setting layout as null
frame.setLayout(null);
// Creating Button
JButton button = new JButton("Test");
// Setting position and size of a button
button.setBounds(150,-20,120,40);
button.setBorder(BorderFactory.createLineBorder(Color.BLUE, 3));
button.setBackground(Color.MAGENTA);
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
非常感谢任何帮助。
【问题讨论】:
-
“我想在 JFrame 标题栏上放置一个按钮,如下图所示。” . .为什么?
-
@AndrewThompson,在我们的应用程序中,我们需要在标题栏上有控件,如 MS word、excel 等。
-
标题栏是操作系统组件的一部分,java 无权访问它。如果您想要自定义标题栏,那么您需要使用未装饰的框架并添加您自己的标题栏,正如已经建议的那样。您可以尝试使用 Metal LAF。它确实创建了自己的标题栏。因此,您可以获取框架的根窗格,然后搜索子组件,直到找到自定义标题栏。然后根据标题栏中使用的布局管理器,您也许可以插入自己的组件。
标签: java swing user-interface jframe setbounds