Domanda

Ho creato la sorgente di esempio seguente e mi chiedo cosa devo fare per aggiornare il mio JPanel con un jlabel che ha le informazioni situate dalla riga cliccarono nel jtable.

Volevo anche notare che questo è solo un nuovo esempio di cui ho migliorato il codice del campione un po 'grazie a alcuni membri così qui.Quindi sto postando questo esempio nuido come un modo per imparare

Swingtesting (Main)

public class SwingTesting {

    private final JFrame frame;
    private final TablePane tablePane;
    private final JSplitPane splitPane;
    private final JPanel infoPanel;
    private final JLabel infoLabel;

    public SwingTesting() {
        tablePane = new TablePane();
        infoPanel = new JPanel();
        frame = new JFrame();

        infoLabel = new JLabel();    //this is the panel i want to add the label to
        infoPanel.add(infoLabel);

        splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, tablePane, infoPanel);

        frame.add(splitPane);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new SwingTesting();
            }
        });
    }
} 
.

TablePane

public class TablePane extends JPanel {

    private final JTable table;
    private final TableModel tableModel;
    private final ListSelectionModel listSelectionModel;

    public TablePane() {
        table = new JTable();
        tableModel = createTableModel();
        table.setModel(tableModel);
        table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        table.add(table.getTableHeader(), BorderLayout.PAGE_START);
        table.setFillsViewportHeight(true); 

        listSelectionModel = table.getSelectionModel();
        table.setSelectionModel(listSelectionModel);
        listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
        table.setSelectionModel(listSelectionModel);

        this.setLayout(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.NORTHWEST;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridheight = 1;
        gbc.gridwidth = 3;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.ipadx = 2;
        gbc.ipady = 2;
        gbc.weightx = 1;
        gbc.weighty = 1;

        this.add(new JScrollPane(table), gbc);
    }

    private TableModel createTableModel() {
        DefaultTableModel model = new DefaultTableModel(
            new Object[] {"Car", "Color", "Year"}, 0 
        ){
            @Override public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        addTableData(model);
        return model;
    }

    private void addTableData(DefaultTableModel model) {
        model.addRow(new Object[] {"Nissan", "Black", "2007"});
        model.addRow(new Object[] {"Toyota", "Blue", "2012"});
        model.addRow(new Object[] {"Chevrolet", "Red", "2009"});
        model.addRow(new Object[] {"Scion", "Silver", "2005"});
        model.addRow(new Object[] {"Cadilac", "Grey", "2001"});
    }


    class SharedListSelectionHandler implements ListSelectionListener {

        //When selection changes i want to add a label to the panel
        //currently it just prints out the info from the selected row    
        @Override
        public void valueChanged(ListSelectionEvent e) {
            ListSelectionModel lsm = (ListSelectionModel) e.getSource();
            String contents = "";

            if(lsm.isSelectionEmpty()) {
                System.out.println("<none>");
            } else {
                int minIndex = lsm.getMinSelectionIndex();
                int maxIndex = lsm.getMaxSelectionIndex();
                for(int i = minIndex; i <= maxIndex; i++) {
                    if(lsm.isSelectedIndex(i)) {
                        for(int j = 0; j < table.getColumnCount(); j++) {
                            contents += table.getValueAt(i, j) + " ";
                        }
                    }
                }
                System.out.println(contents);
            }
        }        
    }
}
.

Quindi mi chiedo come accedere a Jpanel dal LislanteListenerListener.Dovrei semplicemente passare il pannello alla classe TablePane?O c'è un modo più corretto per farlo?

Inoltre, la mia listaSleectionListener stampa le informazioni sulla riga due volte per qualche motivo, ho rovinato il ciclo?

Modifica

public class TablePane extends JPanel {

    private final JTable table;
    private final TableModel tableModel;
    private final ListSelectionModel listSelectionModel;

    private final displayPanel;

    public TablePane() {
        //removed code for reading purposes
    }

    //IDE says issue with thinking displayPanel may have already been initialized
    public TablePane(JPanel panel) {
        //this();
        //displayPanel = panel;
    }


    //ListSelectionListener uses panel.add(jlabel)

}
.

È semplice come prendere final Off?

È stato utile?

Soluzione

È possibile passare l'oggetto JLabel all'oggetto TablePane (nel costruttore di TablePane o fornendo un metodo setLabel() personalizzato).Quindi è possibile utilizzare StringBuilder per creare il testo che deve andare sull'etichetta e chiamare setText() sull'etichetta con la costante dell'oggetto StringBuilder (tramite il suo metodo toString()).

Credo che tu stia stampando EveryTihn due volte perché il metodo valueChanged viene chiamato due volte: una volta sulla notifica per la deselezione della riga corrente, quindi nuovamente sulla notifica sulla selezione della nuova riga.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top