Java Swing - 添加图标或文本时JLabel宽度是否已更改?

时间:2011-07-25 11:40:14

标签: java swing size scale jlabel

同一问题,不同背景

在我接受之前,我似乎太仓促,因为问题仍然存在。问题?当内容被添加到JLabel时,JLabel可以自由扩展其父面板。

现在是时候根据“充满鳗鱼的气垫船”来复制它 - 这是建议,现在是:

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);  
    }
}

结果:

enter image description here

正如您所看到的,当文本(或原始问题和图标)添加到绿色面板时,绿色面板会被拉大并抛弃我的整个布局。无论内容如何,​​我希望我的布局保持相同的权重。之所以出现这种情况,是因为我正在尝试将标定图像添加为标签的图标,如原始问题所示。

顺便说一下,setPreferredSize()似乎不起作用。

有没有办法解决这个问题?


原始问题

当我向其添加一个Icon时,我的JLabel元素会大大扩展。为什么会这样?以下是代码的适用部分:

// 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);

从第一张照片中我可以看到,我有一个宽度为W的标签(红色)。我要做的是将我的图标拉伸到宽度W并将其放在标签中。

当我这样做时,标签会扩展(我认为正好是50个像素)并且还会挤压左边缘(绿色)。有谁知道为什么会这样?

我尝试过几个过于冗长无法解释但无法找到问题的事情: - /

enter image description here

3 个答案:

答案 0 :(得分:3)

您的组件会展开,因为它会为其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());
    }
}

enter image description here


以下内容输出到控制台:

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]

答案 1 :(得分:2)

考虑使用JLayeredPane在图层中添加组件。在这样做时,在不透明度,尺寸和添加的组件位置方面存在跳闸和陷阱。

例如,

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);
   }
}

答案 2 :(得分:1)

Java swing对我来说已经很老了但是如果我记得很清楚的话,设置一个首选大小(setPreferredSize())有时会解决这些问题......还可以尝试使用setMaximumSize和setMinimumSize进行顶层。

您可以在java文档中找到更多信息: http://download.oracle.com/javase/tutorial/uiswing/layout/using.html#sizealignment

问候!