How can I set a JLabel's background and border the same as a table header?

前端 未结 4 909
无人共我
无人共我 2021-01-15 12:53

I want to recreate a table header looks using JLabel. The look and feel of the JLabel needs to be exactly like the JTableHeader would

4条回答
  •  醉梦人生
    2021-01-15 13:52

    You need to set a look and feel for the application before trying:

    header.setBackground(UIManager.getColor(new JTableHeader().getBackground()));
    header.setBorder(UIManager.getBorder(new JTableHeader().getBorder()));
    

    you should set a look and feel first like so:

      try {
        for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (Exception e) {
        // If Nimbus is not available, you can set the GUI to another look and feel.
    }
    

    Here is an example:

    enter image description here

    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.table.JTableHeader;
    
    public class Test {
    
        public Test() {
            initComponents();
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        //set nimbus look and feel
                        for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                            if ("Nimbus".equals(info.getName())) {
                                UIManager.setLookAndFeel(info.getClassName());
                                break;
                            }
                        }
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
                        e.printStackTrace();
                    }
    
                    new Test();
                }
            });
        }
    
        private void initComponents() {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            JLabel header = new JLabel("Title");
            header.setBackground(UIManager.getColor(new JTableHeader().getBackground()));
            header.setBorder(UIManager.getBorder(new JTableHeader().getBorder()));
    
            frame.add(header);
    
            frame.pack();
            frame.setVisible(true);
        }
    }
    

提交回复
热议问题