jtable reloads but when clicked on a jcheck box old data popsup - java

i) My Table contains no of columns and a jcheckbox i the last column.
ii) I am using a combobox to select certain value.
iii) based on the value of combo box the jbutton loads the data into the table.
iv) when i reload the data into the table, the new data gets displayed in jtable.
v) The problem is that, When I press the Jcheckbox, the old data is getting displayed in jtable.
code is as below:
public class aap2 extends JFrame {
#SuppressWarnings({ "unchecked", "rawtypes" })
static JComboBox year = new JComboBox(new Object[]
{"2012-13", "2013-14", "2014-15", "2015-16","2016-17","2017-
18","2018-19"});
#SuppressWarnings({ "unchecked", "rawtypes" })
static JComboBox division = new JComboBox(new Object[]
{"Name", "address","profession","others"});
JComboBox schemetype = new JComboBox(new Object[]
{});
JButton showschemes = new JButton("Show Schemes");
static ResultSet rs;
Connection con;
Statement st;
static JPanel panel = new JPanel();
static JPanel panel1 = new JPanel();
static JPanel panel2= new JPanel();
static JPanel panel3= new JPanel();
static JPanel panel4= new JPanel();
static JPanel panel5= new JPanel();
UIManager ui= new UIManager();
static int columns;
static int sel[];
JTable table;
DefaultTableModel dtm;
public aap2(){
division.setMaximumRowCount(5);
year.setMaximumRowCount(5);
year.setForeground(Color.blue);
year.setBackground(Color.white);
year.setSelectedItem("2009-10");
setBounds(00,40,1020,700);
Color c= new Color(160,200,100);
getContentPane().setBackground(c);
Color c3= new Color(0,50,50,2);
panel1.setBackground(c3);
panel2.setBackground(c3);
panel.setBackground(c);
panel.setBorder(new TitledBorder(new LineBorder(Color.white,1),""));
panel.setLayout(new GridBagLayout());
GridBagConstraints gc= new GridBagConstraints();
panel1.setLayout( new GridBagLayout());
GridBagConstraints gc1 = new GridBagConstraints();
gc1.gridx=0;
gc1.gridy=0;
panel1.add( new JLabel("Financial Year"),gc1);
gc1.insets= new Insets(1,10,1,10);
gc1.gridx=1;
gc1.gridy=0;
panel1.add(year,gc1);
gc1.gridx=4;
gc1.gridy=0;
panel1.add( new JLabel("Division"),gc1);
gc1.gridx=5;
gc1.gridy=0;
panel1.add(division,gc1);
gc.gridx=0;
gc.gridy=0;
panel.add(panel1,gc);
JPanel p2= new JPanel();
gc.gridx=0;
gc.gridy=4;
p2.setBackground(c3);
panel.add(p2,gc);
panel3.setLayout( new GridBagLayout());
GridBagConstraints gc3 = new GridBagConstraints();
gc3.insets= new Insets(30,10,1,10);
gc3.gridx=0;
gc3.gridy=2;
panel3.add(showschemes,gc3);
showschemes.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
showschemsActionPerformed(e);
}
});
gc.gridx=0;
gc.gridy=5;
panel3.setBackground(c3);
panel.add(panel3,gc);
add(panel, BorderLayout.NORTH);
setUndecorated(true);
getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void showschemsActionPerformed(ActionEvent e) {
showtable();
}
public void showtable() {
final Vector<String> columnNames = new Vector<String>();
final Vector<Vector<Object>> data = new Vector<Vector<Object>>();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver loaded");
// Establish a connection
con= DriverManager.getConnection
("jdbc:odbc:ysr");
System.out.println("Database connecteddddd");
// Create a statement
st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM ysr2011 where=
'"+division.getSelectedItem()+"' ");
ResultSetMetaData md = rs.getMetaData();
columns = md.getColumnCount();
System.out.println("col" +(columns+1));
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
columnNames.addElement("Save");
while (rs.next()) {
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
row.addElement(new Boolean(false));
data.addElement( row );
}
rs.close();
con.close();
st.close();
}
catch(Exception e1){}
dtm = new DefaultTableModel(data, columnNames) {
public Class getColumnClass(int col) {
if(col==columns){
return Boolean.class;
}else{
return String.class;
}
}
public boolean isCellEditable(int rowIndex, int colIndex) {
return (colIndex == columns);
}
};
dtm.fireTableDataChanged();
table= new JTable(dtm); ;
table.setFont(new Font(" Arial",Font.PLAIN,12));
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setAutoCreateRowSorter(true);
JTableHeader header = table.getTableHeader();
header.setBackground(Color.yellow);
table.setRowSelectionAllowed(false);
header.setFont(new Font(" Arial",Font.BOLD,12));
JScrollPane scrollPane = new JScrollPane(table);
JButton button= new JButton("Save");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int row = 0; row < table.getRowCount(); row++) {
Boolean b = ((Boolean) table.getValueAt(row, columns));
if (b.booleanValue()) {
System.out.print("row " + row + " is " + b + ": ");
for (int col = 0; col < table.getColumnCount(); col++) {
System.out.print(table.getValueAt(row, col) + " ");
}
System.out.println();
}
}
}
});
JPanel buttonpanel= new JPanel();
buttonpanel.add(button);
add(scrollPane,BorderLayout.CENTER);
add(buttonpanel,BorderLayout.SOUTH);
Color c1= new Color(160,200,100);
table.setBackground(c1);
buttonpanel.setBackground(c1);
setBackground(c1);
setVisible(true);
}
public static void main(String args[]){
new aap2();
}
}

