So I got an assignment in Java to make an 8 piece puzzle, and I chose to use JButtons for tiles (don't know if that's even possible). I've got the buttons to appear in a random order when starting it, but I have no idea how to make the tiles able to move when you click on them. So I'm wondering if someone could just point me in the right direction? I've come to conclusion that I need to use Actionlistners and saw an old user here getting tip of doing Actionlistners on every button, but I am having trouble with knowing what to writ, and do I put this in another class?
Any help is very much appreciated!
The product so far:
To make it easier, you could add ninth button which is transparent and not clickable. Every but should has his id, which would also tell hes position.
11 12 13
21 22 22
31 32 33
So for every button you already assign his random number. Now just like you use actionlistners to detect which button is clicked. And when is clicked you check if button that is neighbor is transparent. If transparent you would swap there values, one would become visible,other transparent and not clickable.
To get button neighbors you would use + and - operations.
int leftNeighbour = id - 1;
int rightNeighbour = id + 1;
int topNeighbour = id - 10;
int bottomtNeighbour = id + 10;
I assume that all buttons are saved in an array so you just go like this:
for(Button tempButton : Buttons)
{
if(leftNeighbour > 0 && leftNeighbour == tempButton.id) //we check first if button id is OK, then we compere it with tempButtons id
{
int tempButtonValue = tempButton.value;
tempButton.value = currentButton.value;
currentButton.value = tempButtonValue ;
makeButtonTransparent(tempButton);
break; //we found over neighbor so we can stop for loop
}
//then you check conditions for other neighbor id's. Butt first condition is allays different
}
I hope that I didn't make it over complicated, but this is idea that I got in few minutes, when I was thinking how I would make it with buttons. There is probably some better way to set ID's to buttons, and check if they are neighbors.
Related
How to click a row in table by randomly?
I know how to using Random class to iterate the List but don't know how to click the button of the specific row after randomize due to xpath different.
Please provide me some idea and guideline on how to solve this.
ps: I got some idea, the button is located at the last column, so i just click on the last column button.
Here is simple way to get random number from 1 to 10
int min=1;
int max=9;
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
System.out.println(randomNum);
If we think its row number, then, need to click on last column of that row.
i am imaging last column as td[6] then path will looks like
"//table/tbody/tr["+randomNum+"]/td[6]/button"
I have a Jframe in netbeans with 5 buttons, named buttons 1, 2, 3, 4, and 5. I'm trying to make it so if the buttons are pressed in this order 4, 2, 3, 1, it will display a dialogue box. My only problem is getting it to recognize the buttons have been pressed in the correct order.
If this were my project, I'd use a LinkedList<Integer> or ArrayList<Integer> to hold the Integer representing the buttons that have been pushed and in what order, and then would react if the last 5 presses matched the desired pattern. So each button press would add an Integer to the List, and then would check the last 5 entries, and if they match the pattern, bingo! show the JOptionPane.
Note that for the best help, you should show us what you've tried, and we can help you refine it.
Not sure why you are using buttons for this. Most people would use a JPasswordTextField.
If you really want to use buttons. Then you would need to keep a StringBuilder. Every time a button is pushed you would add the text of the button to the builder. Then you would check if the toString() of the builder is the password.
If the password is incorrect you would display a JOptionPane and then clear the builder so the user can start again.
Here you go:
Make a global String variable, I named it code, and initialize its value by "".
On each corresponding button, add code (for button 1) code+="1;" and check();
Create a method check, which contains these function:
(If you want the numbers of try limited by 5)
System.out.println("Numbers of try: "+code.length());
if(code.length()==5){
if(code.contains("32415")){
System.out.println("You made it!!");
}else{
code="";
}
}
(If you don't want to limit the numbers of try)
if(code.contains("32415")){
System.out.println("You made it!!");
}
Go ahead and try this, it works for me :)
I am trying to display some textviews visible in runtime.
Here's my code:
for (int i=0; i<arrBool.length; i++) {
arrBool[i] = r.nextBoolean();
if(arrBool[i]==true) {
textView[i].setVisibility(View.VISIBLE);
}
}
When I run the application, textviews should randomly be visible. It is working, but my problem is I have set the layout of those textviews. When I run Android Application, the visible textviews go to top left corner and loses the layout position.
How to deal with this?
Change start visibility parameter of views to View.INVISIBLE
It will hold their own places on the layout and prevent from taking this places by other views, which is normal behavior in case of View.GONE
Adding more to teoREtik solution.
In your layout do not specify the android:visible property.
for (int i=0; i<arrBool.length; i++) {
arrBool[i] = r.nextBoolean();
if(arrBool[i]==true) {
textView[i].setVisibility(View.VISIBLE);
else
textView[i].setVisibility(View.INVISIBLE);
}
}
I don't think using the FOR loop will help you out making the random possibility of the visible text view everytime you open. Why don't you just use the integer (0 for false and 1 for true) and a Random like this:
Random rnd = new Random(1); // --> This will randomize numbers up to one;
int enable = rnd.nextInt(); // --> Get the random value from 0 to 1
if(enable == 1) // --> If visibility of the text field is enabled everytime you opened the app...
{
textView.setVisibility(View.VISIBLE);
} else {
textView[i].setVisibility(View.INVISIBLE);
}
You can modify more and experiment on the randomizer for the integer's value by visiting this example at " How can I generate random number in specific range in Android? " topic. Check all the possible answers. Don't mind the green check mark and focus these answered codes by investigate its comments. I'm sure all of these answers about "random" topic, the link I gave you, is guaranteed effective.
About the layout, I recommend not to use the relative layout and instead use the linear layout because using the linear layout stays on the original place proportionally since relative layout is screen resolution dependent on the coordinates. Also try practicing manipulate the string value dimensions under res folder to maintain the size of the text proportionally in different screen resolution (from HVGA to WVGA). Check at " Different font sizes for different screen sizes " for more details about text size proportion.
I've reccently run into issues with indexing my tabs and though I'd give it some concrete ordering by using the setComponentAt method. Here's my code:
public ContainerPane() {
this.setLayout(new BorderLayout());
myPlayerManagerPane = new PlayerManagerPane();
myGameManagerPane = new GameManagerPane();
myCharacterManagerPane = new CharacterManagerPane();
myPaneTab = new JTabbedPane(JTabbedPane.TOP);
myPaneTab.addTab("Character",myCharacterManagerPane);
myPaneTab.addTab("Player",myPlayerManagerPane);
myPaneTab.addTab("Games",myGameManagerPane);
System.out.println(myPaneTab.getTabCount());
//myPaneTab.setEnabledAt(1, false);
//myPaneTab.setEnabledAt(2, false);
myPaneTab.setComponentAt(0, myPlayerManagerPane);
myPaneTab.setMnemonicAt(0, KeyEvent.VK_1);
myPaneTab.setComponentAt(1, myCharacterManagerPane);
myPaneTab.setMnemonicAt(1, KeyEvent.VK_2);
myPaneTab.setComponentAt(2, myGameManagerPane);<---outOfBoundsException
myPaneTab.setMnemonicAt(2, KeyEvent.VK_3);
add(myPaneTab);
}
So for the count I have, 3 tabs (according to me, and getTabCount()), and I am counting from 0 (correct?). I'm setting the last index the last component that I have. But I still have this printing to screen:
3 <---from tabCount
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
Where am I tripping up, is there an easier way to order my panes?
Edit: Commenting out the setComponent methods, and putting in a for loop I get this output:
There are 3 tabs!
Tab at 0 is Character
Tab at 1 is Player
Tab at 2 is Games
And uncommmenting one pair of methods at a time, I get only 2, of the one I've not overwritten, and one of the ones I've now set.
Is setComponentAt removing duplicates? Should I ever have fewer than 3 tabs with my set up? Does JTabbedPanel have odd behaviour for duplicate panes?
You get an error due to changes you are trying to do - by putting some of the panes into another position you automatically remove another tab. That is why you get the error - there is less than 3 tabs after some of the changes (you can check that outputting tabs amount after each of "setComponentAt" operations).
Simple remove all tabs you want to reorder and readd them using either addTab or insertTab - that will get the job done without any errors.
Looking at source code of the setComponentAt you can see that component you're setting is removed:
int count = getComponentCount();
Component children[] = getComponents();
for (int i = 0; i < count; i++) {
if (children[i] == page.component) {
super.remove(i);
}
}
next this component is set as page's component (overriding last present component on that page):
page.component = component;
So setting order of existing tab component you end up with 2 tabs.
I'm not sure how or why setComponentAt wasn't working, though it could be the fact that tabs use a Vector and I've heard they are bad.
If you want to have a fixed order of adding, just use insertTab Like so:
myPaneTab.insertTab("Games",null, myGameManagerPane,"CharacterManagerPane",2);
Where null is for the icon, and doesn't accept it as an empty argument.
This way you know in your source code the index of the tab. The only issue with this is that you can't add a new tab at an index past the current tabCount (which you can find via getTabCount), i.e. you can't count 1,3,4 with your tabs!
I'm sure you could write a new JTabb Class, and overload the insertTab method to do something more helpful but it might obsfuscate where the tab is (I.e this way you could tell it put the tab at index 2 and it goes into index 1.
If you want your tabs in another order, add them in another order:
myPaneTab = new JTabbedPane(JTabbedPane.TOP);
myPaneTab.addTab("Player",myPlayerManagerPane);
myPaneTab.addTab("Character",myCharacterManagerPane);
myPaneTab.addTab("Games",myGameManagerPane);
Et voilĂ .
I'm doing a project (something like a restaurant) for collage, and I'm not very good in Java (they didn't really try to teach us). The principle of the project is to show a message saying what radio buttons and check boxes I've selected.
I have 5 radio buttons, they are for selecting a meal, and 5 check boxes for selecting a side dish. I've managed to have the radio buttons work but I don't know how to make the check boxes work...
This is the code for the radio buttons (this goes for all 5):
private void jRadioButton1ItemStateChanged(java.awt.event.ItemEvent evt) {
if (evt.getSource().equals(jRadioButton1))
{
Meal= jRadioButton1.getText(); //Meal is a String
}
I tried the same code for the check boxes but it only shows one side dish in the message, even though I selected multiple...
The code for the button that shows the message:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(rootPane, "You have chosen:\n" + String.valueOf(Meal) + "\n" + String.valueOf(SideDish));
}
So basically, if anyone is willing to help, please tell me how to make the check boxes work... that every selected check box is shown in the message, like this:
You have chosen:
Pizza //meal
Ketchup //selected side dish #1
Chilli peppers //selected side dish #2
Feta cheese //selected side dish #3
I hope my question is clear...
Since you want to display text for zero or more checkboxes, you need to check for each whether it is selected, and concatenate the resulting text, instead of keeping only one option. Moreover, since check boxes can be checked and unchecked independently, it may be better to check their state only at the moment when the button is pressed instead of attempting to keep track of them all the time. E.g.:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
SideDish = "";
if (jCheckBox1.getState()))
{
SideDish += jCheckBox1.getText();
}
...
if (jCheckBox5.getState()))
{
SideDish += ", " + jCheckBox5.getText();
}
JOptionPane.showMessageDialog(rootPane, "You have chosen:\n" + Meal + "\n" + SideDish);
}
This is just an illustration, which won't always display separating commas properly - I will leave the fix to you as an exercise :-)
A more elegant solution would be to use a collection of Strings to collect the side dishes - again, you may try improving the code towards this.
Btw, you don't need String.valueOf() to print Strings so I removed it from the code above. And the Java coding convention is to start variable/field names with lowercase.
As you can select multiple checkboxes at the same time, you should collect the checked values in a collection. Set<String> comes to mind as you can select one side dish only once.
Also, you did not have this problem as each selection of the radio button overwrote the previous one, but you will need to remove items from the set if their corresponding checkbox is unticked.
Note: Set<> is an interface, you will need an implementing class to actually use it. In your case a HashSet<> would work (see documentation for the available method for Set and HashSet)
When you display the choice of side dishes, you can enumerate the elements in the set and eother print them one-by-one or collect the result in a string by concatenating the elements.
Note: you might not evenneed the set if you have direct access to the checkboxes: at the time of displaying which side dish is chosen, just check the state of each checkbox and accumulate the choices string as outlined above
Here is an example
Lets say you have 4 sidedishes
Vector<JCheckBox> boxes = new Vector<JCheckBox>
boxes.add(checkbox1) .... .add(checkbox4);
and on clicking the button
Vector<String> sideDishes = new Vector<String>();
for(int i=0; i<boxes.size(); i++){
if(boxes.elementAt(i).isSelected(){
sideDishes.add(boxes.elementAt(i).getText();
}
}
I am thinking that first you should learn is how to analyze problem and how to use Google or other search engine sites, So try to read this docs and look to examples