Questo sito utilizza cookies solo per scopi di autenticazione sul sito e nient'altro. Nessuna informazione personale viene tracciata. Leggi l'informativa sui cookies.
Username: Password: oppure
Java - Creazione dinamica componenti java
Forum - Java - Creazione dinamica componenti java

Avatar
rosario.damore (Normal User)
Newbie


Messaggi: 6
Iscritto: 03/10/2010

Segnala al moderatore
Postato alle 10:48
Domenica, 03/10/2010
Ciao a tutti,

io ho un problema simile. Ho Bisogno di creare dei combo box dinamicamente in base ad un numero di attrubuti che gli passo dalla classe main. Vorrei una cosa così

http://oi55.tinypic.com/kaqngn.jpg
[img]http://oi55.tinypic.com/kaqngn.jpg[/img]

Oppure  una cosa con i radio button così

http://i52.tinypic.com/33p5wck.jpg
[img]http://i52.tinypic.com/33p5wck.jpg[/img]

I valori da selezionare sono numeri interi da 1 a 5. Quindi l'utente dovrà valutare gli attribut1 x,y,z ecc,.. con un valore da 1 a 5. Quando preme OK mi deve restituire un arrey di numeri interi con le sue valutazioni.

Possiamo pensare in alternativa anche un componente jslider da 1 a 5. non è un problema. Mi puoi aiutare. Le variabili in entrata sarebbero i numero degli attributi da valutare ( che coinciderà con numero di label e combox) e il numero nome degli stessi che andrà inserito nelle label.

Mi date una mano? Grazie

PM
Avatar
Bonny (Member)
Expert


Messaggi: 437
Iscritto: 24/04/2009

Up
1
Down
V
Segnala al moderatore
Postato alle 11:38
Domenica, 03/10/2010
Codice sorgente - presumibilmente Java

  1. import java.awt.GridLayout;
  2. import java.awt.event.ActionEvent;
  3. import java.awt.event.ActionListener;
  4. import javax.swing.*;
  5.  
  6. public class Esempio extends JFrame {
  7.  
  8.     private JComboBox combo1 = new JComboBox();
  9.     private JComboBox combo2 = new JComboBox();
  10.     private JComboBox combo3 = new JComboBox();
  11.     private JButton conferma = new JButton("Ok");
  12.  
  13.     public Esempio() {
  14.  
  15.         super("Esempio");
  16.         JPanel p = new JPanel();//pannello contenitore componenti
  17.         p.setLayout(new GridLayout(7, 1, 10, 10));//Layout Manager griglia
  18.         p.add(new JLabel("Confronto 1"));         //7 righe 1 colonna
  19.         p.add(combo1);
  20.         p.add(new JLabel("Confronto 2"));
  21.         p.add(combo2);
  22.         p.add(new JLabel("Confronto 3"));
  23.         p.add(combo3);
  24.         p.add(conferma);
  25.         initCombo();//chimata inizializza Combobox
  26.         this.getContentPane().add(p, "Center");
  27.         this.setVisible(true);
  28.         this.setBounds(200, 200, 500, 300);
  29.         this.pack();
  30.         //ascoltatore del JButton conferma
  31.  
  32.         conferma.addActionListener(
  33.                 new ActionListener() {
  34.  
  35.                     public void actionPerformed(ActionEvent event) {
  36.  /*                      
  37.         qui dovrai implementare il codice per creare l'array di risposte per poi  fare    ulteriori istruzioni..
  38.         Mi sono limitato a prepararti la GUI di esempio adesso tocca a te.
  39.   *     Con il metodo "getSelectedItem()" la combobox ti restituisce l'elemento selezionato (tipo Object)
  40.   *     a questo punto.................
  41.   */
  42.                        
  43.                        
  44.                     }
  45.                 });
  46.         /////////////////////////////////////
  47.     }
  48.  
  49.     public void initCombo() {
  50. //inizializzo le comboBox
  51.         for (int i = 1; i < 6; i++) {
  52.             combo1.addItem(String.valueOf(i));
  53.             combo2.addItem(String.valueOf(i));
  54.             combo3.addItem(String.valueOf(i));
  55.         }
  56.     }
  57. }


spero di esserti stati d'aiuto:k:
ps. da non confondere ""getSelectedItem()"" con "getSelectionIndex" qst'ultimo restituisce un intero cioè l'indice dell'elemento selezionato nella combobox.

Ultima modifica effettuata da Bonny il 03/10/2010 alle 11:44
PM
Avatar
rosario.damore (Normal User)
Newbie


