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.
Related
I have 3 buttons
b1
b2
b3
I want to now have these buttons be pressed in turns.
So turn one I press and turn 2 another person presses.
So after turn two, I will compare the names of the buttons.
b1.addActionListener(new ActionListener() {
public void actionPerformed( ActionEvent event ) {
b1.setEnabled(false);
if (!b1.isEnabled() && !b2.isEnabled()) {
//computeWinner(b1.getText(), b2.getText());
} else if(!b1.isEnabled() && !b3.isEnabled()) {
//computeWinner(b1.getText(), b2.getText());
}
}
});
This was what I thought would work, but there are many things wrong with this,
First, since I disable the buttons the second user always has one less option. and second the if statements do not seem to work? how should I compare the
JButton b3 = new JButton ("hello"); <- hello lable of the buttons?
EDIT:
I was able to successfully compare the two buttons. Now my only problem is that for the second player one of the buttons are disabled(how can I capture the first button press and the second without disabling them?). And that after the comparison I don't know how to reset the board to go again. (for a set number of loops.)
Thank you for the help!
The following code will print the label of the button which has been pressed. I hope, you should be able to proceed from here. Feel free to let me know if you face any further issue.
ActionListener actionListener = new ActionListener(){
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getActionCommand());
}
};
There are several options.
Store the buttons in a map<Integer, String>. the integer would be a count for keeping track of pushes. The string would be the actionCommand of the button pressed.
Store the button actionCommands in a list or array.
In either of the above you can provide appropriate logic to compare the buttons and then reset the arrays or map and count.
Note: The actionCommand defaults to the button label unless it explicitly set.
I was wondering if there was a method for JButtons that is, and I'm just guessing here, essentially a boolean that would be assigned a true or false value depending on whether or not a button is clicked. I understand that there are actionListeners and keyListeners and MouseListeners and a plethora of listeners, but I am searching for a method that would do something like this:
public boolean ButtonClickDetector (just pretend it's real)
{
if(JButton.isClicked())
{
return true;
}
else
{
return false;
}
I need this so that I can increase an integer only when a button is clicked. I have thought about just putting integer++; into the actionPerformed but I feel if I had a boolean, the code would function better, be less prone to error, and perhaps a bit more efficient. Please note, I am a high schooler and do not have oodles and oodles of coding experience so PLEASE dumb down your answers. When answering PLEASE PROVIDE AN EXAMPLE AND EXPLANTION OF WHAT YOU ARE SHOWING ME. Accompanying an example and explantion with documentation would be wonderful. Thanks.
No, there are no methods in the JButton class that allows you to perform such a check. You must use some kind of listener. Check the JavaDoc for JButton to see what methods are available.
http://docs.oracle.com/javase/7/docs/api/javax/swing/JButton.html
You can use e.getSource() to see where the event came from.
JButton button = new JButton();
int i = 0;
public void actionPerformed(ActionEvent e) {
if(e.getSource == button) {
i++;
}
}
This will allow you to only increase if that specific button was pressed.
So I have to create a simple GUI in Swing for my Java class and I've stumbled upon this minor cosmetic issue.
I have the following code:
JMenuItem mntmQuit = new JMenuItem("Quit");
mntmQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getModifiers() == MouseEvent.BUTTON1_MASK) {
System.out.println("You should fire.");
} else if (e.getModifiers() == MouseEvent.BUTTON2_MASK || e.getModifiers() == MouseEvent.BUTTON3_MASK) {
System.out.println("Why do you fire this event?");
} else {
System.out.println("And how can I catch when the accelerator was used?");
}
}
});
mntmQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, 0));
I've never seen a menu item that was invoked when right clicking or using any other mouse button than button 1. As it seems Swing sees this differently and sends an action event no matter which mouse button was pressed - in contrary to a JButton which wont fire anything unless it's clicked with mouse button 1.
Now I could live with that as I can easily catch mouse button 1 and perform my actions, but how about catching the usage of the accelerator? It will fire the action event but I don't see any possibility of catching it as it returns '0' as modifier (same as any other mouse buttons except 1, 2 and 3).
Is there any way that I can tell the JMenuItem that it should only react to mouse button 1 and it's accelerator? Similar to the way JButton does it?
JMenuItem mntmQuit = new JMenuItem("Quit");
mntmQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!(e.getModifiers() == InputEvent.BUTTON3_MASK)) {
System.out.println(e.getActionCommand());
}
}
});
mntmQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, 0));
Edit:
I've changed my answer, instead of checking for when the event is fired, you should be checking for when to NOT fire it. So in this case, Button3 or right click. The event will always fire when you press "q" or any mouse click.
The previous answer was bad, you don't want to use e.getModifiers() because it can potentially return true for events that you don't want to return true. e.g. if you had "q" and "w" set to the same button, but they do different things, both events would trigger on the first if statement checking e.getModifiers() == 0
Sorry for the confusion, hopefully this makes more sense.
if (event.getModifiers() == AWTEvent.MOUSE_EVENT_MASK)
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.
So I'm trying to write a JButton that will act like an enter key when pressed. It must be able to fool a JTextField that is in focus into calling its action listeners. It can not use the robot framework, because that will make every program think enter is pressed, which is a problem.
Here is the backstory:
I have a program (written in Swing) which allows someone to enter data in many textfields and other things by hitting enter after typing in the data. It works great.
However, most people that use it are using a second program at the same time which automatically listens for an enter key and shuts off a robot (for those of you who are familiar with FIRST robotics, I'm talking about the SmartDashboard and the Driver Station). There have been quite a few complaints about this. People want to enter data without disabling the robot. As it turns out, the SmartDashboard (the program people want to hit enter on) allows custom swing components to be run along with it.
not entirely sure if I understand your requirement correctly (will delete this if not) ...
You can manually dispatch an event to whatever component you want to address. In the case of wanting to dispatch to the focusOwner
find the focusOwner by querying the KeyboardFocusManager
create a keyEvent with the focusOwner as sender
dispatch that event to the focusOwner
Something like:
Action action = new AbstractAction("fake enter") {
#Override
public void actionPerformed(ActionEvent e) {
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
Component comp = manager.getFocusOwner();
KeyEvent event = new KeyEvent(comp,
KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0,
KeyEvent.VK_ENTER, KeyEvent.CHAR_UNDEFINED);
comp.dispatchKeyEvent(event);
}
};
JButton button = new JButton(action);
button.setFocusable(false);
Action textAction = new AbstractAction("text") {
#Override
public void actionPerformed(ActionEvent e) {
LOG.info("I'm the text action" + ((Component) e.getSource()).getName());
}
};
JComponent comp = Box.createVerticalBox();
for (int i = 0; i < 5; i++) {
JTextField field = new JTextField(20);
field.setName(": " + i);
field.setAction(textAction);
comp.add(field);
}
comp.add(button);
Edit
added some lines for actually playing with it (#Joe commented it's not working). Clicking the button triggers the action of the focused textField (here simply prints out the field's name) Local context is vista and jdk6u27.
You might try getRootPane().setDefaultButton() on the frame. There's an example here.
Grabbing the element with the focus and manually dispatching an enter event didn't quite work, but because I just wanted to effect various JTextField, I came up with a similar solution:
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (focusOwner instanceof JTextField) {
((JTextField) focusOwner).postActionEvent();
}
}
});
Thanks for pointing me in the right direction.