Ячейка GridBagLayout, занимающая весь ряд

1

Я создаю небольшое приложение java swing, и мне нужно создать таблицу с gridBagLayout в scrollpane.

Сначала GridBagLayout не выравнивается в верхней части панели.

Во-вторых, если я центрирую (1,2,3,4) ячейки, они центрируются в середине панели (не в середине ячейки).

Что я делаю не так?

Вот мой код:

//Folder --------------------------------------------------------
    folderPanel.setBackground(Color.WHITE);
    folderPanel.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridheight = 1;
    gbc.gridwidth = 1;
    gbc.weightx = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.anchor = GridBagConstraints.NORTHWEST;

    JLabel iCell = new JLabel();
    JLabel nameCell = new JLabel();
    JLabel typeCell = new JLabel();
    JLabel dateCell = new JLabel();
    iCell.setPreferredSize(new Dimension(50, 60));
    iCell.setHorizontalAlignment(SwingConstants.CENTER);
    nameCell.setPreferredSize(new Dimension(50, 60));
    nameCell.setHorizontalAlignment(SwingConstants.CENTER);
    typeCell.setPreferredSize(new Dimension(50, 60));
    typeCell.setHorizontalAlignment(SwingConstants.CENTER);
    dateCell.setPreferredSize(new Dimension(50, 60));
    dateCell.setHorizontalAlignment(SwingConstants.CENTER);
    int gridy = 0;
    int i = 0;

    iCell.setText("#");
    gbc.gridx = 0;
    gbc.gridy = gridy;
    folderPanel.add(iCell, gbc);
    //---------------------------------------------
    nameCell.setText("Name");
    gbc.gridx = 1;
    gbc.gridy = gridy;
    folderPanel.add(nameCell, gbc);
    //---------------------------------------------
    typeCell.setText("Type");
    gbc.gridx = 2;      
    gbc.gridy = gridy;
    folderPanel.add(typeCell, gbc);     
    //---------------------------------------------
    dateCell.setText("Date");
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.gridx = 3;  
    gbc.gridy = gridy;
    folderPanel.add(dateCell, gbc);

    gridy++;
    i++;

    DBCursor cursor = imagesCollection.find();
    try {
        while(cursor.hasNext()) {
            DBObject obj = cursor.next();

            iCell = new JLabel();
            nameCell = new JLabel();
            typeCell = new JLabel();
            dateCell = new JLabel();
            iCell.setPreferredSize(new Dimension(50, 60));
            nameCell.setPreferredSize(new Dimension(50, 60));
            typeCell.setPreferredSize(new Dimension(50, 60));
            dateCell.setPreferredSize(new Dimension(50, 60));

            iCell.setText(Integer.toString(i));
            gbc.gridx = 0;
            gbc.gridy = gridy;
            folderPanel.add(iCell, gbc);
            //---------------------------------------------
            nameCell.setText((String) obj.get("name"));
            gbc.gridx = 1;
            gbc.gridy = gridy;
            folderPanel.add(nameCell, gbc);
            //---------------------------------------------
            typeCell.setText((String) obj.get("type"));
            gbc.gridx = 2;      
            gbc.gridy = gridy;
            folderPanel.add(typeCell, gbc);     
            //---------------------------------------------
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            dateCell.setText(df.format(obj.get("creationDate")));
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.gridx = 3;  
            gbc.gridy = gridy;
            folderPanel.add(dateCell, gbc);

            gridy++;
            i++;
        }

    } finally {
       cursor.close();
    }
    JScrollPane scroller = new JScrollPane(folderPanel);
  • 2
    Пожалуйста, рассмотрите возможность размещения MCVE .
  • 2
    Вы забыли weightx/weighty значения? Или это умышленно !!!! Высоко ценится грубый рисунок (на бумаге и создание снимка с помощью мобильного телефона / планшета / других устройств) того, как именно должен выглядеть вид.
Теги:
swing
layout-manager
gridbaglayout

2 ответа

2
Лучший ответ
//Folder --------------------------------------------------------
folderPanel.setBackground(Color.WHITE);
folderPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 1;
gbc.weighty = 0;    /////////////////////////////   added
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.NORTHWEST;

