Los eventos de comboboxmodel no funcionan -- java campo con swing campo con events campo con listener camp Relacionados El problema

ComboBoxModel events not working


3
vote

problema

Español

Parece que no puedo entender el concepto de eventos y tales. Después de leer un rato sobre cómo implementar a los oyentes y, tal, me encontré con el tutorial de Java que dice que debería extender #import "DetailOfUser.h" @interface DetailsOfStories () { NSMutableArray *descriptionList; BOOL buttonToggled; int number,number1; NSNumber *num1; } @end @implementation DetailsOfStories @synthesize descriptionList; - (void)viewDidLoad { UILabel *like_count=(UILabel *)[self.view viewWithTag:3]; NSNumber *someNumber = @(number); NSString *someString = [someNumber stringValue]; like_count.text=someString; } - (IBAction)like:(id)sender { if (!buttonToggled) { [sender setTitle:@"Unlike" forState:UIControlStateNormal]; //number is interger number = [num1 intValue]+1; number1=number; UILabel *like_count=(UILabel *)[self.view viewWithTag:3]; NSNumber *someNumber = @(number); NSString *someString = [someNumber stringValue]; like_count.text=someString; buttonToggled = YES; } else { [sender setTitle:@"Like" forState:UIControlStateNormal]; number1 = number1-1; UILabel *like_count=(UILabel *)[self.view viewWithTag:3]; NSNumber *someNumber = @(number1); NSString *someString = [someNumber stringValue]; like_count.text=someString; buttonToggled = NO; } } 4 para obtener el evento de datos de cocción. Por alguna razón todavía no funciona.

¿Hay algo que estoy haciendo mal?

¿Y qué tipo de código se espera en #import "DetailOfUser.h" @interface DetailsOfStories () { NSMutableArray *descriptionList; BOOL buttonToggled; int number,number1; NSNumber *num1; } @end @implementation DetailsOfStories @synthesize descriptionList; - (void)viewDidLoad { UILabel *like_count=(UILabel *)[self.view viewWithTag:3]; NSNumber *someNumber = @(number); NSString *someString = [someNumber stringValue]; like_count.text=someString; } - (IBAction)like:(id)sender { if (!buttonToggled) { [sender setTitle:@"Unlike" forState:UIControlStateNormal]; //number is interger number = [num1 intValue]+1; number1=number; UILabel *like_count=(UILabel *)[self.view viewWithTag:3]; NSNumber *someNumber = @(number); NSString *someString = [someNumber stringValue]; like_count.text=someString; buttonToggled = YES; } else { [sender setTitle:@"Like" forState:UIControlStateNormal]; number1 = number1-1; UILabel *like_count=(UILabel *)[self.view viewWithTag:3]; NSNumber *someNumber = @(number1); NSString *someString = [someNumber stringValue]; like_count.text=someString; buttonToggled = NO; } } 5 para que funcione? Ya que tampoco entiendo eso.

  #import "DetailOfUser.h" @interface DetailsOfStories () {     NSMutableArray *descriptionList; BOOL buttonToggled;     int number,number1;     NSNumber *num1; } @end @implementation DetailsOfStories @synthesize descriptionList; - (void)viewDidLoad {    UILabel *like_count=(UILabel *)[self.view viewWithTag:3];     NSNumber *someNumber = @(number);     NSString *someString = [someNumber stringValue];     like_count.text=someString; } - (IBAction)like:(id)sender {      if (!buttonToggled) {         [sender setTitle:@"Unlike" forState:UIControlStateNormal];         //number is interger         number = [num1 intValue]+1;         number1=number;         UILabel *like_count=(UILabel *)[self.view viewWithTag:3];         NSNumber *someNumber = @(number);         NSString *someString = [someNumber stringValue];         like_count.text=someString;         buttonToggled = YES;     }     else {         [sender setTitle:@"Like" forState:UIControlStateNormal];         number1 = number1-1;         UILabel *like_count=(UILabel *)[self.view viewWithTag:3];         NSNumber *someNumber = @(number1);         NSString *someString = [someNumber stringValue];         like_count.text=someString;         buttonToggled = NO;     } } 6  