When you want to change the data in your table, try to create a new DefaultTableModel object (or any other object that implements the TableModel interface), and call table.setModel(yourNewModel);

Related

How to copy one row from JTable into another JTable

I work on my projekt where i need to copy one row from JTable into another JTable, the second JTable should be only one-row table. I created mouselistener to first JTable where on doubleclick it should copy row and insert it into another JTable but it doesn't work correctly, any ideas how to solve it? i Get the data from database in first table. with code:
public void cputable() {
try {
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test","postgres","postgres");
stat = conn.createStatement();
result = stat.executeQuery("SELECT name,bus_speed,socket,cores,chipset,price*1.3 FROM CPU");
cputable.setModel(DbUtils.resultSetToTableModel(result));
result.close();
stat.close();
}
catch (Exception e){
e.printStackTrace();
}
}
and here is the code which i try to copy row:
cputable.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
JTable cputable =(JTable) me.getSource();
int row = cputable.getSelectedRow();
int col = cputable.getColumnCount();
if (me.getClickCount() == 2) {
cputablebottom.repaint();
for(int i = 0; i < col; i++) {
DefaultTableModel model = (DefaultTableModel) cputable.getModel();
List<String>list = new ArrayList<String>();
list.add( cputable.getValueAt(row, i).toString());
model.addRow(list.toArray());
cputablebottom.setModel(model);
}
Result before and after:
EDIT:
I remake a bit in the code and now it copy the whole list instead of only one row.
cputable.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
JTable cputable =(JTable) me.getSource();
int row = cputable.getSelectedRow();
int col = cputable.getColumnCount();
if (me.getClickCount() == 2) {
cputablebottom.repaint();
DefaultTableModel model1 = (DefaultTableModel) cputable.getModel();
List<String>list = new ArrayList<String>();
model1.addRow(list.toArray());
for(int i = 0; i < col; i++) {
list.add( cputable.getValueAt(row, i).toString());
cputablebottom.setModel(model1);
System.out.println(model1);
System.out.println(list);
}
cputablebottom.setModel(model1);
I've not tried this, but...
DefaultTableModel model1 = (DefaultTableModel) cputable.getModel();
Vector data = model1.getDataVector();
Object rowObj = data.get(row);
Vector newData = new Vector(1);
newData.add(rowObj);
DefaultTableModel model2 = (DefaultTableModel) cputablebottom.getModel();
model2.setRowCount(0);
model2.addRow(newData);
This should preserve the column information of the second table.
Alternatively, you could create a new DefaultTableModel, but you'd have to reconfigure the column information each time
What I suggest you do is have a read of the JavaDocs for DefaultTableModel
Tested example
I don't use DefaultTableModel often, preferring to put an actual object in each row, which I can then define how it is displayed, which would make it generally simpler, but, if a DefaultTableModel is all you have...
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTable top;
private JTable bottom;
public TestPane() {
setLayout(new GridLayout(2, 0));
String[][] rowData = new String[10][10];
for (int row = 0; row < 10; row++) {
String[] data = new String[10];
for (int col = 0; col < 10; col++) {
data[col] = row + "x" + col;
}
rowData[row] = data;
}
String[] names = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
DefaultTableModel model = new DefaultTableModel(rowData, names);
top = new JTable(model);
add(new JScrollPane(top));
DefaultTableModel emptyModel = new DefaultTableModel(new String[10][10], names);
bottom = new JTable(emptyModel);
add(new JScrollPane(bottom));
top.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
int row = top.rowAtPoint(e.getPoint());
if (row > -1) {
DefaultTableModel topModel = ((DefaultTableModel)top.getModel());
DefaultTableModel bottomModel = ((DefaultTableModel)bottom.getModel());
bottomModel.setRowCount(1);
for (int col = 0; col < topModel.getColumnCount(); col++) {
bottomModel.setValueAt(topModel.getValueAt(row, col), 0, col);
}
}
}
}
});
}
}
}
1.Code of 1st class where we are making our table-->
Sell.java
public class Sell extends JFrame {
public static void main(String args[]) {
new Sell();
}
JTextField tf1, tf2, tf3;
JButton b1, b2, b3;
JTable t1;
String s1;
public Sell() {
setBounds(450, 200, 600, 300);
setTitle("Sell");
Container con = getContentPane();
con.setBackground(Color.WHITE);
setLayout(null); // FlowLayout,GridLayout By default it is FlowLayout.
setVisible(true);
setResizable(false); // It allows to resize application size.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tf1 = new JTextField();
tf2 = new JTextField();
tf3 = new JTextField();
b1 = new JButton("Select");
b2 = new JButton("Add");
b3 = new JButton("Invoice");
t1 = new JTable(0, 2);
DefaultTableModel model = (DefaultTableModel) t1.getModel();
model.addRow(new Object[] { "Product", "Price" });
add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);
add(b3);
add(t1);
tf1.setBounds(50, 50, 50, 20);
tf2.setBounds(25, 100, 100, 20);
tf3.setBounds(150, 100, 100, 20);
b1.setBounds(150, 45, 75, 30);
b2.setBounds(100, 195, 75, 30);
b3.setBounds(200, 195, 75, 30);
t1.setBounds(350, 50, 225, 200);
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
s1 = tf1.getText();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/vanisb",
"root", "spirit");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from product where ID='" + s1 + "';");
while (rs.next()) {
tf2.setText(rs.getString("product_name"));
tf3.setText(rs.getString("price"));
}
conn.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(b1, ex);
}
}
});
b2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.addRow(new Object[] { tf2.getText(), tf3.getText() });
}
});
b3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new Invoice(model);
}
});
}
}
2.Code of 2nd class where we have to fetch the last table data-->
Invoice.java
public class Invoice extends JFrame {
public static void main(String[] args) {
}
JLabel l1, l2;
JTextField tf1, tf2;
JTable t2;
JButton b1;
public Invoice(DefaultTableModel model) {
setBounds(450, 200, 600, 300);
setTitle("Invoice");
Container con = getContentPane();
con.setBackground(Color.WHITE);
setLayout(null);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l1 = new JLabel("Name : ");
l2 = new JLabel("Phone No. : ");
tf1 = new JTextField();
tf2 = new JTextField();
b1 = new JButton("Add Customer");
t2 = new JTable(model);
add(l1);
add(l2);
add(tf1);
add(tf2);
add(b1);
add(t2);
l1.setBounds(50, 50, 100, 20);
l2.setBounds(50, 100, 100, 20);
tf1.setBounds(150, 50, 100, 20);
tf2.setBounds(150, 100, 100, 20);
b1.setBounds(100, 175, 150, 30);
t2.setBounds(300, 50, 275, 200);
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
}
});
}
}

