How to create customize title bar with close button on jFrame?

你离开我真会死。 提交于 2019-12-11 06:26:34

问题


I want to create a customised title bar for my JFrame. I can remove the default title bar with

JFrame.setUndecorated(true)

Now i need to create a customised title bar for my JFrame with a close button?


回答1:


Without having done that ever, I think I would go this way:

  1. Indeed set the JFrame to undecorated
  2. Extend JRootPane to add an additional field titleBar
  3. Create a TitleBar component holding the title, the close button, etc...
  4. Set a new LayoutManager on that JRootPane (have a look at JRootPane.RootLayout) and layout the components in the appropriate order (first the title bar, then below the menubar, then below the content pane)
  5. Set an instance of that extends RootPane on your JFrame

There are maybe better ways.




回答2:


I'm not quite sure of how you want to customize the close button, but maybe this can point you in the right direction: How can I customize the title bar on JFrame?

EDIT: Here's an updated working link to a forum about customizing his GUI and one user posted code on his creation of a simple GUI: Here

It looks like you can just modify his removeComponents method and create an addComponents method to fit your needs.




回答3:


The Code According to the Above Link : (Edited for Java 8)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;

class Testing {
  public void buildGUI() throws UnsupportedLookAndFeelException {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame f = new JFrame();
    f.setResizable(false);
    removeMinMaxClose(f);
    JPanel p = new JPanel(new GridBagLayout());
    JButton btn = new JButton("Exit");
    p.add(btn, new GridBagConstraints());
    f.getContentPane().add(p);
    f.setSize(400, 300);
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
    btn.addActionListener((ActionEvent ae) -> {
      System.exit(0);
    });
  }

  public void removeMinMaxClose(Component comp) {
    if (comp instanceof AbstractButton) {
      comp.getParent().remove(comp);
    }
    if (comp instanceof Container) {
      Component[] comps = ((Container) comp).getComponents();
      for (int x = 0, y = comps.length; x < y; x++) {
        removeMinMaxClose(comps[x]);
      }
    }
  }

  public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> {
      try {
        new Testing().buildGUI();
      } catch (UnsupportedLookAndFeelException ex) {
        Logger.getLogger(Testing.class.getName()).log(Level.SEVERE, null, ex);
      }
    });
  }
}

may Work Fine but what if user also Want to set a L&F such as nimbus



来源:https://stackoverflow.com/questions/12822037/how-to-create-customize-title-bar-with-close-button-on-jframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!