开发者

Java Swing - JLabel width changed when icon or text added?

开发者 https://www.devze.com 2023-03-22 13:14 出处:网络
Same Q开发者_如何学Gouestion, different context It seems I was too hasty in my accepting before, since the problem is still there.The problem? JLabel takes the liberty of expanding its parent panel w

Same Q开发者_如何学Gouestion, different context

It seems I was too hasty in my accepting before, since the problem is still there. The problem? JLabel takes the liberty of expanding its parent panel when content is added to it.

It's time for reproducing it per "Hovercraft full of eels"-ses suggestion, and here it is:

import java.awt.*;
import javax.swing.*;

public class TestLabel {    
    public static void main(String[] args) {
    // Var inits
        JFrame frame;
    JPanel panel;
    JLabel label;
    Container pane;
    GridBagConstraints gbc = new GridBagConstraints();

    // Frame, content pane, layout inits
    frame = new JFrame("Label Tester");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        

        pane = frame.getContentPane();   
        pane.setLayout(new GridBagLayout());

        gbc.weighty = 1;
        gbc.fill = GridBagConstraints.BOTH;


        // Add panels (note gbc weighty and fill carries over all instances)
        gbc.weightx = 0.3;
        gbc.gridx = 0;
        gbc.gridy = 0;
        panel = new JPanel();
        panel.setBackground(Color.GREEN);
        frame.add(panel,gbc);

        label = new JLabel("THE PANEL IS NOW DISTORTED TO FIT THIS LABEL WHY IS THIS HAPPENING");
        //label = new JLabel("");
        label.setOpaque(true);
        label.setBackground(Color.WHITE);   
        panel.add(label);

        gbc.weightx = 0.7;
        gbc.gridx = 1;
        gbc.gridy = 0;
        panel = new JPanel();
        panel.setBackground(Color.RED);
        frame.add(panel,gbc);

        gbc.weightx = 0.3;
        gbc.gridx = 0;
        gbc.gridy = 1;
        panel = new JPanel();
        panel.setBackground(Color.BLUE);
        frame.add(panel,gbc);

        gbc.weightx = 0.7;
        gbc.gridx = 1;
        gbc.gridy = 1;
        panel = new JPanel();
        panel.setBackground(Color.YELLOW);
        frame.add(panel,gbc);

        frame.pack();
        frame.setSize(800,600);  

        frame.setVisible(true);  
    }
}

Results:

Java Swing - JLabel width changed when icon or text added?

As you can see, the green panel is forced wider and throws off my whole layout when text (or, in the original question, and icon) is added to it. I want my layout to remain the same weights, regardless of the content. The reason this came up is because I'm trying to add a scaled image as an icon to the label, as seen in the original question.

Incidentally, setPreferredSize() doesn't seem to work.

Is there a way to fix this?


Original Question

My JLabel element expands dramatically when I add an Icon to it. Why is this happening? Here's the applicable portion of the code:

// Show label and BG color
redLabel.setBackground(Color.RED);
redLabel.setOpaque(true);

// Grab stretched image (already loaded elsewhere in the code) and turn to icon
Img = Img.getScaledInstance(redLabel.getWidth(),12,Image.SCALE_REPLICATE);
ImageIcon icon = new ImageIcon(Img); 

// This line throws everything off! 
//It's commented out in the first pic, and included in the second.
redLabel.setIcon(icon);

As you can see from the first pic, I've got a label (in red) of width W. What I'm trying to do is stretch my icon to width W and put it in the label.

When I do this, the label expands (by exactly 50 pixels, I think) and also squeezes over the left edge (green). Does anyone have any idea why this is happening?

I've tried several things that are too verbose to explain but can't find the problem :-/

Java Swing - JLabel width changed when icon or text added?


Your component expands because it allocates the necessary space for its Icon.


public class JLabelDemo {
    private static BufferedImage bi;

