3

I've a JLabel. The code for JLabel is as follows.

panelmain = new JPanel();
panelmain.setLayout(null);
panelmain.setPreferredSize(new java.awt.Dimension(800, 600));
panelmain.addComponentListener(listen);
panelmain.setBorder(null);
titlebar = new JLabel("Hello World");
titlebar.setBounds(10, 10, 100, 30);
panelmain.add(titlebar);

My questing is that if I change font of titlebar (i.e. JLabel), then how to change size (which is already set in code as titlebar.setBounds(10, 10, 100, 30);) of titlebar?

Edit by Girish

My full code is as below.

import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;

import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class IFrame extends JInternalFrame {

    /**
     * 
     */
    private static final long serialVersionUID = 6526561589695424088L;

    private JScrollPane jsp;

    private IFListen listen;

    private JPanel panelmain;

    protected JPanel panel;

    private String title;

    private JLabel titlebar;

    public IFrame()
    {
        this.title="";
        init();
    }

    public IFrame(String title)
    {
        this.title=title;
        init();
    }

    private void init()
    {
        setLayout(null);

        listen=new IFListen();
        panelmain=new JPanel();
            panelmain.setLayout(null);
            panelmain.setPreferredSize(new java.awt.Dimension(800, 600));
            panelmain.addComponentListener(listen);
            panelmain.setBorder(null);

            titlebar=new JLabel("Hello World");
            titlebar.setFont(new java.awt.Font("Monotype Corsiva", 1, 48));
            panelmain.add(titlebar);

            panel=new JPanel();
            panel.setBorder(javax.swing.BorderFactory.createTitledBorder(title));
            panel.setMinimumSize(new java.awt.Dimension(400, 400));
            panel.setSize(400, 400);
            panelmain.add(panel);

        jsp=new JScrollPane(panelmain);
        jsp.setBorder(null);

        add(jsp);

        this.addComponentListener(listen);
    }

    //INFO Custom Methods
    public void setTitleFont(java.awt.Font font)
    {
        titlebar.setFont(font); //Here I want to change size of label.
    }

    //INFO Listener Class for IFrame
    private class IFListen implements ComponentListener
    {
        //INFO Overridden Methods
        @Override
        public void componentResized(ComponentEvent e) 
        {
            if(e.getSource() instanceof IFrame)
                jsp.setBounds(5, 5, getWidth()-20, getHeight()-20);
            else if(e.getSource()==panelmain)
            {
                panel.setLocation(Integer.parseInt(panelmain.getWidth()/2-panel.getWidth()/2+""), 0);
            }
        }

        //INFO Unimplemented Methods
        @Override
        public void componentShown(ComponentEvent arg0) {}

        @Override
        public void componentHidden(ComponentEvent arg0) {}

        @Override
        public void componentMoved(ComponentEvent arg0) {}
    }
}

I've commented where the font size is changed and I want to change size of jlabel.

Girish
  • 213
  • 2
  • 13
  • 1
    Don't use setBounds? The JLabel will resize when the font changes. – almightyGOSU Jul 14 '15 at 11:58
  • I'll try it and get back soon, thanks for response @Gosu – Girish Jul 14 '15 at 12:00
  • 8
    Now you have a concrete examples of why you should not position elements absolutely, but use a layout manager instead. The layout manager takes care of that. – JB Nizet Jul 14 '15 at 12:00
  • @Gosu, I've tried as your suggestion. Removed setBounds, but nothing is displaying :( – Girish Jul 14 '15 at 12:06
  • @JBNizet, I'll check for layout and will back. Thank you. – Girish Jul 14 '15 at 12:11
  • 1
    Don't use setPreferredSize, you've prevented the label from calculating the size it needs. Don't use null layouts, make use of appropriate layouts – MadProgrammer Jul 14 '15 at 12:15
  • @JBNizet, I don't want to use any layout. Because when I've changed layout from null to Borderlayout, then panel's (I didn't mentioned panel's code in question) size is changed too. – Girish Jul 14 '15 at 12:19
  • 1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). 2) Provide ASCII art or a simple drawing of the *intended* layout of the GUI at minimum size, and if resizable, with more width and height. – Andrew Thompson Jul 14 '15 at 12:21
  • 3
    *"I don't want to use any layout."* As an aside, go through some of the questions in the [tag:null-layout-manager] tag. I would guess that of the questions that have accepted answers, 19/20 (or probably higher) were solved by the **use of layouts** (+padding and borders for white space). – Andrew Thompson Jul 14 '15 at 12:25
  • 2
    OK. So what you have doesn't work without a layout manager, and it doesn't work with a layout manager either. So you need a fix, whetever the solution is. All the experimented developers here tell you to use a Layout Manager. What do you think you should do? Try doing it with a layout manager, and if you still have a problem, do what Andrew told you to do. in the above comment. – JB Nizet Jul 14 '15 at 12:28
  • *"I don't want to use any layout."* - Well, aren't you screwed, no seriously, Swing was designed at the core to use layout managers, it's entire API is interconnected through the layout manager API. So, unless you want to re-write the entire API to support working without them, then you're going to be, well screwed...sorry – MadProgrammer Jul 14 '15 at 12:43
  • http://stackoverflow.com/questions/2715118/how-to-change-the-size-of-the-font-of-a-jlabel-to-take-the-maximum-size Take a look here – Adam Jul 14 '15 at 12:47
  • Thanks to all (specially @MadProgrammer and @AndrewThompson) for your valuable support. I've solved my problem using Borderlayout. Thanks for suggesting me for studying of layouts in java. Thanks once again :) – Girish Jul 14 '15 at 13:16

1 Answers1

4

Don't use setPreferredSize, you've just removed all the calculations that the label uses to calculate the size it would like to be.

Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

Make use of appropriate layouts. The important thing here is, no one layout will ever do everything you want. You will need to learn to take advantage of the each layout's strengths (and weaknesses) and use them to your advantage. This is what is commonly known as "compound layouts". Have a look at Laying Out Components Within a Container for more details and ideas

Resizable label

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JLabel label;
        private JSlider slider;

        public TestPane() {
            label = new JLabel("Look, no hands!");
            setLayout(new BorderLayout());
            JPanel panel = new JPanel(new GridBagLayout());
            panel.add(label);

            add(panel);

            slider = new JSlider(8, 96);
            add(slider, BorderLayout.SOUTH);

            slider.addChangeListener(new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                    Font font = label.getFont();
                    font = font.deriveFont((float)slider.getValue());
                    label.setFont(font);
                }
            });
            slider.setValue(8);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

    }

}

JLabel is surprising proficient, changing the font (text/icon) will automatically cause it to invalidate the layout and request a repaint all by itself...

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366