Java 摇摆:
我创建了一个返回 GridBagConstraints 的方法,这样我就不需要不断调用 new GridBagConstraints(); 并设置一堆变量。它是这样工作的:
displayPanel.add(labelPanel, createGBC(0, 0, 2);
displayPanel.add(nosePanel, createGBC(1, 0, 3);
displayPanel.add(mainPanel, createGBC(2, 0, 3);
ETC..
我的 createGBC 的代码:
private GridBagConstraints createGBC(int x, int y, int z) {
gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.anchor = (x == 0) ? GridBagConstraints.EAST : GridBagConstraints.WEST;
if (z == 0) gbc.insets = new Insets(0, 0, 0, 0);
else if (z == 1) gbc.insets = new Insets(8, 0, 0, 0);
else if (z == 2) gbc.insets = new Insets(4, 4, 0, 4);
else if (z == 3) gbc.insets = new Insets(0, 2, 0, 2);
else if (z == 4) gbc.insets = new Insets(0, 0, 16, 0);
else if (z == 5) gbc.insets = new Insets(6, 0, 16, 0);
return gbc;
}
我的问题是:有没有比简单地做大量 else if 语句更好的方法来处理许多不同的插图?我目前的方法出现了几个问题。
我开始忘记将哪些插图分配给 z 的哪个值。(我正在尝试重构以使其更具可读性/可重用性)。
实际上,我可能不得不添加更多的嵌入预设,这将复合问题 1。