kxyz
kxyz

Reputation: 842

Buttons in JFrame, access to methods in AbstractTableModel

I have Table which extends JPanel, MyTableModel extends AbstractTableModel. I want to add in JFrame button ActionPerformed and invoke deleteRow() from MyTableModel on selected row. How should I do it ?

EDIT:

when I add button in Frame from Palette and I add from context menu on button

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    String text1 = titleTextField.getText();
    String text2 = authorTextField.getText();
    int text3 = Integer.parseInt(yearTextField.getText());
    JTable table = table1.getTable();
            MyTableModel model = (MyTableModel) table.getModel();

            System.out.println(text1 + text2 +text3);
            model.addRow(new Book(model.list.size(), text1, text2, text3));
}

I get Null Pointer Exc on -> JTable table = table1.getTable(); -> returning null

UPDATE 3:

MainFrame

    package net.kxyz;

    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import net.kxyz.Table.MyTableModel;
    import xyz.libary.Book;


 public class MainFrame extends javax.swing.JFrame {

public MainFrame() throws FileNotFoundException, IOException {
    initComponents();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    setVisible(true);
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    titleTextField = new javax.swing.JTextField();
    authorTextField = new javax.swing.JTextField();
    try {
        table1 = new net.kxyz.Table();
    } catch (java.io.FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (java.io.IOException e2) {
        e2.printStackTrace();
    }
    butt1 = new net.kxyz.Butt();
    jButton1 = new javax.swing.JButton();
    yearTextField = new javax.swing.JTextField();
    deleteButton = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setText("Title:");

    jLabel2.setText("Author:");

    jLabel3.setText("Year:");

    javax.swing.GroupLayout butt1Layout = new javax.swing.GroupLayout(butt1);
    butt1.setLayout(butt1Layout);
    butt1Layout.setHorizontalGroup(
        butt1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 0, Short.MAX_VALUE)
    );
    butt1Layout.setVerticalGroup(
        butt1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 150, Short.MAX_VALUE)
    );

    jButton1.setText("Addddd");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    deleteButton.setText("DELETE");
    deleteButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            deleteButtonActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(table1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(107, 107, 107)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(0, 0, Short.MAX_VALUE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(jLabel2))
                                    .addGap(1, 1, 1)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(authorTextField)
                                        .addComponent(titleTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(8, 8, 8)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                            .addGap(10, 10, 10)
                                            .addComponent(jButton1))
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(jLabel3)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(yearTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                        .addComponent(butt1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGroup(layout.createSequentialGroup()
                    .addGap(18, 18, 18)
                    .addComponent(deleteButton)
                    .addGap(0, 0, Short.MAX_VALUE)))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(deleteButton)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(titleTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabel2)
                        .addComponent(authorTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(yearTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jButton1)
                    .addGap(1, 1, 1)
                    .addComponent(butt1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addComponent(table1, javax.swing.GroupLayout.PREFERRED_SIZE, 329, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(0, 64, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    String text1 = titleTextField.getText();
    String text2 = authorTextField.getText();
    int text3 = Integer.parseInt(yearTextField.getText());
    JTable table = table1.getTable();
    MyTableModel model = (MyTableModel) table.getModel();
    System.out.println(text1 + text2 + text3);
    model.addRow(new Book(model.list.size(), text1, text2, text3));
}

private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
    JTable table = table1.getTable();
    MyTableModel model = (MyTableModel) table.getModel();
    int row = table.getSelectedRow();
    System.out.println("ROW: " + row);
    model.removeRow(row);
}

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /*
     * Set the Nimbus look and feel
     */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /*
     * If Nimbus (introduced in Java SE 6) is not available, stay with the
     * default look and feel. For details see
     * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /*
     * Create and display the form
     */
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            try {
                new MainFrame().setVisible(true);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
}
// Variables declaration - do not modify
private javax.swing.JTextField authorTextField;
private net.kxyz.Butt butt1;
private javax.swing.JButton deleteButton;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private net.kxyz.Table table1;
private javax.swing.JTextField titleTextField;
private javax.swing.JTextField yearTextField;
// End of variables declaration
}

Table Panel

  /*
   * To change this template, choose Tools | Templates
   * and open the template in the editor.
   */
  package net.kxyz;

  import java.awt.BorderLayout;
  import java.awt.Dimension;
  import java.awt.GridLayout;
  import java.io.FileNotFoundException;
  import java.io.IOException;
  import java.util.ArrayList;
  import javax.swing.*;
  import javax.swing.table.AbstractTableModel;
  import xyz.libary.Book;
  import xyz.libary.DataInterface;
  import xyz.libary.MockDataInterface;


  public class Table extends javax.swing.JPanel {

JTable table;
MyTableModel model;

public JTable getTable() {
    return table;
}
MockDataInterfaceImpl dataInterface = new MockDataInterfaceImpl();

public Table() throws FileNotFoundException, IOException {
    super(new GridLayout(1, 0));
    final ArrayList<xyz.libary.Book> list = dataInterface.getAllBooks();
    model = new MyTableModel(list);
    jTable1 = new JTable(model);
    jTable1.setLayout(null);
    jTable1.setPreferredScrollableViewportSize(new Dimension(500, 70));
    jTable1.setFillsViewportHeight(true);
    JScrollPane scrollPane = new JScrollPane(jTable1);
    add(scrollPane, BorderLayout.SOUTH);
   }

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();

    jTable1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null}
        },
        new String [] {
            "Title 1", "Title 2", "Title 3", "Title 4"
        }
    ));
    jScrollPane1.setViewportView(jTable1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(163, Short.MAX_VALUE))
    );
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration

