简体   繁体   中英

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:

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. Calling add() on this will add the component to the center. 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. Since the panel has a layout manager, you should not call setLocation() on its children.

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.

Or use a proper layout manager which allows you to add many components to the Container like GridLayout or use Container s like Box .

This tutorial explains how to add JLabels to a 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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