我需要帮助更改文本字段的大小。我在面板的开头有一个 JScrollPane (它很大,所以我可以读取更多数据),然后我有一个用于说明的 JLabel,最后我想添加一个 JTextArea,我只需要一行来输入数字。问题是面板中的元素相当大。 我附上结果:
这是我的代码:
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 的新手。
如果您能帮助我,我将不胜感激!
最佳答案
GridLayout
正在执行其设计目的。它为每个组件提供完全相同的空间量,根据可用空间均匀分布。您可能需要使用更灵活的布局管理器,例如......
从改变开始...
GridLayout gridLayout = new GridLayout(0,1);
panel.setLayout(gridLayout);
类似...
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);
看看Laying Out Components Within a Container和 How to Use GridBagLayout了解更多详情
关于java - 更改单个 JOptionPane 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33948947/