有没有办法将JLabel的PreferredSize设置为其组件的大小?

时间:2015-03-06 01:17:38

标签: java swing jlabel

有没有办法获得JLabel组件的(首选我猜测)大小,以便我可以调整它们的大小?我的JLabel大小为0,0,除非我设置了它的首选大小,但将其大小设置为任意像素值似乎是错误的方法,因为使用Swing的整个观点(据我所知)并没有这样做

我已经尝试过的事情:

  • repaint()和refactor()
  • 将LayoutManager添加到JPanel(在本例中为BoxLayout)

这基本上就是我在做的事情:

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

}

}

1 个答案:

答案 0 :(得分:3)

我很好奇您为什么要使用JLabel作为容器,但是...

类似于,覆盖JLabel的{​​{1}}方法......

getPreferredSize

会让你开始。这并没有考虑到任何边界的要求,如果它对您很重要,您也需要添加这些要求......

这也假定您已将布局管理器应用于@Overrride public Dimension getPreferredSize() { LayoutManager lm = getLayout(); return lm.preferredLayoutSize(this); }