I’m creating GUI application which has a few similar elements, so the code is repeated; only variables differ. For example, I have something like this:
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);
In this case variables are: lenPan2, bTitled2, tVllResult, vllOutUnits, cVllOutUnit and border title. Can I somehow create a method which would contain all this data and would only be given variables as arguments?
I was thinking about something like:
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);
(...)
called by:
insertElement(lenPan2, bTitled2, tVllResult, Example, {"Unit 0", "Unit 1", "Unit 2", "Unit 3", "Unit 4"}, cVllOutUnit);
Would it be correct or you’d recommend any other way?
Yes, you can certainly create a helper method to do the GUI creation for you.
Will it make your code easier to read? Sure.
Will it make your code easier to maintain? Sure.
Will it make your code faster (i.e. “optimized”)? No.