Hi, I have problem
I can't add to the JTable new row (public void addRow(ArrayList<Object> newRow)) from the other class with action of the button
Main.java
import com.sun.javaws.Globals;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.event.TableModelEvent;
import javax.swing.table.AbstractTableModel;
import javax.xml.bind.annotation.XmlElementDecl;
public class Main extends GuiClass{
public static int cols;
public static void main(String[] args) {
DbLcDutConnection connection = new DbLcDutConnection();
String query = "SELECT * FROM students";
try {
Statement statement = connection.getConnection().createStatement();
ResultSet resultSet = statement.executeQuery(query);
ResultSetMetaData counter = resultSet.getMetaData();
cols=counter.getColumnCount();
GuiClass gui = new GuiClass();
gui.startGui("ЛК ДУТ");
resultSet.beforeFirst();
while (resultSet.next()){
int row=resultSet.getRow();
gui.addToTable(counter.getColumnCount(), resultSet, row-1);
}
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//Search
public Main() {
}
}
class MyModel extends AbstractTableModel {
static ArrayList<ArrayList<Object>> list = new ArrayList<ArrayList<Object>>();
public int getColumnCount() {
return Main.cols;
}
public String getColumnName(int column){
switch (column) {
case 0:
return "Id";
case 1:
return "Pib";
case 2:
return "Speciality";
case 3:
return "Date of birth";
case 4:
return "Address";
case 5:
return "Phone";
}
return "";
}
public int getRowCount() {
return list.size();
}
public Object getValueAt(int r, int c) {
return list.get(r).get(c);
}
public void setValueAt(Object obj, int r, int c) {
ArrayList<Object> rowArray = new ArrayList<Object>();
rowArray.add(obj);
try {
list.get(r).add(rowArray);
}catch (Exception e){
list.add(new ArrayList<Object>());
list.get(r).add(rowArray);
}
fireTableCellUpdated(r, c);
}
public void addRow(ArrayList<Object> newRow) {
System.out.println(1);
int rowCount = getRowCount();
list.add(new ArrayList<Object>());
for(int i=0; i<newRow.size(); i++){
list.get(rowCount).add(newRow.get(i));
}
fireTableRowsInserted(rowCount, rowCount);
}
}
GuiClass.java
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.ArrayList;
public class GuiClass {
// final AbstractTableModel model = new MyModel();
MyModel model = new MyModel();
String specialities [] = {"Обслуговування компютерних систем і мереж",
"Монтаж, обслуговування та експлуатація апаратних засобів інформатизації",
"Технічне обслуговування і ремонт апаратури зв’язку та оргтехніки",
"Монтаж, обслуговування і ремонт станційного обладнання електрозв’язку"};
String specializations [] = {"Компютерна інженерія", "Телекомунікації"};
JLabel specialityLabel;
JLabel specializationLabel;
JComboBox specialityComboBox;
JComboBox specializatonComboBox;
JPanel studentSearchPanel;
JPanel specPanel;
JTextField searchStudentTextField;
JLabel searchStudentLabel;
JMenuBar menuBar;
JMenu menuFile;
JMenu menuOperations;
JMenu menuReports;
JMenuItem openItem;
JMenuItem saveItem;
JMenuItem saveAsItem;
public JTable mainStudentsTable= new JTable(model);
JScrollPane mainStudentsTableScrollPane;
JPanel registerStudentPanel;
JButton registerStudentButton;
JPanel tablePanel;
public void startGui(String nameOfForm){
JFrame frame = new JFrame();
frame.setTitle(nameOfForm);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
// frame.setUndecorated(true);
// frame.setAlwaysOnTop(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(new BorderLayout());
frame.setLocationRelativeTo(null);
frame.setResizable(true);
frame.setCursor(new Cursor(Cursor.HAND_CURSOR));
// НАЛАШТУВАННЯ ФРЕЙМА
specialityLabel = new JLabel("Спеціальність: ");
specializationLabel = new JLabel("Спеціалізація: ");
specialityComboBox = new JComboBox(specialities);
specializatonComboBox = new JComboBox(specializations);
studentSearchPanel = new JPanel();
searchStudentTextField = new JTextField(20);
searchStudentLabel = new JLabel("ПІБ ");
specPanel = new JPanel();
menuBar = new JMenuBar();
menuFile = new JMenu("File");
menuOperations = new JMenu("Operations");
menuReports = new JMenu("Reports");
menuBar.add(menuFile);
menuBar.add(menuOperations);
menuBar.add(menuReports);
openItem = new JMenuItem("Open");
saveItem = new JMenuItem("Save");
saveAsItem = new JMenuItem("Save as");
menuFile.add(openItem);
menuFile.add(saveItem);
menuFile.add(saveAsItem);
frame.setJMenuBar(menuBar);
mainStudentsTableScrollPane = new JScrollPane(mainStudentsTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
mainStudentsTableScrollPane.setSize(400,400);
// mainStudentsTable = new JTable(Main.studentsTableModel);
registerStudentPanel = new JPanel(new BorderLayout());
registerStudentButton = new JButton("Додати нового студента");
registerStudentButton.addActionListener(new StudentRegisterActionListener());
mainStudentsTableScrollPane.setPreferredSize(new Dimension(200,260));
tablePanel = new JPanel(new BorderLayout());
// СТВОРЕНІ КОМПОНЕНТИ
specPanel.setLayout(new GridBagLayout());
specPanel.add(specialityLabel, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(1, 40, 1, 1), 0, 0));
specPanel.add(specialityComboBox, new GridBagConstraints(1,0,1,1,1,1,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(1,1,1,450),0,0));
specPanel.add(specializationLabel, new GridBagConstraints(0,1,1,1,1,1,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(1,40,1,1),0,0));
specPanel.add(specializatonComboBox, new GridBagConstraints(1,1,1,1,1,1,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(1,1,1,450),0,0));
specPanel.setBackground(Color.GREEN);
// ПАНЕЛЬ СПЕЦІАЛІЗАЦІЙ І СПЕЦІАЛЬНОСТЕЙ
studentSearchPanel.setLayout(new BorderLayout());
studentSearchPanel.setBorder(new TitledBorder("Пошук студента"));
studentSearchPanel.add(searchStudentLabel, BorderLayout.NORTH);
studentSearchPanel.add(searchStudentTextField, BorderLayout.NORTH);
//ПАНЕЛЬ ПОШУКУ СТУДЕНТІВ
tablePanel.add(mainStudentsTableScrollPane, BorderLayout.CENTER);
frame.add(tablePanel, BorderLayout.SOUTH);
frame.add(specPanel, BorderLayout.NORTH);
frame.add(registerStudentPanel, BorderLayout.EAST);
frame.add(studentSearchPanel, BorderLayout.WEST);
registerStudentPanel.add(registerStudentButton, BorderLayout.SOUTH);
StudentRegisterActionListener studentReg=new StudentRegisterActionListener();
// StudentRegisterActionListener.regButton.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// ArrayList<Object> newRow=new ArrayList<Object>();
// newRow.add(studentReg.name.getText());
// newRow.add(2);
// newRow.add(3);
// newRow.add(4);
// newRow.add(5);
// newRow.add(6);
// model.addRow(newRow);
// }
// });
}
public void addToTable(int x, ResultSet resultSet, int row) {
for (int i = 1; i <= x; i++) {
try {
model.setValueAt(resultSet.getObject(i), row, i-1);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public String[] getSpecialities() {
return specialities;
}public String[] getSpecializations() {
return specializations;
}
}
In this class I am doing actiolistner and all is good , but if I do it here I have problem: 106.-117.
StudentRegister.class
import com.mysql.fabric.jdbc.FabricMySQLDriver;
import javax.lang.model.element.Name;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.ArrayList;
class StudentRegisterActionListener extends GuiClass implements ActionListener{
GuiClass gui = new GuiClass();
JTextField name = new JTextField(30);
JTextField dateOfBirth = new JTextField(30);
JTextField address = new JTextField(30);
JTextField phone = new JTextField(30);
JLabel nameLabel = new JLabel("ПІБ: ");
JLabel dateOfBirthLabel = new JLabel("Дата народження");
JLabel addressLabel = new JLabel("Адреса");
public JComboBox getSpecialityComboBox() {
return specialityComboBox;
}
JLabel phoneLabel = new JLabel("Номер телефону");
JComboBox specialityComboBox = new JComboBox(gui.getSpecialities());
JComboBox specializationsComboBox = new JComboBox(gui.getSpecializations());
JLabel specialityLabel = new JLabel("Оберіть спеціальіність");
JLabel specializationsLabel = new JLabel("Оберіть спеціалізацію");
static JButton regButton= new JButton("Реєстрація");
public JTextField getName() {
return name;
}
public JTextField getDateOfBirth() {
return dateOfBirth;
}
public JTextField getAddress() {
return address;
}
public JTextField getPhone() {
return phone;
}
@Override
public void actionPerformed(ActionEvent e) {
mainStudentsTable = new JTable(model);
final JFrame registerStudent = new JFrame("Реєстрація");
registerStudent.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
registerStudent.setLocationRelativeTo(null);
registerStudent.setLayout(new GridBagLayout());
registerStudent.setSize(350,250);
registerStudent.setVisible(true);
registerStudent.add(nameLabel, new GridBagConstraints(0,0,1,1,1,1,GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(1,1,1,1),0,0));
registerStudent.add(name, new GridBagConstraints(1,0,1,1,1,1,GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(1,1,1,1),0,0));
registerStudent.add(dateOfBirthLabel, new GridBagConstraints(0,1,1,1,1,1,GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(1,1,1,1),0,0));
registerStudent.add(dateOfBirth, new GridBagConstraints(1,1,1,1,1,1,GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(1,1,1,1),0,0));
registerStudent.add(addressLabel, new GridBagConstraints(0,2,1,1,1,1,GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(1,1,1,1),0,0));
registerStudent.add(address, new GridBagConstraints(1,2,1,1,1,1,GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(1,1,1,1),0,0));
registerStudent.add(phoneLabel, new GridBagConstraints(0,3,1,1,1,1,GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(1,1,1,1),0,0));
registerStudent.add(phone, new GridBagConstraints(1,3,1,1,1,1,GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(1,1,1,1),0,0));
registerStudent.add(specialityLabel, new GridBagConstraints(0,4,1,1,1,1,GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(1,1,1,1),0,0));
registerStudent.add(specialityComboBox, new GridBagConstraints(1,4,1,1,1,1,GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(1,1,1,1),0,0));
registerStudent.add(specializationsLabel, new GridBagConstraints(0,5,1,1,1,1,GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(1,1,1,1),0,0));
registerStudent.add(specializationsComboBox, new GridBagConstraints(1,5,1,1,1,1,GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(1,1,1,1),0,0));
registerStudent.add(regButton, new GridBagConstraints(2,6,1,1,1,1,GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(1,1,1,1),0,0));
registerStudent.setLocationRelativeTo(null);
registerStudent.pack();
regButton.addActionListener(new ActionListener() {
// private final String URL = "jdbc:mysql://localhost:3306/lc_dut_test_db";
// private final String USERNAME = "root";
// private final String PASSWORD = "vladik0555";
private String query1 = "INSERT INTO students(pib, Speciality, date_of, adress, phone) VALUES(?,?,?,?,?)";
PreparedStatement preparedStatement;
Connection connection;
@Override
public void actionPerformed(ActionEvent e) {
try {
Driver driver = new FabricMySQLDriver();
DriverManager.registerDriver(driver);
connection = DriverManager.getConnection(DbLcDutConnection.URL, DbLcDutConnection.USERNAME, DbLcDutConnection.PASSWORD);
preparedStatement = connection.prepareStatement(query1);
preparedStatement.setString(1, name.getText());
preparedStatement.setString(2, (String) specialityComboBox.getSelectedItem());
preparedStatement.setString(3, dateOfBirth.getText());
preparedStatement.setString(4, address.getText());
preparedStatement.setString(5, phone.getText());
preparedStatement.execute();
name.setText("");
dateOfBirth.setText("");
address.setText("");
phone.setText("");
// mainStudentsTable.setModel(model);
ArrayList<Object> newRow=new ArrayList<Object>();
newRow.add(name.getText());
newRow.add(2);
newRow.add(3);
newRow.add(4);
newRow.add(5);
newRow.add(6);
model.addRow(newRow);
registerStudent.dispose();
preparedStatement.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
}
}