y para agregar un oyente al carbobobox i hago:

  #import "DetailOfUser.h" @interface DetailsOfStories () {     NSMutableArray *descriptionList; BOOL buttonToggled;     int number,number1;     NSNumber *num1; } @end @implementation DetailsOfStories @synthesize descriptionList; - (void)viewDidLoad {    UILabel *like_count=(UILabel *)[self.view viewWithTag:3];     NSNumber *someNumber = @(number);     NSString *someString = [someNumber stringValue];     like_count.text=someString; } - (IBAction)like:(id)sender {      if (!buttonToggled) {         [sender setTitle:@"Unlike" forState:UIControlStateNormal];         //number is interger         number = [num1 intValue]+1;         number1=number;         UILabel *like_count=(UILabel *)[self.view viewWithTag:3];         NSNumber *someNumber = @(number);         NSString *someString = [someNumber stringValue];         like_count.text=someString;         buttonToggled = YES;     }     else {         [sender setTitle:@"Like" forState:UIControlStateNormal];         number1 = number1-1;         UILabel *like_count=(UILabel *)[self.view viewWithTag:3];         NSNumber *someNumber = @(number1);         NSString *someString = [someNumber stringValue];         like_count.text=someString;         buttonToggled = NO;     } } 7  
Original en ingles

I seem not to grasp the concept of Events and such. After reading a while on how to implement the listeners and such I came across the Java tutorial saying I should extend AbstractListModel to get the data event firing. For some reason it still doesn't work.

Is there anything I'm doing wrong?

And what kind of code is expected at addListDataListener(ListDataListener l) for it to work? Since I don't understand that either.

public class CarComboBox extends AbstractListModel<Object> implements ComboBoxModel<Object> {      private JdbcRowSet jdbc;     private int size = 0;     private String selection;      public CarComboBox() {         try {             jdbc = new Query().getCarInfo();              jdbc.beforeFirst();             while (jdbc.next()) {                 size++;             }             jdbc.beforeFirst();         }         catch (SQLException ex) {             System.err.println(ex.toString());         }     }      @Override     public void setSelectedItem(Object anItem) {         selection = (String) anItem;     }      @Override     public Object getSelectedItem() {         return selection;     }      @Override     public void addListDataListener(ListDataListener l) {     }      @Override     public void removeListDataListener(ListDataListener l) {     }      @Override     public int getSize() {     return size;     }      @Override     public String getElementAt(int index) {         try {             jdbc.absolute(index + 1);             return jdbc.getString(2);         }         catch (SQLException ex) {             System.out.println(ex.toString());         }         return null;     } } 

And to add a listener to the CarComboBox I do:

