Is there any way to get the (preferred I guess) size of the components of a JLabel so I can resize it to them? My JLabel gets a size of 0,0 unless I set its Preferred Size, but setting its size to an arbitrary pixel value seems like the wrong approach, since the whole point of using Swing (as far as I understand it) is not doing that.
Things that I've already tried:
- repaint() and refactor()
- adding a LayoutManager to the JPanel (in this case BoxLayout)
This is basically what I am doing:
package invisiblelabel;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class InvisibleLabel {
public static JFrame frame;
public static JPanel panel;
public static JLabel visible;
public static JLabel visibleText;
public static JLabel invisible;
public static JLabel text1;
public static JLabel text2;
public static void main(String[] args) {
createGraphics();
}
public static void createGraphics(){
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
visible = new JLabel();
visible.setPreferredSize(new Dimension (500,500));
Border border = BorderFactory.createLineBorder(Color.black);
visible.setBorder(border);
visible.setLayout(new BoxLayout(visible, BoxLayout.Y_AXIS));
visibleText = new JLabel ("This JLabel is visible, because it is created fitting its text.");
visible.add(visibleText);
invisible = new JLabel();
text1 = new JLabel("You can't read this anyways.");
text2 = new JLabel("You can't read this either.");
invisible.add(text1);
invisible.add(text2);
visible.add(invisible);
panel.add(visible);
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setSize(800,600);
frame.setVisible(true);
visible.repaint();
visible.revalidate();
}
}
}