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
Related
I am using Java in Netbeans and I have a combobox that allows the user to select an option on the list or enter their own option.
I know you can add an item to a combobox through a textfield, I wanted to know if there is a way that when the user enters their own option into the combobox and they click enter their option is added to the list.
I have tried
BusinessTypeComboBox.getItem(typeofBusiness);
BusinessTypeComboBox.addItem(BusinessTypeComboBox.getText());
Does anyone know if this is possible
If i understand you right, the i would do it this way:
Add a KeyListener to the comboBox to know, when the user entered a new item and confirmed it.
Retrieve the list of items from the comboBox.
ComboBoxModel model = comboBox.getModel();
List list = new ArrayList();
for(int i=0; i<model.getSize(); i++) {
list.add(model.getElementAt(i));
}
Append the entered item to the list.
Reinitialize the comboBox with the appended list.
model = new DefaultComboBoxModel(list.toArray());
comboBox.setModel(model);
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
I have been trying to determine why my JComboBox is displaying the 1st item in the list through numerous Google searches, but I'm struggling to find relevant help. It could be that I don't know the correct terminology (hence the overly specific title of this question) and thus not finding the information that would explain my issue. I checked out the JComboBox API, and few of the listeners and models that it uses, but they did not seem likely candidates.
The JComboBox in question is inside a JTable, so I am not aware if that changes the default behaviour of it. The code I am using is as below:
//row and col are final due to usage inside anonymous inner class
public TableCellEditor getCellEditor(final int row, final int col)
{
String[] listItems = new String[arrayList.getSize()];
int i = -1;
for(String s : arrayList)
{
i++;
listItems[i] = s;
}
JComboBox<String> box = new JComboBox<>(listItems);
box.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
if(e.getItem().equals("Add/Edit Projectile"))
{
//Where Editor is a JFrame that will be opened
new Editor();
}
}
}
});
DefaultCellEditor list = new DefaultCellEditor(box);
}
Please note that the Arraylist in my program does not contain Strings, but instead a more complicated set of custom objects that I believe would distract from the main issue.
I haven't included a Renderer for JComboBox's in the JTable as I was happy enough with the way it appeared, and figured that my problem was more going to be something I have neglected to implement in the model/implemented wrong.
I've also provided a couple of screenshots to better portray my problem. The first image is when the JComboBox is not selected, and simply displaying the currently selected item.
The second image is when I have just clicked the JComboBox to bring up the list. As depicted, it will immediately bring up that first item, no matter what it is.
If anyone has any suggestions as to where to look/solutions, I would be very grateful.
EDIT
My particular table has two columns, where the left column is a variable name, and the right column is the value associated with the variable. The tables role is to display the properties of a selected object, where each value for different variable for different objects are likely to not be the same.
In this particular case, the cell displays a JComboBox with all the available Projectiles in the game we are making. Each enemy has a different type of projectile it defaults to. So when I click on a different enemy in our game area, the table will display all of their current properties (defaults if they have not been changed).
Enemies do have a getter for the Projectile, so I could determine what the currently selected enemy is, get it's projectile, do a toString() to find how it is to be represented in the list, and do a setValueAt().
The only problem is at the moment it is always selecting the first item in the list when the list is expanded.
Unless the values for the JComboBox are dynamically generated for each row, you should be able to just prepare the CellEditor ahead of time, for example...
JComboBox cb = new JComboBox(new String[]{"1", "2", "3", "4"});
DefaultCellEditor editor = new DefaultCellEditor(cb);
JTable table = new JTable(new DefaultTableModel(5, 1));
table.getColumnModel().getColumn(0).setCellEditor(editor);
This will set the selected value of the editor to the value of the cell when the editing process starts
Updated
In the case where the combobox values are dynamically generate per row, you could do something more like...
JComboBox cb = new JComboBox();
DefaultCellEditor editor = new DefaultCellEditor(cb) {
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
JComboBox editor = (JComboBox) getComponent();
String[] listItems = new String[arrayList.getSize()];
int i = -1;
for (String s : arrayList) {
i++;
listItems[i] = s;
}
DefaultComboBoxModel model = new DefaultComboBoxModel(listItems);
editor.setModel(model);
editor.setSelectedItem(value);
return editor;
}
};
JTable table = new JTable(new DefaultTableModel(5, 1));
table.getColumnModel().getColumn(0).setCellEditor(editor);
Note the use of editor.setSelectedItem(value);, this will set the selected value to the cells current value...
You could also re-use the model, clearing it each time and re-filling it with new values. You might find this more efficient if you have a large number of rows as you won't need to constantly create a new model each time a cell is edited
Thow this is an oldie...
Your problem is most likely you don't implement "equals" in the class used in the combo.
The Combo needs to select the current item when it is being prepared and does so by iterating through the elements of the model and selects the first one that is equal to the value in the cell. If none is encountered then it leaves the combo as is (either first element or the last used element in a previous cell edit)
This is how you should default to the previously selected element:
//...
Object selectedItem = box.getSelectedItem();
//Add some elements to the jComboBox
box.setSelectedItem(selectedItem);
I have a problem in display data in to respective fields.
I have like this data from database in arraylist.
ArrayList<String> ar= new ArrayList<String>;
ar data is:-> [2, India#1, USA#3, Australia#1, Germany#2];
How to get above data like this arraylist:
Country ArrayList: India,USA,Australai, Gernamy
valucheck arraylist: 1,3,1,2
Here first element is id and others ara values. Like India- EditText field and integer(1,2,3) is radiobutton.
India 1(checked first radio button)
India 3(checked third radio button)
Australia 1(Checked first radio button)
Germany 2(Checked second radio button)
I have been trying lots of time, but could get proper solution, so please update some tricks for display those data
I want to display like this data in to tabular form
What i did,
List<EditText> listET = new ArrayList<EditText>();
ArrayList<String> first= new ArrayList<String>();
if(edittextfield){
first.add("India");first.add("USA");first.add("Australia");first.add("Germany");
EditText et_text_input = new EditText(getContext());
for(int p=0;p<listET.size()+1;p++){
et_text_input.setText(first.get(p));
listET.add(et_text_input);
ll.addView(et_text_input);
}
}else if(radiobuttonfield){
what to do in radiobutton.
}
Here If i put data in list of first in static, then works fine, but how to put about ar list data into first list ..
Take a look at the ListView-class.
Look into ArrayAdapter (http://developer.android.com/reference/android/widget/ArrayAdapter.html) which allows you to display the data in a ListView.
Assuming you mean output to console, you could step through the list and display it's items with tab separation
//As an example of usage, not a solution using your structures
for (MyObject o : ar)
{
System.out.println(o.getCountry() + "\t" + o.getValue())
}
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.