Clicking on button doesn't retrieve data from database - java

So i'm trying to make a frame where it shows a list of every item in my database after you click on the button, but actually when i click on it nothing shows.
public ArrayList show(JTextArea tData) {
ArrayList<Book> books=new ArrayList<>();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
polaczenie =DriverManager.getConnection("jdbc:sqlserver://localhost;databaseName=master",
"sa", "student");
try(Statement stmt = connection.createStatement();) {
ResultSet rs = stmt.executeQuery("{call dbo.showBook}");
while (rs.next()) {
books.add(new Book(
rs.getString("bookNumber"),
rs.getString("title"),
rs.getString("author"),
rs.getString("publicationYear"),
rs.getString("publisher"))
);
}
}
}
catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Error "+ex.getMessage(), "Error", 0);
}
catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Error "+ex.getMessage(), "Error", 0);
}
return books;
}
private void bShowActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
DataBook db=new DataBook();
db.show(tData);
}

Your show method will return a ArrayList<Book>
So:
Have you processed this to display data from the list?
Does your database have data yet ?
"Sorry I can't add comment because my reputation < 50 "
Hope it helps you.
package test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class App extends JFrame {
JPanel contentPane;
JButton action;
JList<Book> listBooks;
public App() {
this.prepareGUI();
}
public void prepareGUI() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(200, 200);
contentPane = new JPanel();
this.setContentPane(contentPane);
action = new JButton("Action");
contentPane.add(action);
listBooks = new JList<Book>();
contentPane.add(listBooks);
action.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Data
Book[] books = new Book[5];
for (int i = 0; i < books.length; i++) {
books[i] = new Book("book " + i, "##");
}
listBooks.setListData(books);
}
});
}
public static void main(String[] args) {
App app = new App();
app.setVisible(true);
}
}
Hope this help you!!!

Related

Deleting rows with right click from MySql table in JTable