repaint() method doesn't work more than once

I am currently working on a gui project which is managing a sql database. I am currently adding,deleting logs and showing tables existing in mysql. The problem is my add and delete buttons on my panel are supposed to repaint/refresh the table on that panel as a record is added or deleted however while testing I discovered that repaint method doesn't refresh the table after the first use of the button. What can cause this problem? Thanks in advance..
public JTabbedPane addComponentToPane() {
//Container pane = new Container();
JTabbedPane tabbedPane = new JTabbedPane();
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
JPanel card3 = new JPanel();
JPanel card4 = new JPanel();
JPanel card5 = new JPanel();
JPanel card6 = new JPanel();
JPanel card7 = new JPanel();
JPanel card8 = new JPanel();
card1.setLayout(new BorderLayout());
card2.setLayout(new BorderLayout());
card3.setLayout(new BorderLayout());
card4.setLayout(new BorderLayout());
card5.setLayout(new BorderLayout());
card6.setLayout(new BorderLayout());
card7.setLayout(new BorderLayout());
card8.setLayout(new BorderLayout());
JScrollPane actor = new JScrollPane(createTables("actor"));
card1.add(actor, BorderLayout.CENTER);
card3.add(createTables("address"), BorderLayout.CENTER);
card4.add(createTables("category"), BorderLayout.CENTER);
card5.add(createTables("city"), BorderLayout.CENTER);
card6.add(createTables("country"), BorderLayout.CENTER);
card7.add(createTables("customer"), BorderLayout.CENTER);
card8.add(createTables("film"), BorderLayout.CENTER);
JButton button = new JButton("Yeni Kayıt");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
addRecord("actor");
card1.remove(actor);
card1.add(createTables("actor"), BorderLayout.CENTER);
card1.validate();
card1.repaint();
}
});
JButton delButton = new JButton("Kayıt sil");
delButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
delRecord("actor");
card1.remove(actor);
card1.add(createTables("actor"), BorderLayout.CENTER);
card1.validate();
card1.repaint();
}
});``
card1.add(button, BorderLayout.SOUTH);
card1.add(delButton, BorderLayout.EAST);
tabbedPane.addTab("Şirketler", null, card1, "şirket tanımları");
tabbedPane.addTab("Sorumlular", card2);
tabbedPane.addTab("Varlık Grupları", card3);
tabbedPane.addTab("Bilgi Varlıkları", card4);
tabbedPane.addTab("Varlık Değerleri", card5);
tabbedPane.addTab("Açıklıklar", card6);
tabbedPane.addTab("Tehditler", card7);
tabbedPane.addTab("Ek-A", card8);
//pane.add(tabbedPane, BorderLayout.CENTER);
return tabbedPane;
}
Create tables method creating a Jtable from sql table.
private JScrollPane createTables(String tablename) {
Connection con = null;
Statement statement = null;
ResultSet result = null;
String query;
JScrollPane jsp = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila", "root", "root");
statement = con.createStatement();
query = "select * from " + tablename;
result = statement.executeQuery(query);
ResultSetMetaData rsmt = result.getMetaData();
int columnCount = rsmt.getColumnCount();
Vector column = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
column.add(rsmt.getColumnName(i));
}
Vector data = new Vector();
Vector row = new Vector();
while (result.next()) {
row = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
row.add(result.getString(i));
}
data.add(row);
}
defTableModel = new DefaultTableModel(data, column);
table = new JTable(defTableModel) {
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
;
};
//table.setAutoCreateRowSorter(true);
TableRowFilterSupport.forTable(table).searchable(true).apply();
table.setRowSelectionAllowed(true);
jsp = new JScrollPane(table);
}
catch (Exception e) {
e.printStackTrace();
// JOptionPane.showMessageDialog(null, "ERROR");
}
finally {
try {
statement.close();
result.close();
con.close();
}
catch (Exception e) {
//JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
return jsp;
}
I could see couple of inconsistencies in the code:
The actor variable is not being set to the added component in the action listener.
First time you are adding new JScrollPane(createTables("actor")) and then onwards you only add createTables("actor").
The (1) might be causing the problem.
I think the problem is the reference to the actor:
card1.remove(actor);
card1.add(createTables("actor"), BorderLayout.CENTER);
Here, the variable actor is not more referenced in card1. To not lose this reference you should do something like this, in both actionPerformed methods:
card1.remove(actor);
actor = new JScrollPane(createTables("actor"));
card1.add(actor, BorderLayout.CENTER);

having NullPointerException in JTable using MouseListener event

I am new to java and I am trying to build a simple project that connects
to database then display it on JTable with MouseClick event. When i click in the row to transfer its content to JTextFields but it returns NullPointerException in line 225. Here's the full code of my project:
package Dbase;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.*;
#SuppressWarnings("serial")
public class MainForm extends JFrame {
Connection con;
Statement stmt;
ResultSet rs;
PreparedStatement pstmt;
#SuppressWarnings("rawtypes")
Vector columnNames = new Vector();
#SuppressWarnings("rawtypes")
Vector data = new Vector();
//JTable table;
private JPanel gui;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainForm frame = new MainForm();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainForm() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
setLookAndFeel();
setSize(800,500);
gui = new JPanel();
gui.setLayout(new BorderLayout(5, 5));
setContentPane(gui);
DBConnect();
initComponents();
tbData();
}
public void DBConnect(){
try{
String host = "jdbc:mysql://localhost:3306/birthdb";
String uName = "admin";
String uPass = "46m1n";
// connection to mysql database
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM childinfo";
rs = stmt.executeQuery(sql);
}
catch(SQLException er){
JOptionPane.showMessageDialog(MainForm.this, er.getMessage());
}
}
private void initComponents(){
//child's information
JLabel lblfirstName = new JLabel("FirstName", JLabel.RIGHT);
JLabel lbllastName = new JLabel("LastName", JLabel.RIGHT);
JLabel lblmiddleName = new JLabel("MiddleName", JLabel.RIGHT);
JLabel lblbirthDate = new JLabel("BirthDate",JLabel.RIGHT);
JLabel lblgender = new JLabel("Gender",JLabel.RIGHT);
JLabel lblbirthType = new JLabel("BirthType", JLabel.RIGHT);
JLabel lblmultiBirth = new JLabel("If Multiple Birth, Child Was", JLabel.RIGHT);
JLabel lblbirthOrder = new JLabel("BirthOrder", JLabel.RIGHT);
JLabel lblbirthWeight = new JLabel("BirthWeight",JLabel.RIGHT);
JLabel lblregistry = new JLabel("Registry",JLabel.RIGHT);
JTextField txtfirstName = new JTextField();
JTextField txtlastName = new JTextField();
JTextField txtmiddleName = new JTextField();
JTextField txtbirthDate = new JTextField();
JTextField txtgender = new JTextField();
JTextField txtbirthType = new JTextField();
JTextField txtmultiBirth = new JTextField();
JTextField txtbirthOrder = new JTextField();
JTextField txtbirthWeight = new JTextField();
JTextField txtregistry = new JTextField();
JButton newData = new JButton("New");
JButton updateData = new JButton("Update");
JButton deleteData = new JButton("Delete");
JButton printData = new JButton("Print");
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem;
menuBar = new JMenuBar();
setJMenuBar(menuBar);
//trial menu
menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);
menuBar.add(menu);
//trial menu item
menuItem = new JMenuItem("Quit");
menuItem.setMnemonic(KeyEvent.VK_Q);
menu.add(menuItem);
//trial row panel
JPanel row = new JPanel(new GridLayout(6,4,5,10));
row.add(lblregistry);
txtregistry.setEditable(false);
row.add(txtregistry);
row.add(lblfirstName);
txtfirstName.setEditable(false);
row.add(txtfirstName);
row.add(lbllastName);
txtlastName.setEditable(false);
row.add(txtlastName);
row.add(lblmiddleName);
txtmiddleName.setEditable(false);
row.add(txtmiddleName);
row.add(lblgender);
txtgender.setEditable(false);
row.add(txtgender);
row.add(lblbirthDate);
txtbirthDate.setEditable(false);
row.add(txtbirthDate);
row.add(lblbirthType);
txtbirthType.setEditable(false);
row.add(txtbirthType);
row.add(lblmultiBirth);
txtmultiBirth.setEditable(false);
row.add(txtmultiBirth);
row.add(lblbirthOrder);
txtbirthOrder.setEditable(false);
row.add(txtbirthOrder);
row.add(lblbirthWeight);
txtbirthWeight.setEditable(false);
row.add(txtbirthWeight);
gui.add(row, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new BorderLayout(3,3));
gui.add(buttonPanel,BorderLayout.WEST);
JPanel btn = new JPanel(new GridLayout(6,1,5,5));
btn.add(newData);
btn.add(updateData);
btn.add(deleteData);
btn.add(printData);
buttonPanel.add(btn);
}
#SuppressWarnings("unchecked")
private void tbData(){
try{
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT ChildID, FirstName, LastName, MiddleName FROM childinfo";
rs = stmt.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for(int i = 1; i <= columns; ++i){
columnNames.add(md.getColumnName(i));
}
while(rs.next()){
#SuppressWarnings("rawtypes")
Vector row = new Vector(columns);
for(int i = 1; i<= columns; i++){
row.addElement(rs.getObject(i));
}
data.addElement(row);
}
rs.close();
stmt.close();
}
catch(SQLException e){
JOptionPane.showMessageDialog(MainForm.this, e.getMessage());
}
DefaultTableModel model = new DefaultTableModel(data,columnNames);
JTable table = new JTable(model){
#SuppressWarnings({ "rawtypes" })
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.setRowSelectionAllowed(true);
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
int row = table.getSelectedRow();
try{
String dataClick = (table.getModel().getValueAt(row, 0).toString());
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM childinfo WHERE ChildID='"+dataClick+"'";
rs = stmt.executeQuery(sql);
if(rs.next()){
txtregistry.setText(Integer.toString(rs.getInt("ChildID"))); *this is where i get the error*
txtfirstName.setText(rs.getString("FirstName"));
txtlastName.setText(rs.getString("LastName"));
txtmiddleName.setText(rs.getString("MiddleName"));
txtgender.setText(rs.getString("Gender"));
txtbirthDate.setText(rs.getString("BirthDate"));
txtbirthType.setText(rs.getString("BirthType"));
txtmultiBirth.setText(rs.getString("IfMultiBirth"));
txtbirthOrder.setText(Integer.toString(rs.getInt("BirthOrder")));
txtbirthWeight.setText(Integer.toString(rs.getInt("BirthWeight")));
}
}
catch(SQLException er){
JOptionPane.showMessageDialog(MainForm.this, er.getMessage());
}
}
});
JScrollPane scrollPane = new JScrollPane(table);
gui.add(scrollPane, BorderLayout.CENTER);
}
private void setLookAndFeel(){
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception ee){
}
}
JTextField txtfirstName;
JTextField txtlastName;
JTextField txtmiddleName;
JTextField txtbirthDate;
JTextField txtgender;
JTextField txtbirthType;
JTextField txtmultiBirth;
JTextField txtbirthOrder;
JTextField txtbirthWeight;
JTextField txtregistry;
JTable table;
Kindly help me to fix the problem.
You're shadowing all the variable names for the components used in your class. E.g. Replace
JTextField txtfirstName = new JTextField();
with
txtfirstName = new JTextField();

