Send 2D Array to JTable - java

I am using swing and java in Eclipse to send data to JTable from a 2D Array
String [][] row = {{"iphone"},{"34567"}};
I have a 2D array. I am wanting to display it in JTable using eclipse.
The JTable will have to header like "Phone" and "Price" and the Jtable gets filled by the click of a button.
String[] columns = {"Phone","Price"};
Can some please help me to get it displayed in JTable

DefaultTableModel model = new DefaultTableModel(new Object[]{"Column1", "Column2"})
JTable table = new JTable(model);
To add a row:
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(new Object[]{"iPhone", "73567",});
Placing the above code inside the action performed of the button.
public void actionPerformed(ActionEvent e)
{
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(new Object[]{"iphone", "73576"});
}

Related

Appending a new row to a JTable at runtime

I am developing a Java application that uses a JTable. I want to allow the user to enter data in a JTable that can later be printed or saved. The issues is: Suppose the user has entered some data and the cursor is on the last cell of the row in a table (I have uploaded an image-suppose the cursor is on the highlighted cell).How do I make it in such a way that when a user presses the Enter Button(Keyboard button) the application will add/append a new row that is empty to the table so that the user can fill in other data.
Attachment
Try this...
JTable table = new JTable();
DefaultTableModel tblModel = new DefautlTableModel(0,0);
table.setModel(tblModel);
//an action or click then you should run this code
tblModel.addRow(new Object[]{""});
DefaultTableModel tbm = (DefaultTableModel) jTable1.getModel();
Vector rowData = null;
tbm.addRow(rowData);

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...

Insert row on jtable with DefaulTableModel on different methods

i want to add or insert column from different methods into one table.. cant explain it clearly but i show my codes to you to understand..for example.
(....)
DefaultTableModel dtm = new DefaultTableModel();
JTable table = new JTable();
Constructor(){
table.setModel(dtm);
(.....)
}
public void methodOne(){
String id = num.getText();
rs = stat.executeQuery("SELECT * FROM payments;");
Vector<String> header = new Vector<String>();
header.add("PAYMENT");
header.add("AMOUNT");
header.add("MODIFIER");
header.add("DATE MODIFIED");
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while(rs.next()) {
Vector<Object> row = new Vector<Object>();
row.add(rs.getString("description"));
row.add(rs.getString("amount"));
row.add(rs.getString("remarks"));
row.add(rs.getString("date"));
data.add(row);
} // loop
dtm.setDataVector(data , header);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(0,0,490,250);
panel.add(scrollPane);
validate();
}
public void methodTwo(){
(.....)
rs = stat.executeQuery("SELECT * FROM record where idNum ='"+id+"';");
while(rs.next()){
Vector<Object> row = new Vector<Object>();
row.add(rs.getString("description"));
row.add(rs.getString("amount"));
row.add(rs.getString("remarks"));
row.add(rs.getString("date"));
data.add(row);
} // while
}
those value inside row are the value i want to add on my table, i dont have any idea on how to id.. i want it to be like this:
first when you run the java it will autoumatically create a table
http://i1023.photobucket.com/albums/af355/guiacustodio/javaaaaaaaaaaaaaaaaaaaaaaa_zpse9a22225.jpg
i have a button and textfield i enter number on the textfield i.e
[PAY BUTTON] TextField:[__100]
i clicked the button and this is what will happen:
http://i1023.photobucket.com/albums/af355/guiacustodio/javaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_zps43879eab.jpg
First of all, the data Vector you are using is defined inside methodOne so the same data is not accesible via methodTwo.
Secondly it is not because there is data being added to data in a tablemodel that the table will refresh, you have to call one of the methods that trigger an refresh event in the gui, normally one calls the method fireTableChanged on the tablemodel after you added data.
Thridly: there is an interesting library called GlazedLists that handles a lot of these things automatically !

Populate a jTable from an ArrayList

I'm trying to populate a JTable from an ArrayList, The ArrayList is filled with data from my database.
this is the code I tried :
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(new String[]{"Numéro d'ordre", "Article", "Quantité", "Remarque"});
for (gestionstock.LigneBonInterne o : listLigneBonInterne) {
model.addRow(new String[]{o.getNumOrder().toString(), o.getdesgArt(), o.getQte().toString(), o.getRemarque()});
System.out.println(o.toString());
}
jTable1.setModel(model);
But I get this error message :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at magasinier.BonInterneDetails.(BonInterneDetails.java:63)
the ligne 63 is : jTable1.setModel(model);
I did a test to see if the ArrayList is filled, and I found that the ArrayList is filled with records which means that there is no problem with filling the ArrayList
How can I solve this problem ?
EDIT :
I tried to create the JTable using code and assign it to ScrollPane :
JTable jTable1 = new JTable(model);
jTable1.setModel(model);
jScrollPane1.setViewportView(jTable1);
But I still get the same error this time is the line : jScrollPane1.setViewportView(jTable1);
Initialize the JTable jTable1 prior to setting the TableModel
jTable1 = new JTable(model);
jTable1.setModel(model);
In Netbeans palette you can specify some custom post-initialization code or use a custom constructor.

Dynamically add images to JTable cells

I am dynamically adding data to a cell with the following code:
for(int i = 0; i < matchedSlots.size(); i++)
{
String title = matchedSlots.get(i).getTitle();
String director = matchedSlots.get(i).getDirector();
int rating = matchedSlots.get(i).getRating();
int runTime = matchedSlots.get(i).getRunningTime();
DefaultTableModel tm = (DefaultTableModel) searchResults.getModel();
tm.addRow(new Object[] {title,director,rating,runTime});
}
what do I need to add to the above to be able to add an image in the first cell of each row
By default JTable can render Images. You just need to override getColumnClass() in the TableModel and return Icon.class for 1st column.
Look at Renderers and Editors for more details.
ImageIcon image = new ImageIcon("image.gif");
...
tm.addRow(new Object[] {image,title,director,rating,runTime});
You may need to change your table model to account for the new column if you haven't already.
This short article should help you with the image renderer: http://mdsaputra.wordpress.com/2011/06/13/swing-hack-show-image-in-jtable/

Categories