Messaggi: 6
Iscritto: 03/10/2010

Up
0
Down
V
Segnala al moderatore
Postato alle 11:52
Domenica, 03/10/2010
Ciao Bonny,

grazie per il tuo aiuto. Vedo nel tuo codice che hai dichiarato 3 ComboBox
Codice sorgente - presumibilmente Java

  1. private JComboBox combo1 = new JComboBox();
  2.     private JComboBox combo2 = new JComboBox();
  3.     private JComboBox combo3 = new JComboBox();



Io invece volevo che il programma creasse tante combobox quanti sono gli attributi. Magari gli passo una varibile nel costruttore.

Poi volevo che nelle combobox si potessero selezionare uno dei valori {1,2,3,4,5}

Mi dai una mano? Grazie

PM
Avatar
Bonny (Member)
Expert


Messaggi: 437
Iscritto: 24/04/2009

Up
0
Down
V
Segnala al moderatore
Postato alle 12:13
Domenica, 03/10/2010
Codice sorgente - presumibilmente Java

  1. package prova;
  2.  
  3. import java.awt.GridLayout;
  4. import java.awt.event.ActionEvent;
  5. import java.awt.event.ActionListener;
  6. import javax.swing.*;
  7.  
  8. public class Esempio extends JFrame {
  9.  
  10.     private Extendscombo vetCombo[];
  11.     private JButton conferma = new JButton("Ok");
  12.  
  13.     public Esempio(int numeroCombo) {
  14.  
  15.         super("Esempio");
  16.         vetCombo = new Extendscombo[numeroCombo];
  17.  
  18.         JPanel p = new JPanel();
  19.         //ad ogni combo va allegata una JLabel il +1 è per il JButton
  20.         int n = (numeroCombo * 2) + 1;
  21.         p.setLayout(new GridLayout(n, 1, 10, 10));
  22.  
  23.         for (int i = 0; i < numeroCombo; i++) {
  24.             p.add(new JLabel("Confronto " + (i + 1)));
  25.             vetCombo[i] = new Extendscombo();
  26.             p.add(vetCombo[i]);
  27.         }
  28.         p.add(conferma);
  29.         this.getContentPane().add(p, "Center");
  30.         this.setVisible(true);
  31.         this.setBounds(200, 200, 500, 300);
  32.         this.pack();
  33.  
  34.         conferma.addActionListener(
  35.                 new ActionListener() {
  36.  
  37.                     public void actionPerformed(ActionEvent event) {
  38.                     }
  39.                 });
  40.     }
  41. }//fine class esempio
  42.  
  43. class Extendscombo extends JComboBox {
  44.  
  45.     public Extendscombo() {
  46.         super();
  47.         for (int i = 1; i < 6; i++) {
  48.             this.addItem(String.valueOf(i));
  49.         }
  50.     }
  51. }



Ho esteso la classe JComboBox cosi nel costruttore le inizializzo, da quello che ho capito sono tutte uguali.
poi ho creato un vettore di qst e con un ciclo le ho inserite nel pannello.

PM
Avatar
Bonny (Member)
Expert


Messaggi: 437
Iscritto: 24/04/2009

