This question already has an answer here:
Display JCheckBox in JTable
(1 answer)
Closed 6 years ago.
i am create a swing based authentication system and i have a table where i wish to print some necessary details and want the last columnn to have a checkbox. Even after giving a boolean value it is printing true or false rather than a checkbox
controlPanel.removeAll();
System.out.println("coming1");
JournalApprovalClass JAC = new JournalApprovalClass();
JournalApproval JA = new JournalApproval();
String[] columns = { "Author1", "Author2", "Author3",
"Author4", "Author5", "Author6", "Title",
"JournalName", "Scopus", "ImpactFactor",
"JournalMonth", "JournalYear", "NamePublisher",
"VolumeIssuePageNo", "BtechMtech", "OtherDetails",
"Approval" };
System.out.println("coming2");
try {
JA.adminApprovalJournalApproval();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("coming3");
DefaultTableModel model = new DefaultTableModel(
journalTable.values2, columns);
JTable journalAdminApprovalTable = new JTable(model);
journalAdminApprovalTable
.setPreferredScrollableViewportSize(new Dimension(
1200, 100));
journalAdminApprovalTable.setFillsViewportHeight(true);
TableColumn column = null;
for (int i = 0; i <= 16; i++) {
column = journalAdminApprovalTable.getColumnModel()
.getColumn(i);
column.setPreferredWidth(50);
if (i == 16) {
column.setPreferredWidth(10);
}
}
System.out.println("coming4");
JScrollPane scrollPane = new JScrollPane(
journalAdminApprovalTable);
controlPanel.add(scrollPane);
controlPanel.revalidate();
controlPanel.repaint();
System.out.println("coming5");
This is where i am trying to create to create the table the data object is created in another class
ma.values[0] = au.Author1;
ma.values[1] = au.Author2;
ma.values[2] = au.Author3;
ma.values[3] = au.Author4;
ma.values[4] = au.Author5;
ma.values[5] = au.Author6;
ma.values[6] = au.Title;
ma.values[7] = au.JournalName;
ma.values[8] = au.Scopus;
ma.values[9] = au.ImpactFactor;
ma.values[10] = au.JournalMonth;
ma.values[11] = au.JournalYear;
ma.values[12] = au.NamePublisher;
ma.values[13] = au.VolumeIssuePageNo;
ma.values[14] = au.BtechMtech;
ma.values[15] = au.OtherDetails;
ma.values[16] = new Boolean(true);
/*if (au.AdminApproval == "NO") {
ma.values[16] = new JCheckBox("Approval");
} else
ma.values[16] = new Boolean(true);*/
ma.values1[i] = new Object[17];
ma.values1[i] = ma.values;
System.out.println(ma.values1[i] + " " + ma.values[0] + " "
+ i);
i++;
}
resultSet.next();
}
journalTable.values2 = new Object[i][];
for (int j = 0; j < i; j++)
journalTable.values2[j] = journalTable.values1[j];
return;
Everything is working properly but the thing what i wish for is to have checkbox which is always checked(the reason behind giving true).
when i run the code i get the following output
last column i need a checkbox
It is because your model is operating on String rather than Object. I am not able to run your code, but if I were you I would:
Try to change String[] columns to Object[] columns.
If that
doesn't help, take a look at this
Related
How to take the values of the dynamic textfield?
I suppose to set number of textfields I want at beginning of my program and set the values in this fields and write it into txt file
// this is the foreach loop suppose to take the values and send them to addburst function
for( JTextField f : bt )
{
Burst b = new Burst();
b.addBurst(Integer.parseInt(f.getText()));
}
*addburst function
public boolean addBurst(int x) {
if (FManger.write(x, BurstFileName, true)) {
return true;
} else {
return false;
}
}
*Write Function
public boolean write(int Query, String FilePath, boolean appendType) {
PrintWriter writter = null;
try {
System.out.print("\nwritting in ! " + FilePath);
writter = new PrintWriter(new FileWriter(new File(FilePath),
appendType));
writter.println(Query);
System.out.println(" ... Done ! ");
return true;
} catch (IOException e) {
System.out.println(e);
} finally {
writter.close();
}
return false;
}
I added the dynamic textfields by the constructor
public FillData(int x) {
initComponents();
getContentPane().setBackground(Color.ORANGE);
PnoPanel.setLayout(new GridLayout(x,2));
BuPanel.setLayout(new GridLayout(x,2));
ArrPanel.setLayout(new GridLayout(x,2));
JLabel ProcessNumber[] = new JLabel[x];
JTextField BurstTime[] = new JTextField[x];
JTextField ArrivalTime[] = new JTextField[x];
for (int i = 0; i < x; i++)
{
ProcessNumber[i] = new JLabel(" Process "+(i+1));
BurstTime[i] = new JTextField();
ArrivalTime[i] = new JTextField();
PnoPanel.add(ProcessNumber[i]);
BuPanel.add(BurstTime[i]);
ArrPanel.add(ArrivalTime[i]);
}
}
x is the number of textfields
I wrote the following code that I thought would work, I wanted to open a new JFrame on a button click that shows a progress bar that gets updated:
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int numOfRows = getRows();//function that returns number of rows
int numOfColumns = getColumns();//function that returns number of columns
String myquery = "select * from foo_table";
rs = null;
try {
rs = st.executeQuery(myquery);
// extract column information
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
columnData = new ArrayList<String>(columnCount);
for (int i = 1; i <= columnCount; i++) {
columnData.add(rsmd.getColumnName(i));
}
// sql result data
table_ResQues.setModel(new ListTableModel(Collections.<List<Object>>emptyList(), Collections.<String>emptyList()));
rowData = new ArrayList<List<Object>>();
final JFrame progFrame = new JFrame("Processing...");
JPanel mainPPanel = new JPanel(new BorderLayout());
JProgressBar progBar = new JProgressBar(0,100);
progFrame.setBounds(850,300,400,100);
progFrame.setVisible(true);
progBar = new JProgressBar(0,100);
mainPPanel.add(progBar, BorderLayout.NORTH);
progFrame.add(mainPPanel);
progFrame.setVisible(true);
int countRows = 0;
int area = numOfRows*numOfColumns;
int totalTime = area % 200000;
int xPerSec = totalTime/100;
while (rs.next()) {
row = new ArrayList<Object>(columnCount);
for (int i = 0; i < columnCount; i++) {
row.add(rs.getObject(i + 1));
}
rowData.add(row);
countRows++;
if(countRows*numOfColumns == 200000){
progBar.setValue(xPerSec++);
countRows = 0;
}
}
table_ResQues.setModel(new ListTableModel(rowData, columnData));
}catch (SQLException e1) {
JOptionPane.showMessageDialog(frame, e1.getMessage(), "SQL Exception", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
});
But when googling my problem I realized it is a threading issue, and I never had any experience with threading or SwingWorker, can anyone help me implement what I want using SwingWorker? Should my while-loop be the one that's running in the background? should it be a class by itself? Sorry, i'm really confused.
I have solved it by creating a new class that extends SwingWorker and overriding it's methods. Thanks for the help in the comments.
I've made a GUI in Java that connects with a MySQL server and inserts,deletes,updates data. I have a section on this GUI that you can write in a text area a MySQL query and the result is displayed on a Jtable. Everything works fine! I can print the data from the JTable or save them to a text file!
Now, I want to add another feature: When I double click on a specific cell, I would like to change the data of the JTable, and I want this data to be updated in the MySQL table with the click of a button as well.
I've searched all over the internet, but I can't find a good example or a good solution. The JTable I have is dynamic; that means that what ever query is inserted the data will be displayed with the quired column names and data
Here is the code:
ArrayList columnNames = new ArrayList();
ArrayList data = new ArrayList();
data_connector getdata1 = new data_connector();
host = getdata1.getHost();
username = getdata1.getUsername();
password1 = getdata1.getPassword();
mysql_command = getdata1.getMysql_command();
command_name = getdata1.getCommand_name();
setTitle(command_name);
// Connect to an MySQL Database, run query, get result set
String url = "jdbc:mysql://"+host+":3306/xxxxx";
String userid = username;
String password = password1;
String sql = mysql_command;
// Java SE 7 has try-with-resources
// This will ensure that the sql objects are closed when the program
// is finished with them
try (Connection connection = DriverManager.getConnection( url, userid, password );
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql ))
{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
columnNames.add(md.getColumnName(i));
// Get row data
while (rs.next())
{
ArrayList row = new ArrayList(columns);
for (int i = 1; i <= columns; i++)
row.add(rs.getObject(i));
data.add(row);
}
}
catch (SQLException e)
{
System.out.println(e.getMessage());
JOptionPane.showMessageDialog(null, e.getMessage());
mysql_fail_flag = 1;
}
// Create Vectors and copy over elements from ArrayLists to them
// Vector is deprecated but I am using them in this example to keep
// things simple - the best practice would be to create a custom defined
// class which inherits from the AbstractTableModel class
Vector columnNamesVector = new Vector();
Vector dataVector = new Vector();
for (int i = 0; i < data.size(); i++)
{
ArrayList subArray = (ArrayList)data.get(i);
Vector subVector = new Vector();
for (int j = 0; j < subArray.size(); j++)
subVector.add(subArray.get(j));
dataVector.add(subVector);
}
for (int i = 0; i < columnNames.size(); i++ )
columnNamesVector.add(columnNames.get(i));
contentPane.setLayout(null);
// Create table with database data
table = new JTable(dataVector, columnNamesVector)
{
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
return o.getClass();
}
return Object.class;
}
};
// table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(5, 5, xframeWidth-20, yframeHeight-70);
getContentPane().add(scrollPane);
JPanel buttonPanel = new JPanel();
buttonPanel.setBounds(5, 856, 1574, 1);
getContentPane().add(buttonPanel);
buttonPanel.setLayout(null);
In the form you actually create your JTable, I don't think this is easy. What you want to do is subclassing AbstractTableModel, and overwrite the setValueAt() method. You subclass could look like this:
class MyModel extends AbstractTableModel
{
private ResultSet result;
private ResultSetMetaData metadata;
public MyModel (ResultSet rs)
{
super();
result = rs; // mustn't be null, maybe check and throw NPE
metadata = result.getMetaData();
}
public int getRowCount ()
{
result.last();
return result.getRow(); // See http://stackoverflow.com/questions/8292256/get-number-of-rows-returned-by-resultset-in-java
}
public int getColumnCount ()
{
return metadata.getColumnCount();
}
public Object getValueAt (int row, int col)
{
result.absolute(row);
return result.getString(col);
}
public String getColumnName (int col)
{
return metadata.getColumnName(col);
}
public void setValueAt (Object value, int row, int col)
{
result.absolute(row);
result.updateObject(col, value);
}
}
I haven't tested it, but your code must look like this. Note that you mustn't close the Statement, Connection or the ResultSet (or create a new ResultSet cause some db drivers like MySQL destroy the old one) to prevent any Exceptions.
OK!!! i managed to update every cell separately by just editing the cell and then pressing enter!
This works only for 1 table but its ok for my project! Here is the code...
private class RowColumnListSelectionListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
rowIndexStart = table.getSelectedRow();
rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
colIndexStart = table.getSelectedColumn();
colIndexEnd = table.getColumnModel().getSelectionModel().getMaxSelectionIndex();
for ( i = rowIndexStart; i <= rowIndexEnd; i++) {
for ( j = colIndexStart; j <= colIndexEnd; j++) {
Object cell_value = table.getValueAt(i,j);
Cell_value_string_before = (String) cell_value;
}
}
}
}
public test_table() {
setIconImage(Toolkit.getDefaultToolkit().getImage(test_table.class.getResource("/com/sun/java/swing/plaf/windows/icons/Computer.gif")));
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setBounds(100, 100, 688, 589);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
xframeWidth = screenSize.width; //dynamic size for frame x-axes
yframeHeight = screenSize.height; //dynamic size for frame y-axes
int xlocation = xframeWidth*2; //dynamic location x-axes
int ylocation = yframeHeight*2; //dynamic location y-axes
setBounds(0,0, xframeWidth, yframeHeight);
setResizable(false);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnNewMenu = new JMenu("Αρχείο");
menuBar.add(mnNewMenu);
JMenuItem mntmNewMenuItem_1 = new JMenuItem("Εξαγωγή σε .txt αρχείο");
mntmNewMenuItem_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser =new JFileChooser();
fileChooser.setDialogTitle("Δημιουργία αρχείου .txt");
FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt", "text");
fileChooser.setFileFilter(filter);
int returnVal = fileChooser.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
File file = fileChooser.getSelectedFile();
File newfile = new File(file.getPath()+".txt");
// PrintWriter os = new PrintWriter(file);
FileWriter fw = new FileWriter(newfile,true); //filewriter
BufferedWriter bw = new BufferedWriter(fw); //buffered writer
PrintWriter os = new PrintWriter(bw, true);
os.print("");
for (int col = 0; col < table.getColumnCount(); col++) {
os.print(table.getColumnName(col) + "\t");
os.print(";");
}
os.println("");
os.println("");
for (int row = 0; row < table.getRowCount(); row++) {
for (int col = 0; col < table.getColumnCount(); col++) {
//os.print(table.getColumnName(col) + "\t");
// os.print(": ");
os.print(table.getValueAt(row, col) + "\t");
os.print(";");
// os.print(table.getRowCount() + "\t");
}
os.println("");
}
os.close();
System.out.println("Done!");
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
mnNewMenu.add(mntmNewMenuItem_1);
JMenuItem mntmNewMenuItem_2 = new JMenuItem("Εκτύπωση");
mntmNewMenuItem_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (! table.print()) {
System.err.println("User cancelled printing");
}
} catch (java.awt.print.PrinterException e1) {
System.err.format("Cannot print %s%n", e1.getMessage());
}
}
});
mnNewMenu.add(mntmNewMenuItem_2);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
ArrayList columnNames = new ArrayList();
ArrayList data = new ArrayList();
// data_connector getdata1 = new data_connector();
// host = getdata1.getHost();
// username = getdata1.getUsername();
// password1 = getdata1.getPassword();
// mysql_command = getdata1.getMysql_command();
// command_name = getdata1.getCommand_name();
//setTitle(command_name);
// Connect to an MySQL Database, run query, get result set
String url = "jdbc:mysql://localhost:3306/υπαλληλοι απε-μπε";
String userid = "ziorange";
String password = "120736";
String sql = "SELECT * FROM `ΥΠΑΛΛΗΛΟΙ 2 test`";
//String sql = "SELECT `ΚΩΔΙΚΟΣ`,`ΕΠΩΝΥΜΟ`,`ΟΝΟΜΑ`,`ΟΝΟΜΑ ΠΑΤΡΟΣ`,`ΑΜΚΑ`,`ΑΡΙΘΜΟΣ ΜΗΤΡΩΟΥ ΙΚΑ (αν υπάρχει)` FROM `ΥΠΑΛΛΗΛΟΙ 2` WHERE `ΚΩΔΙΚΟΣ`>'0' AND `ΗΜΕΡΟΜΗΝΙΑ ΑΠΟΧΩΡΗΣΗΣ`>'2009-12-31 00:00:00' OR `ΕΙΔΙΚΟΤΗΤΑ` !='ΑΝΤΑΠΟΚΡΙΤΗΣ ΕΞ' AND `ΛΟΓΟΣ ΑΠΟΧΩΡΗΣΗΣ`='-' ORDER BY `ΕΠΩΝΥΜΟ`";
// Java SE 7 has try-with-resources
// This will ensure that the sql objects are closed when the program
// is finished with them
try
{
connection = DriverManager.getConnection( url, userid, password );
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.add( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
ArrayList row = new ArrayList(columns);
for (int i = 1; i <= columns; i++)
{
row.add( rs.getObject(i) );
}
data.add( row );
}
}
catch (SQLException e)
{
//
System.out.println( e.getMessage() );
JOptionPane.showMessageDialog(null, e.getMessage() );
mysql_fail_flag=1;
}
// Create Vectors and copy over elements from ArrayLists to them
// Vector is deprecated but I am using them in this example to keep
// things simple - the best practice would be to create a custom defined
// class which inherits from the AbstractTableModel class
Vector columnNamesVector = new Vector();
Vector dataVector = new Vector();
for (int i = 0; i < data.size(); i++)
{
ArrayList subArray = (ArrayList)data.get(i);
Vector subVector = new Vector();
for (int j = 0; j < subArray.size(); j++)
{
subVector.add(subArray.get(j));
}
dataVector.add(subVector);
}
for (int i = 0; i < columnNames.size(); i++ )
columnNamesVector.add(columnNames.get(i));
contentPane.setLayout(null);
// Create table with database data
table = new JTable(dataVector, columnNamesVector)
{
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setColumnSelectionAllowed(true); //epilegei to kathe keli ksexwrista
table.getSelectionModel().addListSelectionListener(
new RowColumnListSelectionListener());
table.getDefaultEditor(String.class).addCellEditorListener(
new CellEditorListener() {
public void editingCanceled(ChangeEvent e) {
System.out.println("editingCanceled");
}
public void editingStopped(ChangeEvent e) {
System.out.println("editingStopped: apply additional action");
rowIndexStart = table.getSelectedRow();
rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
colIndexStart = table.getSelectedColumn();
colIndexEnd = table.getColumnModel().getSelectionModel().getMaxSelectionIndex();
for ( i = rowIndexStart; i <= rowIndexEnd; i++) {
for ( j = colIndexStart; j <= colIndexEnd; j++) {
Object cell_value = table.getValueAt(i,j);
Cell_value_string_after = (String) cell_value;
ia=i+1;
ja=j+1;
column_name_selected2 = table.getColumnName(ja-1);
}
}
if(Cell_value_string_before.equals(Cell_value_string_after)){
System.out.println("Do nothing");
}
else{
System.out.println("UPDATE DATABASE");
update_database();
}
}
});
JScrollPane scrollPane = new JScrollPane( table );
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(5, 5, xframeWidth-20, yframeHeight-70);
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
buttonPanel.setBounds(5, 856, 1574, 1);
getContentPane().add( buttonPanel );
buttonPanel.setLayout(null);
}
public void update_database(){
Object get_lastname = table.getValueAt(ia-1, 5);
String get_lastname_string = (String) get_lastname;
Object get_name = table.getValueAt(ia-1, 6);
String get_name_string=(String) get_name;
System.out.println("RESULT= "+ column_name_selected2 + " - "+Cell_value_string_after+ " - " + get_lastname_string+ " - " + get_name_string );
if(column_name_selected2.equals("ΕΠΩΝΥΜΟ") || column_name_selected2.equals("ΟΝΟΜΑ")){
JOptionPane.showMessageDialog(null, "To επώνυμο και το όνομα δεν μπορεί να αλλάξει","Μήνυμα:",JOptionPane.WARNING_MESSAGE);
}
else{
try {
PreparedStatement update = (PreparedStatement) connection.prepareStatement
("UPDATE `ΥΠΑΛΛΗΛΟΙ 2 TEST` SET `" +column_name_selected2+"` = ? WHERE ΕΠΩΝΥΜΟ= ? AND ΟΝΟΜΑ =? ");
update.setString(1,Cell_value_string_after);
update.setString(2,get_lastname_string);
update.setString(3,get_name_string);
int all_edit_query_status=update.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I write a code that add/delete data from database to JTable which has 3 columns when User press "Add" or "Delete" Button (JtoggleButton) and then press the buttons(JButton) that their labels are the number from 1 to 9.
Here the user interface of the code:
When I try to add data to the table in the first time, it's ok and the number of columns is still 3 columns:
But when I add data in the second or third time continuously , there are more 3 extra blank columns added into the table too which I don't need it.:
Here the code that I think the problem is occurred:
final DefaultTableModel defaultmodel2 = new DefaultTableModel();
final JToggleButton tglbtnAdd = new JToggleButton("Add");
final JToggleButton tglbtnDelete = new JToggleButton("Delete");
JButton button = new JButton("1");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection dbconbt1 = DriverManager.getConnection("" +"jdbc:sqlserver://localhost;databaseName=Store;user=<>;password=<>");
Statement sqlstatement = dbconbt1.createStatement();
ResultSet dbresultset1 = sqlstatement.executeQuery("select * from Store.dbo.Product where ProductID = 'P-1'");
ResultSetMetaData rsmetadata = dbresultset1.getMetaData(); // Get metadata on them
int numcols = rsmetadata.getColumnCount(); // How many columns?
if(tglbtnAdd.isSelected() == true)
{
for (int i = 1; i <= numcols; i++)
{
defaultmodel2.addColumn( rsmetadata.getColumnName(i));
}
while (dbresultset1.next())
{ Vector<Object> row = new Vector<Object>(numcols);
for (int i = 1; i <= numcols; i++)
{
row.addElement( dbresultset1.getObject(i) );
}
defaultmodel2.addRow(row );
}
}
if(tglbtnDelete.isSelected() == true)
{
defaultmodel2.removeRow(0);
}
// Get row
dbresultset1.close();
sqlstatement.close();
dbconbt1.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Every time you call actionPerformed, you are also calling defaultmodel2.addColumn( rsmetadata.getColumnName(i));
This means, that each time an actionPerformed method is called, it is adding more columns to the column model.
You have a few choices...
Check to see if the table model already contains columns and don't add new ones
Check to see if the table model has the particular column and don't add it if it does
Uses the columns from "Product List" table instead...
I'm having a bit of a problem when running the code below. This code is used when a button on a gui screen is pressed. Basically the function of this button is to read text entered into 2 text fields, derive a third value from the 2, and save all 3 in a row in a table on the GUI screen, using a 2d array.
However, i get a NullPointerException when executing it at the 5th line inside the method addItem().
saleData is the 2D array with data which is in the table.
i have instantiated the temp[][] object with 1 row more than the saleData object because i need to add a row to the table, and then i make saleData=temp.
This code worked as it is in the Gui class before i tried using OOP to create a separate class for the GUI to work from.
The nullpointer exception refers to the temp object, i know this because i printed out the value of temp and it was a null.
Does anyone have any ideas?
thanks in advance.
public void addItem() {
int len = saleData.length + 1;
Object[][] temp = new Object[len][3];
for (int k = 0; k < saleData.length; k++) {
for (int i = 0; i < 3; i++) {
temp[k][i] = ((DefaultTableModel) table.getModel()).getValueAt(k, i);
}
}
tblContainer.removeComponent(table);
try {
int qty = Integer.parseInt(txtQty.getText());
String item = (String) items.getSelectedItem();
String sql = "Select Sell_price from stockInfo where parts like '" + item + "'";
double total = 0;
if (saleData.length != 1) {
for (int i = 0; i < saleData.length; i++) {
String sql2 = "Select sell_price from stockinfo where parts like '" + temp[i][1].toString() + "'";
try {
System.out.println("Check 0");
pst = conn.prepareStatement(sql2);
System.out.println("Check 1");
rs = pst.executeQuery();
System.out.println("Check 2");
while (rs.next()) {
System.out.println("Check 3");
String qt = temp[i][0].toString();
temp[i][2] = Double.parseDouble(rs.getString("sell_price")) * Integer.parseInt(qt);
System.out.println("Check 4");
}
} catch (Exception e) {
Dialog.show("Error", "Error 1: " + e, "OK", null);
}
}
}
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
double price = Double.parseDouble(rs.getString("Sell_Price"));
total = qty * price;
try {
for (int m = 0; m < saleData.length; m++) {
for (int n = 0; n < 3; n++) {
((DefaultTableModel) table.getModel()).setValueAt(m, n, temp[m][n]);
}
}
temp[saleData.length][0] = qty;
temp[saleData.length][1] = item;
temp[saleData.length][2] = total;
saleData = temp;
table = new Table(new DefaultTableModel(saleColumns, saleData, true));
tblContainer.addComponent(table);
((TableLayout) table.getLayout()).setGrowHorizontally(true);
saleForm.revalidate();
} catch (NullPointerException e) {
}
}
} catch (SQLException e) {
Dialog.show("Error", "SQL Error Record Sale", "OK", null);
}
} catch (NumberFormatException nfe) {
Dialog.show("Error", "Please enter a valid quantity", "OK", null);
}
}
The temp array can not be null. You just created it.
temp[k][i] can be null (and should be, by the way), but that does not matter - it is being assigned a value.
If a dimension of temp would not be big enough, you'd get an ArrayIndexOutOfBoundsException
So this leaves for two things that can get to be null (if the error stems from that line, and not for example from the inside of getValueAt(k,i) ):
table
table.getModel()
Use a debugger, and it will make your life easier...