我正在创建具有一些类似元素的 GUI 应用程序,因此重复代码;只有变量不同。例如,我有这样的事情:
lenPan2 = new JPanel();
lenPan2.setLayout(new GridBagLayout());
bTitled2 = BorderFactory.createTitledBorder(bGreyLine, "Example", TitledBorder.LEFT, TitledBorder.TOP);
lenPan2.setBorder(bTitled2);
tVllResult = new JTextField("");
tVllResult.setColumns(10);
tVllResult.setFont(defFont);
lenPan2.add(tVllResult, new GBC(10, 2, 2, 1));
String[] vllOutUnits = {"Unit 0", "Unit 1", "Unit 2", "Unit 3", "Unit 4"};
cVllOutUnit = new JComboBox<String>(vllOutUnits);
cVllOutUnit.setSelectedIndex(1);
cVllOutUnit.setPreferredSize(new Dimension(240, 25));
cVllOutUnit.setFont(defFont);
lenPan2.add(cVllOutUnit, new GBC(12, 2, 4, 1));
cVllOutUnit.addActionListener(this);
在这种情况下,变量是:lenPan2、bTitled2、tVllResult、vllOutUnits、cVllOutUnit和边框标题。我可以以某种方式创建一个包含所有这些数据并且只将变量作为参数提供的方法吗?
我在想类似的事情:
private static insertElement(JPanel jp, BorderFactory bf, JTextField jtf, String bt, String[] vll, JComboBox cvl)
{
this.jp = jp;
this.bf = bf;
(...)
jp = new JPanel();
jp.setLayout(new GridBagLayout());
bf = BorderFactory.createTitledBorder(bGreyLine, bt, TitledBorder.LEFT, TitledBorder.TOP);
jp.setBorder(bf);
(...)
调用者:
insertElement(lenPan2, bTitled2, tVllResult, Example, {"Unit 0", "Unit 1", "Unit 2", "Unit 3", "Unit 4"}, cVllOutUnit);
它是正确的还是你会推荐任何其他方式?