JTable that can save to a file - java

Does anyone know of a JTable based Swing component OR code example that can save to a file? i.e: provides a menu item or button that when clicked on prompts the user for a file location and saves the table's contents to a file (CSV, XLS, TXT, or whatever).
The easy part is looping through the rows and saving to a file. But there also needs to be a UI component ON the table itself that allows the user to initiate the save.

Write your own. All you do is use the table.getModel().getValueAt(...) method and loop through the rows and columns and then write the data to a file.

I have implemented this using the following approach:
Create an Action implementation: DelimitedExportAction. I typically add this action to a JToolBar, JMenuBar or JPopupMenu.
Expose a method void registerTable(JTable tbl). Internally this method adds a FocusListener to the JTable. When a given JTable gains focus set the tableToExport instance variable and enable the action.
When the actionPerformed(ActionEvent) method is called, invoke your export logic if tableToExport != null.
Rather than iterate over the TableModel I recommend iterating over the JTable, and for each row calling getValueAt(int, int) on the underlying TableModel, remembering to convert between view and model row / column indices. This is more intuitive to the end user as it means any sorting and filtering applied to the JTable is preserved during the export. (In my implementation I actually offer users the choice of exporting all data or visible data.)
Define a DelimitedExportFormatter whose role is to convert each object returned by getValueAt(int, int) to a String. Similar to when providing renderers to a JTable this class should permit you to provide a Format for a given Class or specific column, whereby a column specific format takes precedence. The default format applied to all other values should be: value == null ? "" : value.toString().
I allow the action to be configured in different modes (which also governs the action's icon):
Export to file: Launches a file chooser dialog allowing user to specify save destination.
Export to Excel: Saves the exported data as a temporary file and opens it within Excel.
Configurable export: Launches a dialog whereby the user can specify: row delimiter, field delimiter, columns to export, rows to export (all, visible, selected), save destination (Excel / File).
I'm afraid I can't provide the code as it is proprietary but hopefully this will put you on the right track. Good luck!

I recently created a very simple tutorial that exports data from JTable into excel file, using Tab-Separated Values(TSV) format. The application provides an Export button, which then triggers a dialog box (JFileChooser) to assist the user in specifying the file location/destination. I hope this helps somehow.
https://sites.google.com/site/teachmemrxymon/java/export-records-from-jtable-to-ms-excel

I don't know of any JTable-like Swing component that fulfills this exact need.
However, where would you expect the button to be placed on the table? In my opinion you would be better served by either adding the JTable to a JScrollPane and putting your "save" button on the JScrollPane or adding the JScrollPane to a JPanel and putting the "save" button on the JPanel. I don't see the logic behind having a button on the JTable itself.
If you want a menu item, you'd probably want to create the menubar and add the JTable to whatever container is holding the menubar. There's still no adding of a button to the table itself, mind you, but it would be the same thing visually.

Related

How to delete table row using jButton from another jFrame?

I am currently using FileWriter to write data into .txt tile.
Once I double click the row in the table, it links to another jFrame.
I wanted to set a button at the particular jFrame so that it is able to delete the row in the table. How can I perform the action?
Use the MVC (Model-View-Controller) paradigm.
Have a controller class, maybe containing the main method.
That holds the views (JFrame) and the data models (i.e. a DefaultTableModel).
That table model is passed to the table, which actually is also a listener to changes of the table model.
On button press let the button tell the controller that a row should be deleted.
This is done on the table model, and change events are fired. Automatically when using a DefaultTableModel. Or do it manually when using an AbstractTableModel.
MVC is not necessarily more direct, but there are not calls from one component to another components littered through the sources. It decouples things.
This can be done by adding a New button. Go into the codding of the button and add a simple sql statement saying to drop a row from the table And the another statement to show the table again by Select * from tablename;

How to auto refresh gui screen in java, after update taking place in a stored file?

I have a java swing application which reads the values for its components from a .text file. I'm trying to update one of its value and store it in .text file and then need a refresh possibly in the GUI screen as well. Value is modified in the file but GUI could not detect the change without a restart. I have went through repaint(), re-validate() with the use of timers. Can anyone specify what i could do? Thanks in advance.
A good solution to this would be to store all of your GUI components in an ArrayList or some other sort of List that you may prefer.
You would initially read the text file and add it's respective components into the list, and then you would load that list into your GUI. When the file is edited, you can loop through it again and if a component does not exists in the list you can add it in. If any components in the list don't correspond to the file you can remove them from the list. After that happens, you can reload the GUI with the components in the list.
You need to watch your file and fire an event if your file changes. This event must set the component values which will force the component to automatically refresh.

how can i programatically select a particular text from JTable when i do search in it?

here are the screenshots of the application
Rows will be displayed in the Table according to the text which is written in the search textfield.
Now i want to mark that particular text as per the shown in the second image with the yellow color
I know how to select a row or a particular cell.
but I don't know how to select a particular text inside the cell of any row in the table.
I am guessing you know how to search in JTable, so I am not pasting code of it here.
You can look over the SwingX library. It has this kind of function as you said predefined it it. You just need to add it to your table. This is where you can find it. Give it a try you will surely like it.
The basic premise would be to use a custom TableCellRenderer that provided the functionality that you require.
The problem is how to implement it.
I would create a TableCellRenderer based on a JTextField, remove it's border and make it transparent. This will allow you to use the text highlighting functionality provided by JTextCompoent to highlight portions of the text, as demonstrated here.
The next problem is then knowing what to highlight. There are a number of possibilities.
You could provide a method in your table model that could return the current text that should be highlighted.
I'd, personally, probably use the JTable#putClientProperty and JTable#getClientProperty methods to seed the search text.
Or, you could actually provide a simple model that directly to the renderer which had a method that returned the current search text. This might actually be more useful as you could link it to field, the method building the filter and the renderers and allow them to simply seed each other

2 column jcombobox

I had quite a lot use for a multicolumn jcombobox, but have not yet found any nor managed to make my own. I have tried several approaches found in web, but they have not worked. Afterwards I read somewhere that those (old) does not work under current Java version.
I have managed to make my own so far, that the combobox has a table as dropdown list and I can select an item with mouse, but the goal is that when the user starts to type into the edit box, drop down list opens and cursor moves based on the text the user has written. It seems that the events from e.g. JTextField editor = (JTextField) comboBox.getEditor().getEditorComponent() does not work.
Has anybody managed to make a two column combobox or have any ideas, how I could get the event when the user starts to type.
You are looking for autocomplete functionality (as I understand the question): it's supported in SwingX - and quite easy to use.
It boils down to implemneting a custom ObjectToStringConverter and configure the comboBox with an autoCompleteDecorator using that converter. Something like:
/**
* A converter which expects an item of an array type and returns
* a string representation of its first value.
*/
public static class ArrayToStringConverter extends ObjectToStringConverter {
#Override
public String getPreferredStringForItem(Object item) {
if (!(item instanceof Object[])) return DEFAULT_IMPLEMENTATION.getPreferredStringForItem(item);
Object[] array = (Object[]) item;
return DEFAULT_IMPLEMENTATION.getPreferredStringForItem(array[0]);
}
}
// usage
// assuming an model with items being arrays
JComboBox combo = new JComboBox(arrayModel);
// the renderer supporting multiple columns, f.i. a table
combo.setCellRenderer(new TabularListRenderer());
AutoCompleteDecorator.decorate(combo, new ArrayToStringConverter());
A complete working example (including the renderer and showing how-to force the width of the popup to be larger than the combo itself) is TableAsListRenderer in my incubator section
BTW: the autocomplete functionality is a standalone module, accessible via maven or manually downloadable from the maven rep at java.net, you would want the swingx-autocomplete-1.6.4.jar (plus the corresponding doc/sources, if interested)
Has anybody managed to make a two column combobox or have any ideas, how I could get the event when the user starts to type.
you can to put JTable to the JComboBox, but by default you can to select only value from entire JTables row, not directly from JTables Cell (required additional workaround, not tried yet)
i still searching for this answer too
here's i try so far..
i create Jpopup and put the Jtable in there..
then i use jlabel not jcombobox,
when user click jlabel, then the popup(Jtable) will show in that jlabel location..
when user select value on jtable,
then the popup will dispose,
then the jlabel will show the result..
for your case, you can use jtextfield not jlabel
EDIT :
heres related question
enter link description here

JTable Editor Change with Live Data

I have a table model that is populated by live (external) data source that updates every xx seconds. The data is displayed in a JTable.
The user can override the data in the table cell through an celleditor that extends the AbstractCellEditor. If the user clicks away, the code checks to see if the new value equals the value in the table model. If it doesn't, it assumes it's an override.
The problem is, say a you click on a field, don't change the value, and external data source updates the table model in the meantime, the code thinks the user set an override using the old value rather than just cancelling the override.
What is the standard logic and implementation to do this?
How do I detect whether a user has
made a change or not?
I made a class which I call TableCellListener that listens for changes made via a cell editor. It takes a copy of the value before the cell starts editing and compares it to the value of the cell after it stops editing. It sounds like it might be what you want.
Another solution might be to check if the table is currently editing the cell before you update the TableModel in the background. Maybe you popup a dialog giving the user a chance to accept the update or cancel it.
Your table model should maintain state that indicates if a table cell was overriden on a cell-by-bell basis. If you dont do that, you will also run into the problem where a user has overriden a cell and the live data comes in and changes to the same value that the use has put in. You will then cancel that override.
You can populate this state in an overriden setValueAt(Object,int,int) method in your TableModel. This method will get called by the JTable when your AbstractCellEditor finished editing.

Categories

Resources