Up
0
Down
V
Segnala al moderatore
Postato alle 12:28
Domenica, 03/10/2010
mmmm:/ nella classe Esempio ti conviene dichiarare una var intera che conterrà il valore di numeroCombo e nel costruttore fai this.nuova_var = numeroCombo;
altrimenti il Listener del bottone conferma non la riconosce!
Codice sorgente - presumibilmente Java

  1. package prova;
  2.  
  3. import java.awt.GridLayout;
  4. import java.awt.event.ActionEvent;
  5. import java.awt.event.ActionListener;
  6. import javax.swing.*;
  7.  
  8. public class Esempio extends JFrame {
  9.  
  10.     private Extendscombo vetCombo[];
  11.     private JButton conferma = new JButton("Ok");
  12.     private int numeroC = 0;
  13.  
  14.     public Esempio(int numeroCombo) {
  15.  
  16.         super("Esempio");
  17.  
  18.         this.numeroC = numeroCombo;
  19.         vetCombo = new Extendscombo[this.numeroC];
  20.  
  21.         JPanel p = new JPanel();
  22.         //ad ogni combo va allegata una JLabel il +1 è per il JButton
  23.         int n = (this.numeroC * 2) + 1;
  24.         p.setLayout(new GridLayout(n, 1, 10, 10));
  25.  
  26.         for (int i = 0; i < this.numeroC; i++) {
  27.             p.add(new JLabel("Confronto " + (i + 1)));
  28.             vetCombo[i] = new Extendscombo();
  29.             p.add(vetCombo[i]);
  30.         }
  31.         p.add(conferma);
  32.         this.getContentPane().add(p, "Center");
  33.         this.setVisible(true);
  34.         this.setBounds(200, 200, 500, 300);
  35.         this.pack();
  36.  
  37.         conferma.addActionListener(
  38.                 new ActionListener() {
  39.  
  40.                     public void actionPerformed(ActionEvent event) {
  41.          //qui crei un array di interi , per esempio, di dimensione numeroC
  42.          // e con un ciclo che va da 0 a numeroC recupero tutte le risposte
  43.          //selezionate sulle combobox,ovviamente il metodo getSelectionItem
  44.          // restituisce un oggetto di classo Object quindi devi fare un casting
  45.          //o usi il metodo getSelectionIndex xò stai attento l'indice parte da 0
  46.          //quindi basta fare 'combo.getSelectionIndex() + 1' (risparmi casting)
  47.                     }
  48.                 });
  49.     }
  50. }//fine class esempio
  51.  
  52. class Extendscombo extends JComboBox {
  53.  
  54.     public Extendscombo() {
  55.         super();
  56.         for (int i = 1; i < 6; i++) {
  57.             this.addItem(String.valueOf(i));
  58.         }
  59.     }
  60. }


PM
Avatar
rosario.damore (Normal User)
Newbie


Messaggi: 6
Iscritto: 03/10/2010

Up
0
Down
V
Segnala al moderatore
Postato alle 17:51
Lunedì, 04/10/2010
Ciao Bonny,

ho implementato il codice con lo JSlider:

