更改单个JOptionPane大小

时间:2015-11-27 00:55:04

标签: java swing layout

我需要帮助改变TextField的大小。我在面板的开头有一个JScrollPane(这很大,所以我可以读取更多数据),然后我有一个JLabel指令,最后我想添加一个JTextArea,我只需要一行输入一个数字。问题是面板中的元素非常大。 我附上结果:

Layout

这是我的代码:

public static void delete()
{
    int deletePosition;
    String[] options = {"Confirm", "Cancel"};
    JPanel panel = new JPanel();

    JLabel label0 = new JLabel("Write the Position[#]:");
    JLabel labelJump1 = new JLabel("");
    JTextField txtDelete = new JTextField(1);
    GridLayout gridLayout = new GridLayout(0,1);
    panel.setLayout(gridLayout);

    String fullText = "";
    JTextArea textArea = new JTextArea(15,30);
        textArea.setText(fullText);
        textArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(textArea);

    panel.add(scrollPane);
    panel.add(label0);
    panel.add(labelJump1);
    panel.add(txtDelete);

    try
    {
        if (theEntityCollection.checkEmpty())
            JOptionPane.showMessageDialog(null, "The collection is EMPTY");
        else
        {
            for(int i = 0 ; i < theEntityCollection.getArraySize() ; i++)
            {

                fullText += "Position [" + (i+1) + "]\n\n" + theEntityCollection.getEntity(i);
                    if (i != theEntityCollection.getArraySize() - 1)
                        fullText += "_____________________\n\n"; 
                textArea.setText(fullText);
            }
            deletePosition = JOptionPane.showOptionDialog(null, panel, "ENTITY COLLECTION", JOptionPane.NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options , options[0]);
        }
    }
    catch(Exception e)
    {
        System.out.println("FAILED");
    }
    fullText = "";
}

我必须说我是Java GUI的新手。

如果你能帮助我,我会非常感激!

1 个答案:

答案 0 :(得分:2)

GridLayout gridLayout = new GridLayout(0,1); panel.setLayout(gridLayout); 正在完成它的设计目标。它为每个组件提供了基于可用空间均匀分布的完全相同的空间量。您可能需要使用更灵活的布局管理器,例如......

从chaning开始...

GridBagLayout gridLayout = new GridBagLayout();
panel.setLayout(gridLayout);
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(2, 2, 2, 2);

类似......

panel.add(scrollPane);
panel.add(label0);
panel.add(labelJump1);
panel.add(txtDelete);

然后改变......

panel.add(scrollPane, gbc);
panel.add(label0, gbc);
panel.add(labelJump1, gbc);
panel.add(txtDelete, gbc);

更像是......

{{1}}

请查看Laying Out Components Within a ContainerHow to Use GridBagLayout了解详情