Understanding JComboBoxModel - java

I am getting what, to me, seems like odd behavior. I've created createComboBoxModel. I then create 2 new JComboBoxes and add the model to each as ComboBoxDefaultModel. Although the combo boxes are different instances, using the model seems to somehow tie the 2 together. When I make a selection in one combobox it forces the same selection in the other combobox as well. Is this the way it is supposed to behave and if so why? If not then do I have some kind of coding error that causes this behavior? TIA.

Related

JList and ListCellEditor?

I have a Swing application that shows a list of complex objects to the user. These are nicely rendered using a ListCellRender, which fills a JPanel with more UI controls. Obviously editing does not work and the components are not enabled to accept input.
Now I want the user to be able to edit the entries. Basically you could think of in-place editing. I tried to simply enable the panel that renders the list entries - but it does not work. What else could/should I do to have an editable list?
So basically the answer is to favour JTable over JList. For anyone questioning that, the JTable can be configured to show one column only, and the difference would not be visible to the user.
Programming wise JTable is more complex and thus justifies that JList is used in simple cases (only one columne, no editing required).

JavaFX ChoiceBox EventHandling

I'm trying to detect ChoiceBox item selection. I read this post and I know that it is possible to do, this way:
choiceBoxObject.getSelectionModel().selectedIndexProperty().addListener(myChangeListenerObject)
also I saw this sentence in Documentation for ChoiceBox class which confirms code above:
ChoiceBox item selection is handled by SelectionModel As with ListView
and ComboBox
Another solution came to my mind and I was wondering is there anything wrong with it? why nobody mentioned this way? What is the difference between these two approaches?
choiceBoxObject.valueProperty().addListener(myChangeListenerObject);
There's nothing wrong with using the valueProperty, and in fact for simply reacting to changes in the selected value, it's probably the preferred solution.
The documentation is just indicating that there is a complete SelectionModel underlying the selection of items. This has a far richer API than simply knowing what is selected: there are selectNext(), selectFirst() methods, etc etc. So if you needed to programmatically change the selection there is a rich API available. As also pointed out in the documentation, you can even replace the selection model with a different implementation, though use cases for this are likely to be (very) rare.

Swing JTable custom rendering

I have this kind of progamming task without JavaFx, instead it's Java Swing. I realized my knowledge is still limited.
I have one single JTable.
But, within this JTable I need a custome Cell Renderer.
The goal is to make this kind of JTable: Example image
My current solutions are: Example Image
Create a Single JTable:
get each Column and set its CellRenderer with a custom Renderer (below).
Create a new Class implements TableCellRenderer:
return different JPanel inside getTableCellRendererComponent
method using switch case (as column counted).
After hours, and hours, I think my current solutions is quite daunting tasks. Thus, My question is:
What are the simplest method of creating this Custom JTable to achieve the main goal as mentioned above?
you have two options
1) JPanel nested another JComponents and solve that by using standard LayoutManagers note scrolling isn't natural nor nice
2) JTable with JPanel can solve that, notice about scrolling inner JScrollPane inside another JScrollPane
I've been facing this problem for a while, and I decided to do it myself. Extending the existing implementation of a table, adding some concepts for what I expect from a table, and writting some editors/listeners for that. All the same, but with a treetable.
I'm working on this project called SUMI.
It contains a java package (ar.com.tellapic.sumi.treetable) that is an extension of a JXTreeTable from SwingLabs.
The project is being developed and I didn't provide any documentation yet. You can do what you want by creating a renderer and if needed, an editor, for lastly attaching actions to each object.
If you decide to use it and you need help, email me, I'll help you without any problem.
Or, you could read the source by your own.
Regards,
EDITED (again):
To clear a little bit this answer, I've just created a wiki page in the project wiki and put the relevant code there. If someone feels that the code should be inserted here, please let me know.
Basically, I try to explain how to find a straight solution to the renderer/editor problems you may find using JTable with your specifics needs by using part of my project, in order to get something like this:
Note that the screenshot was taken after clicking on the respective tick-button.
Once you create a nested panel for one row, as suggested by #mKorbel, you can add any number of them to a GridLayout(0, 1) in a JScrollPane. If rendering many rows becomes an issue, you can adopt the same approach used by JTable, illustrated here.
Even though, JTable can be customized to whatever you desire through cell renderer and cell editors, it is never preferred because you have to do a lot of messy codings for that. Instead, for your problem, I suggest to use JScrollPane and add your component (view panel as your sample jTable ) to its viewPort.
For this implementation, represent each rows with your custom class that extends JPanel. And add the required row components (that may be any components like jlabel, jtextfields or even jpanel too) in it. For the simplicity, you can use null layout for the row panel and add the components at any location you want.
I hope this will help you workout with your problem. If you got any problem in this implementation, feel free you ask again.

Java Swing Threading Problem

