adding check box in the jTable [duplicate] - java

This question already has an answer here:
How to add checkboxes to JTABLE swing [closed]
(1 answer)
Closed 8 years ago.
i am using swings for creating the desktop application . i have created the functionality which provided the data from the database and insert that into the Jtable .now i want to use provide the additional facility that include the additional column with the check box and the a button to delete that perticuler column (which is checked ) when the button is clicked .i have used the netbeans and it provide the maximum drag and drop option. i am not able to figure it out that the how and where to insert the instance of the checkbox in the current code for inserting the checkbox for the each and every row .
For providing the checkbox with the each row do have to generate the multiple instance of the check box
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
java.sql.Connection con = new DBConnection().getConnection();
PreparedStatement pst;
String Q;
Q = "select * from userregister ";
try {
pst = con.prepareStatement(Q);
ResultSet rs = null;
rs = pst.executeQuery();
String a, b, c, d;
int x = 0;
// DefaultTableModel dt = new DefaultTableModel(data, columnNames);
JCheckBox c1 = new JCheckBox();
for (int i = 0; rs.next(); i++) {
a = rs.getString(1);
b = rs.getString(2);
c = rs.getString(3);
d = rs.getString(4);
jTable2.setValueAt(a, i, 0);
jTable2.setValueAt(b, i, 1);
jTable2.setValueAt(c, i, 2);
jTable2.setValueAt(d, i, 3);
jTable2.setValueAt(, i,4);
}
//jTable1.setAutoscrolls(rootPaneCheckingEnabled);
// TODO add your handling code here:
} catch (SQLException ex) {
Logger.getLogger(NewJFrame1.class.getName()).log(Level.SEVERE, null, ex);
}
}
this is the methods that insert the data into the table . also i want to know that how do i be able to find out that which check box is checked and how to use the variable to respond the request of the multiple deletes . plz help

You have to take a look to Concepts: Editors and Renderers section of How to Use Tables tutorial.
This JCheckBox you're looking for is the default renderer/editor for Boolean class. Having said this JTable makes use of TableModel.getColumnClass() to decide the proper renderer/editor. If you use DefaultTableModel the implementation of the aforementioned method always return Object.class so you would have to override it to return Boolean.class. For instance let's say the first column will contain booleans:
DefaultTableModel model = new DefaultTableModel() {
#Override
Class<?> getColumnClass(int columnIndex) {
return columnIndex == 0 ? Boolean.class : super.getColumnClass(columnIndex);
}
};
It is all well explained in the linked tutorial.
Addendum
Another approach is shown in this Q&A: Checkbox in only one JTable Cell. This is useful when a given column may contain different types of values (booleans, numbers, strings...) so overriding getColumnClass() is not feasible. Don't think it's your case but it might be helpful.
also i want to know that how do i be able to find out that which check
box is checked and how to use the variable to respond the request of
the multiple deletes
Just iterate over the rows asking for the column value (true/false). If it's "selected" (true) then delete it:
TableModel model = table.getModel();
for(int i = 0; i < model.getRowCount(); i++) {
if((Boolean)model.getValueAt(i, 0)) {
// delete the row
}
}
Off-topic
Database calls are time consuming tasks and may block the Event Dispatch Thread (a.k.a. EDT) causing the GUI become unresponsive. The EDT is a single and special thread where Swing components creation and update take place. To avoid block this thread consider use a SwingWorker to perform database calls in a background thread and update Swing components in the EDT. See more in Concurrency in Swing trail.

Related

Ordering ID using order by in UCanAccess

