初始化后的JPanel的setSize

时间:2011-05-24 12:17:47

标签: java swing jpanel

我引入一个ResultSet来显示我的表的内容。事情是,虽然结果显示我一直在尝试调整JPanel的高度,以便一旦填充它就会显示。我尝试在setSize(300, y)循环中使用while(ResultSet.next),并在循环之外尝试使用它。但是什么都没有 这是我的代码:

package SimpleCRUD;

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class ShowContactsFrame extends JFrame {
    GridBagLayout layout = new GridBagLayout();
    GridBagConstraints Constraint = new GridBagConstraints();
    JLabel lblFname, lblLname, lblPhoneNumber;
    Statement st;
    String showAll = "SELECT * FROM `contacts`.`contacts`;";
    ResultSet rt;
    int y = 0;

    public ShowContactsFrame() {
        super("Contact List");
        try {
            AppCRUD initCRUD = new AppCRUD();
            rt = initCRUD.DBhandle.createStatement().executeQuery(showAll);

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel panel = new JPanel(layout);
        add(panel);
        getContentPane().add(panel, BorderLayout.NORTH);

        lblFname = new JLabel("lblFname");
        lblLname = new JLabel("lblLname");
        lblPhoneNumber = new JLabel("lblPhoneNumber");

        Insets inset = new Insets(10, 10, 10, 10);

        Constraint.insets = inset;

        try {
            while (rt.next()) {
                Constraint.gridx = 0;
                Constraint.gridy = y;
                panel.add(new JLabel(rt.getString(2)), Constraint);
                Constraint.gridx = 1;
                Constraint.gridy = y;
                panel.add(new JLabel(rt.getString(3)), Constraint);
                Constraint.gridx = 2;
                Constraint.gridy = y;
                panel.add(new JLabel(rt.getString(4)), Constraint);
                y++;
                panel.setSize(300, y);
            }

        } catch (Exception ex) {

            ex.printStackTrace();
        }
        JOptionPane.showMessageDialog(null, y);

    }

}

2 个答案:

答案 0 :(得分:3)

如果您想设置面板的大小,请按以下顺序使用setPreferredSize()代替setSize()

panel.setPreferredSize(new Dimension(300, 300));
frame.pack();
frame.setVisible(true);

您必须这样做,因为组件由布局管理器控制,因此忽略了对setSize()的调用。然后仅在setLayout()为空时使用,即不使用经理。

答案 1 :(得分:1)

我建议您在构建GUI元素并设置大小后在JFrame上调用pack()。