# Refactoring code duplication so the same textArea is not used in 4 different classes

Looking for the best way to do this. Currently in 4 different classes I have:

textArea = new JTextArea(10, 55) {
{
setOpaque(false);
}

@Override
protected void paintComponent(Graphics g) {
for (int i = 0; i < list.size(); i++) {
if(i == lineIndex)
g.setColor(Color.black);
g.drawRect(0, 20, 750, 20);
}
super.paintComponent(g);
}
};


I've simplified down what I actually have. As you can see there is duplication. The only data that is different is what is in the list. A list is passed into each of these classes There are some other stuff in the class which depends on the textarea and the lineIndex variable changes in the class depending on what the user does. I call the repaint() method of the textarea when I need the textarea to draw something else. The paintcomponent does a simple draw.

I'm not sure of the best way for each of the classes to contain the textarea so I dont have duplication. In each of the classes I have an addList(List list) method which the textareas need to use.

Hope I explained this ok.

Thanks

• Might help to have a little bit more of the code, but at the moment I don't see any reason you need to pass the list in (unless it changes size... with is problematic). Why not pass in the size - immediate code reuse... – Clockwork-Muse Dec 14 '11 at 0:37
• The content of each list is slightly different. I'm not sure what other code to put in. Maybe I could have a method in each class. Something like addTextAreaAndList(TextArea ta, List l) – Decrypter Dec 14 '11 at 11:19
• I'm assuming the contents of the list were different. You haven't included any code where that's relevant or referenced, though. Yes, you reference the size, but unless I see something different, there's no reason you can't pass in the integer index, and avoid the whole loop anyways. Also, you probably want to move that call to super.paintComponent() to before you paint the rectangle, as otherwise your painting will be 'behind' whatever the super call draws. – Clockwork-Muse Dec 14 '11 at 16:47

class MyTextArea extends JTextArea{

private final List<Foo> list;

MyTextArea(int row, int col, List<Foo> list) {
super(row, col);
this.list = list;
setOpaque(false);
}

@Override
protected void paintComponent(Graphics g) {
for (int i = 0; i < list.size(); i++) {
if(i == lineIndex)
g.setColor(Color.black);
g.drawRect(0, 20, 750, 20);
//use list...
}
super.paintComponent(g);
}
}