How to inactivate buttons that have not been pressed - java

I'm a very unexperienced programmer, so please bear with me for my lack of knowledge.
I have a program with 168 different buttons, which each count how many times they have been each pressed. After having either pressed or not pressed all of the buttons i need to inactivate and grey-out those which have not been pressed. So far I've used an 3D array to store how many times each button has been pressed, and have made a simple code:
if(a[0][0][0]<1)
{
ImageButton button_a1=(ImageButton) findViewById(R.id.button1a);
button_ca1.setEnabled(false);
button_ca1.setAlpha(6);
}
The only problem is that since each buttonID is different i have to do this 168 separated times. Is there any way to make this into a simple loop that doesn't take up over 1000 lines of code?
The program is written using Eclipse and is used for an Android app.

If all the buttons are in same layout, you can use getChildCount():
LinearLayout layout = setupLayout();
int count = layout.getChildCount();
View v = null;
for(int i=0; i<count; i++) {
v = layout.getChildAt(i);
if (v instanceof ImageButton) {
v.setEnabled(false);
v.setAlpha(6);
}
}
If not, simply create a Set, List or Array with all buttons and iterate over it:
List<ImageButton> buttons = new ArrayList<ImageButton>();
// be sure buttons is visible in the method
// when creating the buttons put them inside the list
Then in your method:
if(a[0][0][0]<1)
{
// disable all buttons
for(ImageButton button : buttons) {
button.setEnabled(false);
button.setAlpha(6);
}
}

Related

Java if two buttons have the same icons increase score and if not display "wrong match"

Creating a really basic Memory game using Java Swing. I created my GUI with a list of blank buttons where I set the icon property to none.
My code for some of the buttons is:
private void tbtnCard3ActionPerformed(java.awt.event.ActionEvent evt) {
tbtnCard3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Card3Logo.png")));
if(tbtnCard5.isSelected()){
score++;
lblScore.setText(""+score);
}
}
private void tbtnCard4ActionPerformed(java.awt.event.ActionEvent evt) {
tbtnCard4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Card7EWaste.png")));
if(tbtnCard7.isSelected()){
score++;
lblScore.setText(""+score);
}
}
private void tbtnCard5ActionPerformed(java.awt.event.ActionEvent evt) {
tbtnCard5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Card3Logo.png")));
if(tbtnCard3.isSelected()){
score++;
lblScore.setText(""+score);
}
}
I have about 20 toggle buttons and for example the code above works and the scores go up by 1 when a match is found. So for tbtnCard3, if tbtnCard5 is selected the score goes up by 1. Now my question is how would I make it so that if tbtnCard3 is selected but tbtnCard 5 is not selected, display "Wrong Match". Since im using if Selected I'm not too sure how to display "wrong match" when the case is false. It doesn't make sense to say else ifSelected as no parameters can be put either....
In my opinion, the OPs suggestion is not a good approach. You do not want the listener of one button to be "aware" of some other component unnecessarily. Suppose you have an 8-by-8 grid with toggle buttons. You don't want each toggle button listener to be aware of the other 63 toggle buttons.
I believe there is a much simpler (and cleaner) approach. What you want is for the toggle button listener to register and deregister the toggle when the state of the button changes. Let say, you add the toggle button to or remove from a list (most likely a custom class) where you can trigger some logic when the list size reaches two. Then, depending on the outcome of the comparison, it will count a match (and disable these two toggle buttons in the current state), or will display some message like "Try again" and then toggle the buttons to hide the image.
In pseudocode, this will look something like this:
public class ToggleListener implements ItemListener {
public void actionPerformed (ItemEvent event) {
JToggleButton button = (JToggleButton) event.getSource();
if (event.getStateChange()==ItemEvent.SELECTED) {
// TODO Add the button to your list..
} else {
// remove button
}
}
}
In your Swing application, you can create a single instance of the above listener and add it to every single toggle button. And, as you can see, this listener is only responsible to register and unregister the component associated with the triggered event.
The "List Listener" on the other hand, is responsible to trigger the comparison logic when the size of the list reaches two. So, if you click on the same toggle button over and over again, the only thing the button listener will do is add or remove the button from the list depending on the button's current state. However, once a second button is toggled to reveal its image, the list listener will trigger the comparison logic. I am not 100% sure, but I think you could use JavaFX ObservableList interface or one of its implementing classes to do this. If the ListChangeListener.Change class is not suitable to figure out the size of the list to trigger the logic, you will have to implement this on your own. Regardless, in pseudocode, you need to do something like this:
public void onListChange(Event event) {
if (list.size() == 2 && btn1.getIconName().equals(btn2.getIconName())) {
displayMatchMessage();
btn1.setEnabled(false);
btn2.setEnabled(false);
list.clear(); // you should remove matched items from list manually
} else {
displayMismatchMessage();
btn1.setSelected(false); // flip the card
btn2.setSelected(false); // flip the card
// list.clear(); // you should not need this because the setSelected should trigger the Item Listener which should remove item from list.
}
}
Doing something like this is a much cleaner implementation where the button listener have a single job to do and the "list listener" has another job to do. Neither one encroaches on the other's job.