CarComboBox ccb = new CarComboBox(); ccb.addListDataListener(new ListDataListener() 
           
     
     

Lista de respuestas

6
 
vote
vote
La mejor respuesta
 

Supongo que estás usando el funcionario tutorial .

Sin embargo, no debe tocar Listmodel y ComboBoxModel. Esas son características más avanzadas que probablemente no necesite. Los 4 ejemplos en el tutorial no usan Listmodel y ComboboxModel.

Si usa un JCOMBOBOBOBOBOBOBOBOBOBOX (NO LISTMODEL o COMBOBOXMODEL), lo que sucede es que cuando alguien realiza una selección, se enciende un 9988777667 . Este evento es mágicamente despedido por swing; No tienes que preocuparte por cómo se genera. Sin embargo, ¿cuál es su responsabilidad es tener algunos objetos (cero, uno o más) que puedan recibir y hacer algo sobre la ActionEvent:

  public class MyClass implements ActionListener {    JComboBox comboBox = ...;     ...        // You must register explicitly every ActionListener that you        // want to receive ActionEvent's from comboBox.        // Here we register this instance of MyClass.        comboBox.addActionListener(this);    ...     @Override     public void actionPerformed(ActionEvent e) {       if (e.getSource() instanceof JComboBox) {          System.out.println("MyClass registered an ActionEvent from a JComboBox.");          System.out.println("Selected: " +                 ((JComboBox) e.getSource()).getSelectedItem());       }    } }   

Tenga en cuenta que si no tiene ningún otroEventamiento de Action Firm por diferentes componentes de swing Puede omitir el if (e.getSource() instanceof JComboBox) ya que sabe que su ActionEvent siempre proviene de un JcomBobox.

En mi ejemplo, el JCOMBOBOX está dentro de MyClass, pero no tiene que ser:

  0.00011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011... 0  
 

I'm guessing that you are using the official tutorial.

However you should not touch ListModel and ComboBoxModel. Those are more advanced features you probably do not need. The 4 examples in the tutorial do NOT use ListModel and ComboBoxModel.

If you use a standard JComboBox (no ListModel or ComboBoxModel), what happens is that when someone makes a selection, an ActionEvent is fired. This event is magically fired by Swing; you don't have to worry about how it is generated. However what is your responsibility is to have some (zero, one or more) objects being able to receive and do something about the ActionEvent:

public class MyClass implements ActionListener {    JComboBox comboBox = ...;     ...        // You must register explicitly every ActionListener that you        // want to receive ActionEvent's from comboBox.        // Here we register this instance of MyClass.        comboBox.addActionListener(this);    ...     @Override     public void actionPerformed(ActionEvent e) {       if (e.getSource() instanceof JComboBox) {          System.out.println("MyClass registered an ActionEvent from a JComboBox.");          System.out.println("Selected: " +                 ((JComboBox) e.getSource()).getSelectedItem());       }    } } 

Note that if you don't have any other ActionEvent's fired by different Swing components you can skip the if (e.getSource() instanceof JComboBox) since you know your ActionEvent always comes from a JComboBox.

In my example the JComboBox is inside MyClass, but it does not have to be:

JComboBox comboBox = ...; MyClass myClass = ...; comboBox.addActionListener(myClass); ... comboBox.addActionListener(someOtherActionListener); 
 
 
 
 
4
 
vote

No necesita anular 0.00011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011... 11111111- 0.00011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011... 2 MÉTODO. El 0.00011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011... 3 ya cuida a los oyentes. Aquí está la implementación de abstractlistmodel.addlistdatalistener () :

  0.00011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011... 4  

La idea de las clases abstractas es que hacen la mayor parte del trabajo para usted. Por lo general, solo necesitas implementar métodos abstractos.

 

You don't need to override addListDataListener() and removeListDataListener() method. The AbstractListModel already take care of the listeners. Here is the implementation of AbstractListModel.addListDataListener():

public void addListDataListener(ListDataListener l) {     listenerList.add(ListDataListener.class, l); } 

The idea of abstract classes is that they do most of the work for you. Usually you only need to implement abstract methods.

 
 
 
 
4
 
vote

xxlistener y xxmodel son lados diferentes de la moneda: el primero es el observador para este último que es el observable. El oyente se registra en el modelo cuando quiere recibir notificaciones en los cambios. Es responsabilidad del modelo a

  • Administre a sus oyentes (que normalmente se maneja ya por el abstractxxmodel, como ya se explica en @USERWHATEANNUMBER;)
  • Fire las notificaciones si se aprueba: Esa es la parte que un modelo personalizado debe hacerse cargo, en su caso

como

  @Override public void setSelectedItem(Object item) {    selection = item;    fireContentChanged(this, -1, -1); }   

Podría posiblemente (hay preferencias personales alrededor :-) A menudo no necesita implementaciones de modelos personalizados, sino que también puede reutilizar los predeterminados proporcionados. En su contexto y asumiendo que el contenido del resultado es inmutable, podría ser una opción para llenar el modelo predeterminado con los datos en la hora de construcción, como

  DefaultComboBoxModel model = new DefaultComboBoxModel(); forEachRowInResultSet {     model.addElement(resultSet.getString(2)); }    

Si, por otro lado, el contenido cambia de vez en cuando la implementación del modelo no es válida de todos modos: el modelo debe notificar a sus oyentes cada vez que algo haya cambiado

  Object one = model.getElementAt(index); Object other = model.getElementAt(index) if (!one.equals(other)) {    listener must have received a contentsChanged }    
 

XXListener and XXModel are different sides of the coin: the former is the observer to the latter which is the observable. The listener registers itself to the model when it wants to get notified on changes. It's the responsibility of the model to

  • manage its listeners (that's typically handled already by the AbstractXXModel, as already explained by @userWhateverNumber ;)
  • fire the notifications if appropirate: that's the part a custom model must take over, in your case

like

@Override public void setSelectedItem(Object item) {    selection = item;    fireContentChanged(this, -1, -1); } 

Arguably (there are personal preferences around :-) you often don't need custom model implementations but can just as well re-use the provided DefaultXXModels. In your context and assuming the content of the resultset is immutable it might be an option to fill the default model with the data at construction time, like

DefaultComboBoxModel model = new DefaultComboBoxModel(); forEachRowInResultSet {     model.addElement(resultSet.getString(2)); }  

If, on the other hand, the content changes then your model implementation is invalid anyway: the model must notify its listeners whenever something had changed

Object one = model.getElementAt(index); Object other = model.getElementAt(index) if (!one.equals(other)) {    listener must have received a contentsChanged }  
 
 
 
 

Relacionados problema

0  StartService indefinido para OnClickListener en fragmento  ( Startservice undefined for onclicklistener in fragment ) 
Estoy recibiendo este error en un fragmento El Método StartService (Intención) no está definido para el tipo Nuevo View.OnclickListener En OncReReEval, te...

6  El juego de tiempo de espera en la web.xml no funciona en Java [duplicado]  ( Timeout set in the web xml is not working in java ) 
Esta pregunta ya tiene respuestas aquí : sesión Tiempo de sesión: web.xml vs session.maxinactiveinte...

0  Firefox SDK: escuche un cambio en el no competencia específico de: Configuración de configuración  ( Firefox sdk listen for a change in non addon specific aboutconfig entry ) 
Estoy tratando de escuchar los cambios en la configuración de Firefox sobre: ​​Configurar que el usuario podría haber cambiado mientras se ejecuta mi compleme...

106  File Cambio de oyente en Java  ( File changed listener in java ) 
Me gustaría recibir una notificación cuando se haya cambiado un archivo en el sistema de archivos. No he encontrado nada más que un hilo que encuestan la prop...

1121  Huido de detección de gesto en la distribución de la cuadrícula  ( Fling gesture detection on grid layout ) 
Quiero obtener fling Detección de gesto Trabajar en mi aplicación Android. Lo que tengo es un GridLayout que contiene 9 ImageView S. La fuente se pued...

1  Añadir oyente jdatecooser  ( Add listener jdatechooser ) 
Me he creado este metod para agregar oyentes en mi DataChooser. public final void añadirEsccuhaDataChoser() { jDateChooser1.getDateEditor().addPropert...

4  ¿Patrones para compensar la falta de búsqueda de métodos de tiempo de ejecución basados ​​en argles polimórficos en Java?  ( Patterns to compensate for lack of runtime method lookup based on polymorphic ar ) 
Parece que Java no puede elegir la implementación del método más apropiada según el tipo de tiempo de ejecución de un argumento, como se documentó aquí . Rec...

1  Swing: Order de la ejecución de los oyentes en componente personalizado  ( Swing listeners execution order on custom component ) 
Mi componente personalizado está compuesto por tres JTree S dentro de un JPanel . Solo se debe seleccionar un JTree . Código> JTree . Me gustaría agrega...

1  Solución creativa a dos oyentes de cola JMS diferentes (TIBCO)  ( Creative solution to two different jms queue listeners tibco ) 
Tenemos una situación en la que dos instancias de aplicación diferentes escuchan intermitentemente en la misma cola. La solución lógica es solo apuntar a un...

0  ¿Cómo contar el número de sesiones activas en las aplicaciones Java EE?  ( How to count number of active sessions in java ee applications ) 
Estoy usando JAAS para la autenticación en JBoss. Estoy usando la base de datosERVERLOGINMODULO para realizar la autenticación. Ahora quiero rastrear el núm...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos