I am trying to show the form many times here in this example 10 times, Can someone help me in doing it?
In the below example i am showing only button to keep it simple, along with the button i will add other components like textbox etc..., In the below example, i am getting the error- times should be made final. If i make it final then, i wont be able to write times = times - 1.
private void showForm(int times){
if(times >= 1){
JButton btn = new JButton("ADD");
container.add(btn);
times = times - 1;
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showForm(times);
}
});
}
}
Just write it like this:
private void showForm(final int times){
if(times >= 1){
JButton btn = new JButton("ADD");
container.add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showForm(times - 1);
}
});
}
}
If by pressing the button you want new buttons to appear, minus 1 every time (this is what I understand), to actually make it work you also need to add revalidate() and a loop
private void showForm(final int times) {
if (times >= 1) {
for (int i=0; i<times; i++) {
JButton btn = new JButton("ADD");
container.add(btn);
container.revalidate();
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showForm(times-1);
}
});
}
}
}
else forget the loop but keep revalidate (or you won't see any visible changes)
Related
I'm making a game similar to 'who wants to be a millionaire?' and I have a 'Next' button which takes the player to the next question. However, since I am allowing up to four players to play, I want this 'Next' button to disable after a maximum of 3 clicks, (or less if there is one/two/three players playing).
Here is my code so far for the 'Next' button:
nextButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
StatusPage.setVisible(false);
QuestionPage.setVisible(true);
option1.setEnabled(true);
option2.setEnabled(true);
option3.setEnabled(true);
option4.setEnabled(true);
if (Player2JButton.isEnabled()){
counter = 1;
}
else if (Player3JButton.isEnabled()){
counter = 2;
}
else if (Player4JButton.isEnabled()){
counter = 3;
}
else {
System.out.println("Error getting next question.");
}
if (generalKnowledge.isEnabled()){
currentQuest = quest.setQnA(option1, option2, option3, option4, question1, "generalKnowledge");
}
else if (geography.isEnabled()){
currentQuest = quest.setQnA(option1, option2, option3, option4, question1, "geography");
}
else if (hipHopMusic.isEnabled()){
currentQuest = quest.setQnA(option1, option2, option3, option4, question1, "hipHopMusic");
}
else {
System.out.println("Error getting next question.");
}
}
});
Have you thought about using a simple int variable that will count the number of times one of the players pressed that button?
What do you think about this:
final int NUMBER_OF_PLAYERS=4;
int count=0;
nextButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
count++;
if(count-1==NUMBER_OF_PLAYERS)
{
nextButton.setEnabled(false); //disable the button
}
///Your code
}
});
I guess I'll add it as an answer. Here's a working sample, without some Android-yitter.
We'll use an int counter. Every time someone clicks you increment counter within the actionPerformed-block. If counter is greater than 2, it's been clicked 3 times. We'll disable nextButton with #setEnabled.
public class ButtonCycle extends JPanel implements ActionListener {
private int counter = 0;
private JButton btn;
public ButtonCycle() {
this.btn = new JButton("Next");
this.btn.addActionListener(this);
add(this.btn);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("Button cycling through animations");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(250,250));
f.setContentPane(new ButtonCycle());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
#Override
public void actionPerformed(ActionEvent a) {
switch(this.counter) {
case 0:
case 1:
this.counter++;
break;
case 2:
((JButton) a.getSource()).setEnabled(false);
// or like this
this.btn.setEnabled(false);
break;
}
}
}
Should give you what you need.
I am trying to do a simple Minesweeper game using JFrame, however I am having troubles with the creation of objects. I am creating 96 buttons, some of which get the property of being wrong ("F") and right ("R"):
public class GUIBase extends JFrame {
private JButton button;
private JButton fButton;
public GUIBase() {
super("Minesweeper");
setLayout(new FlowLayout());
//Fields
int position;
for (int i = 0; i < 96; i++) {
position = (int) (Math.random() * 100);
if (position < 80) {
button = new JButton("R");
button.setToolTipText("Is this the correct one?");
add(button);
} else {
fButton = new JButton("F");
fButton.setToolTipText("Is this the correct one?");
add(fButton);
}
}
I then use ActionListener in order to check whether or not the button is correct. If the button is correct, it will get .setEnabled(false), otherwise the game ends:
//Action
Action action = new Action();
button.addActionListener(action);
fButton.addActionListener(action);
}
private class Action implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("Somethin");
if (event.getSource() == button) {
button.setEnabled(false);
} else if (event.getSource() == fButton) {
JOptionPane.showMessageDialog(null, "You lost!");
System.exit(0);
} else {
JOptionPane.showMessageDialog(null, "An error ocurred");
System.exit(0);
}
}
}
Everything in the game turns out as planned, however only the last correct button ("R") and last wrong one ("F") are connected to the ActionListener. The rest of the buttons do not do anything when pressed.
How can I fix this?
The problem is that you only have two variables (attributes of the class GUIBase, specifically), and your are assigning to it each time you create a new button. Hence, you only have a reference to the last buttons.
You need an array of buttons. Let's see:
public class GUIBase extends JFrame {
public final int MAX_BUTTONS = 96;
private JButton[] buttons;
// ...
}
The next step is to create the array itself at the beginning:
public GUIBase() {
super("Minesweeper");
setLayout(new FlowLayout());
this.buttons = new JButton[MAX_BUTTONS];
//Fields
int position;
for (int i = 0; i < buttons.length; i++) {
position = (int) (Math.random() * 100);
this.buttons[ i ] = new JButton("R");
this.buttons[ i ].setToolTipText("Is this the correct one?");
this.add(this.buttons[ i ]);
Action action = new Action();
this.buttons[ i ].addActionListener(action);
}
}
You'll probably need more depth in arrays in order to completely understand the code. Basically, an array is a continuous collection of variables, which you can index by its position, from 0 to n-1, being n the number of positions.
Then you'll probably be able to fill the gaps yourself.
Hope this helps.
One part of your problems is coming from your action listener.
Of course, one part is that your code probably needs a list/array to keep track of all created buttons; but at least right now, you can rework your code without using arrays/list:
private class Action implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("Somethin");
if (event.getSource() instanceofJButton) {
JBUtton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
if (buttonText.equals("R") ...
else if (buttonText.equals("F")
You see, the whole point here is: as of now, you just need to know what kind of button was created. And your ActionListener knows which button it was clicked on ...
I've implemented code that will - amongst other things - make a series of JButton's disabled after being clicked. The code for this is below:
ActionListener disableButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (!(event.getSource() instanceof JButton)) {
return;
}
theModel.currentWord.append(event.getActionCommand());
wordDisplay.setText(theModel.getCurrentWord());
((JButton) event.getSource()).setEnabled(false);
}
};
theModel.randomLetters();
for (int i = 0; i < 16; i++) {
dice = new JButton(theModel.letters.get(i));
dice.addActionListener(disableButton);
boggleGrid.add(dice);
}
Notice the "((JButton)event.getSource()).setEnabled(false);" line. This, after completing the previous lines, makes any clicks on the button inactionable. I wish to reverse this when a seperate button is clicked. It's code is below:
JButton submitWordButton = new JButton("Submit Word");
submitWordButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent submit) {
wordDisplay.setText("");
theModel.currentWord.delete(0, 16);
((JButton) submit.getSource()).setEnabled(true);
}
});
info.add(submitWordButton, BorderLayout.SOUTH);
My dilemma is I don't know how to reference the JButton's outside of the ActionListener that disables them once clicked and hence enabled them again. The button I want to use to do this (the one with code most recently pasted above) is in another class. Any ideas?
I have 20 loop-generated JToggleButtons and I need to count how many of them are active.
private void generarBotones(){
JToggleButton b;
this.panelCuerpo.setLayout(new GridLayout(4,5));
for(int i = 1; i<=20; i++){
b = new JToggleButton();
b.setText(String.valueOf(i));
this.panelCuerpo.add(b);
b.addActionListener(new ActionListener() {
int clicks = 0;
#Override
public void actionPerformed(ActionEvent ae2){
clicks = clicks + 1;
System.out.println(clicks);
}
public void setCantidadBoletas(int clicks){
cantidadBoletas = clicks;
}
});
}
}
The problem here is that it counts how many times is EACH ONE of them clicked instead of count how many of them are selected.
PS. I tried to use (b.isSelected()) but b needs to be final to access it so it wasn't the solution.
If you declare the JToggleButton inside the loop, you can make it final:
for (int i = 1; i<=20; i++) {
JToggleButton b = new JToggleButton();
Then you can use b.isSelected:
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (b.isSelected())
clicks++;
else
clicks--;
}
});
}
clicks would have to be a class variable.
Suggestions:
Create a field, JToggleButton[] toggleButtons = new JToggleButton[20]
Or use an ArrayList if you so choose
In your for loop create your JToggleButton and assign it to the proper array item.
In the ActionListener simply iterate through the array, counting how many of its JToggleButton items are selected.
You're done.
Create a class attribute that will count the selected toggles:
private int selectedCount;
Initialize the counter to 0 in your constructor:
this.selectedCount = 0;
Increment or decrement the counter every time the state of a toggle changes:
b.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
if (ev.getStateChange() == ItemEvent.SELECTED){
YourClass.this.selectedCount++;
} else if (ev.getStateChange() == ItemEvent.DESELECTED){
YourClass.this.selectedCount--;
}
System.out.println(YourClass.this.selectedCount);
}
});
There are many ways to get this done and the best way depends on the rest of your code. I tried to keep it as close to yours.
You can just declare the buttons as final inside the loop and keep a global count of the number of buttons selected, which will be modified in the ActionListener:
public class ButtonsCount extends JFrame {
int clicks = 0;
ButtonsCount() {
JLabel label = new JLabel("0");
JPanel buttonsPanel = new JPanel(new GridLayout(4,5));
for(int i = 1; i <= 20; i++) {
final JToggleButton b = new JToggleButton();
b.setText(String.valueOf(i));
buttonsPanel.add(b);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae2){
if (b.isSelected())
label.setText(String.valueOf(++clicks));
else
label.setText(String.valueOf(--clicks));
}
});
}
add(buttonsPanel);
add(label, BorderLayout.PAGE_END);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new ButtonsCount();
}
}
I have a code below
jSlider1.setValue(0);
int i =0;
while (i <= jSlider1.getMaximum()) {
jSlider1.setValue(i);
// JOptionPane.showMessageDialog(rootPane,"deded");
Thread.sleep(2000);
i++;
}
What I want is I want to move JSlider automatically its min to max value. I have writeen above code. But I can not get the output. But when I remove the comment of "JOptionPane.showMessageDialog(rootPane,"deded"); " , It's work properly with the message. Please help me. I am in big trouble. I like to have a sample code if any one know the sollution.
Thank you
I am assuming you have create some JPanel or JFrame where you add this slider so,
final JSlider jSlider1 = new JSlider();
jSlider1.setValue(0);
jSlider1.setMaximum(100);
jSlider1.setBounds(0, 50, 300, 50);
final Timer increaseValue = new Timer(50, new ActionListener() {// 50 ms interval in each increase.
public void actionPerformed(ActionEvent e) {
if (jSlider1.getMaximum() != jSlider1.getValue()) {
jSlider1.setValue(jSlider1.getValue() + 1);
} else {
((Timer) e.getSource()).stop();
}
}
});
panel.add(jSlider1);
JButton moveSlider = new JButton("Start");
moveSlider.setBounds(10, 106, 55, 30);
moveSlider.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
increaseValue.start();
}
});
panel.add(moveSlider);