Test[] array = new Test[3];
array[0] = new RowBoat("Wood", "Oars", 10);
array[1] = new PowerBoat("Fiberglass", "Outboard", 35);
array[2] = new SailBoat("Composite", "Sail", 40);
I have the above array and I need to display the results to a swing GUI with a next button that will display the first index values, and when the next button is clicked it will display the next index values and so on.
for (int i=0;; i++) {
boatMaterialTextField.setText(array[i].getBoatMaterial());
boatPropulsionField.setText(array[i].getBoatPropulstion());
}
I have the above code working and of course it displays the last item in the array.
My question is: How would I display the first index in the array and when the user clicks next display the next item in the array as well as go to the previous index when a back button is clicked?
Simply put I need to page through each index when a button is clicked.
You do not need a loop. When the frame first loads you can simply display the first item in the array. You can then create a next button.
JButton nextBtn;
int currentIndex;
...
currentIndex = 0;
//display the first item in the array.
boatMaterialTextField.setText(array[currentIndex].getBoatMaterial());
boatPropulsionField.setText(array[currentIndex].getBoatPropulstion());
nextBtn = new JButton("Next>>");
nextBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(currentIndex < array.length){
boatMaterialTextField.setText(array[++currentIndex].getBoatMaterial());
boatPropulsionField.setText(array[currentIndex].getBoatPropulstion());
}
}
});
You can add another button for previous that simply decrements the currentIndex each time ensuring to check that it never becomes negative.
Related
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.
I just want an action to occur once, just once when clicked. Here is the code:
String previousValue = Counter.getText(" ");
Counter.setText("0");
AmouseClicked(java.awt.event.MouseEvent evt) {
If(callquestion==1 && A.isFocusable()) {
int d= Integer.parseInt(Counter.getText());
int e= 10;
int f=d+10;
Counter.setText(f+" ");
}
}
Note- Counter is a JLabel that displays the output, A is Jlabel that holds the correct answer .I have A,B,C,D jlabels.
The initial value is 0. So I want each time a button is cliked, 10 just be added ones, if u click again. The 10 remains. I have callquestion1 to 20. So after a play gets the correct answer, he clicks the next to go to the next Qus.
I just need each button to add 10 if clicked again do nothing.
I'm trying to make a game where the button would light up and the user would have to press the button in a given time.
Currently, my program has 12 buttons that do something. I'm trying to make it so that these buttons are randomly called by the program. So far, I just have these for 12 buttons that just change the text when pressed by the user.
Now I need a way of making it so that they are randomly pressed the program itself and not the user. Any idea's on how this is done in java?
// **** Panels for buttons ****
JPanel panelButtons = new JPanel(); // making the panel for the buttons
panelButtons.setLayout(new GridLayout(3, 4)); // setting the layout of the buttons to 3x4 as shown above
b1 = new JButton(" ⃝"); // creating button and setting its default text
b1.setFont(fontText); // setting the font
b1.addActionListener(new ActionListener(){ // action listener to do something when pressed
public void actionPerformed(ActionEvent e) {
sendMessage(user + "1" ); // sends the name of the user that pressed the button and which button
String field1 = b1.getText(); // gets the text from the button and stores it in a String
if(field1 == " ⃝"){ // checks if the string is equal to an empty circle
b1.setText("⬤"); // if true then change to a full circle
}
else if (field1 == "⬤"){ // opposite of the above if statement
b1.setText(" ⃝");
}
}
});
panelButtons.add(b1); // adding the button to the panel
b2 = new JButton(" ⃝"); // creating button and setting its default text
b2.setFont(fontText); // setting the font
b2.addActionListener(new ActionListener(){ // action listener to do something when pressed
public void actionPerformed(ActionEvent e) {
sendMessage(user + "2" ); // sends the name of the user that pressed the button and which button
String field2 = b2.getText(); // gets the text from the button and stores it in a String
if(field2 == " ⃝"){ // checks if the string is equal to an empty circle
b2.setText("⬤"); // if true then change to a full circle
}
else if (field2 == "⬤"){ // opposite of the above if statement
b2.setText(" ⃝");
}
}
});
panelButtons.add(b2); // adding the button to the panel
You can create a list that holds your button. Use the random number generator to create a random number within the length of the list. Use that (random) index to modify the corresponding button.
Put your twelve buttons in an ordered collection.
Put your twelve corresponding actions in another ordered collection in form of a Consumer<JButton>'(useCallable`(and ignore the return) or just create something like that if you are not using java 8).
Perform a mapping from the Button collection to the action collection.
Create a class implementing ActionListener like this:
private static class Listener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
button2action.get((JButton)e.getSource()).accept(a);
}
}
pick up a random element from the value set of the map if you want to get random button pressed.
int randomIndex = new random().nextInt(button2action.entrySet().size());
Iterator<Entry<JButton, Consumer<JButton>>> iter = button2action.entrySet().iterator();
for (int i = 0; i < randomIndex; i++){
Entry<JButton, Consumer<JButton>> entry = iter.next();
}
entry.getValue().accept(entry.getKey());
add new button action pairs to the map if you want to add new buttons.
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);
I'm trying to make randomized JTextField's yellow by using Arrays. I've only managed to make 1 textfield yellow, and then white after 1 sec at each click. What I want to do is when you press the button the first randomized Textfield get yellow and then white. And when you press the second time the first randomzied textfield AND the seconds will turn yellow and then White and so on.. The array works as you can see I Printing it and when you press the button it prints all the randomized numbers in order.
The problem is that JTextField can't handle int's, and it apparently have to be "Final" so it makes it very hard to make multiply JTextField's yellow. I pasted my arrays to you so that you can get a better understanding what I'm trying to do. Does anyone know the solution?
//my Arrays
JTextField[] boxes = new JTextField[9]; //Array for the textfields
int[] clicked = new int[100];
int clickAmount = 0;
//At startup it fills the boxes array with the textfield:
boxes[0] = textfield1;
boxes[1] = textfield2;
boxes[2] = textfield3;
boxes[3] = textfield4;
boxes[4] = textfield5;
boxes[5] = textfield6;
boxes[6] = textfield7;
boxes[7] = textfield8;
boxes[8] = textfield9;
public void timePaus (final JTextField textfield) {
new Timer(1000, new ActionListener() {
public void actionPerformed (ActionEvent e) {
textfield.setBackground(Color.white);
// stop the timer
((Timer) e.getSource()).stop();
}
}).start();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { //Button
int randomint = this.randomBox(); //Finds a number between 0-8
final JTextField ThatTextfield = boxes[randomint]; //Puts a textfield into an array
clicked[clickAmount] = randomint+1; //adds textfield number into an array
clickAmount++;
ThatTextfield.setBackground(Color.yellow); //make choosen textfield yellow
for (int i = 0; i < clickAmount; i++)
{
timePaus(ThatTextfield); //make choosen textfield white after 1 sec
System.out.println(clicked[i]);
}
}
Considerations:
Place your JTextFields in an ArrayList<JTextField>, but create them in a for loop for the sake of avoiding unnecessary repetation.
When you want to randomize the ArrayList, call Collections.shuffle(myTextFieldList) on your List of JTextFields.
Give your class an int maxIndex field.
In your Swing timer, iterate through the now randomized List of JTextFields, displaying each one up to the value held by the maxIndex and not above the size of the List.
Increment the maxIndex in the timer.
Alternatively, you could create two more ArrayList<JTextField>, one to shuffle the collected text fields. Then remove the 0th JTextField from this list in your button's listener, and place it into the other ArrayList, and then iterate through the 2nd ArrayList's JTextfield in your Timer.