Fetch data and image path from database and put them in Jtable - java

I am trying to fetch some data in a jtable (on click of button) and in the database i have the path of the images stored. so i want to put them in the cell of JTable. My code is very big, because it contains some other information, like when we give a proper information in the text field, then only it will fetch me the data from the database.
This program is running fine, and there is no error in it, I just want to insert photos in one of the column in the table.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
#SuppressWarnings("serial")
public class VCstVote extends JFrame implements ActionListener{
JFrame frame;
JTextField tauid, tphone;
JLabel label, auid, aphone;
JButton cls, ok, vote;
JCheckBox chkbx;
JPanel panel,panel1,panel2, panel3;
static JTable table,table2;
DefaultTableModel model1 = new DefaultTableModel();
VCstVote() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException{
final UIManager.LookAndFeelInfo[] plafInfos =UIManager.getInstalledLookAndFeels();
UIManager.setLookAndFeel(plafInfos[1].getClassName() );
frame = new JFrame();
frame.setSize(930, 400);
frame.setTitle("VOTE YOUR CANDIDATE");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
vote = new JButton("VOTE YOUR CANDIDATE");
label = new JLabel("CASTE YOUR VOTE");
label.setFont(new Font("Verdana", Font.BOLD, 18));
panel.add(label);
panel1 = new JPanel();
cls= new JButton("CLOSE");
panel1.add(vote);
panel1.add(cls);
panel2 = new JPanel();
auid = new JLabel("UNIQUE ID",11);
tauid = new JTextField(10);
auid.setFont(new Font("Verdana", Font.BOLD, 10));
aphone = new JLabel("PHONE", 11);
aphone.setFont(new Font("Verdana", Font.BOLD, 10));
tphone = new JTextField(10);
ok = new JButton("SUBMIT");
panel2.add(auid);
panel2.add(tauid);
panel2.add(aphone);
panel2.add(tphone);
panel3 = new JPanel( new FlowLayout(FlowLayout.LEFT, 3,3));
panel3.add(ok);
panel2.add(panel3);
String[] columnNames = {"Candidate Name", "Department Name","Year","Photo","CASTE VOTE"};
model1.setColumnIdentifiers(columnNames);
table = new JTable();
table.setModel(model1);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
cls.addActionListener(this);
ok.addActionListener(this);
vote.addActionListener(this);
frame.add(scroll, BorderLayout.WEST);
frame.add(panel2,BorderLayout.EAST);
frame.add(panel,BorderLayout.NORTH);
frame.add(panel1,BorderLayout.SOUTH);
frame.validate();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String action=ae.getActionCommand();
Connection conn = null ;
String cfn= null;
String cln=null;
if(action=="SUBMIT")
{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#127.0.0.1:1521:orcl", "scott","tiger");
String query1="insert into vote (vuid,uphno) values(?,?)";
String query2 = "select uphno from accounts where vuid='"+tauid.getText()+"'";
String query3 = "select p.cfname, p.clname, p.deptname, l.dyear from potential p, leads l where p.cfname=l.cfname and p.clname=l.clname and p.deptname =l.deptname";
String query4 = "Select a.ufname, a.ulname from vote v, accounts a where a.uphno=v.uphno and v.vuid='"+tauid.getText()+"'";
chkbx = new JCheckBox();
PreparedStatement ps1 = conn.prepareStatement(query1);
PreparedStatement ps2 = conn.prepareStatement(query2);
PreparedStatement ps3 = conn.prepareStatement(query3);
PreparedStatement ps4 = conn.prepareStatement(query4);
ResultSet rs2= null;
ResultSet rs3= null;
ResultSet rs4= null;
rs2=ps2.executeQuery();
while(rs2.next())
{
ps1.setString(1, tauid.getText());
ps1.setString(2, rs2.getString(1));
ps1.executeUpdate();
conn.commit();
}
rs4= ps4.executeQuery();
while(rs4.next())
{
cfn = rs4.getString(1);
cln = rs4.getString(2);
}
JOptionPane.showMessageDialog(null, "Hii.. "+cfn+" "+cln+" Please Select Only one Candidate for voting, otherwise you vote will not be counted..");
rs3= ps3.executeQuery();
while(rs3.next())
{
String fname= rs3.getString(1);
String lname= rs3.getString(2);
String dept= rs3.getString(3);
String year= rs3.getString(4);
model1.addRow(new Object[]{fname+" "+lname,dept,year});
table.getColumn("CASTE VOTE").setCellEditor(new DefaultCellEditor(chkbx));
}
for (int i=0;i<model1.getRowCount();i++)
{
model1.setValueAt("false", i, 3);
}
}
catch(SQLException e)
{
JOptionPane.showMessageDialog(null,"Please Enter correct information");
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
if(action=="VOTE YOUR CANDIDATE")
{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#127.0.0.1:1521:orcl", "scott","tiger");
String query1 ="select cfname,clname,deptname,luid from potential";
String test = tphone.getText();
String query2="update vote set cfname=?, clname=?, deptname=?, luid=?, votcount=1 where uphno="+test;
ResultSet rs1 = null;
PreparedStatement ps1= conn.prepareStatement(query1);
PreparedStatement ps2 = conn.prepareStatement(query2);
rs1 =ps1.executeQuery();
for(int i=0;i<model1.getRowCount();i++)
{
Object st = model1.getValueAt(i,3);
String ss= st.toString();
if(ss.equals("true"))
{
rs1.next();
String fname = rs1.getString(1);
String lname = rs1.getString(2);
String dept = rs1.getString(3);
String uid = rs1.getString(4);
ps2.setString(1, fname);
ps2.setString(2, lname);
ps2.setString(3, dept);
ps2.setString(4, uid);
ps2.executeUpdate();
conn.commit();
JOptionPane.showMessageDialog(null,"Successfully registred Your Vote");
}
else{
rs1.next();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
if(action=="CLOSE")
{
frame.setVisible(false);
}
}
public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException
{
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
new VCstVote();
}
}
Please help me out of this, I tried many websites and codes, but it seems they are only for a defined set of data and images, none of them has a code which indicates jtable fetching data from database and rendering an image.

i have the path of the images stored. so i want to put them in the
cell of JTable.
put Icon / ImageIcon to JTable (data are stored in TableModel)
is required to override getColumnClass to Icon / ImageIcon for rendering image in the JTables cell
EDIT
I tried this type of coding, but instead it is showing me the path
only.
is required to override getColumnClass to Icon / ImageIcon
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
//or
#Override
public Class<?> getColumnClass(int colNum) {
switch (colNum) {
case 0:
return Integer.class;
case 1:
return Double.class;
case 2:
return Long.class;
case 3:
return Boolean.class;
case 4:
return String.class;
case 5:
return Icon.class;
/*case 6:
return Double.class;
case 7:
return Double.class;
case 8:
return Double.class;*/
default:
return String.class;
}
}
e.g. used in code
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.table.*;
public class TableIcon extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
private JTable table;
private JLabel myLabel = new JLabel("waiting");
private int pHeight = 40;
private boolean runProcess = true;
private int count = 0;
public TableIcon() {
ImageIcon errorIcon = (ImageIcon) UIManager.getIcon("OptionPane.errorIcon");
ImageIcon infoIcon = (ImageIcon) UIManager.getIcon("OptionPane.informationIcon");
ImageIcon warnIcon = (ImageIcon) UIManager.getIcon("OptionPane.warningIcon");
String[] columnNames = {"Picture", "Description"};
Object[][] data = {{errorIcon, "About"}, {infoIcon, "Add"}, {warnIcon, "Copy"},};
DefaultTableModel model = new DefaultTableModel(data, columnNames) {
private static final long serialVersionUID = 1L;
// Returning the Class of each column will allow different
// renderers to be used based on Class
#Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
table = new JTable(model);
table.setRowHeight(pHeight);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER);
myLabel.setPreferredSize(new Dimension(200, pHeight));
myLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(myLabel, BorderLayout.SOUTH);
new Thread(this).start();
}
public void run() {
while (runProcess) {
try {
Thread.sleep(1250);
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ImageIcon myIcon = (ImageIcon) table.getModel().getValueAt(count, 0);
String lbl = "JTable Row at : " + count;
myLabel.setIcon(myIcon);
myLabel.setText(lbl);
count++;
if (count > 2) {
count = 0;
}
}
});
}
}
public static void main(String[] args) {
TableIcon frame = new TableIcon();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocation(150, 150);
frame.pack();
frame.setVisible(true);
}
}

Related

How to use fireTableDataChanged in this case? (Or what other method should I use?) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am making a small program that retrieves data from a sqlite database and populates the JTable. User can also populate the database by the proper form. Mu question is, how to update the JTable so it shows content added by user? For now, it only shows it after rerunning the whole application.
Here's the code for the table:
package kpkw;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import static javax.swing.WindowConstants.EXIT_ON_CLOSE;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
public class MainTable {
//protected List<List<Object>> allMembers = new ArrayList<>();
//protected List<Object> member = new ArrayList<>();
protected MainTable(){
}
private void PassFromDBtoTable(List<List<Object>> allMembers){
Connection c = null;
Statement stmt = null;
ResultSet rs = null;
try {
c = DriverManager.getConnection("jdbc:sqlite:HistoriaPrzeplywow.s3db");
c.setAutoCommit(false);
stmt = c.createStatement();
rs = stmt.executeQuery( "SELECT * FROM HistoriaPrzeplywow;" );
while ( rs.next() ) {
List<Object> member = new ArrayList();
int idSQL = rs.getInt("ID");
String id2SQL = rs.getString("ID2");
int id3SQL = rs.getInt("ID3");
String typSQL = rs.getString("Typ");
String imieSQL = rs.getString("Imie");
String nazwiskoSQL = rs.getString("Nazwisko");
int naleznoscSQL = rs.getInt("Naleznosc");
String tytulemSQL = rs.getString("Tytulem");
String dataSQL = rs.getString("Data");
member.add(idSQL);
member.add(id2SQL);
member.add(id3SQL);
member.add(typSQL);
member.add(imieSQL);
member.add(nazwiskoSQL);
member.add(ManageCurrency(naleznoscSQL));
member.add(tytulemSQL);
member.add(dataSQL);
allMembers.add(member);
}
}
catch ( SQLException e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
finally{
if(rs!=null&& stmt!=null && c!=null){
try{
rs.close();
stmt.close();
c.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
}
}
private String ManageCurrency(int naleznoscSQL){
String currency = Integer.toString(naleznoscSQL);
currency = new StringBuilder(currency).insert(currency.length()-2, ".").toString();
return currency;
}
private void ResizeColumnWidth(JTable table){
final TableColumnModel columnModel = table.getColumnModel();
for(int col = 0; col < table.getColumnCount(); col++){
int width = 70;
for(int row = 0; row < table.getRowCount(); row++){
TableCellRenderer renderer = table.getCellRenderer(row, col);
Component component = table.prepareRenderer(renderer, row, col);
int componentSize = component.getPreferredSize().width;
width = Math.max(componentSize ,width);
}
columnModel.getColumn(col).setPreferredWidth(width);
}
} // method doesn't work so far
private void initUI(){
JFrame mainFrame = new JFrame();
JPanel mainPanel = new JPanel();
JMenuBar menuBar = new JMenuBar();
JMenu plikMenu = new JMenu("Plik");
List<List<Object>> allMembers = new ArrayList<>();
List<Object> member = new ArrayList<>();
PassFromDBtoTable(allMembers);
for(int i = 0; i< member.size(); i++){
System.out.println(member.get(i));
}
MyTableModel mtb = new MyTableModel(allMembers);
JTable rekordy = new JTable(mtb);
JScrollPane scrollPane = new JScrollPane(rekordy);
ResizeColumnWidth(rekordy);
rekordy.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
rekordy.setAutoCreateRowSorter(true);
JMenuItem noweKPMenuItem = new JMenuItem("Nowe KP...");
JMenuItem noweKWMenuItem = new JMenuItem("Nowe KW...");
JMenuItem zakonczMenuItem = new JMenuItem("Zakończ");
mainFrame.setLayout(new BorderLayout());
mainFrame.setTitle("Historia Przepływów");
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainFrame.setSize(660, 200);
mainFrame.setJMenuBar(menuBar);
//JButton test = new JButton("test");
//mainFrame.add(mainPanel);
mainPanel.setLayout(new BorderLayout());
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
mainPanel.add(scrollPane, BorderLayout.CENTER);
//mainPanel.add(test);
menuBar.add(plikMenu);
plikMenu.add(noweKPMenuItem);
plikMenu.add(noweKWMenuItem);
plikMenu.add(zakonczMenuItem);
mainFrame.add(scrollPane, BorderLayout.CENTER);
mainFrame.setVisible(true);
noweKPMenuItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
//KP run = new KP();
KP.run();
}
});
}
public class MyTableModel extends AbstractTableModel{
protected List<List<Object>> allMembers = new ArrayList<>();
public MyTableModel (List<List<Object>> allMembers) {
this.allMembers = allMembers;
}
protected MyTableModel(){
}
String[] columnNames = {"ID", "ID2", "ID3", "Typ", "Imię", "Nazwisko","Należność", "Tytułem", "Data"};
#Override
public String getColumnName(int column) {
return columnNames[column];
}
#Override
public int getRowCount() {
return allMembers.size();
}
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
//List<Object> row = allMembers.get(rowIndex);
return allMembers.get(rowIndex).get(columnIndex);
}
#Override
public boolean isCellEditable(int row, int column)
{
return false;
}
protected void addRecord(int ID, String ID2, int ID3, String typ, String imie, String nazwisko, int naleznosc, String tytulem, String data){
Connection c = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:HistoriaPrzeplywow.s3db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
//pstmt = c.createStatement();
String sqlCommand = ("INSERT INTO HistoriaPrzeplywow (ID,ID2,ID3,Typ,Imie,Nazwisko,Naleznosc,Tytulem,Data) VALUES (?,?,?,?,?,?,?,?,?);");
pstmt = c.prepareStatement(sqlCommand);
pstmt.setInt(1, ID);
pstmt.setString(2, ID2);
pstmt.setInt(3, ID3);
pstmt.setString(4, typ);
pstmt.setString(5, imie);
pstmt.setString(6, nazwisko);
pstmt.setInt(7, naleznosc);
pstmt.setString(8, tytulem);
pstmt.setString(9, data);
pstmt.executeUpdate();
c.commit();
List<Object> rowData = new ArrayList<>();
rowData.add(ID);
rowData.add(ID2);
rowData.add(ID3);
rowData.add(typ);
rowData.add(imie);
rowData.add(nazwisko);
rowData.add(tytulem);
rowData.add(data);
allMembers.add(rowData);
fireTableDataChanged();
}
catch(SQLException| ClassNotFoundException e){
e.printStackTrace();
}
finally{
if(c!=null){
try{
c.close();
// pstmt.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
}
}
}
/*MainTable(){
initUI();
}*/
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//System.out.println(new File(".").getAbsoluteFile());
MainTable guiMainTable = new MainTable();
guiMainTable.initUI();
}
});
}
}
And here's the form's code:
package kpkw;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class KP extends JFrame {
private ArrayList<JPanel> naleznosciArrayList = new ArrayList<>();
private ArrayList<JTextField> zaCoArrayList = new ArrayList<>();
private ArrayList<JTextField> zloteArrayList = new ArrayList<>();
private ArrayList<JTextField> grArrayList = new ArrayList<>();
private static int liczbaWierszy = -1;
public KP() {
initUI();
}
private void usunPole(JPanel nal){
nal.remove(naleznosciArrayList.get(liczbaWierszy));
naleznosciArrayList.remove(liczbaWierszy);
liczbaWierszy--;
}
private void initUI(){
setTitle("KP");
setSize(500, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JMenuBar menubar = new JMenuBar();
this.setJMenuBar(menubar);
JMenu plik = new JMenu("Plik");
menubar.add(plik);
JPanel container = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
this.add(container);
JPanel title = new JPanel();
JLabel kpTytul = new JLabel("Generator KP");
kpTytul.setFont(new Font("Serif",Font.BOLD, 14));
container.add(title);
title.add(kpTytul);
JPanel pola1 = new JPanel();
pola1.setLayout(new GridLayout(2,2));
container.add(pola1);
JLabel lData = new JLabel(" Data");
JTextField tData = new JTextField(1);
tData.setEditable(false);
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
tData.setText((dateFormat.format(date)));
JLabel lNumer = new JLabel(" KP");
JPanel numery = new JPanel();
numery.setLayout(new BoxLayout(numery, BoxLayout.X_AXIS));
JTextField tNumerRef = new JTextField(1);
tNumerRef.setEditable(false);
Connection c = null;
Statement stmt = null;
ResultSet rs = null;
try {
c = DriverManager.getConnection("jdbc:sqlite:HistoriaPrzeplywow.s3db");
c.setAutoCommit(false);
stmt = c.createStatement();
rs = stmt.executeQuery( "SELECT Count(*) FROM HistoriaPrzeplywow;" );
rs.next();
int numberOfRows = rs.getInt(1)+1;
tNumerRef.setText(Integer.toString(numberOfRows));
}
catch(SQLException e){
e.printStackTrace();
}
finally{
if(c!=null&&rs!=null){
try{
c.close();
//stmt.close();
rs.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
}
JTextField tNumerReg = new JTextField(1);
JTextField tNumerRok = new JTextField(1);
DateFormat rokFormat = new SimpleDateFormat("yyyy");
Date dataRok = new Date();
tNumerRok.setText((rokFormat.format(dataRok)));
tNumerRok.setEditable(false);
numery.add(tNumerRef);
numery.add(tNumerReg);
numery.add(tNumerRok);
pola1.add(lData);
pola1.add(tData);
pola1.add(lNumer);
pola1.add(numery);
JPanel pola2 = new JPanel();
pola2.setLayout(new GridLayout(3,2));
container.add(pola2);
JLabel lImie = new JLabel(" Imię");
JTextField tImie = new JTextField(1);
JLabel lNazwisko = new JLabel(" Nazwisko");
JTextField tNazwisko = new JTextField(1);
//JLabel lZaCo = new JLabel("Za co");
//JTextField tZaCo = new JTextField(1);
pola2.add(lImie);
pola2.add(tImie);
pola2.add(lNazwisko);
pola2.add(tNazwisko);
JPanel naleznosci = new JPanel();
naleznosci.setLayout(new BoxLayout(naleznosci, BoxLayout.X_AXIS));
JLabel lZaCo = new JLabel("Tytułem:");
JTextField tZaCo = new JTextField(1);
zaCoArrayList.add(tZaCo);
JLabel gap = new JLabel(" ");
JLabel lKasa = new JLabel("Wartość:");
JTextField tZlote = new JTextField(1);
zloteArrayList.add(tZlote);
JLabel lZl = new JLabel("zł");
JTextField tGr = new JTextField(1);
grArrayList.add(tGr);
JLabel lGr = new JLabel("gr");
JLabel gap2 = new JLabel(" ");
JLabel gap3 = new JLabel(" ");
//JLabel lWinien = new JLabel("Winien");
//JTextField tWinien = new JTextField(1);
naleznosci.add(lZaCo);
naleznosci.add(tZaCo);
naleznosci.add(gap);
naleznosci.add(lKasa);
naleznosci.add(gap3);
naleznosci.add(tZlote);
naleznosci.add(lZl);
naleznosci.add(tGr);
naleznosci.add(lGr);
container.add(naleznosci);
JPanel separator = new JPanel();
container.add(separator);
separator.add(new JSeparator(SwingConstants.HORIZONTAL));
JButton generuj = new JButton("Generuj");
container.add(generuj);
generuj.setAlignmentX(Component.LEFT_ALIGNMENT);
generuj.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if(tImie.getText().equals("") || tNazwisko.getText().equals("") || tNumerReg.getText().equals("") || tZaCo.getText().equals("") || tZlote.getText().equals("") || tGr.getText().equals("")){
//System.out.println("Nie wypełniono wszystkich pól");
ErrorWindow.setMessage("<html><center>Nie wypełniono wszystkich pól</center></html>");
ErrorWindow.main();
}
else {
try{
int ID = Integer.parseInt(tNumerRef.getText());
int ID3 = Integer.parseInt(tNumerRok.getText());
String typ = "KP";
String naleznosc = tZlote.getText() + tGr.getText();
int naleznoscInt = Integer.parseInt(naleznosc);
MainTable mt = new MainTable();
mt.new MyTableModel().addRecord(ID, tNumerReg.getText(), ID3, typ, tImie.getText(), tNazwisko.getText(), naleznoscInt, tZaCo.getText(), tData.getText());
}
catch(NumberFormatException e) {
e.printStackTrace();
}
}
}
});
}
public static void run() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
KP gui = new KP();
gui.setVisible(true);
}
});
}
}
Any help will be appreciated.
MainTable mt = new MainTable();
mt.new MyTableModel().addRecord(...);
Don't create a new JTable. You need to access the existing TableModel of the JTable that is displayed in the frame. Then you invoke the addRecord(...) method on that table model.
Also in your custom TableModel you are using:
fireTableDataChanged();
That is the wrong method since you did not change all the data. All you did was add a single row of data, so you should be using:
fireTableRowsInserted(...);

