It's a prototype for a virtual therapist, mainly for Java practice purposes. I've been trying to clear this JTextArea for 2 days now.
I've cleaned and rebuilt which got me through a few other hurdles, I'm at a loss for what to try. setEnabled() is coded out because I was just trying it on and off with different methods. Everything but the clear button works fine. I get a response in the text area after pressing enter with JTextField input. But it just won't clear.
public void actionPerformed(ActionEvent event)
{
String inp = event.toString(); //this is input in a JTextField
if(inp.contains("sad") || inp.contains("lonely"))
{
txtArea.setText(response1);
}else if(inp.contains(""))
{
txtArea.setText(response2);
}
else if(event.getSource() == clear) //clear is a button
{
//clear.setEnabled(true);
txtArea.setText(""); //I've tried selectAll(), replaceSelection()
}
}
From what I can see in your code this might help with the clear problem. In your code the if branch for the clear can never be reached due to the else after an condition(contains an emty string) that is always true. I moved it to the front - so it is reachable.
I can't say for sure from your posted code, but the event.toString() looks also suspicious as well as the last(in the changed code below) condition, that is always true.
//this looks odd/suspicious to me too!
String inp = event.toString(); //???!!! this is input in a JTextField
/* rather something like
* if(event.getSource() instanceof JTextField){
* inp = ((JTextField)event.getSource()).getText();
* }
*/
if(event.getSource() == clear) { //clear is a button
//clear.setEnabled(true);
txtArea.setText(""); //I've tried selectAll(), replaceSelection()
} else if(inp.contains("sad") || inp.contains("lonely")) {
txtArea.setText(response1);
} else if(inp.contains("")) { //??? always true!! rather: inp.equals("") or inp.isEmpty() ...
txtArea.setText(response2);
}
Related
I have multiple JTextFields and JComboBox in my JFrame. So whenever I click the _Add_ button it will check if the four (4) text fields in Current Medication Panel is Empty. If it is not then Execute, but it also depends if the Personal info Panel text fields are filled.
But I have a problem when I use the if and else statement, if I use the if and else:
if(condition if the first textfield is empty) {
// execute something like the textfield turn to red
} else if(condition if the second textfield is empty) {
// execute something like the textfield turn to red
} else if(condition if the third textfield is empty) {
// execute something like the textfield turn to red
} else{
// execute save information of the patient
}
In this situation if the 1st text field is empty then it will turn to red but if both 1st and 2nd text field is empty only the 1st text field turn to red.
I also tried the if, and if and if but were should put the else whenever there is no empty or invalid input where it will execute and save the patient info like this:
if(condition if the first textfield is empty) {
// execute something like the textfield turn to red
}
if(condition if the second textfield is empty) {
// execute something like the textfield turn to red
}
if(condition if the third textfield is empty) {
// execute something like the textfield turn to red
}
if(condition if the fourth textfield is empty) {
// execute something like the textfield turn to red
} else
If I use this only the last if statement only works for the else statement.
So if the last statement is true then execute, but not then else statement execute which is patient save info.
Is there any thing I can do about this? or is there any tutorial for me to learn more about Java and about if and else?
In the Add button action listener's actionPerformed method, you can try this:
public void actionPerformed(ActionEvent e) {
if (! textFieldsValid()) {
// one or more of the text fields are empty
// may be display a message in a JOptionPane
System.out.println("The text fields are not filled with data, etc...");
return;
}
// else, text fields have valid data, so do whatever processing it further...
}
/*
* This method checks if the text fields are empty and sets their borders as red. Returns
* a boolean false in case any of the text fields are empty, else true.
*/
private boolean textFieldsValid() {
boolean validTextFields = true;
if (textField1.getText().isEmpty()) {
validTextFields = false;
textField1.setBorder(new LineBorder(Color.RED));
}
if (textField2.getText().isEmpty()) {
validTextFields = false;
// textField2.setBorder(...)
}
// ... same with textField3 and textField4
return validTextFields;
}
but were should put the else
It is not mandatory to follow if with else. The purpose of specifying else is to allow your code execution flow to go through all other case when if was not satisfied (true).
if i use this only the last if statement only works for the else
statement
Because, if might have satisfied, so it executes else case. I would suggest to include return in each if case. So that, if any of the if case was satisfied. Then, it won't execute further code.
This should not be news to you: you are doing it wrong.
There are several ways to implement your desired solution,
here is one of them:
boolean performSave = true;
if (field1 is empty)
{
do some stuff.
performSave = false;
}
if (field2 is empty)
{
do some stuff.
performSave = false;
}
... repeat for any number of fields.
if (performSave) // no fields are empty.
{
save stuff.
}
i´m here because i´m getting crazy looking always into my code and try figuring out what I did wrong.
Guess I need some help and your new eyes which can help me out.
the problem is... I´m running through a rountine of checkboxes and when a checkbox is clicked a new one will be display. -> that works.
When i´m done I want to click a refresh-button and the checkboxes should be reseted as in the beginning.
To start over again.
But I don´t get it how...
this is the code what listens to the checkboxes...
/** Listens to the check boxes. */
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
if (source == chinButton) {
System.out.println("Chinbutton Pressed");
glassesButton.setVisible(true);
lblPass.setForeground(Color.green);
chinButton.setEnabled(false);
} else if (source == glassesButton) {
System.out.println("GlassesButtonPressed");
lblNewLabel_5.setForeground(Color.green);
hairButton.setVisible(true);
glassesButton.setEnabled(false);
} else if (source == hairButton) {
System.out.println("hairButtonPressed");
teethButton.setVisible(true);
lblNewLabel_6.setForeground(Color.green);
hairButton.setEnabled(false);
} else if (source == teethButton) {
System.out.println("teethButtonPressed");
chckbxTested_1.setVisible(true);
lblPass_1.setForeground(Color.green);
teethButton.setEnabled(false);
} else if (source == chckbxTested_1) {
System.out.println("chckbxTestedButtonPressed");
lblNewLabel_9.setForeground(Color.green);
System.out.println("chckbxTestedButtonPressed2");
chckbxTested_1.setEnabled(false);
btnSavePdfprint.setVisible(true);
}
}
I would really appreciate if there is someone out there who would help me with that issue.
THANKS
Hi I'm new to stackoverflow so bear with me if I make mistakes.
I'm making this Java Simon Says Game for a class project. It works by a random number generator for each sequence#. I show the sequence through doClick() but remove the actionlisteners beforehand and add it afterwards.
The problem is the buttons won't unpress or unarm until all other buttons have been pressed. I've tried using thread.sleep to put a delay between each if...else statements yet it only stays pressed for longer. I've tried updating the gui through repaint(), revalidate(), updateUI() within the try... catch of the thread.sleep but that didn't work either.
I've realized this issue is mainly cosmetic because when I tried implementing setPressed or setArmed it said it wasn't being pressed but it looked pressed.
Here is the code snippet in it's most simplest form without thread.sleep or my previous attempts in comments.
public void sequence2() //This is where the issue happens. The buttons won't unpress until every button has been pressed.
{
level.setText(" Level 2"); //Level indicator
Green.removeActionListener(Listener);
Red.removeActionListener(Listener);
Yellow.removeActionListener(Listener);
Blue.removeActionListener(Listener);
if(sequence1 == 1)
{
Green.doClick(300); //Programmatically clicks the button
}
else if(sequence1 == 2)
{
Red.doClick(300);
}
else if(sequence1 == 3)
{
Yellow.doClick(300);
}
else if(sequence1 == 4)
{
Blue.doClick(300);
}
if(sequence2 == 1)
{
Green.doClick(300);
}
else if(sequence2 == 2)
{
Red.doClick(300);
}
else if(sequence2 == 3)
{
Yellow.doClick(300);
}
else if(sequence2 == 4)
{
Blue.doClick(300);
}
Green.addActionListener(Listener);
Red.addActionListener(Listener);
Yellow.addActionListener(Listener);
Blue.addActionListener(Listener);
}
I'm very new to java so I'm not skilled in multithreading or working on the Event Dispatch Thread for that manner. But if that's the only solution I'll need some more help with that.
I have the full code in a zip file with previous attempts commented out if that will help.
https://drive.google.com/file/d/0Bxg4WleC9jD2VFhoZmZBNjV6Vkk/view?usp=sharing
Invoking doClick() may be an awkward choice for this, as it uses a Timer internally. Instead, use a JToggleButton, which will allow you to control each button's appearance based on its selected state using setSelected(). A complete example is shown in the game Buttons. In the ActionListener of your Swing Timer, select the current button, play its note and increment the sequence index. When all notes have been played, unselect all the buttons.
Addendum: Can you show how you implement the timer?
In outline, given a suitable list of toggle buttons:
private static final int MAX = 4;
List<JToggleButton> buttons = new ArrayList<JToggleButton>(MAX);
private int i;
The timer's listener might look like this:
#Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
JToggleButton b = buttons.get(i);
if (i > MAX) { // reset i and all the buttons
for (JToggleButton b : buttons) {
b.setSelected(false);
}
timer.stop();
i = 0;
} else {
b.setSelected(true);
// play tone i
i++;
}
}
A toggle button's item listener should update the button's appearance as indicated by its state:
#Override
public void itemStateChanged(ItemEvent e) {
JToggleButton b = (JToggleButton) e.getItem();
if (b.isSelected()) {
// change icon, color etc.
} else {
// restore icon, color etc.
}
}
i have a problem with my code. I think that my problem is easy,but i have compiled for 3 days without good results. I have three images. They are put on screen one-one each time. User choose from 4 button if image's side is up, down, right or left. Also, i want to understand if user was wrong and then i will count errors. When user make 3 errors then the game will stop. I have shown code below. Please help me if you have any good idea.
The problem is that at the first loop,run right.It goes at the first if. After that it do the loop and then it does not go to second if.
if it is more helpful,some details:
i want to make a programma that it will show to user an image.This image has 4 sides (up,down,right,left).When the image is at "up side",user has to click on up button,when the image is at "down side",user has to click on down button etc. User can do 3 errors max. At first,program show the image at right side,if user clicks on right button then i want to show the "second image" at left side.If user does not at left side,then i want to add an error(error++) and after it shows the third image at up side etc. I hope it is more helpful to understand. If you can't please let me know.
My program is at Netbeans,java.
Thank you
public void actionPerformed(ActionEvent e)
{
while(errors<3)
{
image.setIcon(createImageIcon("visual1" + e.getActionCommand() + ".PNG"));
if (k==1)
{
if(e.getSource() == right_button)
{
image.setIcon(createImageIcon("visual2" + e.getActionCommand() + ".PNG"));
}
}
else if ( k==2 )
{
if(e.getSource() == left_button )
{
image.setIcon(createImageIcon("visual3" + e.getActionCommand() + ".PNG"));
}
}
else if (k==3 )
{
if(e.getSource() == up_button)
{
System.out.print("if3");
}
}
else
{
errors++;
}
k=k+1;
}
}
You should consider calling Repaint and Invalidate, right after you update your GUI like this -
mainframe.repaint();
mainframe.invalidate();
here mainframe is your JFrame object.
A problem I see with your while loop is that it is at risk of getting stuck in an infinite loop, since the variable used as an exit criterion is only updated some of the time, in an else block. I think you should re-arrange your logic:
Get rid of that while loop as it will only cause trouble. It is useful for a linear command line program but not for an event-driven GUI program like yours.
Read in all images and create all ImageIcons in the class constructor, and store them in variables. There's no need to re-read the images multiple times (unless they're huge).
Instead of using a while loop, increment the error variable in your method above, and then write the method so that it will change behaviors depending on the value of error (depending on the state of the class).
e.g.,
// somewhere in your code create your icons
Icon rightIcon = ......;
Icon leftIcon = .....;
Icon upIcon = .....;
Icon downIcon = .....;
// elsewhere in your code
public void actionPerformed(ActionEvent e) {
if (errors >= 3) {
// notify user of error
return; // end this method
}
// check if current icon matches image
// if so, change icon
// if not increment error
}
Note that an enum Direction {UP, DOWN, LEFT, RIGHT} and a Map<Direction, Icon> could be helpful here.
public void itemStateChanged(ItemEvent event)
{
if(event.getSource() == doctorBox)
{
if (doctorBox.isSelected() == true)
JOptionPane.showMessageDialog(null, "you are a doctor");
else if (doctorBox.isSelected() != true)
JOptionPane.showMessageDialog(null, "you are not a doctor");
}
}
when the application is run... the checkbox is by default unchecked
when I check the "doctorBox" ... I get two dialog boxes popping together: "you are a doctor" and "you are not a doctor", also the checkbox doesn`t get checked!
why does that happen? how do I change the code to work correctly?
Here are some great samples. Remove all CheckBoxes except one and make sure you have a single listener to a single CheckBox per the details at the provided link. My guess is that there is strangeness occurring due to the way in which the listeners have been added in conjunction with the CheckBoxes.
Couple things to help you
for your logic, Since you know that the choice is either on or off, try the following
if(doctorBox.isSelected())
//do something
else
//do something else
with the checkbox not getting selected, change from an ItemListener to an ActionListener.
private class aListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == doctorBox){
if(doctorBox.isSelected())
JOptionPane.showMessageDialog(null, "you are a doctor");
else {
JOptionPane.showMessageDialog(null, "you are not a doctor");
}
}
}
}
If you look at your current code, and step through it using a debug you will see that your ItemListener gets fired 2 times. The first time checks it, the 2nd time it unchecks it. All on a single click. I cant explain the inner working of an itemListener in this case. ActionListener works much better