Can't add a row to a jTable even when using getModel - java

I've been searching through this website for numerous hours now on how to get my button to an a row to an already existing table, this table created by simply clicking the swing Controls, and adding a table and altering the fields through the properties.
The table's variable name is 'table'.
And when confronted with this line of code:
table.getModel().insertRow(table.getRowCount(),new Object[]{nome[i],data[i]});
The 'insertRow' part is redded and I can't seem to fix it.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String direcdate=direc1.getText();
File folder = new File(direcdate);
File[] listOfFiles=folder.listFiles();
String[] nome = new String[250];
String[] data = new String[250];
int i=0;
for (File listOfFile : listOfFiles) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
if (listOfFile.isFile()) {
nome[i]= listOfFile.getName ();
data[i] =sdf.format(listOfFile.lastModified());
i++;
}
else if (listOfFile.isDirectory()) {
nome[i]= "Folder: " + listOfFile.getName ();
data[i] =sdf.format(listOfFile.lastModified());
i++;
}
}
for(int increm=0;increm<i;increm++)
{
table.getModel().insertRow(table.getRowCount(),new Object[]{nome[i],data[i]});
}
}
Any ideas or suggestions?
EDIT: where the table model is located:
public class GAPAC_TESTE extends javax.swing.JFrame {
public GAPAC_TESTE() {
initComponents();
ultimaalt.setText("0");
jTextPane2.setText("Após escolher a diretoria, escolha uma das opções.");
DefaultTableModel model = new javax.swing.table.DefaultTableModel();
table = new javax.swing.JTable(model);
}

table.getModel().
That method return a TableModel. Did you look at the API for the TableModel interface? It does not contain an insertRow(...) method.
The DefaultTableModel has the insertRow(...) method. So assuming your table is using a DefaultTableModel the code would be:
DefaultTableModel model = (DefaultTableMode)table.getModel();
model.insertRow(...);
Don't always write you code in a single statmentment. Break the statement up into multiple statements so you understand exactly which part of the statement causes the problem and it makes sure you assign the variable to the proper class.

If you implement a TableModel, you will be able to exactly determine how data is added and which data types are displayed in your table.

Related

How to get the contains of file in jtable?

I create a jtable like this :
String name = temp.getName();
String enemy = namaFileUtama.toString();
DefaultTableModel models = (DefaultTableModel) Main_Menu.jTable4.getModel();
List<ReportMomentOfTruth> theListRMOT = new ArrayList<ReportMomentOfTruth>();
ReportMomentOfTruth rmot = new ReportMomentOfTruth();
rmot.setNameOfMainFile(name);
rmot.setNameOfComparingFile(enemy);
theListRMOT.add(rmot);
for (ReportMomentOfTruth reportMomentOfTruth : theListRMOT) {
models.addRow(new Object[]{
reportMomentOfTruth.getNamaFileUtama(),
reportMomentOfTruth.getNamaFilePembanding(),
});
}
You know, I dont get an idea. How can I get the contains the file if I click one row in jtable then the contains will be show in jTextArea ? Any suggestion ? any example perhaps ?
Thanks
edit
You know, I am using netbeans, I can get a method like this
private void jTable4MouseClicked(java.awt.event.MouseEvent evt) {
if (evt.getClickCount() == 1) {
}
}
Now how to ?
How can I get the contains the file if I click one row in jtable then the contains will be show in jTextArea?
You can better use JEditorPane that has a method setPage() that can be used to initialize the component from a URL.
Just get the values of selected row and use below code to set the content in JEditorPane.
sample code:
final JEditorPane document = new JEditorPane();
document.setPage(new File(".../a.java").toURI().toURL());
Add ListSelectionListener to detect the selection change event in the JTable
final JTable jTable = new JTable();
jTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int row = jTable.getSelectedRow();
if(row != -1){
String firstColumnValue = jTable.getModel().getValueAt(row, 0).toString();
String secondColumnValue = jTable.getModel().getValueAt(row, 1).toString();
// load the JEditorPane
}
}
});;
Read more...

How to show data from database to jtable with checkboxes in the first column in jtable?