I am using ucanaccess to link my database to my code but whenever I run it it doesnt work as I intend it to if it even runs at all. I just want to reorder the primary key (ID) into numerical order using ORDER BY ID;. When I edit the database it doesnt reorder when I run the method, it just pushes the edited ID to the bottom and orders them there. I am also confused if I should use an array sort in order to reorganize the entire table? Any help is appreciated. This runs whenever I attempt to edit the table in the GUI.
Source code google drive
public void reorder()
{
for(int i = 0 ; i < size - 1;i++)
{
for(int j = i+1 ; j< size;j++)
{
if(launch[i].getID() > launch[j].getID())
{
Launch temp = launch[i];
launch[i] = launch[j];
launch[j] = temp;
System.out.println(launch[i]);
}
}
}
}
public void orderByID()
{
String sql = "SELECT * FROM LaunchPriceList ORDER BY ID DESC";
try
{
dbman.updateQuery(sql);
//reorder();
}
catch(SQLException e)
{
System.out.println("Error Order by: " + e);
}
}
I am unable to access your code (for whatever the n/w restrictions). Having said that...
You can start off by creating a custom implementation of TableModel by extending AbstractTableModel
Coming to populating the TableModel, you start with iterating through the result set and creating a TreeSet with a custom Comparator that compares the ID attribute.
once done, you can create the table with the previously populated table model. E.g.
JTable t = new JTable(model);
Updating the TableModel with refreshed data will automatically refresh the table.

Updating a JTable after setModel

I have a JTable and I can't manage to make it update its content, I am in IntelliJ IDEA.
I'll share some code first
I have all the objects declared in the main class, which extends a JFrame
private Object[][] transactionsData;
private String[] transactionsColumnNames = new String[] {"uid","data","ora","product","ini","amount","final"};
private DefaultTableModel transactionsModel;
private JTable transactionsTable;
Then in the createUIComponents() method, that I managed to understand, is called at the very beginning, when the UI needs to be created, I initialize the table like this:
transactionsData = Main.db.getTransactions();
transactionsModel = new DefaultTableModel(transactionsData,transactionsColumnNames);
transactionsTable = new JTable(transactionsData,transactionsColumnNames){
#Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component component = super.prepareRenderer(renderer, row, column);
int rendererWidth = component.getPreferredSize().width;
TableColumn tableColumn = getColumnModel().getColumn(column);
tableColumn.setPreferredWidth(Math.max(rendererWidth + getIntercellSpacing().width, tableColumn.getPreferredWidth()));
return component;
}
};
transactionsTable.setRowSelectionAllowed(true);
transactionsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
transactionsTable.setDefaultEditor(Object.class, transactionsEditor);
transactionsTable.getTableHeader().setFont(new Font("Segoe",Font.PLAIN,16));
sorter = new TableRowSorter<>(transactionsTable.getModel());
transactionsTable.setRowSorter(sorter);
transactionsTable.getSelectionModel().addListSelectionListener(e -> {
if ( transactionsTable.getSelectedRows().length > 0 ) {
logUIDField.setText(transactionsTable.getValueAt(transactionsTable.getSelectedRow(), 0).toString());
transactionsTable.clearSelection();
uidFilter();
}
});
Now, each time I click a button i switch the content of the frame and the table is displayed, I need it to update its content before being displayed, because its content is taken from an online database, and of course, its content may have changed, so I do this:
storicoButton.addActionListener(e -> {
if( Main.db.hasTag() )
logUIDField.setText(Main.db.tag.getUid());
else
logUIDField.setText("");
transactionsData = Main.db.getTransactions();
transactionsModel = new DefaultTableModel(transactionsData, transactionsColumnNames);
transactionsTable.setModel(transactionsModel);
uidFilter();
CardLayout cardLayout = (CardLayout) rootPanel.getLayout();
cardLayout.show(rootPanel, "Card4");
});
But I can't manage to make it update its content, I tried everything I could find on the internet, and on this site, but everyone says to just use setModel, but it doesn't work, and I can't find what I'm doing wrong.
I tried to read the sizes of transactionsData, transactionsModel and transactionsTable before and after I click the button, transactionsData and transactionsModel actually update, since their size changes accordingly ( I checked looking at the database while I ran the program ) but transactionsTable doesn't change at all.
I tried repaint(), various methods that looks like "updateSomething", I tried with local variables, global variables, initializing new model, updating the model, initializing the table with the model or with data and columns, nothing. I'm desperate.
I hope someone here can help me.
At the moment here is late, and tomorrow I need to wake up early, after work I'll try starting clean, rewriting everything from scratch, maybe I'll find the solution myself, in the mean time I hope someone here could push me in the right direction at least.
Il post the code of that uidFilter() which I found online, it's the first thing I'm going to remove tomorrow, because I suspect it can change something, but I don't have the time to do that now
private void uidFilter() {
RowFilter<TableModel, Object> rf = null;
//If current expression doesn't parse, don't update.
try {
rf = RowFilter.regexFilter(logUIDField.getText(), 0);
} catch (java.util.regex.PatternSyntaxException e) {
return;
}
sorter.setRowFilter(rf);
}

