1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
GridBagConstraints c = new GridBagConstraints(); c.insets.bottom = 2; c.insets.top = 2; c.insets.left = 2; c.insets.right = 2; JTextArea area = new JTextArea(); c.weighty = 1; panel.add(area, c); c.weighty = 0; for (int i = 9; i >= 1; i--) { switch (i) { case 9: c.gridx = 2; c.gridy++; break; case 8: c.gridx--; break; case 7: c.gridx--; break; case 6: c.gridx = 2; c.gridy++; break; case 5: c.gridx--; break; case 4: c.gridx--; break; case 3: c.gridx = 2; c.gridy++; break; case 2: c.gridx--; break; case 1: c.gridx--; break; } panel.add(new JButton(String.valueOf(i)), c); }
Refactorings
No refactoring yet !
Elij
November 21, 2007, November 21, 2007 05:08, permalink
I've demonstrated using fall through's
However you could use delegates instead of a switch statement...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
GridBagConstraints c = new GridBagConstraints(); c.insets.bottom = 2; c.insets.top = 2; c.insets.left = 2; c.insets.right = 2; JTextArea area = new JTextArea(); c.weighty = 1; panel.add(area, c); c.weighty = 0; for (int i = 9; i >= 1; i--) { switch (i) { case 9: case 6: case 3: c.gridx = 2; c.gridy++; break; case 8: case 7: case 5: case 4: case 2: case 1: c.gridx--; break; } panel.add(new JButton(String.valueOf(i)), c); }
Andy
November 26, 2007, November 26, 2007 23:38, permalink
Here's a version without the switch. Note that you have to add 3 to i in the if statement so that it does not evaluate true when i = 1, 2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
GridBagConstraints c = new GridBagConstraints(); c.insets.bottom = 2; c.insets.top = 2; c.insets.left = 2; c.insets.right = 2; JTextArea area = new JTextArea(); c.weighty = 1; panel.add(area, c); c.weighty = 0; for (int i = 9; i >= 1; i--) { if ((i + 3) % 3 == 0) { c.gridx = 2; c.gridy++; else c.gridx--; panel.add(new JButton(String.valueOf(i)), c); }
Andy
November 26, 2007, November 26, 2007 23:45, permalink
Sorry, I left out a closing bracket.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
GridBagConstraints c = new GridBagConstraints(); c.insets.bottom = 2; c.insets.top = 2; c.insets.left = 2; c.insets.right = 2; JTextArea area = new JTextArea(); c.weighty = 1; panel.add(area, c); c.weighty = 0; for (int i = 9; i >= 1; i--) { if ((i + 3) % 3 == 0) { c.gridx = 2; c.gridy++; } else c.gridx--; panel.add(new JButton(String.valueOf(i)), c); }
Writing a calculator type app in java, so this just adds the buttons, using GridBagLayout. Can anyone think of a better way to do the layout properties instead of the switch statement?