Codice sorgente - presumibilmente Java

  1. public class Matrice extends javax.swing.JFrame {
  2.    
  3.     private boolean done = false;
  4.    
  5.     public Matrice() {
  6.         initComponents();
  7.     }
  8.    
  9.     public Matrice(String name, int max, int attributi) {
  10.         initComponents(name, max, attributi);
  11.     }
  12.    
  13.     // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
  14.     private void initComponents(String name, int max, int attributi) {
  15.         jLabel1[attributi] = new javax.swing.JLabel();
  16.         jSlider1 = new javax.swing.JSlider();
  17.         jButton1 = new javax.swing.JButton();
  18.  
  19.         setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  20.         setTitle("Valutazione Attributi");
  21.        
  22.         jLabel1[attributi].setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
  23.         jLabel1[attributi].setText("Valuta l'attributo "+name+" in confronto all'attributo Y");
  24.  
  25.         jSlider1.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
  26.         jSlider1.setMajorTickSpacing(1);
  27.         jSlider1.setMaximum(5);
  28.         jSlider1.setMinimum(1);
  29.         jSlider1.setMinorTickSpacing(1);
  30.         jSlider1.setPaintLabels(true);
  31.         jSlider1.setPaintTicks(true);
  32.         jSlider1.setSnapToTicks(true);
  33.         jSlider1.setValue(1);
  34.  
  35.         jButton1.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
  36.         jButton1.setText("OK");
  37.         jButton1.addActionListener(new java.awt.event.ActionListener() {
  38.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  39.                 jButton1ActionPerformed(evt);
  40.             }
  41.         });
  42.  
  43.        
  44.         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  45.         getContentPane().setLayout(layout);
  46.         layout.setHorizontalGroup(
  47.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  48.             .addGroup(layout.createSequentialGroup()
  49.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  50.                     .addGroup(layout.createSequentialGroup()
  51.                         .addGap(65, 65, 65)
  52.                         .addComponent(jLabel1[attributi]))
  53.                     .addGroup(layout.createSequentialGroup()
  54.                         .addGap(166, 166, 166)
  55.                         .addComponent(jButton1))
  56.                     .addGroup(layout.createSequentialGroup()
  57.                         .addContainerGap()
  58.                         .addComponent(jSlider1, javax.swing.GroupLayout.DEFAULT_SIZE, 391, Short.MAX_VALUE)))
  59.                 .addContainerGap())
  60.         );
  61.         layout.setVerticalGroup(
  62.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  63.             .addGroup(layout.createSequentialGroup()
  64.                 .addContainerGap()
  65.                 .addComponent(jLabel1[attributi])
  66.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  67.                 .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
  68.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 169, Short.MAX_VALUE)
  69.                 .addComponent(jButton1)
  70.                 .addContainerGap())
  71.         );
  72.        
  73.        
  74.         java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
  75.         setBounds((screenSize.width-300)/2, (screenSize.height-150)/2, 300, 150);    
  76.         }// </editor-fold>//GEN-END:initComponents
  77.  
  78.     private void initComponents() {
  79.         for (int i=0; i<8; i++){
  80.         jLabel1[i] = new javax.swing.JLabel();
  81.         jSlider1 = new javax.swing.JSlider();
  82.         jButton1 = new javax.swing.JButton();
  83.  
  84.         setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  85.         setTitle("Valutazione Attributi");
  86.        
  87.         jLabel1[i].setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
  88.         jLabel1[i].setText("Valuta l'attributo X in confronto all'attributo Y");
  89.  
  90.         jSlider1.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
  91.         jSlider1.setMajorTickSpacing(1);
  92.         jSlider1.setMaximum(5);
  93.         jSlider1.setMinimum(1);
  94.         jSlider1.setMinorTickSpacing(1);
  95.         jSlider1.setPaintLabels(true);
  96.         jSlider1.setPaintTicks(true);
  97.         jSlider1.setSnapToTicks(true);
  98.         jSlider1.setValue(1);
  99.  
  100.         jButton1.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
  101.         jButton1.setText("OK");
  102.         jButton1.addActionListener(new java.awt.event.ActionListener() {
  103.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  104.                 jButton1ActionPerformed(evt);
  105.             }
  106.         });
  107.  
  108.         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  109.         getContentPane().setLayout(layout);
  110.         layout.setHorizontalGroup(
  111.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  112.             .addGroup(layout.createSequentialGroup()
  113.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  114.                     .addGroup(layout.createSequentialGroup()
  115.                         .addGap(65, 65, 65)
  116.                         .addComponent(jLabel1[i]))
  117.                     .addGroup(layout.createSequentialGroup()
  118.                         .addGap(166, 166, 166)
  119.                         .addComponent(jButton1))
  120.                     .addGroup(layout.createSequentialGroup()
  121.                         .addContainerGap()
  122.                         .addComponent(jSlider1, javax.swing.GroupLayout.DEFAULT_SIZE, 391, Short.MAX_VALUE)))
  123.                 .addContainerGap())
  124.         );
  125.         layout.setVerticalGroup(
  126.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  127.             .addGroup(layout.createSequentialGroup()
  128.                 .addContainerGap()
  129.                 .addComponent(jLabel1[i])
  130.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  131.                 .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
  132.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 169, Short.MAX_VALUE)
  133.                 .addComponent(jButton1)
  134.                 .addContainerGap())
  135.         );
  136.         }
  137.         java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
  138.         setBounds((screenSize.width-300)/2, (screenSize.height-150)/2, 400, 250);
  139.         }// </editor-fold>//GEN-END:initComponents
  140.  
  141. private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
  142. // TODO add your handling code here:
  143.         setDone(true);
  144.  
  145.     }//GEN-LAST:event_jButton1ActionPerformed
  146.    
  147.  
  148.     public static void main(String args[]) {
  149.         java.awt.EventQueue.invokeLater(new Runnable() {
  150.             public void run() {
  151.                 new Matrice().setVisible(true);
  152.             }
  153.         });
  154.     }
  155.    
  156.     public double visualizza() {
  157.         int rating;
  158.         this.setVisible(true);
  159.         while (!isDone()){}
  160.         rating = jSlider1.getValue();
  161.         this.dispose();
  162.         return rating;
  163.     }
  164.  
  165.    
  166.     // Variables declaration - do not modify//GEN-BEGIN:variables
  167.     private javax.swing.JButton jButton1;
  168.     private javax.swing.JSlider jSlider1;
  169.     private javax.swing.JLabel jLabel1[];
  170.     // End of variables declaration//GEN-END:variables
  171.     public boolean isDone() {
  172.         return done;
  173.     }
  174.  
  175.     public void setDone(boolean done) {
  176.         this.done = done;
  177.     }
  178.    
  179. }



Adesso il problema è che quando lo compilo mi dice

Codice sorgente - presumibilmente Delphi

  1. Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
  2.     at Matrice.initComponents(Matrice.java:80)
  3.     at Matrice.<init>(Matrice.java:6)
  4.     at Matrice$3.run(Matrice.java:151)



perchè non mi crea le 8 JLabels in automatico?

PM