2016-08-30 3 views
0

Я хочу добавить ярлык динамически в панели с горизонтальной и вертикальной ориентацией. Я пробовал этот код.Как добавить динамическую кнопку в панели?

GridBagConstraints labelConstraints = new GridBagConstraints(); 

     // Add buttons 
     for(int i = 0; i < indexer; i++) 
     { 
      // Label constraints 
      labelConstraints.gridx = 1; 
      labelConstraints.gridy = i; 

      // Add them to panel     
      panel.add(listOfLabels.get(i), labelConstraints); 
     } 

     // Align components top-to-bottom 
     GridBagConstraints c = new GridBagConstraints(); 
     c.gridx = 0; 
     c.gridy = indexer; 
     c.weighty = 1; 
     panel.add(new JLabel(), c); 


     indexer++; 
    } 

, но мне нужно привести как это изображение:

view image

Я не хочу, чтобы изменить размер JLabel и количество ярлыка изменения.

+1

Может быть, если вы добавите, что вы получаете, люди могут помочь вам. – Harald

ответ

1

Я думаю, что вы не установили gridx и Gridy правильно, ниже коды надежда может решить проблему:

int rows = 5; 
    int columns = 5; 
    JLabel label; 
    pane.setLayout(new GridBagLayout()); 
    GridBagConstraints constraints= new GridBagConstraints(); 

    for(int rowIndex = 0; rowIndex < rows; rowIndex++){ 
     for(int columnIndex = 0 ; columnIndex < columns; columnIndex++){ 
      label = new JLabel(String.format("table row:%d, column:%d ", rowIndex+1,columnIndex+1)); 
      constraints.fill = GridBagConstraints.HORIZONTAL; 
      constraints.gridx = columnIndex; 
      constraints.gridy = rowIndex; 
      pane.add(label, constraints); 
     } 
    } 
2

Не уверен, что имелось в виду, добавив метку динамически здесь.

Для меня динамическое добавление компонента добавляет его в runtime. Следующий пример демонстрирует это с менеджером MigLayout:

package com.zetcode; 

import java.awt.event.ActionEvent; 
import javax.swing.BorderFactory; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.SwingUtilities; 

import net.miginfocom.swing.MigLayout; 

/* 
Demonstrating dynamic addition of labels 
with MigLayout manager. 

Author: Jan Bodnar 
Website: zetcode.com 
*/ 
public class MigLayoutDynamicLabelsEx extends JFrame { 

    private int counter = 0; 

    public MigLayoutDynamicLabelsEx() { 

     initUI(); 
    } 

    private void initUI() { 

     MigLayout layout = new MigLayout("wrap 4"); 
     setLayout(layout); 

     JButton addBtn = new JButton("Add"); 
     addBtn.addActionListener((ActionEvent e) -> { 
      JLabel lbl = createLabel(); 
      add(lbl, "w 100lp, h 30lp"); 
      pack(); 
     }); 

     add(addBtn); 
     add(createLabel(), "w 100lp, h 30lp"); 
     add(createLabel(), "w 100lp, h 30lp"); 
     add(createLabel(), "w 100lp, h 30lp"); 

     pack(); 

     setTitle("MigLayout dynamic example"); 
     setLocationRelativeTo(null); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 

    private JLabel createLabel() { 

     counter++; 
     String text = "#table no." + counter; 

     JLabel lbl = new JLabel(text); 
     lbl.setBorder(BorderFactory.createEtchedBorder()); 

     return lbl; 
    } 

    public static void main(String[] args) { 

     SwingUtilities.invokeLater(() -> { 
      MigLayoutDynamicLabelsEx ex = new MigLayoutDynamicLabelsEx(); 
      ex.setVisible(true); 
     }); 
    } 
} 

В начале, есть кнопка и три метки. Нажатие кнопки на кнопке добавляет новую метку в макет. Ограничение wrap 4 создает 4 столбца на строку. Окно реорганизуется с помощью метода pack().

Скриншот:

Screenshot of the example