Visualizzazione dei risultati da 1 a 5 su 5

Discussione: JTable in JOPtionpane

  1. #1

    JTable in JOPtionpane

    Salve ragazzi, avrei bisogno di un vostro aiuto.

    Ho la necessità di mostrare una tabella in un JOPtionPane.

    Fin qui nessun problema ci sono riuscito con questo codice:

    codice:
    Vector vRicette = db.eseguiQuery("SELECT CodiceRicetta FROM RicettaIngredienti");
    				        	Vector vettoreRicette = new Vector();
    				        	vettoreRicette.add("Nome Ricetta");
    				        	TableExample tableRicette = new TableExample(vRicette,vettoreRicette);
    				        	jScrollPane3 = new javax.swing.JScrollPane();
    						    jScrollPane3.setName("jScrollPane3");
    						    jScrollPane3.setViewportView(tableRicette);
    						    jScrollPane3.getViewport().add(tableRicette);
    						    jScrollPane3.setVisible(true);
    						    String gelato=JOptionPane.showInputDialog(null, jScrollPane3, "Ricette Salvate", JOptionPane.INFORMATION_MESSAGE);
    io voglio che quando un utente fa un doppio clik su una riga della tabella tale nome venga assegnato alla variabile sitringa gelato.....


    è possibile fare una cosa del genre????

  2. #2
    Utente di HTML.it L'avatar di andbin
    Registrato dal
    Jan 2006
    residenza
    Italy
    Messaggi
    18,284

    Re: JTable in JOPtionpane

    Originariamente inviato da bircastri
    codice:
    jScrollPane3.setViewportView(tableRicette);
    jScrollPane3.getViewport().add(tableRicette);
    Queste due righe di per sé non servirebbero. Basta passare il componente (il JTable) al costruttore di JScrollPane.

    Originariamente inviato da bircastri
    codice:
    jScrollPane3.setVisible(true);
    Anche questa è inutile. I normali componenti (escludendo le finestre top-level) sono già "visibili" per default.

    Originariamente inviato da bircastri
    codice:
    String gelato=JOptionPane.showInputDialog(null, jScrollPane3, "Ricette Salvate", JOptionPane.INFORMATION_MESSAGE);
    io voglio che quando un utente fa un doppio clik su una riga della tabella tale nome venga assegnato alla variabile sitringa gelato.....
    Questo JOptionPane non può/sa farlo "di serie". Dovresti estendere JOptionPane (conoscendo bene come funziona) e quindi non dovresti più usare i metodi statici ma l'uso diretto del componente. A questo punto forse sarebbe più semplice e pratico realizzare una propria dialog estendendo JDialog.
    Andrea, andbin.devSenior Java developerSCJP 5 (91%) • SCWCD 5 (94%)
    java.util.function Interfaces Cheat SheetJava Versions Cheat Sheet

  3. #3
    Eh forse hai ragione.

    Vabbè innanzitutto grazie per i consigli sul codice inutile diciamo....

    Poi in pratica quello che dovrei fare, è che invece di richiamare una JOptionPane richiamo una JDialog inserisco la tabella ecc ecc.......

  4. #4
    Scusate ma non capisco come fare, devo fare una Jdialog che contiene la mia tabella poi come faccio a passare l'elemento selezionato???????

  5. #5
    scusate ragazzi, io ho preso questa classe.

    codice:
    public class TableFilterDemo extends JPanel {
        private boolean DEBUG = false;
        static Visualizzazioni db;
        private JTable table;
        private JTextField filterText;
        private JTextField statusText;
        MyTableModel tableModel;
        private TableRowSorter<MyTableModel> sorter;
    
        public TableFilterDemo() {
            super();
            setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    
            //Create a table with a sorter.
        	Vector v = db.eseguiQuery("SELECT CodiceRicetta FROM RicettaIngredienti GROUP BY CodiceRicetta");
        	tableModel = new MyTableModel(v);
            sorter = new TableRowSorter<MyTableModel>(tableModel);
            table = new JTable(tableModel);
            table.setRowSorter(sorter);
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            table.setFillsViewportHeight(true);
    
            //For the purposes of this example, better to have a single
            //selection.
            table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    
            //When selection changes, provide user with row numbers for
            //both view and model.
            table.getSelectionModel().addListSelectionListener(
                    new ListSelectionListener() {
                        public void valueChanged(ListSelectionEvent event) {
                            int viewRow = table.getSelectedRow();
                            if (viewRow < 0) {
                                //Selection got filtered away.
                                statusText.setText("");
                            } else {
                                int modelRow = 
                                    table.convertRowIndexToModel(viewRow);
                                statusText.setText(
                                    String.format("Selected Row in view: %d. " +
                                        "Selected Row in model: %d.", 
                                        viewRow, modelRow));
                            }
                        }
                    }
            );
    
    
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
    
            //Add the scroll pane to this panel.
            add(scrollPane);
    
            //Create a separate form for filterText and statusText
            JPanel form = new JPanel(new SpringLayout());
            JLabel l1 = new JLabel("Filter Text:", SwingConstants.TRAILING);
            form.add(l1);
            filterText = new JTextField();
            //Whenever filterText changes, invoke newFilter.
            filterText.getDocument().addDocumentListener(
                    new DocumentListener() {
                        public void changedUpdate(DocumentEvent e) {
                            newFilter();
                        }
                        public void insertUpdate(DocumentEvent e) {
                            newFilter();
                        }
                        public void removeUpdate(DocumentEvent e) {
                            newFilter();
                        }
                    });
            l1.setLabelFor(filterText);
            form.add(filterText);
            JLabel l2 = new JLabel("Status:", SwingConstants.TRAILING);
            form.add(l2);
            statusText = new JTextField();
            l2.setLabelFor(statusText);
            form.add(statusText);
            SpringUtilities.makeCompactGrid(form, 2, 2, 6, 6, 6, 6);
            add(form);
        }
    
        /** 
         * Update the row filter regular expression from the expression in
         * the text box.
         */
        private void newFilter() {
            RowFilter<MyTableModel, Object> rf = null;
            //If current expression doesn't parse, don't update.
            try {
                rf = RowFilter.regexFilter(filterText.getText(), 0);
            } catch (java.util.regex.PatternSyntaxException e) {
                return;
            }
            sorter.setRowFilter(rf);
        }
    
    
    
    
        class MyTableModel extends AbstractTableModel{
            
            
        	Vector v = null;
        	// intestazioni delle colonne
        	String[] ColName = {"Ricette Salvate"};
        	
        	public MyTableModel(Vector v) {
        	//	System.out.println("vediamo se l'errore è qui sopra");
        		this.v = v; // inizializzato con il vettore
        	//	System.out.println("vediamo se l'errore è qui sotto");
        	}
              
        
    
        /*	public int getRowCount() { 
        	//	System.out.println("Stampo"+v.size());
        		return null==v?0:v.size();}*/
        	 public int getRowCount() {
                 return v.size();
             }
       
        	public String getColumnName(int col) {
        		return ColName[col];
        		
        		}
    
        	public int getColumnCount() {
                return ColName.length;
            }
    
            /*
             * Don't need to implement this method unless your table's
             * editable.
             */
            public boolean isCellEditable(int row, int col)
            {
            // nessuna cella editabile
            return false;
            }
    
            public Object getValueAt(int row, int col) {
            	//Object rowVal = v.get(row);
            	 //return((Object[])rowVal)[col];//[col];
            	Object colonna = null;
            	try{
            		Vector riga = (Vector)v.elementAt(row);
    	        	colonna = riga.elementAt(col);
    	      //System.out.println("stampo questo "+colonna);
    	        	return colonna;
            	}
            	catch(ArrayIndexOutOfBoundsException e){
            		System.out.println("errore: "+e);
            	}
            	return colonna;
    
            	}}
    
        /**
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
         */
        public static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("Ricettario");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            //Create and set up the content pane.
            TableFilterDemo newContentPane = new TableFilterDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
    
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
        	db = new Visualizzazioni("provaDB");
        	try {
    			db.connetti();
    		} catch (InstantiationException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		} catch (IllegalAccessException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    }
    in pratica è la classe tablefilterdemo di java. Io ho soltato inserito nella tabella i risultati del mio database.

    Ora voglio che attraverso un pulsante Carica si apra questo nuovo frame e consenta all'utente di selezionare la riga che gli interessa.

    questo lo faccio in questo modo

    TableFilterDemo filterdemo = new TableFilterDemo();
    filterdemo.createAndShowGUI();

    in questo modo io mi creo la finestra e l'utente può iniziare a ricercare la riga che gli occorre.

    Poi quando ha trovato ciò che gli occorre voglio che o con un doppio click o con un pulsnte debba restituirmi il contenuto della riga cioè se clicca sulla riga 2 che contiene la scritta ciao mi deve resituire ciao.

    mi potete dire come procedere?????

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.