So my argument in my if statement below has to check if my JRadioButton is checked, but for some reason, even if it's not checked, the program still runs.
public void actionPerformed(ActionEvent e) {
String actionCheck = Binary.userInput1.getText();
if(Binary.binary.isEnabled() && actionCheck.matches("[01]+")){ // checks if its binary
int decimalValue = Integer.parseInt(actionCheck, 2);
String convertedDecimal = Integer.toString(decimalValue);
Binary.userInput2.setText(convertedDecimal);
}
else if (Binary.decimal.isEnabled() && decimalCheck(Binary.userInput1)){
int binaryValue = Integer.parseInt(actionCheck);
Binary.userInput2.setText(Integer.toBinaryString(binaryValue));
}
else
Binary.userInput1.setText("WRONG INPUT! -- try again");
}
What am I missing?
The buttons are called binary and decimal (Yes i know, my class is called Binary also, newbie errors)
Answer was found!
It's not isEnabled() that should be used in this case but the method isSelected()
Try to use yourJRadioButton.isSelected() instead of isEnabled().
Related
I recently run in to same problem as this guy 4 years before. He get some answers there but non of it work either for him or me and then the question was not updated anymore.
How to get string from JTextField and save it in variable?
The point is to check what is typed in textfield and if, like in example is yet decimal dot in the TextField, then consume event and not allow to add second decimal dot.
Main problem I figured out is that I need to add this inside the key event as shown belox. But this. statement inside the event reffers to event itself and not on JTextField.So I need to find bypass or other solution how to write getText statement
String text = this.getText().toString();
if someone have ideas of how to improve code as well I'm opened to any suggestions except for rewriting it as formatted field because the user experience is a little different, from the point where I was trying formatted field.
public class TxtfNumber extends JTextField {
String text = this.getText().toString();
public TxtfNumber(){
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
#Override
public boolean dispatchKeyEvent(KeyEvent evt) {
switch (evt.getID()) {
case KeyEvent.KEY_TYPED:
String text = this.getText().toString();
if(evt.getKeyChar()=='.'&& text.contains(".")){
evt.consume();
}
}
return false;
}
});
}
}
SOLUTION
I accidentally run in solution when I used lambda expression. The formula you need to use is the name of class then .this.
So in this case,
String text = TxtfNumber.this.getText().toString();
is the solution.
But eventually, when I know how to implement JTextField, I no longer need a solution by string. So I'm giving the whole code here for later use. Feel free to use it as Choose Bean component.
It restricts the user to use only one minus sign at the start of the text, one decimal dot anywhere and then type in two decimal numbers.
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import javax.swing.JTextField;
public class TxtfNumber extends JTextField {
public TxtfNumber(){
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
#Override
public boolean dispatchKeyEvent(KeyEvent evt) {
switch (evt.getID()) {
case KeyEvent.KEY_TYPED:
//restricts input charactes
if(!Character.isDigit(evt.getKeyChar()) && (evt.getKeyChar()!='.') && (evt.getKeyChar()!='-') && (evt.getKeyChar()!=','))
evt.consume();
//change , and . for securing of different keyboard language
if (evt.getKeyChar()==',')
evt.setKeyChar('.');
//allow only one decimal dot in text
if (evt.getKeyChar()=='.' && TxtfNumber.this.getText().contains("."))
evt.consume();
//allow minus sign only at the start of text
if (evt.getKeyChar()=='-' && TxtfNumber.this.getText().length() != 0)
evt.consume();
//allow two decimal numbers after dot
for (int i = -1; (i = TxtfNumber.this.getText().indexOf(".", i + 1)) != -1; i++) {
if (i+3 == TxtfNumber.this.getText().length())
evt.consume();
}
break;
}
return false;
}
});
}
};
I am a noob in Java and programing and I am making an app where the user is trying to guess a city based on a picture. The user sees a picture of the city and has three buttons under the picture with different answers in them. The pictures are randomized from an array and the buttons text changes so that atleast one of the buttons has the correct answer. I want a TextView with "correct" to show if user is correct and one with "incorrect" to show if user is wrong. The text is showing up when pressing any button and not when the button with the correct text is pressed. So this is what I have tried and am stuck on. And yes I know I have many mistakes in my code, such as names of methods and so. I will change these later.
I have three booleans that are set to false, they are representing which button is pressed. You will understand more later.
Boolean test1 = false;
Boolean test2 = false;
Boolean test3 = false;
In main i have three buttons and they all call on the checkanswer function. Also they all turn their own boolean to true there, which u will se why soon. Example of one of the buttons.
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
test1 = true;
checkanswer();
}
});
So here is the checkanswer function
public void checkanswer() {
DisplayRandomImage();
//Giving three strings random city names from the "cities" array.
Random rndBtnTxt = new Random();
String randomCity1 = cities[rndBtnTxt.nextInt(cities.length)];
String randomCity2 = cities[rndBtnTxt.nextInt(cities.length)];
String randomCity3 = cities[rndBtnTxt.nextInt(cities.length)];
//Setting the random city names to the three different buttons.
btn1.setText(randomCity1);
btn2.setText(randomCity2);
btn3.setText(randomCity3);
//takes the picked image from the "DisplayRandomImage" method.
String str = String.valueOf(pickedImg);
//Tells what to call the different pictures, they are known as numbers make sure they are given names instead.
if (pickedImg == 0)
str = "venice";
if (pickedImg == 1)
str = "new york";
//If-statement checking so that atleast one button has the correct answer.
if (randomCity1 != str || randomCity2 != str || randomCity3 != str) {
Random rndbtn = new Random();
Button x = btnArray.get(rndbtn.nextInt(btnArray.size()));
//Sets one of the three buttons so that it has the correct answer.
x.setText(str);
}
//See where the correct answer is
String buttonText1 = btn1.getText().toString();
String buttonText2 = btn2.getText().toString();
String buttonText3 = btn3.getText().toString();
//check if the button that the user pressed has the correct answer
if (test1.equals(true) && buttonText1.equals(str)){
CorrectAnswer();
test1 = false;
}
if (test2.equals(true) && buttonText2.equals(str)){
CorrectAnswer();
test2 = false;
}
if (test3.equals(true) && buttonText3.equals(str)){
CorrectAnswer();
test3 = false;
}
else
WrongAnswer();
}
I am not sure what I am doing wrong here. For example the "test1" is set to True when I press "btn1" and if "buttontext1" equals to the same as "str" does it should work. But for some reason it seems randomised which of the three buttons calls for the CorrectAnswer method. What am I doing wrong here?
Can we see CorrectAnswer? Also,
right off the bat, I noticed that instead of using test1, test2 and test3 to indicate which button was pressed, you can just pass some sort of argument into checkAnswer, like int button.
So onClick would look like this for the first button, and subsequent buttons by incrementing the 1:
public void onClick(View v) {
checkanswer(1);
}
and checkanswer would look like this:
public void checkanswer(int button) {
... (previous stuff) ...
//check if the button that the user pressed has the correct answer
if (button == 1 && buttonText1.equals(str)){
CorrectAnswer();
}
if (button == 2 && buttonText2.equals(str)){
CorrectAnswer();
}
if (button == 3 && buttonText3.equals(str)){
CorrectAnswer();
}
else
WrongAnswer();
}
So try this out.
Its pretty hard to tell where the bug is, if you only show us pieces of the full code.
Mistakes could be e.g. in CorrectAnswer()...
I would recommend binding onlick-listeners to your buttons instead of changing booleans.
Check this out here: https://developer.android.com/reference/android/widget/Button
Additionally I noticed another mistake:
randomCity1 != str || randomCity2 != str || randomCity3 != str
This will return true if at least one of the Strings does not contain the right answer
You probably want to enter the if-Statement, when there isnt already a button with the correct answer.This is what you would like to use:
randomCity1 != str && randomCity2 != str && randomCity3 != str
EDIT: Check out the answer of Barcode for another example of using onClicklisteners.
Thank you both for answering the question, i have found a way to complete this problem:
public void testingMethod(int button){
switch(button){
case 1:
if (buttonText1 == str)
CorrectAnswer();
else
WrongAnswer();
break;
case 2:
if (buttonText2 == str)
CorrectAnswer();
else
WrongAnswer();
break;
case 3:
if (buttonText3 == str)
CorrectAnswer();
else
WrongAnswer();
break;
}
}
And since you were wondering how the method CorrectAnswer looked like here it is, yes I know it's probably unnecessary having this method but I am noob after all.
public void CorrectAnswer() {
findViewById(R.id.txtIncorrect).setVisibility(View.GONE);
findViewById(R.id.txtCorrect).setVisibility(View.VISIBLE);
}
I am making a colour changer using RGB input, and I want to make sure the input's are integers whilst parsing. If one of the RGB values is not parsable, then it should clear that field but keep the fields that parsed fine. My code works but I have to use 3 try/catch statements but I want to reduce it to one. How would I merge all these three if possible?
How would I merge all these three if possible?
Move common code to helper method. I added value range check too.
private static int getChannelValue(JTextField field) {
String error;
try {
int value = Integer.parseInt(field.getText());
if (value >= 0 && value <= 255)
return value;
error = "Out of range";
} catch (NumberFormatException f) {
error = "Not an integer number";
}
JOptionPane.showMessageDialog(null, "No. " + error);
field.setText("");
return -1; // invalid
}
int r = getChannelValue(codeR);
int g = getChannelValue(codeG);
int b = getChannelValue(codeB);
if (r != -1 && g != -1 && b != -1)
centreName.setForeground(new Color(r, g, b));
I assume that you are having all of these values gather once a JButton is clicked? Well, instead of doing that why not store the values when the client is done writing to the TextFields and then use parseInt on that specific field?
field.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) { }
#Override
public void focusLost(FocusEvent e) {
// parse and store int here
}
});
Since Color only accepts integers 0-255, you could instead use a regex
inputString.matches("[12]?\\d?\\d")
The regex accepts 1/2/nothing for the first digit, a number or nothing for the second digit, and requires the third digit
This works for 0-255, but also accepts numbers like 05, 00, and 260 (but not 005, unless you make it [012]), but Integer.parseInt() will figure them out
You may want to also exclude values like 260, which is covered in: Validate if input string is a number between 0-255 using regex
inputString.matches("1?[0-9]{1,2}|2[0-4][0-9]|25[0-5]")) will exclude values like 260, but not 05 or 00
I am trying to make it so that instead of hitting the enter key in my java program to make the enter action occur, I can instead hit the enter key while a custom method is running. At this point, I have looked into Hashmaps but am pretty confused if this going to do what I want. Any help would be greatly appreciated. It seems like this should be an easy thing to do, but for some reason I am just not getting a solution to it.
So, I am thinking my code will be something like this. Essentially, I am making a game of Hot Potato and I need to have the players take turn entering a character (e, d, and c for team 1 and o, k, and n for team 2). This will be involving a GUI interface as well. A have a while loop that will end once a timer reaches zero. What I would like is for the players to be able to put in a letter into a JTextField in the GUI and then simply press spacebar (as they will be sharing a keyboard). Once they enter the right letter (I made it randomized), they can hit spacebar and they will have "tossed the potato" to the other player.
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE)
{
KeyEvent.VK_ENTER;
}
}
I am working all of this out of the actionPerformed(ActionEvent ev) method. The fuller code looks like this. The if statement is commented out because I would like the game to start when the main button is pressed, but right now I get a ton of compilation errors when I uncomment the JButton and have it working with the String text that is the dialogue from the text you enter into a JTextField.
public void actionPerformed(ActionEvent ev) {
Object eventSource = ev.getSource();
String text = entryText.getText(); // text entered into JText
//JButton eventButton = (JButton) eventSource;
System.out.println(text);
//if (eventButton.equals(main))
{
int totalTime = 1000*(HotPotato.randNum());
long startTime = System.currentTimeMillis();
System.out.println(totalTime/1000);
Boolean p1Start = false;
String input = "";
while (System.currentTimeMillis() - startTime <= totalTime)
{
p1Start = !p1Start;
char a = HotPotato.randLetterBoth(p1Start);
String aString = String.valueOf(a);
while (!input.equals(aString))
{
System.out.print(aString); // temporary, shows test letter
input = theKeyboard.next();
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE)
{
KeyEvent.VK_ENTER;
}
}
}
}
if (p1Start)
{
System.out.print("Team 2 Wins!");
}
else
{
System.out.print("Team 1 Wins!");
}
setLabels();
myPicture.makeHotPotatoOn(myHotPotato.state());
myPicture.repaint();
}
}
I am making a basic calculator for Android in Java. I am stuck in one final step where it must add the input with the previous input. Have a look at the code:
public void displayValue(){
String mything = display.getText().toString();
input = Integer.parseInt(mything);
}
public void number1(View view){
if (input == 0){display.setText("");}
display.append(Integer.toString(1));
displayValue();
}
public void number2(View view){
if (input == 0){display.setText("");}
display.append(Integer.toString(2));
displayValue();
}
public void plus(View view){
displayValue(); //result= 0
result = result + input; //result= input
input = 0; //input=0
//in this step input becomes 0 to let the user enter new number input but this
//input never add the old result and the equal shows the old result.
}
public void equal(View view){
displayValue();
display.setText(Integer.toString(result));
}
I noticed that if I add a line in equal method and add the result to input I get the correct answer but that's not gonna be helpful as there will be minus button too.
Any ideas?
Thanks.
It's definitely hard to tell because you don't include full code, which would be helpful, but could it be because you call displayValue(); in some places before doing the math? Specifically in the plus method.
Ok finally I came up with a solution.
As the only option for calculation of result and new input is in equal method (because logically when user press the equal button, so wants to ends the equation), so I added two boolean values for each minus and plus calculation. Then I added both calculation for adding or minus 2 values.
Then when the user inter first part of the calculation and then hit plus sign, the boolean value of plus becomes true and after entering new input and hitting the equal sign, it does the true part of the calculation. Well it is a bit hard to explain but i guess by looking at the code you would get what I mean.
boolean whenMinus = false;
boolean whenPlus = false;
public void plus(View view){
displayValue();
result = input;
input = 0;
whenPlus = true;
}
public void minus(View view){
displayValue();
result = input;
input = 0;
whenMinus = true;
}
public void equal(View view){
if (whenPlus == true){result = result + input; whenPlus = false;}
if (whenMinus == true){result = result - input; whenMinus = false;}
display.setText(Integer.toString(result));
}
I am not sure if it is the correct way of making this calculator. But I fixed my problem anyway. It would be great to comment me and let me know if it is the standard way or its kinda hacking. I am not a pro anyway.