Как изменить переменную в конкретном декораторе во время выполнения в java
Вот такая ситуация.
Абстрактный класс Items с JLabel label
, а display()
функция для отображения элемента на экране, добавив JLabel в JPanel:
public abstract class Items {
public JLabel label;
// to add label to panel (display on screen)
public abstract void display(JPanel panel);
}
Конкретная реализация:
public class ConcreteItem extends Items {
public ConcreteItem() {
// set the label of concrete item
ImageIcon icon = new ImageIcon(new URL("https://..."));
this.label = new JLabel(icon);
}
@Override
public void display(JPanel panel) {
panel.add(this.label);
}
}
Декоратор:
public abstract class ItemDecorator extends Items {
public Items decoratedItem;
public ItemDecorator(Items decoratedItem){
super();
this.decoratedItem = decoratedItem;
}
@Override
public void display(JPanel panel) {
this.item.display(panel);
}
}
и бетонный декоратор:
public class ConcreteDecorator extends ItemDecorator {
public ConcreteDecorator(Items decoratedItem) {
super(decoratedItem);
// set the label of concrete decorator
ImageIcon icon = new ImageIcon(new URL("https://..."));
this.label = new JLabel(icon);
}
@Override
public void display(JPanel panel) {
super.display(panel);
panel.add(this.label); // add label of concrete decorator to the screen
}
}
и клиентский класс:
public class Client {
public Client() {
Jpanel panel = new JPanel();
// create item with decorators (these are created somewhere else, furthur being returned to Client class)
ConcreteItem concreteItem = new ConcreteItem();
ConcreteDecorator decorator = new ConcreteDecorator(concreteItem);
// and this is the only stuff in Client class
Items item = decorator;
// display all elements on screen
item.display(panel);
}
}
Поэтому, когда я создаю Items
объект украшен ConcreteDecorator
, то display()
функция должна добавить все метки на панель. И я хотел бы установить видимость метки в ConcreteDecorator наfalse
, т.е. label.setVisible(false)
, во время выполнения, чтобы убрать его с экрана. Как я могу сделать это из класса Client, используя толькоitem
объект?
2 ответа
Как flag
является общедоступным полем, вы должны просто иметь возможность вызывать его из Client
учебный класс:
item.flag = false;
Что-то вроде странной иерархии классов...
Поскольку flag
является общедоступным полем, вы можете изменить его везде, где есть доступ к экземпляру Items
, нравиться:
public class ConcreteDecorator extends ItemDecorator {
public ConcreteDecorator(Items item) {
super(item);
}
@Override
public void display() {
item.flag = false; // <<< change flag here
super.display();
System.out.print("Adding decorators to Item...");
}
}
Помимо шаблона декоратора, у вас должна быть более строгая видимость; использоватьprivate
а также protected
везде, где возможно.