简体   繁体   English

用Java生成jLabel代码

[英]Generate jLabel code in Java

Can anyone explain me why my code doesn't seem to work? 谁能解释我为什么我的代码似乎不起作用? Result of this code is an empty screen. 该代码的结果是一个空白屏幕。

Altough my labels array contains all and right labels. 我的标签数组完全包含所有和正确的标签。 I probably miss something but can't find out what.... thanks in advance! 我可能错过了一些东西,但找不到。

 //create the array
private static JLabel[] labels = new JLabel[135];

private  void setup(){

  for(int i = 0; i < labels.length; i++){
    int x; 
    int y = 0;
    int z = 0;
    int r;
    z++;
      if (z == 16) {
          z=0;
          y += 40;
      }
    x = 40*z+40;

    labels[i] = new JLabel("foo");
    labels[i].setText("test");
    labels[i].setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0,0,0)));
    labels[i].setMaximumSize(new java.awt.Dimension(32, 32));
    labels[i].setMinimumSize(new java.awt.Dimension(32, 32));
    labels[i].setPreferredSize(new java.awt.Dimension(32, 32)); 
    labels[i].setLocation(x, y);

    this.add(labels[i]);
    //this.setVisible(true);

  } 
  //this.pack();
  //this.rootPane.add(this);

}

The answer depends on what layout manager you use for your content pane (which you didn't post). 答案取决于您用于内容窗格(未发布)的布局管理器。

You add your labels to your JFrame like this: 您可以像这样将标签添加到JFrame

this.add(labels[i]);

JFrame.add() redirects to the add() method of the content pane which by default is a JPanel with BorderLayout layout manager. JFrame.add()重定向到内容窗格的add()方法,默​​认情况下是具有BorderLayout布局管理器的JPanel Calling add() on this will add the component to the center. 对此调用add()会将组件添加到中心。 Adding another component will replace the previously added component. 添加另一个组件将替换之前添加的组件。

So you end up with a Jrame which only has 1 JLabel added to its center. 因此,您最终得到一个Jrame ,其中心仅添加了1个JLabel Since the panel has a layout manager, you should not call setLocation() on its children. 由于面板具有布局管理器,因此不应在其子级上调用setLocation()

You may use a null layout (position components absolutely) which you may or may not do corrently as you did not post all your code. 您可以使用null布局(绝对定位组件),因为您未发布所有代码,所以您可能会或可能不会这样做。

Or use a proper layout manager which allows you to add many components to the Container like GridLayout or use Container s like Box . 或者使用适当的布局管理器,该管理器允许您将许多组件(例如GridLayout添加到Container或使用Container例如Box

This tutorial explains how to add JLabels to a JFrame. 教程说明了如何将JLabel添加到JFrame。

The following snippet from the tutorial is where your problem might lie: 教程中的以下片段可能是您的问题所在:

Now that we have created the JLabel, it needs to be added to the JFrame: 现在,我们已经创建了JLabel,需要将其添加到JFrame中:

frame.getContentPane().add(textLabel, BorderLayout.CENTER);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM