Search code examples
javaswingjlabeljinternalframe

How to add JLabel in JInternalFrame?


I have a HTML table in Jlabel(java),I want to display JLabel in JInternalFrame or I want to add small HTML table into Jinternalframe without JLabel. how can I achieve ? I want JLabel in place of header not in the body.

    package code;

    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JButton;
    import javax.swing.JLabel;

    import java.awt.FlowLayout;

    class JInternalFrameTest extends JFrame {

        JInternalFrameTest()
        {
            setTitle("JInternalFrame");
            setJInternalFrame();
            setSize(700,300);
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }

        void setJInternalFrame()
        {
            String htmlContent = "<html><body><table border = '1'>";
            htmlContent += "<tr><td>Hai</td></tr></table></body></html>";
            JLabel label = new JLabel();
            label.setText(htmlContent);
            JInternalFrame jn = new JInternalFrame("I want jlabel here",true,true,true);
jn.add(label);
            jn.setLayout(new FlowLayout());
            jn.add(new JButton("JButton"));
            jn.setVisible(true);
            add(jn);
        }
    }

    public class JavaApp {
        public static void main(String[] args) {     
            JInternalFrameTest jn = new JInternalFrameTest();
        }
    }

Solution

  • Look like an issue due to inattentive - just add your label to jn control:

    jn.add(label);
    

    Here is the result of fix (I have also added <tr><td>sdfsdfsf</td></tr> to your table. enter image description here

    UPD: After several clarifications in question it was decided that this new label should be added into title bar of the JInternalFrame. It can be also done:

    void setJInternalFrame() {
         String htmlContent = "<html><body><table border ='1' bgcolor='#EEEEEE'>"
                    + "<tr><td>Hai</td></tr></table></body></html>";
    
         JInternalFrame jn = new JInternalFrame("I want jlabel here", true, true, true);
    
         JComponent titleBar = ((BasicInternalFrameUI) jn.getUI()).getNorthPane();
    
         JLabel label = new JLabel();
         label.setText(htmlContent);
         label.setBounds(128, 0, 40, 20);
         titleBar.add(label);
    
         jn.setLayout(new FlowLayout());
         jn.add(new JButton("JButton"));
         jn.setVisible(true);
         add(jn);
    }
    

    The result will be following:

    enter image description here

    For changing the height for the title bar you can use following command:

    titleBar.setPreferredSize(new Dimension(titleBar.getPreferredSize().width, 100));
    // don't forget to set a proper size for the label
    label.setBounds(128, 10, 40, 100);
    

    Result:

    enter image description here

    Hope this will help.