I know how to populate jtable and i had prepared the code for the above which works fine. But the problem is that it is working in another project but bot in my current project. The code for both the project is same. Here is the code... purchaswtab is the table name which has been already created using swing palette. And this function is executed in the event of the exit button of the Item Master.
the array elements of an array ap are defined as i have to fetch them from the given position from the resultset.
public void populatetable(ItemMaster imm)
{
imm.dispose();
String t[][]=new String [30][10];
int[] ap={19,1,2,4,18,16,17};
Object[] h1=new Object[7];
String a1,a2;
int j=0,i=1;
int len=0;
try
{
st=fun.connect1();
String query="select * from Temp_Purchase";
ResultSet rs=st.executeQuery(query);
ResultSetMetaData rsmd=rs.getMetaData();
while(rs.next())
{
int k=0;
for(i=1;i<=7;i++,k++ )
{
t[j][i-1]=rs.getString(ap[k]);
System.out.println(t[j][i-1]);
}
j++;
len++;
}
fun.close();
}
catch(Exception e)
{
fun.close();
System.out.println("Exception:"+e);
}
DefaultTableModel de=(DefaultTableModel)purchaseTab.getModel();
purchaseTab=new JTable(de);
//Code for filling data into table
for(i=0;i<len;i++)
{
for(j=1;j<=7;j++)
{
h1[j-1]=t[i][j-1];
}
if(h1[0]=="0")
{
h1[0]=Boolean.FALSE;
}
de.insertRow(i,h1);
}
//jsp.setViewportView(Table);
}
replace evetything inside while(rs.next()) to de.addRow(new Object[..., ..., ...]);
you have to declare DefaultTableModel de as local variable, initialized before fun is called
then to pass DefaultTableModel de to JTable, e.g. myTable(de); or myTable.setModel(de)
use Object[] instead of limitations for String[], then you can to store various data type in DefaultTableModel
From #mKorbel's answer
Create and add a DefaultTableModel like:
DefaultTableModel model=new DefaultTableModel(data,header);
JTable table = new JTable(model);
Here data is double vector and header is single vector.
data = get(field);
Object[] d={data.get(i).get(0),data.get(i).get(1),data.get(i).get(2)};
model.addRow(d);
Get data from database
get(field){
//Your Database connection
//Get data into vector
//return vector
}

Reading a Access file using Jackcess and creating a Jtable with the data