I am stuck in "If" & "Else" function one of my android app

I my app I am fetch some text data from the server and showing this text data in the TextView. Here is something works fine. I am add an little arrow ImageView right to the TextView and this TextView is expandable so when TextView is more then 2 lines and if anyone click this TextView it expand and again click to shrink and I am also add an little arrow image right to the TextView (so user understant that it is an expandable text), here is everything is fine all code are works perfectly but now I want to remove this litter arrow image when the TextView is under 2 lines and when TextView is more then 2 lines it show. I want to tell you one more thing that I am also add a rotation in the arrow image so when the user click the text the little arrow image rotate the 180 degree and also text is expand and when user click the text second time arrow image again rotate to his previous position and text is shrink in 2 lines.
I want to remove this little arrow when the text is under 2 lies I do not want to remove the arrow image when text line more then 2, I'm guessing you understand.
I am new to the Java Code and I am learning is language so now I want to learn how to do this implementation in my app, I have add my code below so that you can understand batter.
textViewMyVideoTitle.setText(videoLists.get(0).getVideo_title());
my_title_layout_expand.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isTextViewClicked) {
//This will shrink textview to 2 lines if it is expanded.
textViewMyVideoTitle.setText(videoLists.get(0).getVideo_title());
myTitleImageView.setRotation(imageView.getRotation() + 0);
myTitleImageView.setVisibility(View.VISIBLE);
textViewMyVideoTitle.setMaxLines(2);
isTextViewClicked = false;
} else {
//This will expand the textview if it is of 2 lines
textViewMyVideoTitle.setText(videoLists.get(0).getVideo_title());
myTitleImageView.setRotation(imageView.getRotation() - 180);
myTitleImageView.setVisibility(View.VISIBLE);
textViewMyVideoTitle.setMaxLines(Integer.MAX_VALUE);
isTextViewClicked = true;
}
}
});
So anybody can help me to achieve this code
As you say, your text doesnt have more than 2 lines, so your function wont work until the text has more than 2 lines.
You may try to use TextView's getLineCount() method to get this info and decide.
So I mean outside your onClickListener do something like this:
if (textViewMyVideoTitle.getLineCount() <= 2) {
my_title_layout_expand.setVisibility(View.VISIBLE);
} else {
my_title_layout_expand.setVisibility(View.GONE);
}
Or since it gives you the right number only after layout been 'rendered' you might need the following:
textViewMyVideoTitle.post(new Runnable() {
#Override
public void run() {
// Get the line count and put the if-else statement here
}});

Advice on Implementing a simple Delete button in Swing

