powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / SWT. Subclassing not allowed
11 сообщений из 11, страница 1 из 1
SWT. Subclassing not allowed
    #34633128
bemtaill
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Я хочу расширить функциональность swt List путем добавления пары методов, но получаю “Subclassing not allowed”. Я могу перегрузить checkSubclass, но это есть не хорошо как я понял. Насколько серьезны последствия данного подхода и как вообще можно расширять функциональность стандартных SWT виджетов?
...
Рейтинг: 0 / 0
SWT. Subclassing not allowed
    #34633460
Фотография Blazkowicz
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
По-моему там только Composite можно расширять и делать все что с ним хошь. При этом желательно иметь хороший экспириенс в WinAPI и думать о переносибельности на linux.
Связано это с тем что виджеты сильно завязаны на нативные контролы.
...
Рейтинг: 0 / 0
SWT. Subclassing not allowed
    #34633461
swt
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
глава из книги SWT: The Standard Widget Toolkit, Volume 1 :

книга
1.2.1 Subclassing in SWT
Generally speaking, subclassing is not the safest way to extend a class in an object-oriented language, due to the fragile superclass problem.

The term fragile superclass comes from the C++ programming world. It normally refers to the fact that when a new method or field is added to a superclass, subclasses need to be recompiled or they might corrupt memory. Java solves the static or binary compatibility portion of the problem using a name-lookup mechanism that is transparent to the programmer. However, there is also a dynamic portion of the problem where subclasses can inadver-tently depend on the implementation of a superclass. For example, a subclass may depend on the fact that the internal implementation of the superclass calls a certain public method that is reimplemented in the subclass. Should the superclass be changed to no longer call this method, the subclass will behave differently and might be subtly broken. In SWT, where the implementation of most classes differs between platforms, the chances of this happening are increased. For this reason, subclassing in arbitrary places in the Widget class hierarchy is discouraged by the implementation.

In order to allow subclassing where it is normally disallowed, the Widget method checkSubclass() must be redefined.


checkSubclass() Throws an SWTException("Subclassing not allowed") when the instance of the class is not an allowed subclass.


The protected method checkSubclass() is called internally by SWT when an instance of a widget is created. Subclasses can override this method to avoid the check and allow the instance to be created. The following code fragment defines an inner class that is a subclass of the class Label and reimplements the setText() method.

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
Label label = new Label(shell, SWT.NONE) {
    protected void checkSubclass() {

    }

    public void setText(String string) {
        System.out.println("Setting the string");

        super.setText(string);
    }
};


Why Aren't the Widget Classes "final"?
Java allows the programmer to tag a class as final, disallowing subclasses. In fact, in very early versions of SWT, classes that should not be subclassed were clearly marked as such using the final keyword. Unfortunately, this proved to be too inflexible. In particular, it meant that if a problem was found in an SWT class, only the SWT team could fix it. There was no way to temporarily "patch" the class by creating a subclass to override the problem method(s). Customers who needed to ship their product before a fix could be integrated into the next SWT release were willing to risk the dynamic fragile superclass problem in order to have the freedom to make this kind of patch. The checkSubclass() method is a compromise that allows them to do this without removing all constraints on subclassing.

It is important to note that this really is the only reason why the checkSubclass() method was added. Well-written SWT programs should never override checkSubclass().

In SWT, user interfaces are constructed by composition of widget instances. Event listeners (see Events and Listeners, below) are added to widgets to run application code when an event occurs, rather than overriding a method. Application programmers use listeners instead of subclassing to implement the code that reacts to changes in the user interface.

Subclassing is allowed in SWT but only at very controlled points, most notably, the classes that are used when implementing a custom widget: Composite or its subclass Canvas. To indicate this, the checkSubclass() method in Composite does not constrain the allowable subclasses. To create a new kind of widget in SWT, you would typically subclass Canvas, then implement and use event listeners to give it the required appearance and behavior. Note that you should still not reference internal details of the superclasses, because they may vary significantly between platforms and between subsequent versions of SWT. For an example of creating a custom widget, see MineSweeper in the Applications part of the book.[10]

[10] A good article that describes how to create custom widgets, entitled Creating Your Own Widgets Using SWT, can be found in the "articles" area at www.eclipse.org.
...
Рейтинг: 0 / 0
SWT. Subclassing not allowed
    #34634141
bemtaill
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Мда. Жаль.
Спасибо всем.
...
Рейтинг: 0 / 0
SWT. Subclassing not allowed
    #34634271
Juga
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Проблемы никакой нет. Ну нельзя наследовать, но обёртку то никто не мешает написать.
...
Рейтинг: 0 / 0
SWT. Subclassing not allowed
    #34640886
bemtaill
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
JugaПроблемы никакой нет. Ну нельзя наследовать, но обёртку то никто не мешает написать.

Пишу оболочку вот вопрос возник. У меня раньше было так :

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
  
 class  Test{
  private   void  initGui(){
  CheckboxTableViewer dependenceTableViewer =  new  CheckboxTableViewer (...);
  dependenceTableViewer.addSelectionChangedListener( new  ISelectionChangedListener(){
       public   void  selectionChanged(SelectionChangedEvent event) {
          //...........
          updateStatus(); 
        }
      });
  }

   private  updateStatus(){
     //........
  }
}

Я сделал оболочку для CheckboxTableViewer и теперь имею:
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
 public   class  DependenceTable {
    private  Table table;
    private  List<String> defaultDependenceList;
    private  List<String> tableModelDependenceList;
    private  CheckboxTableViewer dependenceTableViewer;
   ..............
}

 class  Test{
  private   void  initGui(){
    DependenceTable dependenceTable=  new  DependenceTable (...);
    // И тут мне нужно по идее добавить listener который бы слушал события для 
   // dependenceTableViewer и при получении данного события вызывал бы приватный метод 
   // updateStatus() класса Test. Как  реализовать  данную схему?
  }

   private  updateStatus(){
     //........
  }
}
...
Рейтинг: 0 / 0
SWT. Subclassing not allowed
    #34641954
Juga
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Пишеш метод для класса оболочки
Код: plaintext
1.
2.
addListener( int  eventType, Listener listener){
                             dependenceTableViewer.addListener(eventType, listener);
                    }
в общем никаких проблем.
...
Рейтинг: 0 / 0
SWT. Subclassing not allowed
    #34641957
Juga
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
в реализации listener'a указываеш что ему делать
...
Рейтинг: 0 / 0
SWT. Subclassing not allowed
    #34642337
bemtaill
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Jugaв реализации listener'a указываеш что ему делать
Проблема в том что метод updateStatus приватный в классе Test и из реализации listener'а его видно не будет. А делать его public я не хочу. Как быть?
...
Рейтинг: 0 / 0
SWT. Subclassing not allowed
    #34642949
Juga
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
у листнера есть аргумент Event который всегда знает кто его вызвал.
...
Рейтинг: 0 / 0
SWT. Subclassing not allowed
    #34643040
bemtaill
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Jugaу листнера есть аргумент Event который всегда знает кто его вызвал.
Спасибо, разобрался.
...
Рейтинг: 0 / 0
11 сообщений из 11, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / SWT. Subclassing not allowed
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]