How to randomly get item from string array? - java

I am trying to generate random questions from my String array called Questions. There 10 items inside. I am trying to set the text of JLabel where once the button is click one of the questions from the array will randomly be selected and displayed. However these 2 sections of code doesn't return anyting.
public String getNextQuestion() {
int NextQues = (int)(Math.random()*10);
return Questions[NextQues];}
public void actionPerformed (ActionEvent e) {
if(e.getSource() == Button) {
Hello.setText(Questions[NextQues]);

Don't hardcode the magic number 10 in getNextQuestion(). I would prefer
ThreadLocalRandom over Math.random(). Like,
public String getNextQuestion() {
return Questions[ThreadLocalRandom.current().nextInt(Questions.length)];
}
Then invoke that method in actionPerformed like,
public void actionPerformed(ActionEvent e) {
if (e.getSource() == Button) {
Hello.setText(getNextQuestion());
}
}

You should be calling your method getNextQuestion
OK, you need an actionlistener on your button in order for something to happen. Something like
public String getNextQuestion() {
int NextQues = (int)(Math.random()*10);
return Questions[NextQues];}
// inside main method
...
Button.addActionListener (
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Hello.setText(getNextQuestion());
}
});
...

Related

Java game involving adjacent JButtons

I'm making a small game involving a grid of JButtons (MxN) and the main premise is to click on buttonA and then on buttonB, coloring buttonB and adjacent buttons of the same color as buttonB with the color of buttonA. I have made it so you are able to choose 3 possible difficulties. The colors are randomly generated. The main problem is getting the colors to change.
This is the method that I call after selecting the difficulty of the game:
public static void gameMechanics(int m, int n) {
final String[] pickedColour = {""};
final String[] placedColour = {""};
JButton[][] picked = new JButton[m][n];
JButton[][] placed = new JButton[m][n];
picked[m][n].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickedColour[0] = picked[m][n].getText();
}
});
placed[m][n].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
placedColour[0] = placed[m][n].getText();
}
});
if (pickedColour[0] == "R" && placedColour[0] != "R") {
placed[m][n].setBackground(Color.RED);
placed[m][n].setText("R");
}
else if (pickedColour[0] == "G" && placedColour[0] != "G") {
placed[m][n].setBackground(Color.GREEN);
placed[m][n].setText("G");
}
else if (pickedColour[0] == "B" && placedColour[0] != "B") {
placed[m][n].setBackground(Color.BLUE);
placed[m][n].setText("B");
}
}
I would consider using JPanels and painting them, using a MouseListener instead.
However, if you're set on using JButtons, try this:
button.setBackground(Color.GREEN);
button.setOpaque(true);
Note that this might not work if you're setting the look and feel using UIManager.
Also, you're doing a ton of extra work to map the color to the button - it could get confusing and cause errors down the road. Instead, you might try creating your own class:
class ColoredButton extends JButton {
private static final long serialVersionUID = 3040767030924461426L;
private Color color;
public ColoredButton(Color c) {
this.color = c;
this.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
changeColor();
}
});
}
public void changeColor() {
this.setBackground(this.color);
this.setOpaque(true);
}
}
Now, you can construct a new ColoredButton:
// Now, this button will turn green when clicked
ColoredButton temp = new ColoredButton(Color.GREEN);

JButtons don't follow the intended handlers?

I'm making a minesweeper game, in the first part, I'm deciding whether or not there is a bomb at a certain button by using boolean1 (the field is a 16x16 array) I have tested this part, and the output is correct. 50 random true values and the rest are false my problem starts at the second part, where I want to get a certain action by the button based on the value of the boolean1. When implementing the code, all of the jbuttonsfollow the second ActionListener where the icon is set to bomb I want to get the jbuttons to also follow the first handler.
1st procedure
static void placeMines()
{
for (int x=0;x<16;x++)
{
for (int y=0;y<16;y++)
{
if(boolean1[x][y]=(true))
{
boolean1[x][y]=false;
}
}
}
int minesPlaced = 0;
Random random = new Random();
while(minesPlaced < 50)
{
int a = random.nextInt(Width);
int b = random.nextInt(Height);
boolean1[a][b]=(true);
minesPlaced ++;
}
}
2nd procedure:
static void buttonfunctions()
{
for(int c=0;c<16;c++)
{
for(int d=0;d<16;d++)
{
if (boolean1[c][d]=false)
{
final int temp3=c;
final int temp4=d;
jbuttons[c][d].addActionListener(new ActionListener()
{
#Override
public void actionPerformed (ActionEvent e)
{
jbuttons[temp3][temp4].setIcon(clickedCell);
}
});
}
if(boolean1[c][d]=true)
{
final int temp1=c;
final int temp2=d;
jbuttons[temp1][temp2].addActionListener(new ActionListener()
{
#Override
public void actionPerformed (ActionEvent e)
{
jbuttons[temp1][temp2].setIcon(bomb);
}
});
}
}
}
}
In order to check if a boolean is true, you want to do :
if (myBoolean)
doing
if (myBoolean == true)
is equivalent, but more verbose than needed.
doing
if (myBoolean = true) is syntactically correct, but has the effect of assigning true to myBoolean, and then evaluating the result of the assignment, which is true. So, going back to your code:
If the intent of the following code is to reset the matrix:
if(boolean1[x][y]=(true))
{
boolean1[x][y]=false;
}
then you should just do
boolean1[x][y] = false;
Also
if (boolean1[c][d]=false)
should probably be:
if (! boolean1[c][d])
There may be more stuff wrong with your code, but you may want to start fixing this.

Multiple Jtextfields to be filled before Jbutton enable