JTable aren't refreshing when selecting from Combobox

The scrollPane table isn't refreshing for every time I selected something from the combo. Initially it has data but after I selected something, the data is removed successfully but new data isn't populating in
public void ConsultFrame(String id, String name, String ic){
GenerateMed("dp-000"); // to begin the scrollpane filled with Fever's medicine
JButton proc = new JButton("Proceed");
JButton addmed = new JButton(">>");
selected = new JTable(data, columnNames){
#Override
public boolean isCellEditable(int row,int column){
switch(column){
case 0:
return false;
case 1:
return false;
default: return true;
}
}};
selectedPane = new JScrollPane(selected);
//Dispensary's category combobox related
disp = dbDisp.getDispensary();
final JComboBox cBox = new JComboBox();
for(int count=0; count<disp.size(); count++)
cBox.addItem(disp.get(count).getDSP_desc());
cBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent event) {
for(int count=0; count<disp.size(); count++){
if(cBox.getSelectedItem().equals(disp.get(count).getDSP_desc())){
System.out.println(disp.get(count).getDSP_ID());
GenerateMed(disp.get(count).getDSP_ID());
break;
}
}
}
});
JTextArea tArea = new JTextArea(5, 30);
JScrollPane desc = new JScrollPane(tArea);
tArea.setLineWrap(true);
desc.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );
JPanel info = new JPanel();
info.setLayout(new FlowLayout(FlowLayout.LEFT));
info.add(new JLabel("<html>Patient's ID : " + id + "<br>Patient's Name: " + name + "<br>Patient's IC : " + ic + "<br><br>Medical Description : </html>"));
info.add(desc);
JPanel medSelect = new JPanel();
medSelect.setLayout(new GridLayout(1,2));
medSelect.add(scrollPane);
medSelect.add(selectedPane);
JPanel medic = new JPanel();
medic.setLayout(new BorderLayout());
medic.add(cBox, BorderLayout.NORTH);
medic.add(medSelect, BorderLayout.CENTER);
medic.add(proc, BorderLayout.SOUTH);
JPanel all = new JPanel();
String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm").format(Calendar.getInstance().getTime());
title = BorderFactory.createTitledBorder(timeStamp);
title.setTitleJustification(TitledBorder.RIGHT);
all.setBorder(title);
all.setLayout(new GridLayout(2,1));
all.add(info);
all.add(medic);
JFrame consult = new JFrame();
consult.setTitle(name + "'s consultation");
consult.setResizable(false);
consult.setVisible(true);
consult.setSize(500, 460);
consult.setLocationRelativeTo(null);
consult.add(all);
}
This is where my Combobox's is heading as soon as something is selected and I've tried repaint & revalidate
public void GenerateMed(String dps_id){
if (tModel != null) {
for (int i = tModel.getRowCount() - 1; i > -1; i--)
tModel.removeRow(i);
}
tModel = dbMed.getDPSMedicine(dps_id);
tModel.fireTableDataChanged();
table = new JTable(tModel){
#Override
public boolean isCellEditable(int row,int column){
return false;
}};
table.setShowGrid(false);
table.setShowHorizontalLines(false);
table.setShowVerticalLines(false);
//Table customization
table.getTableHeader().setReorderingAllowed(false);
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.changeSelection(0, 0, false, false);
scrollPane = new JScrollPane(table);
scrollPane.repaint();
scrollPane.revalidate();
}
scrollPane = new JScrollPane(table);
The above line of code creates a new scrollPane, but doesn't add the scrollPane to the frame.
However, there is no need to even create a new JTable or a new JScrollPane. Get rid of all the code.
Instead you just change the model of your JTable by using:
table.setModel( dbMed.getDPSMedicine(dps_id) );
So basically your method becomes one line of code.
Also, use proper method names. Method names should NOT start with an upper case character.

