I had 9 hunks of form-identical code such as this:
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
btnExitActionPerformed(evt);
}
});
...with 9 corresponding linked hunks of code like this:
private void btnExitActionPerformed(ActionEvent evt) {
// some code *********************
}
... and a large number of similar repeated hunks of code
for FocusListener
and MouseListener
.
I tried to cut down the number of lines of code by assigning the button's text to its action command and using this:
public void actionPerformed(ActionEvent e)
{
String c = e.getActionCommand();
switch (c) {
case "Clear output": btnClearOutputActionPerformed(e); break;
case "Search": btnSearchActionPerformed(e); break;
case "Exit": btnExitActionPerformed(e); break;
...
}
}
It works, but that's not a lot better. Still repetitive. Looking for elegant.
I can't believe the following method even compiles, but it doesn't work because doClick()
calls the method recursively. I was naively hoping doClick()
would execute the method btnPatternMouseClickedActionPerformed()
.
public void actionPerformed(ActionEvent e){
Component[] c ;
c = theFrame.getComponents();
JButton b;
for(Component x: c)
{
if(x instanceof JButton)
{
b = (JButton) x;
if(b.getText().equals(e.getActionCommand()))
{
b.doClick(); // want it to execute code elsewhere
return;
}
}
}
}
At first I thought the above method was close. Now I'm about to give up.
I have three questions:
(1) Is there a way to cut down on such repeated hunks of code as shown in the first two paragraphs?
(1a) Is the last method above close? Can it be easily fixed?
(2) Would a technique similar to the actionPerformed
method above (the one that uses switch
) to replace hunks of code for FocusListener
and MouseListener
be a waste of time to implement?