Make multiple JTextFields change color Java - java

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.

Related

If I have an arraylist of labels using mouselistener, how do I get an index when a label is clicked?

I'm making a card game. It has an arraylist of Jlabels corresponding to each card the player has.
When the card jlabel is clicked, how do I get the index of the individual JLabel, so I can call a playcard() method that plays the card using the given index?
JLabel temp = new JLabel(icon);
temp.setBounds(new Rectangle(new Point(shift, 550), temp.getPreferredSize()));
temp.addMouseListener(this);
currentdeck.add(temp);
//for loop that adds each jlabel to currentdeck
public void mousePressed(MouseEvent arg0)
{
JLabel label = (JLabel)arg0.getSource();
//int i = (how would I get the index)?
if(MouseInfo.getPointerInfo().getLocation().getX()>=label.getX()&&MouseInfo.getPointerInfo().getLocation().getY()>=label.getY())
{
UNO.playcard(int i);
}
}
It seems like you want to use the indexOf() method of ArrayList.
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object)

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.

JButtons and Mouse Listeners or Action Listeners

I am making a little game of math, which consists of creating a random numbered sequence of numbers between 1-9 or 10-99, then separating the number > 10 and then create a sequence out of it. Example, I have 4 numbers to generate, I generate 1, 3, 5, 10. Then I separate the number 10 and concatenate the numbers together like this : 1 3 5 1 0. Now the objective of the game is to reassemble the numbers together to get the sum. So I'd have to click 1, 3, 5, then 1 and 0 while keeping the mouse pressed to obtain 10. Finally I check the sum pressed in with the original sum to find if it's the right answer.
Anyways, I have some trouble with the MouseEvent and the buttons. First I created the numbers randomly, then put them in an int array. After that, I take that array and switch it into a String so I can put them on a Button. Then, when I create my button, I get the String and I do a String.charAt(i) to get a single digit of my sequence. I add my MouseListener on the button and then add my button to the panel.
I would like to get the value of the digit on my button when I press that button. I tried getSource(), getText() or other methods, but it didn't work. Should I use ActionListener for this or MouseListener?
Here's some snippet of my code:
fixedSequence is the String version of the number sequence
GameLogic is the class where I do the logic of the game
sequencePanel is the JPanel that shows the buttons of the sequence
Creating the int array sequence:
private void createSequence(int cutNumber) {
//cutNumber is the number of digits in my sequence
for(int i = 0; i < cutNumber; i++) {
numberSequence[i] = numberGenerator();
}
}
Creating the String array out of my int array:
private void sequenceToString() {
StringBuilder builder = new StringBuilder();
for(int value: numberSequence) {
builder.append(value);
}
fixedSequence = builder.toString();
}
Now to create the sequence with buttons:
private void createASequenceButton(char c, Container container) {
JButton button = new JButton(String.valueOf(c));
button.setAlignmentX(LEFT_ALIGNMENT);
button.addMouseListener(new SequenceButtonListener());
container.add(button);
}
private void addNumberSequence() {
//GameLogic is where I create the number sequence and where I do the
//logic of the game
for(int i=0; i < GameLogic.getFixedSequence().length(); i++) {
createASequenceButton(GameLogic.getFixedSequence().charAt(i),
sequencePanel);
}
}
Now for the MouseListener part:
private class SequenceButtonListener implements MouseListener {
public void mousePressed(MouseEvent event) {
//This is where I want to get the value in int or string of
//the button I pressed so I can do my calculation with it
}
}
I'd like some opinion on the way I did it, if I could do it an easier way or it's only possible with ActionListener instead of MouseListener.
Thank you for your time,
Carl

How can my program randomly press a button?

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.

Java, Page through array

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.

Categories

Resources