Hi I badly need some help I already search about Jtextfield to be filled before jbutton enables, DocumentListener most people use to determined if Jtextfield is being populated. I tried DocumentListener and it works but all I want is all Jtextfield must be not empty before the Jbutton enables here is my code.
Ftext.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
change();
}
#Override
public void removeUpdate(DocumentEvent e) {
change();
}
#Override
public void changedUpdate(DocumentEvent e) {
change();
}
private void change(){
if (Ftext.getText().equals("") && Mtext.getText().equals("") && Ltext.getText().equals("") && Addtext.getText().equals("")) {
SaveButton.setEnabled(false);
} else {
SaveButton.setEnabled(true);
}
}
});
if (Ftext.getText().equals("") && Mtext.getText().equals("") && Ltext.getText().equals("") && Addtext.getText().equals(""))
Means that all the fields must be empty. Some times you need to read this logic aloud...
"if field is empty AND field is empty AND field is empty..."
If you used || (or) instead, it would mean that if any one of the fields was empty the statement would be true for example...
if (Ftext.getText().equals("") ||
Mtext.getText().equals("") ||
Ltext.getText().equals("") ||
Addtext.getText().equals("")) {...
You should also consider using .getText().isEmpty() or .getText().trim().isEmpty() if the fields shouldn't contain just spaces.
You might also consider writing a single DocumentListener implementation instead of creating a new anonymous class for each field
public class FieldValidationHandler implements DocumentListener() {
private List<JTextField> monitorFields;
public FieldValidationHandler(JTextField... fields) {
monitorFields = Arrays.asList(fields);
for (JTextField field : monitorFields) {
field.getDocument().addDocumentListener(this);
}
}
#Override
public void insertUpdate(DocumentEvent e) {
change();
}
#Override
public void removeUpdate(DocumentEvent e) {
change();
}
#Override
public void changedUpdate(DocumentEvent e) {
change();
}
private void change(){
boolean enabled = true;
for (JTextField field : monitorFields) {
if (field.getText().trim().isEmpty()) {
enabled = false;
break;
}
}
SaveButton.setEnabled(enabled);
}
}
Then you'd just create a single instance...
FieldValidationHandler handler = new FieldValidationHandler(Ftext, Mtext, Ltext, Addtext);
Now, this approach is a little sneaky, in that it adds the DocumentListener to the fields you specify via the constructor automatically.
Another approach might be to have some kind "Validation" controller, that you would pass to this handler and it would call some kind of "validate" method when change was called.
This would separate the listener from the fields, but this is all a matter of context at the time.
I would personally have a "register" and "unregister" process which would allow you to add or remove fields as you need to

detect enter key in JTextField and do something in actionperformed

As i have seen many answers are too obscure for a entry level student like me.
i am following the steps by first addActionListner(this) to my JTextField.
what i am trying to do next and confuses the most is under:
public void actionperformed(Actionevent ae){
if(ae.getSource() == "Enter pressed")
{
outArea.setText(result);
}
}
which does not work because i feel like the code ae.getSource() == "Enter presses" is not working correctly and even i replaced the action i took under actionPerformed by a simple print line command like System.out.println("working"), it won't execute.
here is what i do if a button is pressed.
public void actionperformed(Actionevent ae){
if(ae.getSource() == "JButton")
{
System.out.println("JButton was pushed");
}
}
no matter how, lets say i have a GUI with a piece of given code like these:
public static void main(string[] args){
new myProg();
}
public myProg(){
....
buildTheGUI();
...}
}
//GUI Objects
...
JTextField input = new JTextField(10);
...
//method building the GUI
public void buildTheGUI(){
...
input.addActionListner(this);
...
//a method called actionPerformed
public void actionperformed(Actionevent ae){
}
i am now trying to detect the enter key by actionListner not by any other method because it's given.
Firstly, actionPerformed is triggerd by an action event, typically on most systems, this is triggered by the Enter key (with context to the JTextField)...so you don't need to check for it.
Secondly, the source of the ActionEvent is typically the control that triggered it, that would be the JTextField in this case.
Thirdly, String comparison in Java is done via the String#equals method...
if ("Enter presses".equals(someOtherString)) {...
Your actionPerformed method for the Button is wrong, try better this:
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof JButton) {
JButton button = (JButton) e.getSource();
System.out.println("This button was pushed: " + button.getText());
}
}
And your for KeyListener try this to learn how it works:
#Override
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyChar());
System.out.println(e.getKeyCode());
}
Dont forget to let your class implement ActionListener and KeyListener.

how to afect jlabel by changing different combobox values

I'm having some trouble using two comboboxes to affect the state of one item. Each combo box has a value between 1 and 99, I'm trying to change the values in each, combine them, then display this value on a jlabel. So far I can only the first combobox seems to impact the formula. I have simplified it to the following and thanks for any help :)
private int value1int, value2int;
value1.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent ex)
{
if (ex.getStateChange() == ItemEvent.SELECTED)
{
// assume single selection
int value1int = (Integer)ex.getItemSelectable().getSelectedObjects()[0];
}
}
});
value2.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent exs)
{
if (exs.getStateChange() == ItemEvent.SELECTED)
{
// assume single selection
int value2int = (Integer)exs.getItemSelectable().getSelectedObjects()[0];
}
}
});
overallValue2.setText((Integer.toString(value1int + value2int)));
overallValue2.revalidate();
you have to do something like that:
public class GUI extends JFrame ...
private int labelVal;
...
// combobox events - The same code to both comboboxes must works
public void itemStateChanged(ItemEvent exs)
{
if (exs.getStateChange() == ItemEvent.SELECTED)
{
// assume single selection
int aux = (Integer)combobox1.getSelectedItem()+(Integer)combobox2.getSelectedItem();
int labelVal= aux;
}
}
Them refresh the screen

Categories

Resources