is there any way to retrieve database rows using component other than jTable where unique jButtons for each row can added and made to perform specific task?
Currently I'm using the following code... jTable appears in a dialog box
public static DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
System.out.println("7");
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
public void searchb2() throws SQLException {
this.be_cgpa = be_cg.getText();
this.maj_proj = Major.getText();
this.h_percent = hss_percent.getText();
this.s_percent = sss_percent1.getText();
preparedStatement = con.prepareStatement("select name,age,gender,email_id,phone_num,state from resume1 where qualification='be' and be_cgpa>='" + be_cgpa + "'" + "and maj_proj_tech='" + maj_proj + "'" + "and hss_percent>='" + h_percent + "'" + "and sss_percent='" + s_percent + "'");
ResultSet rs;
rs = preparedStatement.executeQuery();
JTable table = new JTable(buildTableModel(rs));
JOptionPane.showMessageDialog(null, new JScrollPane(table));
}
Can this code be modified to add jButton in each row?
There is no reason you can't use JTable and add a column containing buttons to the table.
See Table Button Column for one way to do this. This class expects you to provide an Action that is invoked when the button is clicked. All you need to do is add another String of text to the "vector" after you have finished looping through the column data.
Also, use a PreparedStatement for your SQL. It is easier to code and understand and less error prone than your current code.
table button column is definitely the best way of achieving particular cell's value on clicking the corresponding button but seems to be 1 of the hardest thing in jtable.
another approach for implementing the above is enabling cell selection and using list selection model and list selection listener.
On clicking any cell you can get cell's data in a variable.
you can even fix a column and make an ordinary column with text as "button i" where i=row number. and on clicking this cell, you'll get only particular column's data of corresponding row and can even open a new frame or dialog box depending on your coding, this will make it work like a jbutton! (Actually due to fixed column, clicking any cell in that row will perform that task with column number same as fixed column)
Here is a sample code :
final JTable table;
table = new JTable(data, columnNames)
{
public boolean isCellEditable(int rowIndex, int colIndex) {
return false; //Disallow the editing of any cell
}
};
table.setCellSelectionEnabled(true);
ListSelectionModel cellSelectionModel = table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int[] selectedRow = table.getSelectedRows();
for (int i = 0; i < selectedRow.length; i++) {
selectedData = (String) table.getValueAt(selectedRow[i],2);
}
new NewJFrame().setVisible(true);
System.out.println("Selected: " + selectedData);
}
Related
I'm showing the method were the JTable is constructed, the error is when adding the rows inside the for (int i = 1; i <= numero_columnas; i++) loop, or the way the DefaultTableModel model = new DefaultTableModel(); is declared, I can't find the error.
public void verTablaTable (Connection db, String nombre) throws Exception{
Statement stmt=db.createStatement();
ResultSet sst_ResultSet = stmt.executeQuery("SELECT * FROM "+nombre);
ResultSetMetaData md = sst_ResultSet.getMetaData();
int numero_columnas = md.getColumnCount();
DefaultTableModel model = new DefaultTableModel();
for (int i=1;i<=numero_columnas; i++){
model.addColumn(md.getColumnName(i));
}
JTable tabla =new JTable(model);
DefaultTableModel model1 = (DefaultTableModel) tabla.getModel();
Vector row = new Vector();
row.setSize(numero_columnas);
while (sst_ResultSet.next()){
for (int i = 1; i <= numero_columnas; i++){
row.set(i-1,sst_ResultSet.getString(i));
}
model1.addRow(row);
}
tabla.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane sp_vertabla = new JScrollPane(tabla);
sp_vertabla.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
sp_vertabla.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
sp_vertabla.setBounds(50,30,700,500);
JPanel cont_vertabla = new JPanel(null);
cont_vertabla.setPreferredSize(new Dimension(750,600));
cont_vertabla.add(sp_vertabla);
f_vertabla.setContentPane(cont_vertabla);
f_vertabla.pack();
f_vertabla.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//f_vertabla.setResizable(false);
f_vertabla.setVisible(true);
f_vertabla.addWindowListener(this);
}
this is the way the JTable looks
The row listed in the above pic, is the last one in the mysql table
Try adding the line
Vector row = new Vector();
inside the while loop.
When a user clicks a button initially, a query is run and each row is put into a JPanel and added to the display for the user to view. Which works fine.
My problem is, I want the user to be able to filter these results according to values that they provide ( through a JTextField ) , and I want the displayed records to update as the value of the JTextField changes. My queries are formed and executed each time the JTextField is changed, but I can't find a way to update the records displayed.
Any help would be appreciated.
The code took a while to edit to the satisfaction of stackoverflow, but here it is. Hopefully you can follow the logic. This is the method that deals with formation and execution of the queries, which works(again).
The problem is displaying the new results.
private void processSearch(){
int count = 0;
double width;
remove(allInfo);
allInfo = new JPanel();
allInfo.setLayout(new GridLayout(0, 1, 5, 10));
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
width = screenSize.getWidth();
try {
DatabaseConnetor connect = new DatabaseConnetor();
Connection conn = connect.connect();
String query = "";
String whereClause = "";
int unEmpty = 0;
String [] searches ={searchNameTxt.getText(), searchMailTxt.getText(), searchContactTxt.getText(), (String) searchGender.getSelectedItem()};
String [][] keys = {{"first_name", "middle_name", "family_name", "surname"}, {"email"}, {"contact", "contact2"}, {"gender"}};
for(int i=0; i < searches.length; i++){
if(!searches[i].trim().isEmpty()){
unEmpty++;
}
for(int i=0; i < searches.length; i++){
int counter = 0;
if(!searches[i].trim().isEmpty()){
whereClause += " AND ";
int len = keys[i].length;
if(len == 1){
whereClause += " ("+keys[i][0]+" LIKE '%"+searches[i]+"%') ";
}else if(len > 1){
whereClause += " ( ";
while(counter < len){
if(counter == len-1)
whereClause += keys[i][counter]+" LIKE '%"+searches[i]+"%'";
else
whereClause += keys[i][counter]+" LIKE '%"+searches[i]+"%' OR ";
counter++;
}
whereClause += " ) ";
}
}
}
query = "SELECT photo, first_name, middle_name, family_name, surname, gender, email, contact, contact2 FROM user WHERE rights = 2" + whereClause;
PreparedStatement preparedStatement = conn.prepareStatement(query);
String gen = "", middle = "", family = "", cont = "", phot = "";
ResultSet result = preparedStatement.executeQuery();
while(result.next()){
JPanel data = new JPanel();
data.setPreferredSize(new Dimension((int)(width*0.75), 50));
data.setLayout(new GridLayout(1, 0, 5, 10));
if(result.getString(1) == "NULL")
phot = "";
data.add(new JLabel(phot)); //Photo
data.add(new JLabel(result.getString(2))); //First Name
if(result.getString(3) == "NULL")
middle = "";
data.add(new JLabel(middle)); //Middle Name
if(result.getString(4) == "NULL")
family = "";
data.add(new JLabel(family)); //Family Name
data.add(new JLabel(result.getString(5))); //Surname
if(result.getString(6).equals("M"))
gen = "Male";
else
gen = "Female";
data.add(new JLabel(gen)); //Gender
data.add(new JLabel(result.getString(7))); //E-Mail
data.add(new JLabel(result.getString(8))); //Contact1
if(result.getString(9) == "NULL")
cont = "";
data.add(new JLabel(cont)); //Contact 2
allInfo.add(data);
}
add(allInfo);
connect.disconnect(conn);
connect = null;
conn = null;
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
a query is run and each row is put into a JPanel and added to the display for the user to view
I would suggest you use a JTable to display the data from a database. A JTable is designed to display data in a row/column format.
Read the section from the Swing tutorial on How to Use Tables for more information and examples.
I want the user to be able to filter these results according to values that they provide ( through a JTextField ) , and I want the displayed records to update as the value of the JTextField changes.
A JTable supports dynamic filtering of the data displayed in the table. The above tutorial has a section on Sorting and Filtering that shows how to filter as text is entered into a text field. Filtering the table is more efficient then redoing the SQL query.
Adding data to the table is straight forward. Instead of creating a panel with each column of data you can add a new row of data to the TableModel:
String sql = "Select * from ???";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
// Create table with database data
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
#Override
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;
}
};
JTable table = new JTable( model );
JScrollPane scrollPane = new JScrollPane( table );
I am new to SWT and I need to use it's table widget. I would like to Right send queries to my database and a table is created. The setText() function only takes a new array of strings or a String, How what should I do in order for my rows to be displayed despite the number of columns. This is my code:
try{
ResultSet getTable=dbconnect.connect.createStatement().executeQuery("select * from Status");
ResultSetMetaData md = getTable.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
tblclmnNewColumn = new TableColumn(table, SWT.NONE);
tblclmnNewColumn.setWidth(100);
tblclmnNewColumn.setText(md.getColumnName(i));
columnNames.add( md.getColumnName(i));
}
for(int i=0;i<columnNames.size();i++){
String set;
if(i==columnNames.size()-1){
set="getTable.getString"+"("+'"'+columnNames.get(i)+'"'+")";
}else{
set="getTable.getString"+"("+'"'+columnNames.get(i)+'"'+")"+",";
}
columsresultset.add(set);
element[i]=columsresultset.get(i);
System.out.println(columsresultset.get(i));
}
String elements[]=new String[columsresultset.size()];
while (getTable.next()) {
TableItem tableItem =(TableItem) new TableItem(table, SWT.NONE);
tableItem.setText(elements);
}
How about using setText(yourDatabaseColumnIndex - 1, yourDatabaseColumnValue). Of course you have to create your TableColumns anyway, just as you did in your code. Example:
while(resultSet.next())
{
TableItem tableItem = new TableItem(table, SWT.NONE);
for(int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++)
{
tableItem.setText(i-1, resultSet.getString(i));
}
}
No guarantees that I didn't miss any ; or { or something ;-). Also you could optimize this a little by writing the column count to a variable.
Every time I implement a database viewer I have some functions that populate the table and adjust the column size. I would like to find ready component that can view the query result, also to sort, edit the entries in the table and automaticaly adjust the size of the column with respect to data. I want to use metadata to define the type of the entities automaticaly. The only thing that I will pass will be the ResultSet of the query and the component will do the rest. Any idea?
What I have done so far:
private static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
public static void showResult(ResultSet rs) throws SQLException{
//creates the table
JTable table = new JTable(buildTableModel(rs));
table.setEnabled(false);
//abjust table size
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumnAdjuster tca = new TableColumnAdjuster(table);//the class for adjusting the column size
tca.adjustColumns();
//JFrame
JFrame view = new JFrame("View");
view.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//add to frame
JScrollPane pane = new JScrollPane(table);
view.add(pane);
//settings
view.setVisible(true);
view.setSize(table.getWidth(), 400);
}
And also I have a class that adjust the column size.
To sort records use order by Clause to query you fire to get all records.
Use TableColumnModel to set column size.
Here is the code
//Your Edit Code
rs=st.executeQuery("select * from ManageVendor order by SName");
table.setModel(buildTableModel(rs));
TableColumnModel tcm=table.getColumnModel();
tcm.getColumn(0).setPreferredWidth(50);
tcm.getColumn(1).setPreferredWidth(200);
tcm.getColumn(2).setPreferredWidth(150);
tcm.getColumn(3).setPreferredWidth(60);
tcm.getColumn(4).setPreferredWidth(50);
tcm.getColumn(5).setPreferredWidth(250);
I am new to Java and I am practicing some new stuff.. I've started working with the database. therefore I made a to do list application with the MVC pattern.
In my Model I get all the results. In My view I try to output this data as a nice table. The problem is that I don't get any output except for a hardcoded piece of code..
here is the code of my view
JTable table = null;
public ToDoListView(ToDoListModel model) {
this.model = model;
setBackground(Color.WHITE);
JTable table = new JTable();
DefaultTableModel tableModel = new DefaultTableModel(new Object[][]{},new String[]{"To do","Date added"});
table.setModel(tableModel);
// this one below is outputted
tableModel.addRow(new Object[]{"something","1-1-2012"});
// this should give me all the results..
for(int i = 0; i < model.getRows().size(); i++) {
tableModel.addRow(model.getRows());
System.out.println("added");
}
add(table);
}
in my Model I have this
private Vector<String> rijen = new Vector<String>();
public void getValue() {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
con = db.connectToAndQueryDatabase("test", "root", "root");
System.out.println("connection established");
st = con.createStatement();
String query = "SELECT id, item, datum FROM toDoList";
rs = st.executeQuery(query);
while(rs.next()) {
System.out.println(rs.getInt("id") + "\n" + rs.getString("item") + "\n" + rs.getDate("datum"));
rijen.add(rs.getInt("id") + "");
rijen.add(rs.getString("item"));
rijen.add(rs.getDate("datum") + "");
}
public Vector<String> getRows() {
return rijen;
}
This is all the relevant code.. I don't know what I miss or what I do wrong. Could someone show me how I could solve it :)?
// This JTable attribut ...
JTable table = null;
public ToDoListView (ToDoListModel model) {
this.model = model;
setBackground (Color.WHITE);
// is hidden by this local variable:
JTable table = new JTable();
In your ToDoModel class you add all data in one large Vector
while(rs.next()) {
System.out.println(rs.getInt("id") + "\n" + rs.getString("item") + "\n" + rs.getDate("datum"));
rijen.add(rs.getInt("id") + "");
rijen.add(rs.getString("item"));
rijen.add(rs.getDate("datum") + "");
}
Then you loop over that Vector to add all those items to the TableModel, but that loop is incorrect
for(int i = 0; i < model.getRows().size(); i++) {
tableModel.addRow(model.getRows());
System.out.println("added");
}
You always add the whole vector instead of just the data for that row.
Combine that with the answer of #user unknown and you might be able to fix your problem