I'm currently working on a Java application that reads an Access file and builds a Jtable model using the data that's collected. I've previously done the same with an Excel file but when I tried with Jackcess it was slightly diffrent and I've ran into some questionmarks.
My work so far:
public class AccessModel{
public DefaultTableModel getAccessModel() throws IOException {
Database db = DatabaseBuilder.open(new File("MyFile.accdb"));
Vector<String> columnNames = new Vector<String>();
Vector<String> vector = new Vector<String>();
Vector<Vector<String>> data = new Vector<Vector<String>>();
StringBuilder output = new StringBuilder();
Table table = db.getTable("Table1");
for (Column column : table.getColumns()) { // get the table column names
output.append(column.getName());
output.append("\n");
columnNames.add(column.getName());
}
for (Column column : table.getColumns()) { // get the column rows and values
vector.add(column.getRowValue(table.getNextRow()).toString());
}
data.add(vector);
// return the model to Gui
DefaultTableModel accessModel = new DefaultTableModel(data, columnNames);
return accessModel;
}
}
As you can see this method will only iterate trough the first row, then exit the loop. I'm either blind to an abvious solution due to 12 hours of straight work, or I'm doing something terribly wrong.
I've stumbled across some half-good solutions where an Iterator is used, but I cannot get the hang of it. Any suggestions on this? Or should I stay on lane with my current line of thought?
JTable (value for view is stored in XxxTableModel, in your case is used DefaultTableModel) is row bases Object,
TableColumn (value is stored in TableColumnModel) to divide row(s) to the columns
you would need to create two Objects,
Vector<String> columnNames (is only one row) for columns identifiers from Table table = db.getTable("Table1");
loop inside Table table = db.getTable("Table1"); to fill two dimensional Vector<Vector<Object>> data = new Vector<Vector<Object>>(); by using Vector<Object> vector = new Vector<Object>();, notice 1st. code line insode loop must be vector = new Vector<Object>();, you have to create a new Vector otherwise you'll add the same rown_times, last code line should be data.add(vector)
.
everything (I'm still think so) is described in Oracle tutorial How to use Tables

Adding row to JTable using JCreator

I want to add rows in JTable, but it didn't work well. Could someone help me? Table is displaying normal but not dynamically
//displays all data in Jtable
void refresh()
{
Vector<Vector<String>> data = new Vector<>();
ResultSet rs = st.executeQuery("SELECT * FROM tblInfo");
while(rs.next())
{
Vector<String> d = new Vector<>();
d.add(rs.getString("ID"));
d.add(rs.getString("Name"));
d.add(rs.getString("User"));
d.add(rs.getString("Pass"));
data.add(d);
}
Vector<String> header = new Vector<>();
header.add("ID");
header.add("Name");
header.add("Username");
header.add("Password");
model = new DefaultTableModel(data, header);
table = new JTable(model);
st.close();
rs.close();
table.setBackground(Color.LIGHT_GRAY);
table.setForeground(Color.white);
scroll = new JScrollPane(table);
getContentPane().add(scroll);
st.close();
rs.close();
}
//adding data to database
void addDoctor()
{
st.executeUpdate("INSERT INTO tblInfo(Name) VALUES ('Name')");
st.close();
}
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
else if(btnAdd == source)
{
addDoctor();
refresh();
}
Thanks for any response. :)
I have edited this code before i've posted.
1) Don't create any Objects inside try - catch - finally block; for Swing GUI, prepare these Objects before, better as local variables.
2) You created a new
model = new DefaultTableModel(data, header);
table = new JTable(model);
and those Object maybe never added to the already visible GUI. Swing GUI doesn't care somehow, and the container doesn't know that you changed (reset, reinitialize) the underlaying model and with JTable. You have to notify Swing GUI for changes, but this isn't the proper of way.
3) Don't to recreate this Object on runtime, reuse Objects that already exist, create JTable and DefaultTableModel only one time.
4) Reset DefaultTableModel by using model.setRowCount(0); and then to add a new rows from JDBC
5) Don't to reinvent the wheel, search for ResultSetTableModel or TableFromDatabase.
6) Move code lines st.close(); & rs.close(); to the finally block.
Use DefaultTableModel.setDataVector() to add a new Vector with the new Data to the existing TableModel/JTable. Or use the insertRow/removeRow methods. Or implement your own AbstractTableModel.

need help on reset/clear jcombobox values

im using below coding to add values to a jcombobox using another jcombobox and i need to add the values to the jcombobox2 according to the one get selected in the jcombobox1 without appending values so can someone tell me a way to reset or clear the combo-box values when another option selected?
below is my coding and i'm new to java and netbeans so if someone can help i'll be grateful :)
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/database1", "root", "senura123");
Statement stat = (Statement) con.createStatement();
String val=jComboBox1.getSelectedItem().toString();
String check; String col;
if ("Vehicles".equals(val)){
check = "select reg_no from vehicle;";
col="reg_no";
}
else if ("Travel Guides".equals(val)){
check = "select username from travelguide;";
col="username";
}
else{
check = "select username from transportofficer";
col="username";
}
ResultSet rslt = stat.executeQuery(check);
while (rslt.next()) {
jComboBox2.addItem(rslt.getString(col));
}
}
See DefaultComboBoxModel.removeAllElements()
Empties the list.
Set a new model into your combobox:
final List<String> values = new ArrayList<String>();
while (rslt.next()) {
values.add(rslt.getString(col));
}
jComboBox2.setModel(new DefaultComboBoxModel(values.toArray()));
See DefaultComboBoxModel.
As a further comment, however, depending on how much latency is involved in your query, you may like to split this work up into EDT and background thread parts using SwingWorker.
Usually it happens because you have an event associated JComboBox. It is solved if you have control item in the JComboBox to act, for example:
jComboBoxExample.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
     do_run ();
   }
});
public void do_run() {
int n=jComboBoxPerfilDocumentos.getItemCount(); <--THIS IS THE SOLUTION
  if (n> 0) {
    String x = jComboBoxPerfilDocumentos.getSelectedItem (). ToString ();
  }
}

Categories