JDBC + Swing: Not able to get table contents

I am learning JDBC, completely new to it. I know MySQL very well. I have a search form in my applet (tab 2), where I search for food. And when I click search, I want it to search for the exact food from the Database and return the table contents of that particular row alone. But I am not getting any result. Only an empty frame opens. But when I put the query as "SELECT * FROM table", I am getting the complete table. But I want only one row, the one that is searched for. Can anyone please tell me where I am going wrong? Here's my code:
import java.awt.*;
import java.awt.event.*;
import java.sql.DriverManager;
import java.util.Vector;
import javax.swing.*;
import com.mysql.jdbc.*;
public class Tryout extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
final Vector columnNames = new Vector();
final Vector data = new Vector();
private JTabbedPane tabbedPane = new JTabbedPane();
private JPanel inputpanel;
private JPanel searchpanel;
public String s;
public Tryout() {
inputpanel = createPage1();
searchpanel = createPage2();
tabbedPane.addTab("Input Form", inputpanel);
tabbedPane.addTab("Search Form", searchpanel);
this.add(tabbedPane, BorderLayout.CENTER);
}
public JPanel createPage1() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//Some code
return panel;
}
public JPanel createPage2() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.LINE_START;
c.weightx = 0.5;
c.weighty = 0.5;
JLabel region = new JLabel("Enter Region");
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridx = 0;
c.gridy = 0;
panel.add(region, c);
JTextField field = new JTextField(20);
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridx = 1;
c.gridy = 0;
panel.add(field, c);
JButton search = new JButton("SEARCH");
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridx = 2;
c.gridy = 0;
panel.add(search, c);
s = field.getText();
search.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
try{
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/delikat", "root", "");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT * FROM delicious WHERE name = ?");
statement.setString(1,s);
ResultSet rs= (ResultSet) statement.executeQuery();
ResultSetMetaData md = (ResultSetMetaData) rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
statement.close();
}
catch(Exception e) {}
JFrame tab=new JFrame();
JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane( table );
tab.add( scrollPane );
tab.setVisible(true);
tab.setSize(300,100);
}
});
return panel;
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Tryout ex = new Tryout();
ex.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ex.setSize(500,500);
ex.setVisible(true);
}
});
}
}
Here is my table:
Also, I am trying to display the table in the panel itself below the search form but it gives error when I add
panel.add(scrollpane);
How do I rectify this problem too?
Thanks
What Sudhanshu means is:
PreparedStatement statement = con.preparedStatement("SELECT * FROM delicious WHERE name = ?");
statement.setString(1,s);
ResultSet rs= (ResultSet) statement.executeQuery();
Enclose name is quotes if its of type string (varchar). Better use PreparedStatement in such cases.
Basic debugging. Did you display the value of "s" that is being used in the PreparedStatement?
s = field.getText();
From what I can see, this statement is executed when you build the GUI which means nothing because the user hasn't even entered any text into this text field.
That statement needs to be executed when you actually invoke the SQL.

Categories