so here's the problem. I have a JDialog box that consists of 3 combo boxes, a text field, a few buttons and a JTable. The JTable information is filtered based on the text field and combo boxes, so for instance it starts with all of the data and gets shrunk down to only the data that starts with any string value the user decides.
What's happening though is that while the values filter correctly, if I click in the JTable (in the white space, where there are no rows) then the rows that were deleted show up, like they were invisible until I clicked on them. I've tried almost everything:
I've tried re-creating the table every time filter is clicked (bad hack that didn't even work), I've called all of the repaint, revalidate, firechanged methods, I rewrote the dialog from scratch to make sure I didn't do any stupid mistakes (if I made one I didn't find it at least), and I've tried putting them on separate threads. The only fix I haven't tried is using a swing worker, but that's because my filtering was a little too complicated for me to figure out what goes where and how to extend the swing worker correctly. The GUI is generated by netbeans (bleh), and has worked in my other dozen or so JDialogs just fine (perfectly in fact). Here's the method that doest the filtering, if any of you can help it would be greatly appreciated.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
nameFilter = "task1";
javax.swing.table.DefaultTableModel dm = (javax.swing.table.DefaultTableModel)jTable1.getModel();
tempParameters = parameters;
String currentString;
int rowNumber = 0;
while (dm.getRowCount()>rowNumber){
currentString = (String)(jTable1.getValueAt(rowNumber,1));
if(!nameFilter.equalsIgnoreCase(currentString.substring(0,nameFilter.length()))){
dm.removeRow(rowNumber);
parameters--;
}
else rowNumber++;
}
parameters = numOfRows;
}
Update, I also implemented the filter from the comment below, and while it filtered out the correct data, it had the exact same problem. In the future I will probably use this filter feature though, so thanks.
Another update, the code is still failing even after removing everything but this chunk, and all (at least I believe..) I am doing here is doing a simple remove row call. Hope this helps a bit.
Have you tried creating a new Model every time you want to filter, instead of clearing it by deleting rows? Create new model, copy relevant rows to new Model, set new Model in table. Really shouldn't be necessary, but it might be a quick fix.
Also, I really have to wonder why you're calling toLowerCase on two strings when you're using equalsIgnoreCase to compare them.
So long as this method is called from the EDT I don't think there would be a threading problem. Try using
SwingUtilties.isEventDispatchThread()
to make sure.
If you look at the API for DefaultTableModel, updates are being sent to your JTable which will repaint itself, so I don't think that is the problem.
I would guess that it is a logic problem. If you can extract the logic into separate methods it will be easier to test and verify whether it is updating the model as you expect.
Couple of observations:
If the filter happens to be larger than the string content of the row, it'll throw in the substring call
Calling the dm.removerow is generating a bunch of tablerowsdeleted events.
You're asking for a rowcount from the model, yet are getting the value through the table (a little inconsistent, if the model gets wrapped around another model you might be acting upon different rows), so instead of jtable1.getvalueat, use the dm.getvalueat.
I think what might be happening is that as the events get fired I see there are repaint and revalidate events fired in the JTable, these can be trampling over each other as they get enqueued in the EDT.
What I would suggest is to create a new datamodel, add the rows that you want to keep, and then reassign it to your jTable1.setModel(newDm);
Also to watch for is if someone else is modifying the model while you're in your eventlistener.
Hope this helps

GUI program, problem with tabbedpanes

I am creating a GUI program using MVC which should look like this..
alt text http://img137.imageshack.us/img137/6422/93381955.jpg
I have created a Window and Panel class. I am thinking of creating the Input and Display tabs in the Panel class and then creating two more classes, InputPanel and DisplayPanel. So the InputPanel will contain the stuff in this picture under the Input tab and same for the Display tab. Is there a better way to design this?
Also, since there are 3 sections in the Input tab (Name and sentence, crime, button), should I create 3 panels or just 1 panel containing all those?
Thanks
To answer your specific question about using three panels instead of 1, I would suggest two. There's rarely a need to create a panel just to create a single widget. So, one widget for the name and sentence, one for the crime.
As for the question about "is there a better way to design this"?... It sounds like you are learning, so I suggest you don't focus too much on the perfect way to do it. Stick with your original design then after the task is done ask yourself what worked* and what didn't. With that information you'll be able to decide for yourself whether what you did was the right design.
There usually isn't a "best" when designing GUI code -- there are many ways to solve the problem. What you've described sounds like a perfectly good way to attack the problem
(*) "worked" in this context means, was it easy to code? Did it allow you to achieve the layout you desired? Does it make the code maintainable over time if, for example, a requirement comes down to reorganize the GUI?.
Bryan gave good advices, I will just add that ergonomics isn't an exact science, although experience helps there.
Tabs are nice, eg. to separate settings, or group in a same panel (toolbox for example) different sets of tools (layers, colors, brushes...).
But they might not be adapted to all workflows. But we are lacking information about the role of the Display tab. Is it supposed to list all crimes in a table? Can't the table, if any, be below the controls?
As hinted by Bryan, it is better to design the GUI, then to test it, like would do a real user. Do you find the workflow easy to understand? (make somebody else to test it!) Does the usage feels natural? Is it fast to use?
Then you can adjust the design in light of these observations.
You were right to create InputPanel and DisplayPanel as seperate classes.
As for further splitting those panels? Yes you should further split them up, but not into separate classes. You should add jPanels inside of your InputPanel, and DisplayPanel, and group the controls within those internal jPanels.
Please let me know if you would like me to clarify what I mean.

Categories