JLabel iCell = new JLabel();
JLabel nameCell = new JLabel();
JLabel typeCell = new JLabel();
JLabel dateCell = new JLabel();
iCell.setPreferredSize(new Dimension(50, 60));
iCell.setHorizontalAlignment(SwingConstants.CENTER);
nameCell.setPreferredSize(new Dimension(50, 60));
nameCell.setHorizontalAlignment(SwingConstants.CENTER);
typeCell.setPreferredSize(new Dimension(50, 60));
typeCell.setHorizontalAlignment(SwingConstants.CENTER);
dateCell.setPreferredSize(new Dimension(50, 60));
dateCell.setHorizontalAlignment(SwingConstants.CENTER);
int gridy = 0;
int i = 0;

iCell.setText("#");
gbc.gridx = 0;
gbc.gridy = gridy;
folderPanel.add(iCell, gbc);
//---------------------------------------------
nameCell.setText("Name");
gbc.gridx = 1;
gbc.gridy = gridy;
folderPanel.add(nameCell, gbc);
//---------------------------------------------
typeCell.setText("Type");
gbc.gridx = 2;      
gbc.gridy = gridy;
folderPanel.add(typeCell, gbc);     
//---------------------------------------------
dateCell.setText("Date");
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 3;  
gbc.gridy = gridy;
folderPanel.add(dateCell, gbc);

gbc.weighty = 1;        ////////////////////////   added
gridy++;
i++;

DBCursor cursor = imagesCollection.find();
try {
    while(cursor.hasNext()) {
        DBObject obj = cursor.next();

        iCell = new JLabel();
        nameCell = new JLabel();
        typeCell = new JLabel();
        dateCell = new JLabel();
        iCell.setPreferredSize(new Dimension(50, 60));
        nameCell.setPreferredSize(new Dimension(50, 60));
        typeCell.setPreferredSize(new Dimension(50, 60));
        dateCell.setPreferredSize(new Dimension(50, 60));

        iCell.setText(Integer.toString(i));
        gbc.gridx = 0;
        gbc.gridy = gridy;
        folderPanel.add(iCell, gbc);
        //---------------------------------------------
        nameCell.setText((String) obj.get("name"));
        gbc.gridx = 1;
        gbc.gridy = gridy;
        folderPanel.add(nameCell, gbc);
        //---------------------------------------------
        typeCell.setText((String) obj.get("type"));
        gbc.gridx = 2;      
        gbc.gridy = gridy;
        folderPanel.add(typeCell, gbc);     
        //---------------------------------------------
        DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        dateCell.setText(df.format(obj.get("creationDate")));
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.gridx = 3;  
        gbc.gridy = gridy;
        folderPanel.add(dateCell, gbc);

        gridy++;
        i++;
    }

} finally {
   cursor.close();
}
JScrollPane scroller = new JScrollPane(folderPanel);
1

Я решил проблему, связанную со всей ячейкой:

Я должен был добавить gbc gridheight и gridwidth каждый раз, когда я установил новую строку:

gbc.gridheight = 1;
gbc.gridwidth = 1;

Код:

