Adding buttons into collection SWT - java

I have a problem with buttons. I found that when i add buttons into ArrayList, I will can manange every added button. But i don't have idea how to use setEnabled after adding it into ArrayList
public ArrayList<Button> buttons = new ArrayList();
buttons.add(newButton)

If you want all of them to setEnabled(true) then iterate through the array list as #DannyDaglas stated.
for(Button button : buttonList)
button.setEnabled(true);
If you want to pick one of them in specific then you can enter the index of the button and setEnabled(true).
int index = 0;
buttonList.get(index).setEnabled(true);
If you are not sure about which index it is and you have objects of the buttons then you can do something like this
int i;
for (i=0;i<buttonList.size();i++){
if(buttonList.get(i).equals(closeButton))
buttonList.get(i).setEnabled(true);
}

Iterate over the array list with:
for(Button button : buttons)
button.setEnabled(true);

Related

Getting lots of marked JCheckBoxes on a new JPanel?

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

Minesweeper, how can i work on cells

I would like to create a minesweeper game. Firstly, this will work on buttons. I think I will work on two dimensional array, and there will be like boolean array that will present where are bombs, for example if booleanArray[0][4] is true, there is a bomb.
Now, how can I implement this in my buttons? I can set Names on these buttons, and then if I click some button, then I will get the name from this div. For example when i click first button, i will get "00" name, then i will get first letter "0" and second letter "0" and parse it to int. And this will be the indexes from my previous booleanArray, in this case it will be booleanArray[0][0].
So, can I do this another, better way, instead of that?
This is the way I will be creating the buttons:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
JButton button = new JButton("");
button.setPreferredSize(new Dimension(50, 50));
button.setName(Integer.toString(i) + Integer.toString(j));
}
}
EDIT
I will have a two dimensional Array, that will reflect my buttons:
and now, how can I check if I hit the bomb after I click for example in the first button?
Just hold a two dimensional array of buttons,
JButton[][] myButtons = new JButton[10][10];
which you use to draw them and they all call the same method with their value
for (int x=0; x<10; x++){
for (int y=0; y<10; y++){
myButtons[x][y] = new JButton("0");
//add to page, or do it elsewhere
myButtons[x][y].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionButtonPressed(x,y);
}
});
}
}
Then a call to yout method selectionButtonPressed() will tell you what button has been pressed, you can take action and even make changes to the button with myButtons[x][y].whatever()
That is one way but you should create the String of the name by using something like:
button.setName(i + ":" j);
This will make it easier to parse out the two values as you can just use the String.split(...) method.
Another option might be to create a HashTable with the JButton as the key and then use a Point object (representing the row/column) as the value Object of the HashTable. Then you just use the get(...) method of the HashMap to retrieve the Point for the clicked button.
Another option is to extend JButton and add two parameters (row, column) when creating the button. Then you also add getRow() and getColumn() methods.
Either of this approaches will keep the logic simple and you only need to create a single ActionListener to be used by all the buttons.

Change all the buttons color in java

I have 20 Buttons and i want change the color of the all the buttons when i click on a special button, is there any way to do this with function(or without function) and do not using setBackground for 20 times
You can put the buttons in an array
JButton[] array = new JButton[20];
//then add the buttons to the array
Then:
for(JButton button : array){
button.setBackground(/*the color you want*/);
}
You should not do button1, button2, etc.
Instead, make a List<Button> buttons. You'll still have to call add() 20 times on that list, but then you can loop over them all.
for (Button b : buttons) {
b.setBackground(color);
}

How to rename set of JButtons?

I have 25 jButtons and i want to change their texts from a loop. Here is my code for 1 button..
void changeText(){
jButton1.setText(jButton1.getText().toUpperCase());
}
I want to do the same for all other buttons without writing a method for each.
Is it possible to use something like this?
void changeText(){
for(int i=0;i<25;i++){
String x = "jButton"+i;
x.setText(x.getText().toUpperCase());
}
}
Surely this wont work. Please suggest me a method.
You can do this by adding the buttons to a collection.
Something like this:
// initialization of jbuttons:
List<JButton> buttons = new ArrayList<JButton>();
JButton jbutton1 = new JButton();
// .. set properties
buttons.add(jbutton1);
// add more jbuttons to the list
Later you can iterate over the list of buttons:
for (JButton button : buttons) {
button.setText(button.getText().toUpperCase());
}

How to get a handle to all JCheckBox objects in order to loop?

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.

Categories

Resources