weird result (java event-handling code) - java

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

Related

I cannot clear my JTextArea, how can I clear the JTextArea?

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);
}

doClick(), and Simon: All buttons will unpress at the same time instead of individually

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.
}
}

JCheckBoxMenuItem only one selected

So I want to have a JMenu Level with three JCheckBoxMenuItem like Easy, normal and expert.
Of course, only one can be checked and if one is checked, it can't be unchecked (enabled(false)) because it's the only one.
I want when one JCheck is checked, all others are unchecked.
So it seems easy, but the only solution I found is to do it with a lot of "if" conditions.
Is there a way to do it with a better algorithm ?
It sounds like you'd be better off using a JRadioButton since check boxes are generally used for multiple-choice options and radio buttons for a single selection out of many. JRadioButtons can be grouped together using a ButtonGroup which allows only one selected at a time.
public void stateChanged(ChangeEvent e) {
if (e.getSource() == cb1 && cb1.isSelected()) {
cb2.setSelected(false);
cb3.setSelected(false);
} else if (e.getSource() == cb2 && cb2.isSelected()) {
cb3.setSelected(false);
cb1.setSelected(false);
} else if (e.getSource() == cb3 && cb3.isSelected()) {
cb1.setSelected(false);
cb2.setSelected(false);
}
}
i just put all my JCheckBoxMenuItems in an array
and every time i select a JCheckBoxMenuItem i call this method
public void clearCheckBoxes(){
for (JCheckBoxMenuItem arrayCB1 : arrayCB) {
if (arrayCB1 != cb) {
arrayCB1.setSelected(false);
} else {
arrayCB1.setSelected(true);
}
}
}
The annoying part was having to manualy put them in the array,maybe the jMenu class has a method that returns the complete array but i didnt bother looking
arrayCB[0]=bridgeCB;
arrayCB[1]=swampCB;
arrayCB[2]=flowerCB;
arrayCB[3]=MountainCB;
arrayCB[4]=Mountain2CB;
arrayCB[5]=forestCB;
arrayCB[6]=parisCB;
arrayCB[7]=roadCB;
arrayCB[8]=waveCB;
arrayCB[9]=lakeCB;
just in case , this is how you create the array
JCheckBoxMenuItem [] arrayCB=new JCheckBoxMenuItem[10];
i dont know about that lots of if statements way of doing it

Java MouseListener not always working

I find it odd that in my project, the mouselistener is not always heard. Has anyone else come across this? Or am I doing something wrong? I have to sometimes click it several times before it opens. I do wait between clicks to see if it is a performance issue.
JButton btnPin = new JButton("Pin");
btnPin.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
if(staffPinDialog == null || staffPinDialog.isShowing() == false)
staffPinDialog = new StaffPinDialog(idClicked);
}
});
StaffPinDialog is a JDialog, where the reference has been created elsewhere. idClicked is also always initialized.
You're not supposed to use a MouseListener to detect button clicks. Use an ActionListener instead.
This will also have the additional advantage of being able to click the button using the keyboard.

How can I enable a text field when a button is clicked?

before I start, I'm a beginner programmer.
How can I enable a text field when a button is clicked.
I have two frames, one that has the JFields and the other for the exception.
When the exception occurs > setEditable(false)
but what statement should I make to enable the JFields once the user click on okay button -that i've made in the exception-?
I've tried to add static boolean to exception frame, and inside the action performed of this class I initialized that boolean to true.
in the other class, I added an if statment, if that boolean is true, then setEditable(true)
-========-
The point of this program, that when the exception occurs the user cannot enter anything in the fields until he closes the exception window.
I wish you'd help me.
With all love, programmers.
The code of action performed for THE EXCEPTION WINDOW FRAME ( having Okay button. )
public void actionPerformed(ActionEvent e){
{
allow=true; //static boolean
Container TheFrame = OKButton.getParent();
do TheFrame = TheFrame.getParent();
while (!(TheFrame instanceof JFrame));
((JFrame) TheFrame).dispose();
}
The code of action performed for THE MAIN PROGRAM (having three fields, an exception will occur once the user enters non digits )
I added some comments to clarify.
public void actionPerformed(ActionEvent event) {
try{
r =Double.parseDouble(RField.getText());
s=Double.parseDouble(SField.getText());
h=Double.parseDouble(HField.getText());
Cone C = new Cone(r,s,h);//class cone
if (event.getSource() instanceof JButton) {
JButton clickedButton = (JButton) event.getSource();
if (clickedButton == VolumeButton) {
Result.append("VOLUME = "+C.volume()+ "\n");
ifV= true;//this's for clearing the fields for new entries.
}
if (clickedButton == AreaButton) {
Result.append("SURFACE AREA = "+C.surfaceArea()+ "\n");
ifA= true;//this's for clearing the fields for new entries.
}
if(ifA&&ifV){ // clearing the fields for new entries.
SField.setText(CLEAR);
HField.setText(CLEAR);
RField.setText(CLEAR);
ifV=false; ifA= false;}
}
SList.addShape(C);
}
catch(NumberFormatException e){
//Object of type "Exception__" already created
Ex.setVisible(true);//class "Exception__" is the one i've made for Exception window
SField.setText(CLEAR);
HField.setText(CLEAR);
RField.setText(CLEAR);
SField.setEditable(false);
HField.setEditable(false);
RField.setEditable(false);
}/*here, if the user clicked on -that okay in Exception window-
and variable allow initialized to "true" those statements should extend. I guess?
- everything worked correctly except for this ?*/
if(Ex.allow){
SField.setEditable(true);
HField.setEditable(true);
RField.setEditable(true); }
}
THANK YOU ALL IT FINALLY WORKED.
I added
Ex.allow(SField,HField,RField);
to the catch.
and added this method in class Exception__:
public void allow(JTextField js,JTextField jh,JTextField jr){
HField =jh;
SField =js;
RField =jr;
}
finally, to the action performed of class Exception__:
SField.setEditable(true);
HField.setEditable(true);
RField.setEditable(true);
WOHOOOO. It feels so awesome lol. Thanks all. should I delete my question or leave it for others who might face the same problem as mine? :P
Your question needs a lot more detail. But if all you want to to show an 'exception window' and allow the user to do anything else only after she dismisses this window, I think all you need is a MessageDialog:
See JOptionPane
If you need more details to be displayed you can create your own modal JDialog.
See How to Make Dialogs
Make the text field hiden by writing:
jTextfield.setVisible(fasle);
in the constructor of your form code. than use the button event " Action -> Action Performed " and write the code:
jTextfield.setVisible(true);
and thus your text field will be visible only after the button will be clicked.

Categories

Resources