class MyTableModel extends AbstractTableModel {

    private String[] columnNames = {"ID", "Title", "Author",
        "Year", "State"};
    ArrayList<Book> list = null;

    MyTableModel(ArrayList<Book> list) {
        this.list = list;
    }

    MyTableModel() {
    }

    public int getColumnCount() {
        return columnNames.length;
    }

    public void removeRow(int row) {

        list.remove(row);
        fireTableDataChanged();
    }

    public int getRowCount() {
        return list.size();
    }

    public String getColumnName(int col) {
        return columnNames[col];
    }

    public Object getValueAt(int row, int col) {

        Book object = list.get(row);

        switch (col) {
            case 0:
                return object.getId();
            case 1:
                return object.getTitle();
            case 2:
                return object.getAuthor();
            case 3:
                return object.getYear();
            case 4:
                return object.isState();
            default:
                return "unknown";
        }
    }

    @Override
    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }
    boolean[] canEdit = new boolean[]{
        false, true, true, true, true,};

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit[columnIndex];
    }

    public void addRow(Book e) {
        list.add(e);
    }

    @Override
    public void setValueAt(Object value, int row, int col) {



        switch (col) {
            case 0:
            // id not editable  list.get(row).setId((int)value);
            case 1:
                list.get(row).setTitle((String) value);

                break;
            case 2:
                list.get(row).setAuthor((String) value);
                break;
            case 3:
                list.get(row).setYear((int) value);
                break;
            case 4:
                list.get(row).setState(value);
                System.out.println("VALUE: " + value);
                break;

        }
        System.out.println("UPDATE ROW: " + row + " COL " + col);
        dataInterface.updateBook(list.get(row));
        fireTableCellUpdated(row, col);
    }
}
 }

Book

package xyz.libary;


public class Book {
int id;
String title;
String author;
int year;
Boolean state;

public Book() {};
public Book(int id, String title, String author, int year) {
    this.id = id ;
    this.title = title;
    this.author = author;
    this.year = year;
    this.state = true;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}


public String getAuthor() {
    return author;
}

public void setAuthor(String author) {
    this.author = author;
}

public Boolean isState() {
    return state;
}

public void setState(Boolean state) {
    this.state = state;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public int getYear() {
    return year;
}

public void setYear(int year) {
    this.year = year;
}

public void setState(Object value) {
    this.state=(Boolean)(value);
}



}

Butt, I dont use

  package net.kxyz;


 public class Butt extends javax.swing.JPanel {

/**
 * Creates new form Butt
 */
public Butt() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jButton1 = new javax.swing.JButton();

