Trying to create multiple JLabels, however only one is appearing

后端 未结 4 1212
时光说笑
时光说笑 2021-01-20 02:23

I am trying to create multiple JLabels of the same form and then trying to add them to the same JPanel. However, only one of the JLabels appears and I can\'t figure out why!

4条回答
  •  孤街浪徒
    2021-01-20 02:47

    You can not use BorderLayout for that, because that layout has only room for 5 components: BorderLayout.CENTER, BorderLayout.NORTH, BorderLayout.WEST, BorderLayout.SOUTH, BorderLayout.EAST.

    Solution with one of the built in layouts:

    I would suggest using a FlowLayout or a GridLayout, depending on what you want. You can still use BorderLayout as outer panel, but just introduce an inner panel with one of the above mentioned layouts.

    So with a GridLayout, you would wrap your labels in a grid layout and then put this one in your border layout. Your code would look like this:

    panel.setLayout(new BorderLayout());
    final JPanel upperPanel = new JPanel(); 
    panel.add(upperPanel, BorderLayout.NORTH); // add some stuff in the north
    
    final JPanel innerPanel = new JPanel(new GridLayout(1,0));
    JLabel[] dashedLineLabel = new JLabel[wordLength];
    for (int i = 0; i < wordLength; i++) {   
        dashedLineLabel[i] = new JLabel("__  ");
        dashedLineLabel[i].setFont(new Font("Serif", Font.BOLD, 30));
        innerPanel.add(dashedLineLabel[i]);
    } 
    
    panel.add(innerPanel, BorderLayout.CENTER);
    

    Solution with MigLayout:

    If you don't want to choose between different layouts, you can also use MigLayout, which is a 3rd party layout manager, that basically gives you all the options in one manager. And you will have a lot cleaner code (imho). The disadvantage is of course that you have to use an external jar file as dependency. (By the way: Since I found out about MigLayout, I have never used another layout manager again.)

    With MigLayout:

    final JPanel labelPanel = new JPanel(new MigLayout("", "", "")); 
    panel.add(labelPanel, "north");
    
    JLabel[] dashedLineLabel = new JLabel[wordLength];
    for (int i = 0; i < wordLength; i++) {   
        dashedLineLabel[i] = new JLabel("__  ");
        dashedLineLabel[i].setFont(new Font("Serif", Font.BOLD, 30));
        panel.add(dashedLineLabel[i], "wrap");
    }
    

提交回复
热议问题