//Folder ----------------------'----------------------------------
    folderPanel.setBackground(Color.WHITE);
    folderPanel.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridheight = 1;
    gbc.gridwidth = 1;
    gbc.weightx = 1;
    gbc.weighty = 0;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.anchor = GridBagConstraints.NORTHWEST;

    JLabel iCell = new JLabel();
    JLabel nameCell = new JLabel();
    JLabel typeCell = new JLabel();
    JLabel dateCell = new JLabel();
    iCell.setPreferredSize(new Dimension(50, 60));
    //iCell.setHorizontalAlignment(SwingConstants.CENTER);
    nameCell.setPreferredSize(new Dimension(50, 60));
    //nameCell.setHorizontalAlignment(SwingConstants.CENTER);
    typeCell.setPreferredSize(new Dimension(50, 60));
    //typeCell.setHorizontalAlignment(SwingConstants.CENTER);
    dateCell.setPreferredSize(new Dimension(50, 60));
    //dateCell.setHorizontalAlignment(SwingConstants.CENTER);
    int gridy = 0;
    int i = 0;

    iCell.setText("#");
    gbc.gridx = 0;
    gbc.gridy = gridy;
    folderPanel.add(iCell, gbc);
    //---------------------------------------------
    nameCell.setText("Name");
    gbc.gridx = 1;
    gbc.gridy = gridy;
    folderPanel.add(nameCell, gbc);
    //---------------------------------------------
    typeCell.setText("Type");
    gbc.gridx = 2;      
    gbc.gridy = gridy;
    folderPanel.add(typeCell, gbc);     
    //---------------------------------------------
    dateCell.setText("Date");
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.gridx = 3;  
    gbc.gridy = gridy;
    folderPanel.add(dateCell, gbc);

    gbc.weighty = 1;
    gridy++;
    i++;

    DBCursor cursor = imagesCollection.find();
    try {
        while(cursor.hasNext()) {
            DBObject obj = cursor.next();

            iCell = new JLabel();
            nameCell = new JLabel();
            typeCell = new JLabel();
            dateCell = new JLabel();
            iCell.setPreferredSize(new Dimension(50, 60));
            nameCell.setPreferredSize(new Dimension(50, 60));
            typeCell.setPreferredSize(new Dimension(50, 60));
            dateCell.setPreferredSize(new Dimension(50, 60));
            MatteBorder border = new MatteBorder(1,
                    0,
                    0,
                    0,
                    Color.GRAY);
            iCell.setBorder(border);
            nameCell.setBorder(border);
            typeCell.setBorder(border);
            dateCell.setBorder(border);
            gbc.gridheight = 1; //////////// ADDED
            gbc.gridwidth = 1; //////////// ADDED

            iCell.setText(Integer.toString(i));
            gbc.gridx = 0;
            gbc.gridy = gridy;
            folderPanel.add(iCell, gbc);
            //---------------------------------------------
            nameCell.setText((String) obj.get("name"));
            gbc.gridx = 1;
            gbc.gridy = gridy;
            folderPanel.add(nameCell, gbc);
            //---------------------------------------------
            typeCell.setText((String) obj.get("type"));
            gbc.gridx = 2;      
            gbc.gridy = gridy;
            folderPanel.add(typeCell, gbc);     
            //---------------------------------------------
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            dateCell.setText(df.format(obj.get("creationDate")));
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.gridx = 3;  
            gbc.gridy = gridy;
            folderPanel.add(dateCell, gbc);

            gridy++;
            i++;
        }

    } finally {
       cursor.close();
    }

    JScrollPane scroller = new JScrollPane(folderPanel);
    scroller.setViewportBorder(new MatteBorder(10, 10, 10, 10, Color.WHITE));


    //Setting --------------------------------------------------------
    address.setFont(textFieldPolice);
    address.setPreferredSize(new Dimension(150, 30));
    address.setForeground(Color.BLACK);
    address.setText(setting.getAddress());
    password.setFont(textFieldPolice);
    password.setPreferredSize(new Dimension(150, 30));
    password.setForeground(Color.BLACK);
    password.setText(setting.getPassword());

    GridLayout glSetting = new GridLayout();
    glSetting.setColumns(1);
    glSetting.setRows(3);
    glSetting.setHgap(10);
    glSetting.setVgap(10);
    settingForm.setLayout(glSetting);   
    settingForm.add(addressLabel);
    settingForm.add(address);
    settingForm.add(passwordLabel);
    settingForm.add(password);
    settingForm.add(saveButton);

    GridBagConstraints gbcSetting = new GridBagConstraints();
    gbcSetting.weightx = 1;
    gbcSetting.weighty = 1;
    gbcSetting.anchor = GridBagConstraints.NORTHWEST;

    gbcSetting.gridx = 0;
    gbcSetting.gridy = 0;
    settingPanel.setLayout(new GridBagLayout());
    settingPanel.add(settingForm, gbcSetting);
    JPanel settingPaddingPanel = new JPanel();
    settingPaddingPanel.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5));
    settingPaddingPanel.setBackground(Color.WHITE);
    settingPaddingPanel.add(settingPanel);

    //Main ------------------------------------------------------------
    pan.setLayout(cl);
    pan.add(scroller, "folderPanel");
    pan.add(latestPanel, "latestPanel");
    pan.add(settingPaddingPanel, "settingPanel");

    this.getContentPane().add(header, BorderLayout.NORTH);
    this.getContentPane().add(menu, BorderLayout.WEST);
    this.getContentPane().add(pan, BorderLayout.CENTER);

    this.setVisible(true);
}
  • 0
    IHMO, прекратите использование setXxXSize() , когда вы используете Layout Manager макетов, так как эта часть вычисления размера JComponent относится к макету.
  • 1
    Вот этот пример , содержит немного объяснения того, что такое weightx/weighty . Надеюсь, это поможет вам и в ваших начинаниях :-)
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню