Get all checked value from the table - java

I'm trying to get all value from a table where the checkbox is checked, I've make codes but it only gets one output and not working if I checked randomly you have to start checking from the start to make it work.
This the Output I need:
this my current codes I've make:
TableModel model = table_test.getModel();
for(int i=0; i<model.getRowCount();++i)
{
Boolean isChecked = Boolean.valueOf(model.getValueAt(i, 0).toString());
String col = model.getValueAt(i,1).toString();
if (isChecked==true) {
try{
textarea.setText(col);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}
this codes only display is one value at the text area.
I hope you can help me with this problem.

You can try below.
TableModel model = table_test.getModel();
for(int i=0; i<model.getRowCount();++i)
{
Boolean isChecked = Boolean.valueOf(model.getValueAt(i, 0).toString());
String col = model.getValueAt(i,1).toString();
if (isChecked==true) {
try{
textarea.append(col);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}

Related

Appending text on a character interval

I am trying to write a program where the participant communicates with the program (I/O) via a console. Trick is, the console is part of a GUI, because I need the program to run off of a executable jar file. I append text with a scrollable text field, like so
textArea.append(printChar);
I give the method a String to work with, and it uses a nested for loop to take it, char by char, and append each Char (using string.substring()).
My problem is that it freezes up the entire time its supposed to be printing, then just displays it all. I don't know why, because I tested it using System.out.print, and it worked exactly as I wanted. So something is different about appending and printing. Any ideas?
Also, I am using Thread.Sleep(100) for my wait time.
public void actionPerformed(ActionEvent evt) {
if (!preforming){
preforming = true;
String input = textField.getText(); //Text from Input
textArea.append(dungeon.name + ": " + input + newline); //Add "text" to bottom of console
String[] output = dungeon.action(input);
//print everything in array output, char by char, with 2-3 seconds after each
for (int i = 0; i < output.length; i++){
String printThis = output[i];
if (printThis.length() > 0){
for (int j = 0; j < printThis.length(); j++){
String printChar = printThis.substring(j, j+1);
textArea.append(printChar);
//System.out.print(printChar);
try{
Thread.sleep(5);
} catch (InterruptedException e) {
System.out.print("Error ");
}
/*try { //useless
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
textArea.append("" + newline);
}
//cleaning up input bar
textField.setText("");
textField.selectAll();
//Make sure the new text is visible, even if there
//was a selection in the text area.
textArea.setCaretPosition(textArea.getDocument().getLength());
preforming = false;
}
}
I've edited my answer as you are showing more of your codes. Since, there is an outer loop in your code, I just included it inside the run method of timer in this new edit. And also I don't have the code for the dungeon so I just temporarily replace it with constant values so the program can run in my test.
public void actionPerformed(ActionEvent evt) {
java.util.Timer timer = new java.util.Timer();
timer.schedule(new java.util.TimerTask() {
public void run() {
if (!preforming){
preforming = true;
String newline = "\n";
String dungeonName = "Star Light";
String input = textField.getText(); //Text from Input
textArea.append(dungeonName + ": " + input + newline); //Add "text" to bottom of console
String[] output = {
"Twinkle twinkle little star.",
"How I wonder what you are.",
"Up above the world so high."
};
//print everything in array output, char by char, with 2-3 seconds after each
for (int i = 0; i < output.length; i++){
String printThis = output[i];
if (printThis.length() > 0){
for (int j = 0; j < printThis.length(); j++){
String printChar = printThis.substring(j, j+1);
textArea.append(printChar);
//System.out.print(printChar);
try{
Thread.sleep(25);
} catch (InterruptedException e) {
System.out.print("Error ");
}
/*try { //useless
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
textArea.append("" + newline);
}
//cleaning up input bar
textField.setText("");
textField.selectAll();
//Make sure the new text is visible, even if there
//was a selection in the text area.
textArea.setCaretPosition(textArea.getDocument().getLength());
preforming = false;
}
}
}, 1);
}

What is the most efficient way to print all query results with column names?

I have a result set ResultSet rs=stmt.executeQuery(); I wrote a method to print query results as following
public void printResults(ResultSet rs) {
// Getting column names
int j = 1;
while (true) {
try {
System.out.print(rs.getMetaData().getColumnName(j)+" ");
j++;
}
catch (Exception e) {
System.out.println("\n");
break;
}
}
// Getting results
while(rs.next()) {
int i = 1;
while (true) {
try {
System.out.print(rs.getString(i)+" ");
i++;
}
catch (Exception e) {
System.out.println("\n");
break;
}
}
}
}
My issue is : is it a good idea to use try && catch ... I feel that it is not? Does it impact speed? What is a better way?
Thank You
You can get column number by
ResultSetMetaData meta= rs.getMetaData();
int columnNum=meta.getColumnCount();
Loop with this columnNum to get the result as well as column name.
for(int i=1;i<=columnNum;i++){
System.out.print(meta.getColumnName(i)+" ");
}
//Get the data
while(rs.next){
for(int i=1;i<=columnNum;i++){
System.out.print(rs.getString(i)+" ");
}
}

How can I immediately see the changed data on my JTable?

I have already used the fireDataChanged methods but I think due to the fact that this is connected to my database it will not do anything.
DelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int selRow = table.getSelectedRow();
Object element = table.getValueAt(selRow, 0);
th = table.getTableHeader();
tcm = th.getColumnModel();
Statement statement = null;
try {
statement = ResultSetTableModelFactory.connection
.createStatement();
if (JisSelected == true) {
String delete = "DELETE FROM J WHERE JNO = '" + element + "';";
statement.executeUpdate(delete);
}
if (SPJisSelected == true) {
String delete = "DELETE FROM SPJ WHERE SNO = '" + element + "';";
statement.executeUpdate(delete);
}
System.out.println(element);
} catch (Exception ex) {
//ex.printStackTrace();
}
model.fireTableDataChanged();
}
});
}
Your ActionListener should perform its work in your implementation of the doInBbackground() method of a SwingWorker. In the interim, you should signify that the operation is pending in whatever way is appropriate to your application, perhaps in a renderer or status indicator. If the database operation succeeds, update the TableModel in your implementation of done(). In no case should you invoke fireTableDataChanged() except from within the model.

2D object giving a nullpointerexception?

I'm having a bit of a problem when running the code below. This code is used when a button on a gui screen is pressed. Basically the function of this button is to read text entered into 2 text fields, derive a third value from the 2, and save all 3 in a row in a table on the GUI screen, using a 2d array.
However, i get a NullPointerException when executing it at the 5th line inside the method addItem().
saleData is the 2D array with data which is in the table.
i have instantiated the temp[][] object with 1 row more than the saleData object because i need to add a row to the table, and then i make saleData=temp.
This code worked as it is in the Gui class before i tried using OOP to create a separate class for the GUI to work from.
The nullpointer exception refers to the temp object, i know this because i printed out the value of temp and it was a null.
Does anyone have any ideas?
thanks in advance.
public void addItem() {
int len = saleData.length + 1;
Object[][] temp = new Object[len][3];
for (int k = 0; k < saleData.length; k++) {
for (int i = 0; i < 3; i++) {
temp[k][i] = ((DefaultTableModel) table.getModel()).getValueAt(k, i);
}
}
tblContainer.removeComponent(table);
try {
int qty = Integer.parseInt(txtQty.getText());
String item = (String) items.getSelectedItem();
String sql = "Select Sell_price from stockInfo where parts like '" + item + "'";
double total = 0;
if (saleData.length != 1) {
for (int i = 0; i < saleData.length; i++) {
String sql2 = "Select sell_price from stockinfo where parts like '" + temp[i][1].toString() + "'";
try {
System.out.println("Check 0");
pst = conn.prepareStatement(sql2);
System.out.println("Check 1");
rs = pst.executeQuery();
System.out.println("Check 2");
while (rs.next()) {
System.out.println("Check 3");
String qt = temp[i][0].toString();
temp[i][2] = Double.parseDouble(rs.getString("sell_price")) * Integer.parseInt(qt);
System.out.println("Check 4");
}
} catch (Exception e) {
Dialog.show("Error", "Error 1: " + e, "OK", null);
}
}
}
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
double price = Double.parseDouble(rs.getString("Sell_Price"));
total = qty * price;
try {
for (int m = 0; m < saleData.length; m++) {
for (int n = 0; n < 3; n++) {
((DefaultTableModel) table.getModel()).setValueAt(m, n, temp[m][n]);
}
}
temp[saleData.length][0] = qty;
temp[saleData.length][1] = item;
temp[saleData.length][2] = total;
saleData = temp;
table = new Table(new DefaultTableModel(saleColumns, saleData, true));
tblContainer.addComponent(table);
((TableLayout) table.getLayout()).setGrowHorizontally(true);
saleForm.revalidate();
} catch (NullPointerException e) {
}
}
} catch (SQLException e) {
Dialog.show("Error", "SQL Error Record Sale", "OK", null);
}
} catch (NumberFormatException nfe) {
Dialog.show("Error", "Please enter a valid quantity", "OK", null);
}
}
The temp array can not be null. You just created it.
temp[k][i] can be null (and should be, by the way), but that does not matter - it is being assigned a value.
If a dimension of temp would not be big enough, you'd get an ArrayIndexOutOfBoundsException
So this leaves for two things that can get to be null (if the error stems from that line, and not for example from the inside of getValueAt(k,i) ):
table
table.getModel()
Use a debugger, and it will make your life easier...

Issue with title text in Java

I have used Jtidy parser in java to fetch the title text.
String titleText=null;
try {
titleText = doc.getElementsByTagName("title").item(0)
.getFirstChild().getNodeValue();
} catch (Exception e1) {
try {
titleText = doc.getElementsByTagName("title").item(1)
.getFirstChild().getNodeValue();
} catch (Exception e2) {
try {
titleText = doc.getElementsByTagName("title").item(2)
.getFirstChild().getNodeValue();
} cathc (...)
}
}
above code is working fine,It is reading title at 0'th index,if not found then at 1'st index,and then at 2'nd index.But here I am getting issue:-for some page,title text is present at mid of page or below that,so this code is not working for such pages.In this way,for such condition, length of program is getting increased.Is there any other solution,which will read the title from entire page in one go?.Please help me.
I suggest you do it like this:
String titleText=null;
NodeList titles = doc.getElementsByTagName("title");
for (int i = 0; titleText == null && i < titles.getLength(); i++) {
try {
titleText = doc.item(i).getFirstChild().getNodeValue();
} catch (SomeException e) {
}
}

Categories