get table names from DB and parse it to JCombobox and then when a tablename is select it should display the table info in the JTable

I need help with retrieving tableNames from my database and then parse it to JCombobox and the when the tableName is click the sql statement will be performed and then display the table in the JTable.
My problem is how to code the selectedItem so that it will execute the query and display IT on the JTable
Here is my gui.java file
package Assignment3.Live;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import net.proteanit.sql.DbUtils;
;
/**
* #author jmickey
*
*/
public class GUI extends JFrame {
// Variables
public Main main;
DBCon db;
MakeTable make;
private JFrame frame = new JFrame();
private JPanel pNorth, pChooser, pdp, pRC, pSCR, pTab, pSouth, pBtn;
public ResultSet rseTo = null;// result set
public PreparedStatement pst = null;
private ResultSetMetaData meta = null;
String tableNamesnow = "";
private JMenuBar jMenuBar;
private JMenu file, help;
private JComboBox<String> jcmb = new JComboBox<String>();
ComboBoxModel<?> giveMeTableName = (ComboBoxModel<?>) jcmb
.getSelectedItem();
private JTable jT = new JTable();
private JTextArea text;
private JButton search, clear, displayRow, deletRow, addRow, query, save,
restore;
private JCheckBox rowS = new JCheckBox("Select by Rows", true);
private JCheckBox colS = new JCheckBox("Selcet by Column", false);
/*
* private String[] columnNames = {}; private Object [][] rowData = {};
*/
public GUI() throws SQLException {
GUInterface();
getTableNames();
arrayOfTable();
}
public void GUInterface() {// constructor
// Menubar
setLayout(new BorderLayout(5, 10));
jcmb.setSelectedItem("");
jMenuBar = new JMenuBar();
file = new JMenu("File");
file.add(new JMenuItem("Start"));
file.add(new JMenuItem("Exit"));
help = new JMenu("Help");
help.add(new JMenuItem("Help"));
jMenuBar.add(file);
jMenuBar.add(help);
// Button
save = new JButton("Save");
clear = new JButton("Clear");
restore = new JButton("Restore");
displayRow = new JButton("Display Row");
deletRow = new JButton("Delet Row");
addRow = new JButton("Add New Row");
query = new JButton("QUERY");
// choose table panel = 1
pChooser = new JPanel();
pChooser.setLayout(new BorderLayout(5, 0));
pChooser.setBorder(new TitledBorder("Tables"));
pChooser.add(new JLabel("Select a table: "), BorderLayout.WEST);
pChooser.add(jcmb, BorderLayout.CENTER);
// Row/Column selection Panel = 2
pRC = new JPanel();
pRC.setLayout(new FlowLayout(FlowLayout.LEFT));
pRC.add(rowS);
pRC.add(colS);
// noth panel holds (pChooser & pRC)
pNorth = new JPanel();
pNorth.setLayout(new GridLayout(2, 1));
pNorth.add(pChooser);
pNorth.add(pRC);
// JTable panel
pTab = new JPanel();
pTab.setLayout(new GridLayout(1, 1));
pTab.add(jT);
pTab.add(new JScrollPane(jT));
// display holds (pNorth & pTab)
pdp = new JPanel();
pdp.setLayout(new BorderLayout(2, 1));
pdp.add(pNorth, BorderLayout.NORTH);
pdp.add(pTab, BorderLayout.SOUTH);
// Save, Clear or restore Panel
pSCR = new JPanel();
pSCR.add(save);
pSCR.add(clear);
pSCR.add(restore);
// Button selection panel
pBtn = new JPanel();
pBtn.setLayout(new GridLayout(2, 2));
pBtn.add(displayRow);
pBtn.add(addRow);
pBtn.add(query);
pBtn.add(deletRow);
// South panel (pSCR & pBtn)
pSouth = new JPanel();
pSouth.setLayout(new BorderLayout(2, 1));
pSouth.add(pBtn, BorderLayout.SOUTH);
pSouth.add(pSCR, BorderLayout.CENTER);
// Table info
jT.setAutoResizeMode(jT.AUTO_RESIZE_OFF);
jT.setGridColor(Color.BLUE);
jT.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jT.setSelectionBackground(Color.BLUE);
jT.setSelectionForeground(Color.WHITE);
jT.setRowSelectionAllowed(true);
/*
* Task 1. change action to diplay row = create the 2.delete row
* 3.insert row
*/
frame.setJMenuBar(jMenuBar);
frame.add(pdp, BorderLayout.NORTH);
frame.add(pSouth, BorderLayout.SOUTH);
frame.setTitle("Walters SPJ Directory");
frame.setResizable(true);
frame.setSize(465, 648);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// display rows
displayRow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// when the search button is clicked
if (e.getSource() == displayRow) {
jcmb.setSelectedItem(giveMeTableName);
for (int i = 0; i < jcmb.getSelectedIndex(); i++)
displayS();
}
}
});
// Checkbos ActionListener
rowS.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
jT.setRowSelectionAllowed(rowS.isSelected());
}
});
colS.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
jT.setRowSelectionAllowed(colS.isSelected());
}
});
// Clear ActionListener
clear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
TableModel myData = DbUtils.resultSetToTableModel(rseTo);
jT.tableChanged(null);
}
});
}
// get tableNames
public void getTableNames() throws SQLException {
rseTo = null;
java.sql.DatabaseMetaData meta = DBCon.con.getMetaData();
rseTo = meta.getTables(null, null, "%", new String[] { "TABLE" });
while (rseTo.next()) {
String nameOfTables = rseTo.getString(3);
String tableCatalog = rseTo.getString(1);
String tableSchema = rseTo.getString(2);
System.out.printf("%s - %s - %s%n", tableCatalog, tableSchema,
nameOfTables);
}
db.stm.close();
}
// get table name to JCombobox
public void arrayOfTable() throws SQLException {
rseTo = db.con.getMetaData().getTables(null, null, "%",
new String[] { "TABLE" });
while (rseTo.next()) {
String giveMeTableName = (rseTo.getString(3));
jcmb.addItem(giveMeTableName);
System.out.println(giveMeTableName);
}
jcmb.setBounds(130, 30, 190, 30);
jcmb.setEditable(false);
jcmb.getSelectedIndex();
return;
}
/*
* Table selection method
*/
public void displayS() {
try {
String sql = "SELECT DISTINCT * FROM " + giveMeTableName;
pst = DBCon.con.prepareStatement(sql);
rseTo = pst.executeQuery();
TableModel myData = DbUtils.resultSetToTableModel(rseTo);
jT.setModel(myData);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
public void displayP() {
try {
String sql = "SELECT DISTINCT * FROM P";
pst = DBCon.con.prepareStatement(sql);
rseTo = pst.executeQuery();
jT.setModel(DbUtils.resultSetToTableModel(rseTo));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
public void displayJ() {
try {
String sql = "SELECT DISTINCT * FROM " + make.tableName;
pst = DBCon.con.prepareStatement(sql);
rseTo = pst.executeQuery();
jT.setModel(DbUtils.resultSetToTableModel(rseTo));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
public void displaySPJ() {
try {
String sql = "SELECT DISTINCT * FROM SPJ";
pst = DBCon.con.prepareStatement(sql);
rseTo = pst.executeQuery();
jT.setModel(DbUtils.resultSetToTableModel(rseTo));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
}
For tasks like this, you need to be aware that you're developing a new (simple) programming language. This means the input is no longer free form but has to obey certain rules. For example:
Table name: S
...
Table name:
P
is bad. The people editing the file should stick to one way to specify the table name; otherwise your parser will quickly get complex.
As a general guideline for tasks like this:
Read the input line by line.
Ignore empty lines
Trim lines to get rid of excessive whitespace
Use patterns like Table name: together with line.startsWith() to find out what the next "block" of your language means.
Read the values of each block and process then. line.split("\\s", -1) is your friend to split the input into words.
Getting it right will become easier when you create a few simple test cases and use unit tests to make sure your parser builds the correct data structures in memory.

JTable Headers not Showing using any methods

I have tried almost every method to get table headers but nothing is working.
Here is the code:
package co.za.gecko.inked.crm;
import java.awt.EventQueue;
import java.awt.ScrollPane;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
public class Welcome extends JFrame {
private JPanel contentPane;
private JTable table;
static Object[][] databaseInfo;
static Object[] columns = {"first name", "last name", "cellphone", "time", "station"};
static ResultSet rows;
static ResultSetMetaData metaData;
static DefaultTableModel dTableModel = new DefaultTableModel(databaseInfo, columns) {
// public Class getColumnClass(int column){
// Class returnValue;
// if((column >= 0) && (column < getColumnCount())){
// returnValue = getValueAt(0, column).getClass();
// } else {
// returnValue = Object.class;
// }
// return returnValue;
// }
};
private JTable table_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Welcome frame = new Welcome();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Welcome() {
setResizable(false);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 1024, 768);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
deleteAllRows(dTableModel);
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
Statement sqlState = conn.createStatement();
String selectStuff = "SELECT `first_name`, `last_name`, `cellphone`, `time` FROM volunteers";
rows = sqlState.executeQuery(selectStuff);
Object[] tempRow;
while(rows.next()){
tempRow = new Object[]{rows.getString(1), rows.getString(2), rows.getString(3), rows.getString(4)};
dTableModel.addRow(tempRow);
}
// get column name ?
// metaData = rows.getMetaData();
// int numOfCol = metaData.getColumnCount();
//
// columns = new String[numOfCol];
//
// for(int i=1; i<= numOfCol; i++){
// columns[i] = metaData.getColumnName(i);
// }
} catch (ClassNotFoundException ex) {
// TODO Auto-generated catch block
System.out.println(ex.getMessage());
} catch (SQLException ex) {
// TODO Auto-generated catch block
System.out.println(ex.getMessage());
}
table_1 = new JTable();
table_1.setModel(dTableModel);
table_1.setBounds(10, 11, 988, 707);
contentPane.add(table_1);
ScrollPane scrollPane = new ScrollPane();
scrollPane.setBounds(0, 0, 1008, 729);
contentPane.add(scrollPane);
}
public static void deleteAllRows(final DefaultTableModel model) {
for( int i = model.getRowCount() - 1; i >= 0; i-- ) {
model.removeRow(i);
}
}
}
I have tried using table_1.getTableHeader();, .add(new scrollpane(table_1.getTableHeader()); and more. any help would be greatly appreciated.
I got the code (the pulling from the database to the dTableModel from youtube tutorials.
you would need to:
put JTable to JScrollPane e.g. JScrollPane scrollPane = new JScrollPane(table); (standard way)
add separate JTable to JFrame.CENTER area and separeate JTableHeader e.g. JTable.getTableHeader() to JFrame.NORTH area

getSelectedRow() returns -1 after loading new data to existing JTable

I'm writing a simple MySQL editor. My problem is that after I select from the combobox a new table from the database and load it and then select a row and try to delete it, getSelectedRow() returns -1 and generates an exception, but that doesn't happen when I delete a row from the table that is loaded at the start of my program.
Here's the crucial code parts from 2 files (in the same code quote):
package omnisql;
import java.sql.*;
import java.util.*;
public class getData
{
static Connect c = new Connect();
static GUI g = new GUI();
static ResultSet result;
public static Vector<Vector<String>> data = new Vector<Vector<String>>();
public static String table="pracownicy";
public static Vector <String> d;
public static List <String> id;
void getData() throws SQLException
{
result=c.stmt.executeQuery("select * from "+table);
id = new ArrayList<String>();
while(result.next())
{
d=new Vector<String>();
id.add(result.getString("id"));
d.add(result.getString("id"));
d.add(result.getString("Nazwisko"));
d.add(result.getString("Imię"));
d.add(result.getString("Płeć"));
d.add(result.getString("Ulica"));
d.add(result.getString("Miejscowość"));
d.add(result.getString("Kod_pocztowy"));
d.add(result.getString("Województwo"));
d.add(result.getString("Telefon"));
data.add(d);
}
}
}
package omnisql;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;
import javax.swing.event.*;
public class GUI extends JFrame implements ActionListener, TableModelListener
{
static Connect c = new Connect();
static getData gd = new getData();
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT,10,5));
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT,10,5));
JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.CENTER,10,5));
JPanel panel3 = new JPanel(new FlowLayout(FlowLayout.LEFT,10,5));
JLabel typbazy = new JLabel("Typ bazy: ");
JLabel wybtab = new JLabel("Wybierz tabelę: ");
JRadioButton postgre = new JRadioButton("PostgreSQL");
JRadioButton mysql = new JRadioButton("MySQL");
JRadioButton sqlite = new JRadioButton("SQLite");
ButtonGroup grupa = new ButtonGroup();
public static JComboBox tabela = new JComboBox();
JButton addrec = new JButton("Dodaj rekord");
JButton delrec = new JButton("Usuń rekord");
JButton reftab = new JButton("Odśwież tabelę");
JTable table;
public static DefaultTableModel model;
TableColumn column;
Vector<String> headers = new Vector<String>();
JScrollPane scroll;
static int rownumber,addrow,delrow,updaterow;
PreparedStatement pst;
String value="";
public static int height,i,firstrow=0, klick=1;
public GUI()
{
panel.add(typbazy);
grupa.add(postgre);
panel.add(postgre);
postgre.addActionListener(this);
grupa.add(mysql);
panel.add(mysql);
mysql.setSelected(rootPaneCheckingEnabled);
mysql.addActionListener(this);
grupa.add(sqlite);
panel.add(sqlite);
sqlite.addActionListener(this);
panel1.add(wybtab);
panel1.add(tabela);
tabela.setPreferredSize(new Dimension(120,20));
tabela.setBackground(Color.white);
tabela.removeAllItems();
tabela.addItem(" ");
tabela.addItem("Pracownicy");
tabela.addItem("Pracownicy 2");
tabela.setSelectedIndex(0);
tabela.addActionListener(this);
headers.add("ID");
headers.add("Nazwisko");
headers.add("Imię");
headers.add("Płeć");
headers.add("Ulica");
headers.add("Miejscowość");
headers.add("Kod_pocztowy");
headers.add("Województwo");
headers.add("Telefon");
model = new DefaultTableModel(gd.data, headers);
table = new JTable(model);
table.setRowSelectionAllowed(true);
table.getModel().addTableModelListener(this);
table.setPreferredScrollableViewportSize(new Dimension(740,159));
column = table.getColumnModel().getColumn(0);
column.setPreferredWidth(20);
column = table.getColumnModel().getColumn(1);
column.setPreferredWidth(100);
column = table.getColumnModel().getColumn(2);
column.setPreferredWidth(70);
column = table.getColumnModel().getColumn(3);
column.setPreferredWidth(70);
column = table.getColumnModel().getColumn(4);
column.setPreferredWidth(100);
column = table.getColumnModel().getColumn(5);
column.setPreferredWidth(100);
column = table.getColumnModel().getColumn(6);
column.setPreferredWidth(100);
column = table.getColumnModel().getColumn(7);
column.setPreferredWidth(100);
column = table.getColumnModel().getColumn(8);
column.setPreferredWidth(80);
scroll = new JScrollPane(table);
panel2.add(scroll);
panel3.add(addrec);
addrec.addActionListener(this);
panel3.add(delrec);
delrec.addActionListener(this);
panel3.add(reftab);
reftab.addActionListener(this);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
getContentPane().add(panel);
getContentPane().add(panel1);
getContentPane().add(panel2);
getContentPane().add(panel3);
}
void initGUI()
{
setSize(800,340);
setTitle("OmniSQL 1.0");
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void tableChanged(TableModelEvent e)
{
rownumber = table.getSelectedRow();
if (rownumber==-1) rownumber=0;
updaterow = Integer.parseInt(gd.id.get(rownumber));
switch (e.getType())
{
case TableModelEvent.UPDATE:
table.getRowCount();
value=table.getValueAt(table.getSelectedRow(),table.getSelectedColumn()).toString();
try
{
pst = c.con.prepareStatement("UPDATE "+gd.table+" SET "+table.getColumnName(table.getSelectedColumn())+" = '"+value+"' where id = "+updaterow+";");
pst.executeUpdate();
}
catch (SQLException err)
{
}
break;
}
}
public void actionPerformed(ActionEvent e)
{
/*if (e.getActionCommand().equals("MySQL"))
{
try
{
c.con.close();
c.connect("jdbc:mysql://localhost:3306/omnisql","root","sqlek","com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException er)
{
}
catch(SQLException err)
{
}
}*/
if (tabela.getSelectedItem()=="Pracownicy")
{
gd.table="pracownicy";
try
{
model.setRowCount(0);
table.removeAll();
gd.getData();
}
catch (SQLException er)
{
}
}
if (tabela.getSelectedItem()=="Pracownicy 2")
{
gd.table="pracownicy2";
try
{
model.setRowCount(0);
gd.getData();
table.revalidate();
}
catch (SQLException er)
{
}
}
/*if(postgre.isSelected())
{
tabela.removeAllItems();
tabela.addItem("Adresy");
tabela.addItem("Adresy 2");
tabela.setSelectedIndex(0);
}
*/
/*if(mysql.isSelected())
{
tabela.removeAllItems();
tabela.addItem(" ");
tabela.addItem("Pracownicy");
tabela.addItem("Pracownicy 2");
}*/
/*
if(sqlite.isSelected())
{
tabela.removeAllItems();
tabela.addItem("Zakłady");
tabela.addItem("Zakłady 2");
tabela.setSelectedIndex(0);
}*/
if (e.getActionCommand().equals("Dodaj rekord"))
{
model.setRowCount(gd.id.size());
rownumber = model.getRowCount()-1;
if(rownumber==-1 && gd.id.size()==0)
{
rownumber=0;
gd.id.add(0, "1");
addrow=Integer.parseInt(gd.id.get(rownumber));
}
else
{
addrow=Integer.parseInt(gd.id.get(rownumber));
addrow++;
}
try
{
pst = c.con.prepareStatement("INSERT INTO "+gd.table+" (id) VALUES("+addrow+")");
pst.executeUpdate();
model.setRowCount(0);
gd.getData();
height = (int)table.getPreferredSize().getHeight();
table.scrollRectToVisible(new Rectangle(0,height,10,10));
}
catch (SQLException exc)
{
}
}
rownumber=table.getSelectedRow();
if (e.getActionCommand().equals("Usuń rekord"))
{
try
{
model.setRowCount(gd.id.size());
System.out.println(rownumber);
delrow = Integer.parseInt(gd.id.get(rownumber));
pst = c.con.prepareStatement("DELETE from "+gd.table+" where id="+delrow);
pst.executeUpdate();
model.setRowCount(0);
gd.getData();
}
catch (SQLException exc)
{
}
}
if (e.getActionCommand().equals("Odśwież tabelę"))
{
try
{
model.setRowCount(0);
gd.getData();
}
catch (SQLException exc)
{
}
}
}
}
I will be really grateful for any help with this problem.
If getSelectedRow() returns -1 that means that nothing is selected.

JTable getSelectedRow does not return the selected row index

I try to get data in the row that is selected but getSelectedRow() doesn't work. Actually, I used that method in the other class, but it works in there. When I try to print the row index; the prompt shows -1; as not selected.
I tried most of solutions that are on the internet but they didn't solve my solutions.
public Canteen() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout( null );
this.setSize( new Dimension(400, 300) );
this.setTitle( "CANTEEN" );
jScrollPane1.setBounds(new Rectangle(0, 0, 230, 235));
jButton1.setText("REFRESH");
jButton1.setBounds(new Rectangle(0, 235, 100, 20));
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
jButton2.setText("CLOSE");
jButton2.setBounds(new Rectangle(120, 235, 110, 20));
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton2_actionPerformed(e);
}
});
jScrollPane1.getViewport().add(jTable1, null);
this.getContentPane().add(jButton2, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jScrollPane1, null);
jTable1 = new JTable (model);
String header [] = {"CUSTOMER", "PRODUCT", "QUANTITY","ORDER NO"};
for (int i = 0; i < 4; i++){
model.addColumn(header[i]);
}
//refresh every 1 minute
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
public void run(){
model.setRowCount(0);
try {
Class.forName(driverName);
conn = DriverManager.getConnection(url,username, password);
statement = conn.createStatement();
ResultSet rs = statement.executeQuery("SELECT USER_NAME, QUANTITY, PRD_NAME, ORDER_NUMBER FROM ORDERS ORDER BY ORDER_NUMBER DESC");
int count = rs.getRow();
String user [] = new String [count];
int i = 0;
while (rs.next()){
String name = rs.getString(1);
String prdName = rs.getString(3);
int number = rs.getInt(2);
int orderNumber = rs.getInt(4);
model.insertRow(i,new Object []{name,prdName,number, orderNumber});
}
conn.close();
}
catch (ClassNotFoundException s) {
System.out.println("Couldn't find the database driver");
System.out.println(s);
}
catch (SQLException s) {
System.out.println("Couldn't connect to the database\n" +s);
}
}
},0, 60000);
}
private void jButton1_actionPerformed(ActionEvent e) {
//set from row 0 for refresh
model.setRowCount(0);
try {
Class.forName(driverName);
conn = DriverManager.getConnection(url,username, password);
statement = conn.createStatement();
ResultSet rs = statement.executeQuery("SELECT USER_NAME, QUANTITY, PRD_NAME FROM ORDERS ORDER BY ORDER_NUMBER DESC");
int count = rs.getRow();
String user [] = new String [count];
int i = 0;
while (rs.next()){
String name = rs.getString(1);
String prdName = rs.getString(3);
int number = rs.getInt(2);
model.insertRow(i,new Object []{name,prdName,number});
}
conn.close();
}
catch (ClassNotFoundException s) {
System.out.println("Couldn't find the database driver");
System.out.println(s);
}
catch (SQLException s) {
System.out.println("Couldn't connect to the database\n" +s);
}
}
private void jButton2_actionPerformed(ActionEvent e) {
System.out.println(jTable1.getSelectedRow());
}
}
Look to your code
private void jbInit() throws Exception {
...
jScrollPane1.getViewport().add(jTable1, null);
this.getContentPane().add(jButton2, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jScrollPane1, null);
jTable1 = new JTable (model);
...
You add jTable1 to the JScrollPane at first and only then you create jTable1. It's incorrect way. jTable1 variable doen't linked now with table you place at the form. I think it's cause of your problem.
Move creation of the jTable1 before adding in into JScrollPane.
...
jTable1 = new JTable (model);
jScrollPane1.getViewport().add(jTable1, null);
this.getContentPane().add(jButton2, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jScrollPane1, null);
...
As your other example shows, getSelectedRow() does work, so you're going to have to debug your code. Comparison with the sscce below may suggest way forward. Both the ActionListener and the ListSelectionListener show the selected row.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
/**
* #see http://stackoverflow.com/q/12301923/230513
*/
public class TableSelection extends JPanel {
private static final String SHOW = "Show";
private DefaultTableModel model = new DefaultTableModel();
private JTable table = new JTable(model);
private JButton button = new JButton(new AbstractAction(SHOW) {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(table.getSelectedRow());
}
});
public TableSelection() {
model.addColumn("Column");
for (int i = 0; i < 16; i++) {
model.addRow(new Object[]{i});
}
table.setPreferredScrollableViewportSize(new Dimension(160, 100));
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
button.setText(SHOW + " " + table.getSelectedRow());
}
}
});
this.add(new JScrollPane(table));
table.setRowSelectionInterval(3, 3);
}
private void display() {
JFrame f = new JFrame("TableSelection");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this, BorderLayout.CENTER);
f.add(button, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new TableSelection().display();
}
});
}
}

Categories