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.
Related
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.
I need a button that, when pressed, enables all the other buttons, and changes the name of a label from "Off" to "On", and when pressed again, disables all the buttons and turns the switch to "off" back again, like an on/off switch. The thing is, I can "turn it" on, but I can't turn it back off.
If Swing, then perhaps you will want to place the buttons that you wish to control into an array or an ArrayList<AbstractButton>. That way the ActionListener of the control button can simply iterate through the array or the collection with a for loop, calling setEnabled(true) or false on the buttons. Consider making the controlling button be a JCheckBox or a JToggleButton.
Note, if you use a JToggleButton, then add an ItemListener to it. If you do so, there's no need to use booleans. Just check the state of the ItemEvent passed into the ItemListener's itemStateChanged method. If the getStateChanged() returns ItemEvent.SELECTED, then iterate through your JButton collection enabling all buttons. If it returns ItemEvent.DESELECTED, do the opposite.
Also note as per Byron Hawkins's comment:
You may want to consider that the ItemListener will receive events when the button is programmatically toggled, and also when the user toggles the button. The ActionListener only gets fired on input from the human user. I've often had bugs because I picked the wrong one.
If your button is pressed down and won't pop back up, chances are you have overridden a method in JToggleButton without calling super's version of it. Instead of overriding methods, create an ActionListener and use addActionListener() to attach to the button. When your listener is notified of button actions, check whether the toggle button is up or down and setEnabled() on the other buttons accordingly.
try use this simple code, use the variable as the flag
public int status = 0; //0 = on, 1=off
public void button_clicked()
{
//on button clicked
if(status == 0)
{
//logic here
status = 1;
buttonname.setText("Off");
}
//off button clicked
else if(status == 1)
{
//logic here
status = 0;
buttonname.setText("On");
}
}
you'll need a boolean to represent the state of the button.
In other words, when your button is off (your boolean variable is false), from your onClick listener, you'll call a method "turnButtonOn()" or something of that nature.
If your boolean variable is true, then you'll call a method turnButtonOff()
public void onClick() {
if(buttonOn){
turnOff();
}
else {
turnOn();
}
buttonOn = !buttonOn;
}
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.
I am making a button using MouseOverArea. After some trial and error, I realized I can override the methods in InputListener to do particular actions when an input event is notified.
For example, do things when mouse left button is pressed while cursor is over the component.
#Override
public void mousePressed(int button, int mx, int my) {
if (isMouseOver() && button == Input.MOUSE_LEFT_BUTTON) {
// Some magic happens
}
}
However, I will not able to do things like changing current game state because no Game object around. I know there are many ways to solve this problem, but I would like to know what is the Slick way to do this.
Are these methods suitable for such behavior ?
One way to modify game states is to use boolean states; Which are boolean variables that hold the state of the game or player. For example:
boolean isMovingUp, isMovingLeft, isMovingRight, isMovingDown;
You can then set these to true/false depending on what mouse or keyboard event takes place and your game class then read these variables, like so:
if (isMovingUp) {
// do something
isMovingUp = !isMovingUp;
}
Hope that helps!
HI all,
I'm trying to write a simple star rating component. I'm fairly new to the Java language and I'm not sure if what i want to accomplish can even be done in Java. Is it possible for me to add a JLabel inside an array of JLabel, and each JLabel in the array will have a mouse event listener. Now is it possible to set it up so that when the mouse event fires on say Label[3] that i can get the index value of it?
Here is how I built my Panel
public Rating(Integer max,int size) {
JLabel position = new JLabel[max];
this.setLayout(new FlowLayout());
for(int i=0; i != max;i++){
position[i]=new JLabel(icons.getIcon("star-empty", size));
position[i].setOpaque(true);
position[i].addMouseListener(this);
add(position[i]);
}
}
#Override
public void mouseEntered(MouseEvent e) {
JLabel a= (JLabel) e.getComponent();
//****Have some code in here to tell me where in the position array the event came from????***
int index = ?????
}
Thoughts/Idea/Suggestions please.
Note I thought of using buttons, but it looks messy and would love to find a way with ImageIcons.
THanks.
Instead of using the same listener for each label like you did:
position[i].addMouseListener(this);
...you can create a special listener class that takes the index number, and allows you to find it later:
position[i].addMouseListener(new RatingMouseListener(i));
Each label will have a separate instance of the listener with a different index value. The code for the inner class would look like something like this:
private class RatingMouseListener extends MouseAdapter {
private final int index;
public RatingMouseListener(int index) {
this.index = index;
}
#Override
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entered for rating " + index);
}
#Override
public void mouseExited(MouseEvent e) {
System.out.println("Mouse exited for rating " + index);
}
}
Then, you just override any method in MouseAdapter.
Also, like other people said, you might want to use JButtons instead of JLabels because they have better support for action events. You can still give them icons.
You could name each JLabel according to its index using its setName method, then use the MouseEvent's getComponent method to get the originating JLabel back, use getName on it and there's your index. That would be one way, but would involve storing the index information in two places (implicitly in its placement in the array, and explicitly as the label's name), so it's pretty much begging for inconsistency to arise.
You could also search through the array for the JLabel reference you get from getComponent, but that's not so great either, especially for large arrays.
The way I usually do it is:
int i;
for (i = 0; i <max; i++)
if (position[i] == e.getcomponent())
break;
now position[i] is the label you are looking for.
Just know that JButtons can look any way you'd like. They can have ImageIcons and don't even have to look like buttons.
Why is the index important? You know how to get the component, so just loop through the array to get the index.
Note I thought of using buttons, but it looks messy and would love to find a way with ImageIcons.
How does using a button solve the problem of determining the index? However, I also agree using a button is better than a label and then you would use an ActionListener instead of a MouseListener. You can make the button look like a label by using:
button.setBorderPainted( false );
Now if you use an ActionListener you can use the setActionCommand(...) method to store the index value of the button. Then in the event you use the getActionCommand(...) method.