【问题标题】:How to place a button over JFrame title bar如何在 JFrame 标题栏上放置一个按钮
【发布时间】: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


【解决方案1】:

您可以像这样将框架设置为未装饰

frame.setUndecorated(true);

注意:在frame.setVisiblle(true);之前添加此语句

【讨论】:

  • 感谢您的快速回复。我们可以将按钮放在现有标题栏的顶部吗?如果我们设置 undecorate,我们必须创建自己的标题栏。
  • 框架未装饰时将没有标题栏。您需要以您喜欢的任何方式创建自己的。
猜你喜欢
  • 2015-05-27
  • 2011-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
相关资源
最近更新 更多