how to show data in jTable in JAVA it append old value

I am using jTable in netbeans. After selection of combobox if i select employee id 1 it show all data of emp 1 in jTable. But next time when i choose emmployee id 2 jTable shows single value of emp id 1's and all another values of empid 2.
My code is given below
Connect c = new Connect();//connection to database
con = (Connection) c.getConnection();
st = (Statement)con.createStatement();
String ddate = (String)text.getSelectedItem();
System.out.println("id " +ddate);
rs = st.executeQuery("select e.employee_id,e.`first_name`, i.outtime, i.outtime_date from tbl_employee e,tbl_outtime i where e.employee_id=i.outtime_emp_id and i.`outtime_date` LIKE '%/"+month2+"/"+year1+"'and outtime_emp_id="+ddate);
while(rs.next())
{
String dat1=rs.getString("outtime_date");
String e1=rs.getString("employee_id");
System.out.println(e1);
st33=(Statement) con.createStatement();
rs33=st33.executeQuery("select i.intime, i.intime_date from tbl_employee e,tbl_intime
i where e.employee_id=i.intime_emp_id and i.`intime_date`='"+dat1+"' and
i.intime_emp_id="+e1);
if(rs33.next())
{
int emp=rs.getInt("employee_id");
System.out.println(emp);
String name=rs.getString("first_name");
String dept=rs33.getString("intime");
String desig=rs.getString("outtime");
String join=rs33.getString("intime_date");
jTable1.setValueAt(emp, cnt, 0);
jTable1.setValueAt(name, cnt, 1);
jTable1.setValueAt(dept, cnt, 2);
jTable1.setValueAt(desig, cnt, 3);
jTable1.setValueAt(join, cnt, 4);
cnt=cnt+1;
}
}
Tell me solution if anyone knows.
read tutorial about JTable
all data for JTables view are stored into XxxTableModel
have to clear XxxTableModel, and add new row(s) from JDBC to the XxxTableModel
Use TableModel for adding row.
Read
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
for samples.
Like all other Swing components, a table consists of two parts: a view part (the JTable) and a model part (the TableModel). The view is updated when the model indicates it has been changed by throwing events. See the table tutorial for more information.
So for your use-case, you can either adjust the existing TableModel or create a new one. I would personally opt to create a new one since you are working with a database.
Note that Swing components should only be accessed and modified on the Event Dispatch Thread, and that long running tasks (as querying a database) should not happen on this thread (see the Swing concurrency tutorial). That is why I would recommend to create a new TableModel. You can create this model on the worker thread you use for querying the database, and the replace the model in one go on the Event Dispatch Thread. The SwingWorker class is most suited for this.

Java swing jTable not being updated

I built a jTable using NetBeans GUI, and I want to update it inside the constructor of the class. I'm planning to add a search option on the frame so the whole update idea is quite critical for me.
My code:
public availableTrumps(TrumpistClient TC){
initComponents();
availableTrumpsTrumpistClient=TC;
String result=null;
String query="SELECT * FROM APP.TRUMPS";
result=this.availableTrumpsTrumpistClient.WritingReading("sql_select", query);
if (result.contains("empty")){
JOptionPane.showMessageDialog(this, "There are now trumps to show.");
}
else if (result.contains("error")){
JOptionPane.showMessageDialog(this, "Error in the connection. Please try again.");
}
else{
int i;
String []data = result.split("\r\n");
String [][] data2 = new String [data.length][];
for (i = 0; i < data.length; i++)
{
data2[i] = data[i].split("&");
}
String[] columnNames = {"From", "To", "Departure Time", "Remaining Places", "Proposer", "ClosingTime", "Cost Per Seat" };
this.jTable1 = new JTable(data2,columnNames);
this.jTable1.setPreferredScrollableViewportSize(new Dimension(500,100));
this.jTable1.setFillsViewportHeight(true);
JScrollPane jps = new JScrollPane(jTable1);
add(jps);
jTable1.revalidate();
}
}
The input two-dimentional array data2 is fine and validated.
I added the last 5 rows of the code to see if they help with something. I don't know if they are mandatory and in any case I do not want to change the graphical properties of the jTable I built with the GUI (just the data in it).
When I run the program, I see that the jTable remains empty.
Why?
I suggest you use a table model, whenever the data changes you change the model. Build the JTable instance only once, not whenever you need to change the data.
As others have said, you don't want to create multiple JTable instances. Create one like this:
DefaultTableModel model = new DefaultTableModel(new Object[0][0],
new String[]{"From", "To", "etc."});
JTable table = new JTable(model);
Then, when you need to add rows, use
model.addRow(dataForThisRow); // Object
If you want to change a cell:
model.setValueAt(newValue, row, col); // Object, int, int
Or, to remove row i:
model.removeRow(i); // int
For more information, see the DefaultTableModel documentation.
If, for some reason, it is imperative that you recreate the table each time, I believe the problem is that you are calling revalidate without calling repaint.

How to fill data in a JTable with database?

I want to display a JTable that display the data from a DataBase table as it is.
Up till now, I have used JTable that displays data from Object [ ][ ].
I know one way to display the data is to first convert the database table into Object [ ][ ] but Is there any other which is easy yet more powerful and flexible.
I would recommend taking the following approach:
Create a Row class to represent a row read from your ResultSet. This could be a simple wrapper around an Object[].
Create a List<Row> collection, and subclass AbstractTableModel to be backed by this collection.
Use a SwingWorker to populate your List<Row> by reading from the underlying ResultSet on a background thread (i.e. within the doInBackground() method). Call SwingWorker's publish method to publish Rows back to the Event Dispatch thread (e.g. every 100 rows).
When the SwingWorker's process method is called with the latest chunk of Rows read, add them to your List<Row> and fire appropriate TableEvents to cause the display to update.
Also, use the ResultSetMetaData to determine the Class of each column within the TableModel definition. This will cause them to be rendered correctly (which won't be the case if you simply use a 2D Object[][] array).
The advantage of this approach is that the UI will not lock up when processing large ResultSets, and that the display will update incrementally as results are processed.
EDIT
Added example code below:
/**
* Simple wrapper around Object[] representing a row from the ResultSet.
*/
private class Row {
private final Object[] values;
public Row(Object[] values) {
this.values = values;
}
public int getSize() {
return values.length;
}
public Object getValue(int i) {
return values[i];
}
}
// TableModel implementation that will be populated by SwingWorker.
public class ResultSetTableModel extends AbstractTableModel {
private final ResultSetMetaData rsmd;
private final List<Row> rows;
public ResultSetTableModel(ResultSetMetaData rsmd) {
this.rsmd = rsmd;
this.rows = new ArrayList<Row>();
}
public int getRowCount() {
return rows.size();
}
public int getColumnCount() {
return rsmd.getColumnCount();
}
public Object getValue(int row, int column) {
return rows.get(row).getValue(column);
}
public String getColumnName(int col) {
return rsmd.getColumnName(col - 1); // ResultSetMetaData columns indexed from 1, not 0.
}
public Class<?> getColumnClass(int col) {
// TODO: Convert SQL type (int) returned by ResultSetMetaData.getType(col) to Java Class.
}
}
// SwingWorker implementation
new SwingWorker<Void, Row>() {
public Void doInBackground() {
// TODO: Process ResultSet and create Rows. Call publish() for every N rows created.
}
protected void process(Row... chunks) {
// TODO: Add to ResultSetTableModel List and fire TableEvent.
}
}.execute();
Another powerful and flexible way to display database data in a JTable is to load your query's resulting data into a CachedRowSet, then connect it to the JTable with TableModel adapter.
Query ---> Database data ---> RowSet
RowSet <--> TableModel adapter <--> JTable
This book by George Reese gives the source code for his class RowSetModel to adapt a RowSet as a TableModel. Worked for me out-of-the-box. My only change was a better name for the class: RowSetTableModel.
A RowSet is a subinterface of ResultSet, added in Java 1.4. So a RowSet is a ResultSet.
A CachedRowSet implementation does the work for you, instead of you creating a Row class, a List of Row objects, and ResultSetMetaData as discussed in other answers on this page.
Sun/Oracle provides a reference implementation of CachedRowSet. Other vendors or JDBC drivers may provide implementations as well.
RowSet tutorial
Depending on what you've done already and what you're willing to do, I've been using Netbeans with its Beans Binding support for a database-driven app very successfully. You bind your JTable to a database and it automatically builds the JPA queries.
Best way to fill jTable with ResultSet
Prerequisites
1) Result Set "rs" is populated with data you need.
2) JTable "jTable1" is created before hand
3) Table Header is implemented before hand
Implementation
java.sql.ResultSet rs = datacn.executeSelectQuery(query);
//Filling JTable with Result set
// Removing Previous Data
while (jTable1.getRowCount() > 0) {
((DefaultTableModel) jTable1.getModel()).removeRow(0);
}
//Creating Object []rowData for jTable's Table Model
int columns = rs.getMetaData().getColumnCount();
while (rs.next())
{
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++)
{
row[i - 1] = rs.getObject(i); // 1
}
((DefaultTableModel) jTable1.getModel()).insertRow(rs.getRow() - 1,row);
}
You have to create a custom TableModel There you can specify where and how the data is coming from.
You really have to fully understand first how JTable + TableModel works and then follow one of the previously posted answers.
I know the question is old but for anyone following Adamski's solution, care should be taken while sharing the ResultSet and ResultSetMetadata between gui and SwingWorker threads. I got an inconsistent internal state exception while using this approach with SQLite. The solution is to load any metadata to private fields before executing the SwingWorker and have the getter functions (getColumnName etc.) to return the fields instead.
I am giving a small method for display database table data in JTable. You need to pass only the resultset of the database table as parameter.
// rs is the ResultSet of the Database table
public void displayData(ResultSet rs)
{
//jt Represents JTable
//jf represents JFrame
int i;
int count;
String a[];
String header[] = {"1","2","3","4","5"}; //Table Header Values, change, as your wish
count = header.length;
//First set the Table header
for(i = 0; i < count; i++)
{
model.addColumn(header[i]);
}
jt.setModel(model); //Represents table Model
jf.add(jt.getTableHeader(),BorderLayout.NORTH);
a = new String[count];
// Adding Database table Data in the JTable
try
{
while (rs.next())
{
for(i = 0; i < count; i++)
{
a[i] = rs.getString(i+1);
}
model.addRow(a); //Adding the row in table model
jt.setModel(model); // set the model in jtable
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Exception : "+e, "Error", JOptionPane.ERROR_MESSAGE);
}
}

Categories