So my issue that I have is implementing a functioning delete button for my GUI.
While I have just about everything working, I have been stumped with trying to implement this function. What it does is as i click the 'Add' button, it creates a row with text fields and a check box. The 'Delete' works in the sense that it only deletes the most recent field create once I click on the checkbox to delete it. My intention is that the GUI works in a dynamic way to where I can click whatever check boxes and delete only those specific rows with the boxes checked.
I've researched methods of using an ItemListener but I'm still wrestling with that as I figure its the most proficient way to go. I've also done the storing the components in an array to iterate over. I feel I'm close with what I have now, any advice appreciated.
Below is the 'Add' button code to create new rows in my GUI. Then there is the 'Delete' button code which places the components in an array, but only deletes the most recent row created that has been checked.
add = new JButton("Add");
add.addActionListener(e ->{
rowPanel = new JPanel(new GridLayout(1,4,5,5));
for(int i = 0; i < 4; i++ ){
rowPanel.add(new JTextField(8));
}
for(int l=0; l < 1; l++){
rowPanel.add(new JCheckBox(), BorderLayout.EAST);
}
infoPanel.add(rowPanel);
infoPanel.revalidate();
infoPanel.repaint();
});
delete = new JButton("Delete");
delete.addActionListener(e -> {
Component[] components = rowPanel.getComponents();
for(Component c : components){
if(c instanceof JCheckBox){
if(((JCheckBox)c).isSelected()){
infoPanel.remove(rowPanel);
}
}
}
infoPanel.revalidate();
infoPanel.repaint();
});
You can use a JTable as a container and add a custom row that is a checkbox and a textfield. This way you just have to get the checkbox's event and see what index in the JTable it is located and delete it.
This might be useful:
https://docs.oracle.com/javase/tutorial/uiswing/components/table.html#editrender

How can I store radiobutton values in an array in the main method?

I am trying to get numerous radiobutton values from multiple fxmlcontroler files (each fxml has one group of 5 radiobuttons... user will select one) and store them in an array in the main method. How do I use the ToggleGroup to achieve that?
Ok, I have come up with a solution. First you must place the desired radio buttons innto a togglegroup:
final ToggleGroup tg1 = new ToggleGroup();
g1b1.setToggleGroup(tg1);
g1b2.setToggleGroup(tg1);
g1b3.setToggleGroup(tg1);
g1b4.setToggleGroup(tg1);
g1b5.setToggleGroup(tg1);
next, add a listener:
tg1.selectedToggleProperty().addListener(new ChangeListener<Toggle>()
add the radio buttons into an array:
Object[] rba = tg1.getToggles().toArray();
use a loop to find the selected radio button:
for(int i = 0; i < rba.length; i++){
if(tg1.getSelectedToggle() == rba[i]){
System.out.println("SELECTED RADIO BUTTON" + i);
}else{
System.out.println(rba[i].toString());
}
}
I did this with one document controller. you surely can find a way to what you need from here

How to set image of a button randomly?

I'am trying to do memory game. I have 12 buttons and 6 images.
I want to randomly set the image to the button. One image to 2 buttons.
ImageIcon[] icons = {icon1,icon2,icon3,icon4,icon5,icon6};
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16;
I know this Random r = new Random(); but no idea how can I use it here.
Edit:
U used this
for (int i = 0; i < buttons.length; i++)
buttons[i].setIcon( iconList.get(i) );
How can I set something like visible(false) of this icon?
Don't have 12 different variable names for your buttons. Instead create an Array to hold your 12 buttons.
Use an ArrayList to contain 12 Icons (two of each image).
Then you can use the shuffle(...) method of the ArrayList to randomly sort the icons.
Then you create a loop to assign each Icon to a button. Something like:
for (int i = 0; i < buttons.length; i++)
buttons[i].setIcon( iconList.get(i) );
Edit:
The above suggestion was to assign the Icons to the button when the button was created.
If you have a game where you have an empty Icon and then you display the Icon when the button is clicked then you need a different approach.
In your ActionListener code you will need to search the button array to see which button was clicked. Once you get the index of this button, then you get the matching Icon:
JButton button = (JButton)event.getSource();
for (int i = buttons.length; i < buttons.length;i++)
{
if (button = buttons[i];
{
button.setIcon( iconList.get(i) );
break;
}
}
The same ActionListener can be used for all buttons since the logic is generic.

Categories

Resources