    jButton1.setText("jButton1");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 300, Short.MAX_VALUE)
    );
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration
}

MockDataInterfaceImpl

 package net.kxyz;

 import java.util.ArrayList;
 import xyz.libary.Book;

 public class MockDataInterfaceImpl{

 ArrayList<Book> book = new ArrayList<>();

public MockDataInterfaceImpl() {

    book.add(new Book(book.size(), "TYTUL", "Autor", 1232));
    book.add(new Book(book.size(), "Ogien", "Mickiewicz", 2012 ));
    book.add(new Book(book.size(), "Woda", "Mickiewicz", 2012 ));
    book.add(new Book(book.size(), "Ziemia", "Mickiewicz", 2012 ));
    book.add(new Book(book.size(), "Powietrze", "Mickiewicz", 2012 ));
}


@Override
public ArrayList getAllBooks() {
     return book;
}

@Override
public void updateBook(Book book) {
    int index = book.getId() ;
    this.book.get(index).setTitle(book.getTitle());
    this.book.get(index).setAuthor(book.getAuthor());
    this.book.get(index).setYear(book.getYear());
    this.book.get(index).setState(book.isState());
    System.out.println("Updated id = " +index);
 }

@Override
public void deleteBook(Book book) {
    int index = book.getId() ;
    this.book.remove(index);
    System.out.println("Remove id = " +index);
    }

@Override
public void addBook(Book book) {
    this.book.add(book);
    }

 }

Upvotes: 0

Views: 492

Answers (2)

Paul Samsotha
Paul Samsotha

Reputation: 209132

Because I don't see an actionPerformed method anywhere in your code, I am going to assume you don't know how to add the code in NetBeans (because some parts are uneditable). That would be just foolish of me to assume that you have no idea how to program event code ;-) So here is the basic steps in Netbeans

  1. Right-click on the button that you want to perform the action on.
  2. Select Event -> Action -> actionPerformed
  3. You should see something like this generated in your source code near the bottom

    private void jButton1ActionPerformed(java.awt.event.ActionEvent e) {
    
    }
    
  4. Enter your code in that method for deleting the row


Also it looks like your JTable and TableModel are in different class than the buttons. What you need to do then is to have a getter for the table in the Table class. After you have that, you can do something like this

private void jButton1ActionPerformed(java.awt.event.ActionEvent e) {
    JTable table = table1.getTable();
    MyTableModel model = (MyTableModel)table.getModel();
    model.removeRow(...);
}

UPDATE

Tested it myself, with shorter code. It works fine. Not ClassCastException

Table.java

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

public class Table extends JPanel {

    JTable table;

    public Table() {
        Object[][] data = {
            {"Hello", "Hello", "Hello", "Hello", "Hello"},
            {"Hello", "Hello", "Hello", "Hello", "Hello"},
            {"Hello", "Hello", "Hello", "Hello", "Hello"},
            {"Hello", "Hello", "Hello", "Hello", "Hello"}};

        table = new JTable(new MyTableModel(data));
        add(new JScrollPane(table));

    }

    public JTable getTable() {
        return table;
    }

    class MyTableModel extends AbstractTableModel {

        private String[] columnNames = {"ID", "Title", "Author",
            "Year", "State"};
        Object[][] list;

        public MyTableModel(Object[][] list) {
            this.list = list;
        }

        @Override
        public int getRowCount() {
            return list.length;
        }

        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return list[rowIndex][columnIndex];
        }
    }
}

TestTable.java

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import practice.Table.MyTableModel;

public class TestTable extends JFrame {

    private Table table1;
    private JButton button;
    public TestTable() {
        table1 = new Table();
        button = new JButton("Get Value at 0, 0");
        button.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                JTable table = table1.getTable();
                MyTableModel model = (MyTableModel)table.getModel();
                System.out.println(model.getValueAt(0, 0));
            }
        });

        add(table1);
        add(button, BorderLayout.SOUTH);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);

    } 

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

Upvotes: 1

Apophis
Apophis

Reputation: 115

Assuming you mean removeRow(int), how about -

jbutton1.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent e) {
      table.deleteRow(row);
   }
});

Upvotes: 0

Related Questions