简体   繁体   中英

Netbeans: How do I add a valueChanged listener to a JTable from the “design” GUI builder?

I right clicked the JTable and inserted some code into "post listeners code" in an awful kludge.

I don't see an option to add

table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
  public void valueChanged(ListSelectionEvent evt) {

to "events" in the "design" view for the JTable. I'm sure there's a way to add a valueChanged(ListSelectionEvent evt) from design view, but how?

maybe it's a bug ?

Row selection change events are produced by ListSelectionModel of JTable, not by JTable itself - so the event cannot be presented in Component Inspector (as event of JTable). Handling this event must be done manually, eg like:

jTable1.getSelectionModel().addListSelectionListener(
    new javax.swing.event.ListSelectionListener() {
        public void valueChanged(ListSelectionEvent evt) {
            customRowSelectionEventHandler(evt);
        }
    }
);

Although maybe there's a way to get the ListSelectionModel for a JTable outside of the "blue", "managed," code?

You can create your own ListSelectionListener in the editable part of the source. You can add an instance of the listener to the selection model of the class variable jTable1 in your table's Post-init Code property:

jTable1.getSelectionModel().addListSelectionListener(new MyListener());

The listener itself might look like this:

private static class MyListener implements ListSelectionListener {

    @Override
    public void valueChanged(ListSelectionEvent e) {
        System.out.println(e.getFirstIndex());
    }
}

Perhaps you could extend InputVerifier .

It's not exactly what it was intended to do, but you could adapt it for your uses.

public class TableVerifier extends InputVerifier {

    @Override
    public boolean verify(JComponent input) {
        assert input instanceof JTable : "I told you I wanted a table!";

        JTable inputTable = (JTable) input;
        int numberColumns = inputTable.getColumnCount();
        int numberRows = inputTable.getRowCount();

        for (int column = 0; column < numberColumns; column++) {
            for (int row = 0; row < numberRows; row++) {
                //DO YOUR STUFF
            }
        }
        return true;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM