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...
Related
I would like to get value from cell when its is no submitted (cell is in edit mode) - "real time"; Is it possible?
I tried this but it is working only if i submit data - press enter
int row = jTable.getSelectedRow();
int col = jTable.getSelectedColumn();
String cellValue = jTable.getValueAt(row, col).toString();
I want to get on keypress cell value without exiting it, get this text real time while typing
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
#Override
public boolean dispatchKeyEvent(KeyEvent e) {
int row = jTable.getSelectedRow();
int col = jTable.getSelectedColumn();
if (e.getID() == KeyEvent.KEY_RELEASED) {
if (jTable.isEditing())
jTable.getCellEditor().stopCellEditing();
String cellValue = (jTable.getValueAt(row, col)!=null) ? jTable.getValueAt(row, col).toString() : "";
System.out.println(cellValue);
}}
jTable.getCellEditor().stopCellEditing() - cause ugly in/out animation while typing
#camickr Sorry for the confusion. Your solution is ok.
I just needed to add jTable.editCellAt(row, col); to get back into edit mode.
Thanks again
cell is in edit mode
The editing must be stopped before the value is saved to the model.
The easiest way to do this is to use:
JTable table = new JTable(...);
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
when you create the table.
Now when you click on the button to do your processing the table loses focus so the data is saved.
Check out Table Stop Editing for more information.
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"});
}
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.
I have a small Java swingui app where I display a JList and the user is able to cut, copy, paste and sort the list.
I use a custom TransferHandler to allow drag and drop on this Jlist. Here is the code in building the JList, it basically builds it from an ArrayList. "lstScripts" is the JList.
ListTransferHandler lh = new ListTransferHandler();
...
DefaultListModel listModelScripts = new DefaultListModel();
for(Script s : scripts) {
listModelScripts.addElement(s.getName());
}
this.lstScripts = new JList(listModelScripts);
this.lstScripts.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
this.lstScripts.addListSelectionListener(this);
JScrollPane sp = new JScrollPane(this.lstScripts);
sp.setPreferredSize(new Dimension(400,100));
this.lstScripts.setDragEnabled(true);
this.lstScripts.setTransferHandler(lh);
this.lstScripts.setDropMode(DropMode.ON_OR_INSERT);
setMappings(this.lstScripts);
...
On my custom TransferHandler class, I've got the importData routine working so that it handles the copy/paste/cut/sort.
public boolean importData(TransferHandler.TransferSupport info) {
String scriptname = null; // The script name on the list
//If we can't handle the import, bail now.
if (!canImport(info)) {
return false;
}
JList list = (JList)info.getComponent();
DefaultListModel model = (DefaultListModel)list.getModel();
//Fetch the scriptname -- bail if this fails
try {
scriptname = (String)info.getTransferable().getTransferData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException ufe) {
System.out.println("importData: unsupported data flavor");
return false;
} catch (IOException ioe) {
System.out.println("importData: I/O exception");
return false;
}
if (info.isDrop()) { //This is a drop
JList.DropLocation dl = (JList.DropLocation)info.getDropLocation();
int index = dl.getIndex();
model.add(index, scriptname);
return true;
} else { //This is a paste
int index = list.getSelectedIndex();
// if there is a valid selection,
// insert scriptname after the selection
if (index >= 0) {
model.add(list.getSelectedIndex()+1, scriptname);
// else append to the end of the list
} else {
model.addElement(scriptname);
}
return true;
}
}
So up to here, everything works fine as far as the GUI. But my problem is I need the original JList "lstScripts" to be automatically updated with the user GUI changes. For example, if the user cuts or reorders the list, I want it to show on in "lstScripts".
I'm not seeing how to make this connection between the TransferHandler and original GUI controller where "lstScripts" resides.
#kleopatra - you helped me! sorry I didnt understand how the model was working.
So in the controller, I create the "lstScripts" JList and add it to my panel (this is the first block of my code above).
pnlScripts.add(lstScripts, BorderLayout.WEST);
And as my code above showed, the listScripts JList had a custom transferhandler set as such:
this.lstScripts.setTransferHandler(lh);
So the transferhandler does all the user dnd (drag and drop) stuff. In the controller, I can get the updated list by doing:
DefaultListModel model = (DefaultListModel)lstScripts.getModel();
for (int i = 0; i < model.getSize(); i++){
scriptnames += model.getElementAt(i).toString() + ",";
}
The scriptnames String variable now contains the updated list.
Thanks!
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/