Hello. The bottom line is this.

There is a database that contains several columns. There is a jFrame in which the output of the database in the table to the screen is implemented via jTableModel. The mediator between the database and jTableModel is a collection that is filled with values ​​when connected to the database. Also in jFrame there is a form for adding new values ​​to the database (several text fields for filling + button to write), which works. The program is implemented in such a way that when a new value is added via the form, it is immediately stored in the database via an SQL query, and then immediately added to the collection. I want these changes to also pass dynamically with a table in jFrame. In this case, I probably should use TableModelListener. But in what case will it work? Maybe I should still + to all of this as a kind of re-supply a new collection to the table, as here TableModel model = new Table(all) ???

 static ArrayList<MyBeans> all = new ArrayList<MyBeans>();// коллСкция TableModel model = new Table(all); JTable table = new JTable(model);//Ρ‚Π°Π±Π»ΠΈΡ†Π° //ДинамичискоС ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΠ΅ table.getModel().addTableModelListener(new TableModelListener(){ @Override public void tableChanged(TableModelEvent e) { System.out.println("zzz");//КакоС Π½ΠΈΠ±ΡƒΠ΄ΡŒ событиС Π½Π° запуска ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊΠ° } }); 

I am sure that presenting it without a code is not easy, but the code is cumbersome, I think there is no need to insert it. If required, I can make additional explanations. Thanks in advance.

    1 answer 1

    Hey. Here it says https://docs.oracle.com/javase/tutorial/uiswing/events/tablemodellistener.html that TableModel manages strings by default. In order for you to set your behavior, you need to make your TableModel, with the interface to the TableModel interface. https://docs.oracle.com/javase/tutorial/uiswing/components/table.html#data Here is an example (it seems like).

    And option 2 is also possible - you make your collection, which is inherited from ArrayList, you add your listener to the constructor, and in the implementation of the add method you call this listener. I will give an example code

     public class MyArrayList extends ArrayList<MyBeans> { private MyListener myListener; public MyArrayList(MyListener mL) { this.myListener = mL; } @Override public boolean add(MyBeans mB) { boolean res = super.add(s); myListener.update(mb); } ... } public interface MyListener { void update(MyBeans mb); } 

    Your class

      final TableModel model = new Table(all); JTable table = new JTable(model);//Ρ‚Π°Π±Π»ΠΈΡ†Π° MyArrayList<MyBeans> all = new MyArrayList<MyBeans>(new MyListener() { public void update(MyBeans mb) { model.addRow(mb); //ΠΊΠ°ΠΊ-Ρ‚ΠΎ Ρ‚Π°ΠΊ } });