jkteater
jkteater

Reputation: 1391

Jpanel size after adding jlabel component

I have a central panel. This is my parent panel. I am adding 3 panels to the parent panel.

The panels are going to be stacked vertically. Like a title panel, then a middle panel, then a bottom panel. I just want to focus on my title panel. When I create a jlabel using text. The label shows and the panel borders stretches the entire width of the parent panel, which is what I want.

private JPanel titlePanel() {
  String text = "<html><b><big><font color=#5C8C5C>Help Dialog</font></big></b></html>";
  JLabel textLabel = new JLabel(text, JLabel.CENTER); 
  JPanel p = new JPanel();
  p.setLayout(new BoxLayout(p, BoxLayout.LINE_AXIS));
  p.add(textLabel);
  p.setBorder(BorderFactory.createLineBorder(Color.black));
  return p;   
}

I am actually wanting to use a icon as the label and not html text. So make the changes to the code.

private JPanel titlePanel() {
  Registry appReg = Registry.getRegistry(this);
  ImageIcon ediLabelIcon = appReg.getImageIcon("ToolLabel.ICON");
  JLabel textLabel = new JLabel(ediLabelIcon, JLabel.CENTER); 
  JPanel p = new JPanel();
  p.setLayout(new BoxLayout(p, BoxLayout.LINE_AXIS));
  p.add(textLabel);
  p.setBorder(BorderFactory.createLineBorder(Color.black));
  return p;   
}

Now the label shows, but the border of the panel is only as wide as the label and not stretched out the width of the parent panel.

I am trying to figure out to extend the panel border the width of the parent panel and not just as wide as the label. This is the code for the parent panel.

 private void createDialog() {

  Component titlePanel = titlePanel();
  Component verbiagePanel = verbiagePanel();
  Component closeButtonPanel = closeButton();
  setTitle("HELP Dialog");
  centerPanel = new JPanel();
  centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS));
  centerPanel.setPreferredSize(new Dimension(600, 300));
  centerPanel.add(titlePanel);
  centerPanel.add(Box.createRigidArea(new Dimension(0, 10)));
  centerPanel.add(verbiagePanel);
  centerPanel.add(Box.createHorizontalGlue());
  centerPanel.add(Box.createRigidArea(new Dimension(0, 10)));
  centerPanel.add(closeButtonPanel);
  getContentPane().add(centerPanel);
  this.pack();

}

Upvotes: 0

Views: 546

Answers (1)

Nestor
Nestor

Reputation: 756

Using HTML in JLabel text switched the mechanism which calculate preferred size fot JLabel. Now I can't explain it in detail, but if you change creating title label to

JLabel textLabel = new JLabel("<html></html>", ediLabelIcon, JLabel.CENTER);

your label will be stretched out to parent panel width.

Or you may choose another layout manager such as GridBagLayout. With GridBagLayout you can force stretch any component to its parent width.

Upvotes: 1

Related Questions