I have a problem with my JComboBox.
description:
I create a new file by writing the name of my file in a Textfield. By clicking on a button I create a file with this value and add this into my JComboBox, but I only see the Object value, for example "[Ljava.io.FIle;#1b1428d" and that's the problem. The user doesn't even know what this value means so I need my filename. I searched for a long time and Yes the toString() doesn't work :D
My Code looks like this: JComboBox TxtDoc = new JComboBox(create());
public File[] create(){
FileSystemView SYSTEM = FileSystemView.getFileSystemView();
String user = System.getProperty("user.home")+"\\notes";
File userdir = new File(user);
File[] fileList = SYSTEM.getFiles(userdir, true);
return fileList;
}
newTxt.addMouseListener(new MouseAdapter() {
#SuppressWarnings("unchecked")
public void mouseClicked(MouseEvent event){
new Documents().createTxtDoc(); // <-- this just open a new frame with my textfield and a button.
TxtDoc.addItem(create());
}
});
thank you for your help
regards Blank
iterate over it:
for (File f : fileList) {
TxtDoc.addItem(f);
}
You're add an array Files as a single element of the combobox (that's what addItem does, adds A (single) item)
There's a few ways you might be able to do this, one might be to simply reset the combo box's model...
TxtDoc.setModel(new DefaultComboBoxModel(create());
This has the the nice side effect of removing all the previous elements first
Having said that, you might not like the results...
You may want to consider providing a custom cell render to render just the name of the file. See How to Use Combo Boxes and Concepts: Editors and Renderers for more details
Related
I have a long List of Checkboxes (about 150) on a JPanel on a scrollPane, the user can check if needed. At the end of this Process there is a JButton, which should take all the marked Checkboxes and put their description on a different JPanel. I am pretty new to Java and can't figure out, how to do this without creating an itemListener for every Checkbox, which just seems very unpractical. I've read a lot of threads about putting the Checkboxes into an ArrayList and checking the elements, but I still don't understand how to do this. My Current Code looks something like this:
JCheckBox checkbx511 = new JCheckBox("This is the text I need");
chckbx511.setToolTipText("<html>This would be a nice bonus</html>");
Anybody know an easy way to get all the selected Elements on a new List?
You should put the descriptions for the checkboxes in an array and then create a list of check boxes, something like this:
// Creating checkboxes
String[] descriptions = { "Description 1", "Description 2", "Description 3"};
List<JCheckBox> checkBoxes = new ArrayList<JCheckBox>();
for (String description : descriptions) {
JCheckBox checkBox = new JCheckBox(description);
checkBoxes.add(checkBox);
jPanel.add(checkBox);
}
Then when you press the button you simply iterate over the list of checkboxes to find out what boxes are selected and add them to your new panel.
// On button press
for (JCheckBox checkBox : checkBoxes) {
if (checkBox.isSelected()) {
otherJPanel.add(new JLabel(checkBox.getText()));
}
}
You should first create a List
List<JCheckBox> list = new ArrayList<>();
Then, you need to store those checkbox into this list. You either add every one by and
list.add(checkbx511);
or change the way you build those to use a loop (the text could be in a String[] to iterate this)
Then, to get the selected checkbox, you just need to iterate your new list and check if it is selected with CheckBox.isSelected(). You store those instance into a other List and you have your result.
List<JCheckBox> resultList = new ArrayList<>();
for(JCheckBox cb : list){
if(cb.isSelected()){
resultList.add(cb);
}
}
Note : There is a way to do this in Stream API but I will let someone else to write it because I don't know it enough.
Note 2 : There is a complicated way without using a List by searching into a JPanel componenent every JCheckBox instance. But this needs a know structure to be written
In my application, I need to display file system files in a JTable. When I click on the JTree node (which is any system folder), the contents of that folder are shown in the JTable.
In the first column of the JTable (where the name of the file or folder icon is shown), the icon is fetched from the system icon and is displayed.
Every thing is working fine. However, the problem is that when the renderer renders icon, the icon of the first file (first row of JTable) is repeated in all rows. I mean the icon does not change in the subsequent rows of the JTable. Here my code is in which a render gets icon and the model displays it in the JTable
class KeyIconCellRenderer extends DefaultTableCellRenderer {
public KeyIconCellRenderer(String ext) {
File file = new File(ext);
Icon icon = FileSystemView.getFileSystemView().getSystemIcon(file);
setIcon(icon);
}
}
and here is code where I am using render to display
private class Selection implements TreeSelectionListener {
public void valueChanged(TreeSelectionEvent e) {
Object[] myData= new Object[6];
TreePath path = e.getPath();
FileUtil util= new FileUtil();
FileMetaData metaData;
Vector<FileMetaData> vList = new Vector<FileMetaData>();
DefaultMutableTreeNode node = (DefaultMutableTreeNode)treeMainView.getLastSelectedPathComponent();
FileInfo info =(FileInfo)node.getUserObject();
File filePath= info.getFilepath();
vList=util.getChildList(filePath);
dtModel.getDataVector().removeAllElements();
for(int i=0;i<vList.size(); i++){
Vector v= new Vector();
metaData=(FileMetaData)vList.get(i);
v.add(metaData.getName());
tblMainView.getColumnModel().getColumn(0).setCellRenderer(new KeyIconCellRenderer(metaData.getClientpath()));
v.add(metaData.getClientpath());
if(metaData.isDirectory()){
v.add("");
}else
{
v.add((FileHelper.getSizeString(metaData.getSize())));
}
if(metaData.isDirectory()){
v.add("");
}else
{
v.add(new Date(metaData.getTime()));
}
if(metaData.isDirectory()){
v.add("Folder");
}else
{
v.add("File");
}
v.add("Pending Upload");
dtModel.insertRow(0, v);
}
tblMainView.repaint();
}
}
as in the attached image, only the icon of the fist file is repeated in all rows,
Please help, it will be a huge favor,
Thanks
[Your surface mistake is to reset the table column's renderer in the loop, each time hard-coding the current icon in the the renderer's constructor. Consequently, the file-icon is used for all.
The basic problem is that you don't seem to fully understand the concept of a renderer: it's there to display the cell data as it is delivered as a parameter in its getXXCellRendererComponent. So that's the place to look-up the icon to use. The way to go is to store the File object in the table cell and query the appropriate icon every time the method is called.
Cheers
Jeanette
I'm very new to Java and am having some issues looping through JCheckBoxes on a UI. The idea is that I have a bunch of checkboxes (not in a group because more than one can be selected.) When I click a JButton, I want to build a string containing the text from each selected checkbox. The issue I'm having is that our instructor told us that the checkboxes need to be created via a method, which means (see code below) that there isn't a discrete instance name for each checkbox. If there were, I could say something like
if(checkBox1.isSelected()) {
myString.append(checkBox.getText());
}
That would repeat for checkBox2, checkBox3, and so on. But the method provided to us for adding checkboxes to a panel looks like this:
public class CheckBoxPanel extends JPanel {
private static final long serialVersionUID = 1L;
public CheckBoxPanel(String title, String... options) {
setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(), title));
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
// make one checkbox for each option
for (String option : options) {
JCheckBox b = new JCheckBox(option);
b.setActionCommand(option);
add(b);
}
}
}
This is called like this:
toppingPanel = new CheckBoxPanel("Each Topping $1.50", "Tomato", "Green Pepper",
"Black Olives", "Mushrooms", "Extra Cheese",
"Pepperoni", "Sausage");
So I now have a panel that contains a border with the title "Each Topping $1.50", and 7 visible checkboxes. What I need to do is get a list of all the selected toppings. We are not supposed to use an ActionListener for each checkbox, but rather get the list when a button is clicked. I'm feeling really clueless here, but I just can't figure out how to get the isSelected property of the checkboxes when the individual checkboxes don't have instance names.
Ideally I'd like to somehow add all the checkboxes to an array and loop through the array in the button's action listener to determine which ones are checked, but if I have to check each one individually I will. I just can't figure out how to refer to an individual checkbox when they've been created dynamically.
I'm assuming you're not allowed to alter the CheckBoxPanel code at all. Which seems like a useless exercise, because in the real world, you'd think that if CheckBoxPanel where a class being provided to you (e.g. in a library) it would include a way of getting the selected options. Anyway, due to the limitation, you could do something like this:
for( int i=0; i<checkBoxPanel.getComponentCount(); i++ ) {
JCheckBox checkBox = (JCheckBox)checkBoxPanel.getComponent( i );
if( checkBox.isSelected() ) {
String option = checkBox.getText();
// append text, etc
}
}
I suggest you maintain a list of checkboxes:
List<JCheckBox> checkboxes = new ArrayList<JCheckBox>();
and before add(b) do:
checkboxes.add(b);
You may then iterate through the list of checkboxes in the buttons action-code using a "for-each" loop construct:
for (JCheckBox cb : checkboxes)
if (cb.isSelected())
process(cb.getText()); // or whatever.
Alternatively, if you need to keep track of the specific index:
for (int i = 0; i < checkboxes.size(); i++)
if (checkboxes.get(i).isSelected())
....
I would suggest that you dont put each of the checkboxes in a List when you create them. Instead, in your shared ActionListener, you maintain a Set of all selected checkboxes. Use the getSource method on the ActionEvent to identify which checkbox the user selected and then cast it to a JCheckBox. If isSelected() returns true for the item in question, attempt to add it to your selectedItems Set. If it is not, then attempt to remove it.
You can then just iterate over the subset of all items (only those that are selected) and print them to the console.
I have generated a GUI from netbeans in which I have placed a combobox too.
By default, the items in combobox are item1, item2, item3, item4.
But I want my own items. Netbeans doesn't allow editing generated code so how can i edit the comnbobox according to me.
Note: I know one method by editing the "model" property of that jComboBox but I don't want to do it like that because I want various items (which are in an array) in that jComboBox so I want to pass that array in that jComboBox like as follows:
jComboBox2 = new javax.swing.JComboBox();
String [] date = new String[31];
for(int i = 0; i < 31; i++) {
date[i] = i + 1;
}
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(date));
There are 2 approaches I am aware of:
Simple approach - After the call to initComponents() in the constructor add you code to build your model and call jComboBox2.setModel(myModel) to set it. So the constructor would look something like:
public SomeClass() {
initComponents();
String [] date = new String[31];
for(int i = 0; i < 31; i++) {
date[i] = i + 1;
}
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(date));
}
Complex approach - add a readable property that holds the desired model. For example:
private ComboBoxModel getComboBoxModel()
{
String[] items = {"Item A", "Item B", "Item C"};
return new DefaultComboBoxModel(items);
}
Then, in the jComboBox2 property sheet, click the button to edit the model.
In the editor panel change the dropdown from Combo Box Model Editor to Value from existing component.
Select Property. Choose the comboBoxModel property. Click OK
I tried the second way once. Never really used it again. Too much work, no real much gain. Plus it displays an empty combo box in the designer which just makes layout harder.
I use the first approach, plus use NetBean's model editor to supply some representative values for the model. That gives me the sensible size behavior in the designer at the cost of one unnecessary line in initComments().
Using Netbeans NEON and other netbeans version
1. Go to the properties of the combobox
2. Then go to model
you can inject your code by using "custom code" feature in the GUI editor for the "model" of combobox
public NewJFrame() {
initComponents();
reformatComboBox();
}
private void reformatComboBox() {
JComboBoxName.removeAllItems();
JComboBoxName.addItem("item1");
JComboBoxName.addItem("item2");
}
Completing blurec answer (I cannot comment yet), in the GUI editor select the comboxbox, go properties, then model, then hit the three dots. Then select Custome Code and add your code, for instance:
new DefaultComboBoxModel<>(functionThatReturnsAnStringArray())
For the posterity:
Right click the ComboBox and select Customize Code. Here at the comboBox.setModel, in the left select custom property.
After new String, add your values in the following form:
Value 1: Integer.toString(myInt1)
Value 2: Integer.toString(myInt2)
If your variables are int of course. If not just put the String variable and you are done.
Hope it helps.
I got a doubt regarding pre-selecting(setSelectedIndex(index)) an item in a ListBox, Im using Spring + GWT.
I got a dialog that contains a panel, this panel has a FlexPanel, in which I've put a couple ListBox, this are filled up with data from my database.
But this Panel is for updates of an entity in my database, thus I wanted it to pre-select the current properties for this items, allowing the user to change at will.
I do the filling up in the update method of the widget.
I tried setting the selectedItem in the update method, but it gives me an null error.
I've searched a few places and it seems that the ListBox are only filled at the exact moment of the display. Thus pre-selecting would be impossible.
I thought about some event, that is fired when the page is displayed.
onLoad() doesnt work..
Anyone have something to help me out in here?
I really think you can set the selection before it's attached and displayed, but you have to have added the data before you can select an index. If this is a single select box you could write something like this:
void updateListContent(MyDataObject selected, List<MyDataObject> list){
for (MyDataObject anObject : list) {
theListBox.addItem(anObject.getTextToDisplay(), anObject.getKeyValueForList());
}
theListBox.setSelectedIndex(list.indexOf(selected));
}
If this is a multiple select box something like this may work:
void updateListContent(List<MyDataObject> allSelected, List<MyDataObject> list){
for (MyDataObject anObject : list) {
theMultipleListBox.addItem(anObject.getTextToDisplay(), anObject.getKeyValueForList());
}
for (MyDataObject selected : allSelected) {
theMultipleListBox.setItemSelected(list.indexOf(selected), true);
}
}
(Note I haven't actually compiled this, so there might be typos. And this assumes that the selected element(s) is really present in the list of possible values, so if you cant be sure of this you'll need to add some bounds checking.)
I've been happily setting both the values and the selection index prior to attachment so as far as I'm aware it should work. There's a bug however when setting the selected index to -1 on IE, see http://code.google.com/p/google-web-toolkit/issues/detail?id=2689.
private void setSelectedValue(ListBox lBox, String str) {
String text = str;
int indexToFind = -1;
for (int i = 0; i < lBox.getItemCount(); i++) {
if (lBox.getValue(i).equals(text)) {
indexToFind = i;
break;
}
}
lBox.setSelectedIndex(indexToFind);
}
Pre-selection should work also with setValue()-function. Thus, no complicated code is needed.