patternjavaMinor
Refactoring code duplication so the same textArea is not used in 4 different classes
Viewed 0 times
refactoringsametheduplicationuseddifferenttextareaclassescodenot
Problem
Looking for the best way to do this.
Currently in 4 different classes I have:
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
A list is passed into each of these classes
There are some other stuff in the class which depends on the textarea and the
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
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
Solution
Write your own class:
class MyTextArea extends JTextArea{
private final List list;
MyTextArea(int row, int col, List 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);
}
}Code Snippets
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);
}
}Context
StackExchange Code Review Q#6806, answer score: 6
Revisions (0)
No revisions yet.