簡體   English   中英

Java Swing-添加圖標或文本時,JLabel寬度是否更改?

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

同一問題,不同背景

由於問題仍然存在,我似乎在接受之前過急。 問題? 當向其添加內容時,JLabel可以自由擴展其父面板。

現在該按照“充滿鰻魚的氣墊船” -ses建議來復制它了,這里是:

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

結果:

在此處輸入圖片說明

如您所見,當向其添加文本(或原始問題和圖標)時,綠色面板被迫變寬,並拋棄了我的整個布局。 無論內容如何,​​我都希望布局保持相同的權重。 出現此問題的原因是因為我試圖將縮放圖像作為圖標添加到標簽,如原始問題所示。

順便說一句, 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像素),並且也在左側邊緣(綠色)上擠壓。 有誰知道為什么會這樣嗎?

我已經嘗試了一些太冗長而無法解釋但找不到問題的東西:-/

在此處輸入圖片說明

您的組件得以擴展,因為它為其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());
    }
}

在此處輸入圖片說明


以下輸出到控制台:

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]

考慮使用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);
   }
}

Java搖擺對我來說已經很老了,但是如果我記得很好的話,設置一個首選大小(setPreferredSize())有時可以解決這類問題。也可以嘗試使用setMaximumSize和setMinimumSize進行頂層放置。

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

問候!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM