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
Related
I am trying to recreate this "TreeGridWithCheckBoxFieldsExample" from the natTableExamples, and I wanted the first column editable, not only the Checkbox but also the Text it contains.
But when I register for TextCellEditor I am not able to set the CheckBox value by clicking it, if I click on CheckBox it goes to edit mode for the text beside it because of the MouseEditAction() in the below code.
uiBindingRegistry.registerFirstSingleClickBinding(
new CellPainterMouseEventMatcher(
GridRegion.BODY,
MouseEventMatcher.LEFT_BUTTON,
checkBoxPainter),
new MouseEditAction());
But if I remove it I won't be able to select the CheckBox, and because of DefaultBooleanDisplayConverter in the below code, the text after editing is not getting edited because the dataValue it gets is of boolean type .
configRegistry.registerConfigAttribute(
CellConfigAttributes.DISPLAY_CONVERTER,
new DefaultBooleanDisplayConverter(),
DisplayMode.NORMAL,
TreeLayer.TREE_COLUMN_CELL);
Thanks.
This is afaik not supported out of the box. Converters and editors are registered per column/cell. Mixing two editors and converters in one column/cell for two different properties of one row object is nothing to achieve easily. You will need to implement custom mechanisms to achieve that.
Hello :) I need help with changing a JComboBox in a JTable. I'm new to GUI-Programming and Swing and couldn't solve this problem: I have to change the behavior of a JComboBox.
You can see the ComboBox in the picture below. If "Ja" is selected there should just be "Nein" as an option and the other way around. It would also be cool if "Nein" is set per default. The code was written from one student from last semester and I have difficulties to adjust the combobox like I have to.
That's the code snippet where the ComboBox gets initialized.
optionsInteger = new JComboBox<String>();
optionsInteger.addItem("Ja");
optionsInteger.addItem("Nein");
optionsInteger.setSelectedItem(optionsInteger.getItemAt(0));
optionsInteger.setSelectedIndex(1);
optionsInteger.setName("optionsInteger");
The ComboBox gets inserted to a JTable in this method:
public void repaintXTable(DefaultTableModel model,JTable table, int xAmount, JScrollPane scrollPane,
JComboBox<String> optionsInteger) {
model.setRowCount(xAmount);
th = table.getTableHeader();
tcm = th.getColumnModel();
tcs = tcm.getColumns();
tcs.nextElement().setHeaderValue("");
tcs.nextElement().setHeaderValue("Lower");
tcs.nextElement().setHeaderValue("Upper");
tc = tcs.nextElement();
tc.setHeaderValue("Integer");
tc.setCellEditor(new DefaultCellEditor(optionsInteger));
for(int i=0;i<xAmount;i++)
{
model.setValueAt("X"+(i+1), i, 0);
}
}
Thank you very much for your help.
In your code, this line
optionsInteger.setSelectedItem(optionsInteger.getItemAt(0));
sets the default selection to the zeroth element (Ja). This line
optionsInteger.setSelectedIndex(1);
sets the default selection to the first element (Nein).
Either set the selected item or the selected index. There's no need to do both.
A JComboBox does not remove the selected element by default. If the selected element is removed, how would the selected element display in your JTable?
If you really want to do this, you'll have to create your own version of a JComboBox.
. If "Ja" is selected there should just be "Nein" as an option and the other way around.
So then you need two separate ComboBoxModels, one model containing "Nein" and the other containing "Ja". Then when you start to edit the cell you check the current value and use the model containing the other value.
Check out How to add unique JComboBoxes to a column in a JTable (Java). This example shows how you can dynamically change the model at the time the cell is about to be edited.
It would also be cool if "Nein" is set per default.
This has nothing to do with the editor. You just add "Nein" to the TableModel when you add the data to the model.
I am working on an application that uses a TableView and has a Table Menu Button to add or remove columns from the list.
Since I wanted my column headers to have tooltips, I had no choice but to create a label and use it in the following manner in :
// Some code here
TableColumn col;
// some code here
col.setGraphic(header_title);
The problem with this is that when the program runs, the table menu button shows a list of empty text:
On the other hand when I do:
// Some code here
TableColumn col;
// some code here
col.setText(rs.getString("column_title"));
col.setGraphic(header_title);
I can see the text on the column menu, but the actual titles are appended to the graphic:
I have tried to look for a way to perform a setContentDisplay(GRAPHIC_ONLY), but this does not seem to exist for TableColumn, and I am not sure how to access the header node in order to set this setting.
Any help would be greatly appreciated.
Just forget about the inbuilt table menu button. It's absolutely minimal and not worth mentioning. If you e. g. want to click away 10 columns you have to click on the button, hide the column, click on the button, hide the column, etc. In other words: It closes as soon as you press a menu item.
You can't even extend it with e. g. a hide all and a show all button. And it's buggy: When the last column gets hidden, the menu button vanishes as well, so you have to restart your application if you want to see anything in your table again.
Just create your own table menu. There are 2 examples on this gist:
example which uses a lookup, i. e. works without reflection
example which uses reflection
Then you can adapt whatever header you want and whatever menu items you want.
I'm trying to set the number of options shown in the JComboBox drop down list when it is used as a JTable RowFilter. Specifically, the filter on occasion can have many options and I'd like to show twice as many as the default (which appears to be 8). See this image:
Combox Box Example http://aalto.tv/test/combobox-image.png
As you can hopefully see, this ComboBox only shows 8 items and I would like to show more if there are more to be seen.
Having searched around the popular solution is to call "setMaximumRowCount" on the JComboBox, however this is having no effect.
Can any one point me in the right direction?
Many thanks for any and all help!
Cheers,
Alex
try the revalidate() (or repaint()) method after setting the rowcount;
if a setXX method does not generate an event to the component, then you have to manually reset it.
failing that, look at the source code of the setMaximumRowCount() method
JComboBox#setMaximumRowCount works for JTable / TableHeader and AutoComplete JComboBox in the JTable too
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.