I have a Java class as shown below which displays my table from my database. I want to add a function that will open a pop-up menu and delete row from table. How can i do that?
import java.awt.BorderLayout;
import javax.swing.*;
import java.sql.*;
import java.util.Vector;
public class Test {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String s;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost/sms", "root", "");
st = con.createStatement();
s = "select * from sent_messages";
rs = st.executeQuery(s);
ResultSetMetaData rsmt = rs.getMetaData();
int c = rsmt.getColumnCount();
Vector column = new Vector(c);
for (int i = 1; i <= c; i++) {
column.add(rsmt.getColumnName(i));
}
Vector data = new Vector();
Vector row = new Vector();
while (rs.next()) {
row = new Vector(c);
for (int i = 1; i <= c; i++) {
row.add(rs.getString(i));
}
data.add(row);
}
JFrame frame = new JFrame();
frame.setSize(500, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JTable table = new JTable(data, column);
JScrollPane jsp = new JScrollPane(table);
panel.setLayout(new BorderLayout());
panel.add(jsp, BorderLayout.CENTER);
frame.setContentPane(panel);
frame.setVisible(true);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR");
} finally {
try {
st.close();
rs.close();
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
}
}
And as a reference i looked to this page but i couldn't bind method from here.
I found an example and i took it as a reference.
I got to handle and rewrite the code as 3 classes shown below:
JTablePopupMenuExample.java
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class JTablePopupMenuExample extends JFrame implements ActionListener {
private JTable table;
private DefaultTableModel tableModel;
private JPopupMenu popupMenu;
private JMenuItem menuItemAdd;
private JMenuItem menuItemRemove;
private JMenuItem menuItemRemoveAll;
List<SentMessagesTable> msgList;
public JTablePopupMenuExample() throws Exception{
super("JTable Popup Menu Example");
// sample table data
String[] columnNames = new String[] {"id", "receiver", "sender", "msg_text", "status", "x_date"};
msgList = new ArrayList<SentMessagesTable>();
ResultSet rs = getTableRows();
while (rs.next()) {
SentMessagesTable msg = new SentMessagesTable();
msg.setId(rs.getInt("id"));
msg.setReceiver(rs.getString("receiver"));
msg.setSender(rs.getString("sender"));
msg.setMsgText(rs.getString("msg_text"));
msg.setStatus(rs.getString("status"));
msg.setxDate(rs.getString("x_date"));
msgList.add(msg);
}
String[][] rowDataTable = new String[34400][6];
for(int i = 0 ; i < msgList.size();i++) {
//burda jtable listesini doldur
rowDataTable[i][0] = String.valueOf(msgList.get(i).getId());
rowDataTable[i][1] = msgList.get(i).getReceiver();
rowDataTable[i][2] = msgList.get(i).getSender();
rowDataTable[i][3] = msgList.get(i).getMsgText();
rowDataTable[i][4] = msgList.get(i).getStatus();
rowDataTable[i][5] = msgList.get(i).getxDate();
}
// constructs the table with sample data
tableModel = new DefaultTableModel(rowDataTable, columnNames);
table = new JTable(tableModel);
// constructs the popup menu
popupMenu = new JPopupMenu();
menuItemAdd = new JMenuItem("Add New Row");
menuItemRemove = new JMenuItem("Remove Current Row");
menuItemRemoveAll = new JMenuItem("Remove All Rows");
menuItemAdd.addActionListener(this);
menuItemRemove.addActionListener(this);
menuItemRemoveAll.addActionListener(this);
popupMenu.add(menuItemAdd);
popupMenu.add(menuItemRemove);
popupMenu.add(menuItemRemoveAll);
// sets the popup menu for the table
table.setComponentPopupMenu(popupMenu);
table.addMouseListener(new TableMouseListener(table));
// adds the table to the frame
add(new JScrollPane(table));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800,1000);
setLocationRelativeTo(null);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new JTablePopupMenuExample().setVisible(true);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public void actionPerformed(ActionEvent event) {
JMenuItem menu = (JMenuItem) event.getSource();
if (menu == menuItemAdd) {
addNewRow();
} else if (menu == menuItemRemove) {
removeCurrentRow();
} else if (menu == menuItemRemoveAll) {
removeAllRows();
}
}
private void addNewRow() {
tableModel.addRow(new String[0]);
}
private void removeCurrentRow(){
int selectedRow = table.getSelectedRow();
tableModel.removeRow(selectedRow);
String jdbcUrl = "jdbc:mysql://localhost/sms";
String username = "root";
String password = "";
String sql = "delete from sent_messages where id = '"+msgList.get(selectedRow).getId()+"'";
// java.sql.Statement stmt = null;
try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password);
java.sql.Statement stmt = conn.createStatement();) {
stmt.executeUpdate(sql);
System.out.println("Record deleted successfully");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void removeAllRows() {
int rowCount = tableModel.getRowCount();
for (int i = 0; i < rowCount; i++) {
tableModel.removeRow(0);
}
}
private ResultSet getTableRows() throws SQLException {
Connection con = null;
java.sql.Statement st = null;
ResultSet rs = null;
String s;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost/sms", "root", "");
st = con.createStatement();
s = "select * from sent_messages";
rs = ((java.sql.Statement) st).executeQuery(s);
}catch(Exception e) {
System.out.println(e.toString());
}
finally {
//con.close();
}
return rs;
}
}
SentMessagesTable.java which involves (getters and setters)
public class SentMessagesTable {
int id;
String receiver;
String sender;
String msgText;
String status;
String xDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getMsgText() {
return msgText;
}
public void setMsgText(String msgText) {
this.msgText = msgText;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getxDate() {
return xDate;
}
public void setxDate(String xDate) {
this.xDate = xDate;
}
}
And TableMouse Listener.java
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JTable;
public class TableMouseListener extends MouseAdapter {
private JTable table;
public TableMouseListener(JTable table) {
this.table = table;
}
#Override
public void mousePressed(MouseEvent event) {
// selects the row at which point the mouse is clicked
Point point = event.getPoint();
int currentRow = table.rowAtPoint(point);
table.setRowSelectionInterval(currentRow, currentRow);
}
}
With that code i was able to delete records from JTable and also from my database.

JTable in GroupLayout not populating from database [duplicate]

I have a text box that allows users to put in select type queries with the idea that when they click a button the result of the select statement will be shown in a JTable. I don't get any errors but also nothing is shown in the textPane when my button is pressed. The I have is below:
public class Console {
String myquery="";
private JFrame frame;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Console window = new Console();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Console() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 950, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea textAreaQuery = new JTextArea();
JTable table_ResQues = new JTable();
JButton btnNewButton = new JButton("Execute");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String connectDB = "jdbc:ucanaccess:///Users/sebastianzeki/Documents/PhysJava/Physiology.mdb;";
System.out.println("Connection To Database Made");
Connection conn = null;
try {
conn = DriverManager.getConnection(connectDB);
} catch (SQLException e1) {
e1.printStackTrace();
}
Statement st = null;
try {
st = conn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
myquery=textAreaQuery.getText();
String stg2 = "Select "+myquery;
ResultSet rs = null;
try {
rs = st.executeQuery(stg2);
table_ResQues.setModel(getDataFromDatabase);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
and the code to build the model:
public TableModel getDataFromDatabase()
{
DefaultTableModel model = new DefaultTableModel(5, 5);
model.setValueAt("Hard", 0, 0);
model.setValueAt("Coded", 1, 1);
model.setValueAt("Data", 2, 2);
return model;
}
}
Ive removed the local variable
No, you removed the instance variable. Did you actually try this with your real code or just edit the question?
I have no idea how to provide a testable database for this question
I already suggested you create a method to simplify the logic. Somethng like:
public TableModel getDataFromDatabase()
{
DefaultTableModel model = new DefaultTableModel(5, 5);
model.setValueAt("Hard", 0, 0);
model.setValueAt("Coded", 1, 1);
model.setValueAt("Data", 2, 2);
return model;
}
Then in your ActionListener you simple do something like:
table_ResQues.setModel( getDataFromDataBase() );
Once you get this basic logic working you move the SQL logic into the getDataFromDatabase() method.
So now you create your SSCCE showing how you actually create the frame and add the components to the frame. The code should be compilable and executable.
Edit:
You have been told to display a table is a scrollpane. It is no extra effort to do this. Instead of using:
panel.add(table);
you use:
panel.add( new JScrollPane( table ) );
I would also suggest that to test your layout you can use code like the following to display a dummy table:
//JTable table_ResQues = new JTable();
JTable table_ResQues = new JTable(5,5);
Then when you use the setModel() method, only the data is affected, not the layout of the table.
I cant help but feel this is a fireTableDataChanged problem though.
I doubt it. That method is invoked by the TableModel when you change the data in the model. It is not used in this case because you are using the setModel(...) method. This will cause the table to repaint() itself automatically.
Here is my solution to your problem. I have retained your variable names though not all of them followed Java conventions. I think all you wanted was that the user would type SQL query in JTextArea and see the result of the query in a JTable.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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 java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.AbstractTableModel;
public class Console {
private JFrame frame;
private JTextArea textAreaQuery;
private JTable table_ResQues;
private JButton btnNewButton;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Console window = new Console();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Console() {
initialize();
}
private void initialize() {
frame = new JFrame("SQL Query");
frame.setBounds(100, 100, 950, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textAreaQuery = new JTextArea();
btnNewButton = new JButton("Execute");
table_ResQues = new JTable();
JPanel queryPanel=new JPanel(new BorderLayout()); // holds JTextArea and JButton
queryPanel.add(new JScrollPane(textAreaQuery), BorderLayout.CENTER);
JPanel btnPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
btnPanel.add(btnNewButton);
queryPanel.add(btnPanel, BorderLayout.SOUTH);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, queryPanel,
new JScrollPane(table_ResQues));
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(150);
frame.setContentPane(splitPane);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
/*try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e2) {
e2.printStackTrace();
}*/
String connectDB = "jdbc:ucanaccess:///Users/sebastianzeki/Documents/PhysJava/Physiology.mdb;";
Connection conn = null;
Statement st = null;
try {
conn = DriverManager.getConnection(connectDB);
//conn = DriverManager.getConnection("jdbc:mysql://localhost/cwcx", "root", "admin");// MySQL connection
st = conn.createStatement();
System.out.println("Connection To Database Made");
} catch (SQLException e1) {
e1.printStackTrace();
}
String myquery = textAreaQuery.getText();
if(myquery.endsWith(";")){
myquery=myquery.substring(0, myquery.length()-1);
}
ResultSet rs = null;
try {
rs = st.executeQuery(myquery);
// extract column information
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
List<String> columnData = new ArrayList<String>(columnCount);
for (int i = 1; i <= columnCount; i++) {
columnData.add(rsmd.getColumnName(i));
}
// sql result data
List<List<Object>> rowData = new ArrayList<List<Object>>();
while (rs.next()) {
List<Object> row = new ArrayList<Object>(columnCount);
for (int i = 0; i < columnCount; i++) {
row.add(rs.getObject(i + 1));
}
rowData.add(row);
}
table_ResQues.setModel(new ListTableModel(rowData, columnData));
} catch (SQLException e1) {
JOptionPane.showMessageDialog(frame, e1.getMessage(), "SQL Exception", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}finally{
if(rs!=null){
try {
rs.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
}
});
}
// this table model is created from two dimensional List rowData and single dimensional List columnData
private static class ListTableModel extends AbstractTableModel{
private static final long serialVersionUID = 1L;
private List<List<Object>> rowData;
private List<String> columnData;
public ListTableModel(List<List<Object>> rowData, List<String> columnData) {
this.rowData = rowData;
this.columnData = columnData;
}
#Override
public int getRowCount() {
return rowData.size();
}
#Override
public int getColumnCount() {
return columnData.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return rowData.get(rowIndex).get(columnIndex);
}
#Override
public String getColumnName(int column) {
return columnData.get(column);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
Object obj=rowData.get(0).get(columnIndex);
return obj.getClass();
}
}
}
On my system, I have tested it with MySQL database. But I have commented out that part. You may try this on your system without any modification. Please do tell me whether you wanted to achieve this solution or not.

How do i get the id of the cell click using JTable?

I am using a JTable to display data from my database. What I want to happen is that when a row is clicked it opens another window.
My Code
Connection to the database
public class JFrametest extends javax.swing.JFrame {
private static Connection connection;
private static Statement stmt;
static {
// standard code to open a connection and statement to Java Derby database
try {
NetworkServerControl server = new NetworkServerControl();
server.start(null);
// Load JDBC driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//Establish a connection
String sourceURL = "jdbc:derby://localhost:1527/"
+ new File("EmailsDB").getAbsolutePath() + ";";
connection = DriverManager.getConnection(sourceURL, "student", "student");
stmt = connection.createStatement();
} // The following exceptions must be caught
catch (ClassNotFoundException cnfe) {
out.println(cnfe);
} catch (SQLException sqle) {
out.println(sqle);
} catch (Exception e) {
System.out.println(e);
}
}
Displaying Data from the database
try {
String query = "select * from messages";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}catch (Exception e) {
e.printStackTrace();
}
As anyone got any ideas on what i can do? is this possible?
You could use a mouseClicked Action Listener to do this.
You can use MouseListener for that, here is simple example:
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TestFrame extends JFrame {
public static void main(String... s) {
new TestFrame();
}
private JTable t;
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
DefaultTableModel model = new DefaultTableModel(0,2);
for(int i=0;i<10;i++){
model.addRow(new Object[]{i,"other info "+i});
}
model.setColumnIdentifiers(new Object[]{"id","info"});
t = new JTable(model);
t.addMouseListener(getListener());
add(new JScrollPane(t));
}
protected void showDialog(int rowAtPoint) {
Object valueAt = t.getValueAt(rowAtPoint, 0);
// other operations
JDialog d = new JDialog();
d.setTitle("id="+valueAt);
d.setModal(true);
d.setAlwaysOnTop(true);
d.setLocationRelativeTo(null);
d.pack();
d.setVisible(true);
}
private MouseListener getListener() {
return new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if(e.getClickCount() >= 1){
int rowAtPoint = t.rowAtPoint(e.getPoint());
if(rowAtPoint != -1)
showDialog(rowAtPoint);
}
}
};
}
}

Add to JList after "enter" key has been pressed

I'm simply trying to do is don't add the item to the JList until I hit enter, because I made a Google-like search box. I think it's the comboBox that is not "reading" the "enter" key.
public void count(){
try{
String sql2 = "select count(*) from workers_info";
stmt = conn.prepareStatement(sql2);
rs=stmt.executeQuery();
while(rs.next()){
String x = rs.getString("count(*)");
z = Integer.parseInt(x);
}
auto = new String[z];
}
catch(SQLException | NumberFormatException e){
}
}
public void cB(){
try{
String sql = "Select concat(first_name, ' ',last_name) as full_name from workers_info";
stmt = conn.prepareStatement(sql);
rs=stmt.executeQuery();
while(rs.next()){
String name = rs.getString("full_name");
auto[i] = name;
i++;
}
AutoCompleteSupport a = AutoCompleteSupport.install(comboSearch, GlazedLists.eventListOf(auto));
a.setStrict(false);
comboSearch.isEditable();
}
catch(SQLException e){
}
}
//this actually is my main concern..why it cant detect when i hit "enter" key?
private void comboSearchKeyPressed(java.awt.event.KeyEvent evt) {
String s1 = (String)comboSearch.getSelectedItem();
if(evt.getKeyCode()==KeyEvent.VK_ENTER){
model.addElement(s1);
workerList.setModel(model);
comboSearch.setSelectedItem(null);
}
}
For that purposes I recommend you to use Key bindings instead of KeyListener. Try next simple example:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
public class Example extends JFrame{
private JComboBox<String> comboBox;
private JList<String> list;
private DefaultListModel<String> model;
Example(){
comboBox = new JComboBox<>(new String[]{"111","222","333"});
list = new JList<>(model = new DefaultListModel<>());
add(comboBox,BorderLayout.SOUTH);
add(new JScrollPane(list));
addKeyBindings((JComponent) getContentPane());
addKeyBindings(comboBox);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
private void addKeyBindings(JComponent c) {
c.getInputMap(JComboBox.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("ENTER"), "doSomething");
c.getActionMap().put("doSomething", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
Object selectedItem = comboBox.getSelectedItem();
if(selectedItem != null){
model.addElement((String)selectedItem);
}
}
});
}
public static void main(String[] args) {
new Example();
}
}

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