    public static void main(String[] args) throws IOException{
        loadImage();

        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                createAndShowGUI();             
            }
        });
    }

    private static void loadImage() throws IOException{
        bi = ImageIO.read(JLabelDemo.class.getResource("../resource/forever-alone.jpg"));
    }

    private static void createAndShowGUI(){
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JPanel panel = new JPanel();
        panel.setBackground(Color.YELLOW);
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        final JLabel emptyLabel = new JLabel();
        final JLabel textLabel = new JLabel("This label has text only");
        final JLabel textAndImageLabel = new JLabel("This label has text and image");
        textAndImageLabel.setIcon(new ImageIcon(bi));

        panel.add(emptyLabel);
        panel.add(textLabel);
        panel.add(textAndImageLabel);
        frame.add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        System.out.println("Empty label dimensions - " + emptyLabel.getSize());
        System.out.println("Text only label dimensions - " + textLabel.getSize());
        System.out.println("Image width: " + bi.getWidth() + ", Image height: " + bi.getHeight());
        System.out.println("Text and image label dimensions - " +textAndImageLabel.getSize());
    }
}

Java Swing - JLabel width changed when icon or text added?


The following is outputted to console:

Empty label dimensions - java.awt.Dimension[width=0,height=0]
Text only label dimensions - java.awt.Dimension[width=129,height=16]
Image width: 194, Image height: 180
Text and image label dimensions - java.awt.Dimension[width=363,height=180]


Consider using a JLayeredPane to add components in layers. There are trips and traps though when doing this in matters of opacity, size and position of components added.

For example,

import java.awt.*;
import javax.swing.*;

public class TestLabel {
   private static final Dimension SIZE = new Dimension(800, 600);

   public static void main(String[] args) {
      GridBagConstraints gbc = new GridBagConstraints();


      JPanel defaultPane = new JPanel();
      defaultPane.setLayout(new GridBagLayout());

      gbc.weighty = 1;
      gbc.fill = GridBagConstraints.BOTH;

      // Add panels (note gbc weighty and fill carries over all instances)
      gbc.weightx = 0.3;
      gbc.gridx = 0;
      gbc.gridy = 0;
      JPanel panel = new JPanel();
      panel.setBackground(Color.GREEN);
      defaultPane.add(panel, gbc);

      gbc.weightx = 0.7;
      gbc.gridx = 1;
      gbc.gridy = 0;
      panel = new JPanel();
      panel.setBackground(Color.RED);
      defaultPane.add(panel, gbc);

      gbc.weightx = 0.3;
      gbc.gridx = 0;
      gbc.gridy = 1;
      panel = new JPanel();
      panel.setBackground(Color.BLUE);
      defaultPane.add(panel, gbc);

      gbc.weightx = 0.7;
      gbc.gridx = 1;
      gbc.gridy = 1;
      panel = new JPanel();
      panel.setBackground(Color.YELLOW);
      defaultPane.add(panel, gbc);
      defaultPane.setSize(SIZE);

      JLabel label = new JLabel("THE PANEL IS NOW DISTORTED TO FIT THIS LABEL WHY IS THIS HAPPENING");
      label.setOpaque(true);
      label.setBackground(Color.WHITE);

      JPanel northPalettePanel = new JPanel();
      northPalettePanel.setOpaque(false);
      northPalettePanel.add(label);

      JPanel palettePanel = new JPanel(new BorderLayout());
      palettePanel.setOpaque(false);
      palettePanel.setSize(SIZE);
      palettePanel.setLocation(0, 0);
      palettePanel.add(northPalettePanel, BorderLayout.NORTH);

      JLayeredPane layeredPane = new JLayeredPane();
      layeredPane.setPreferredSize(SIZE);
      layeredPane.add(defaultPane, JLayeredPane.DEFAULT_LAYER);
      layeredPane.add(palettePanel, JLayeredPane.PALETTE_LAYER);

      JFrame frame = new JFrame("Label Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(layeredPane, BorderLayout.CENTER);
      frame.pack();

      frame.setVisible(true);
   }
}


Java swing is pretty old for me but if I remember well, setting a preferred size (setPreferredSize()) sometime solve these kind of problem ... Also try top lay with setMaximumSize and setMinimumSize.

You can maybe find more information in java documentation: http://download.oracle.com/javase/tutorial/uiswing/layout/using.html#sizealignment

Regards!

0

精彩评论

暂无评论...
验证码 换一张
取 消