Second press of a GUI button - java

I'm trying to allow my button to be pressed a second time in my GUI after calculating and displaying dice rolled by a user. So far the only solution I've come up with is putting a .setSource(false); statement in my actionListener for my button. Where do I place my code (and I'm assuming there may be a more efficient statement to reset my button)?
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (e.getSource() == button){
/* my output when button is pressed
.
.
. */
e.setSource(false);
}
});

Perhaps utilize a class global boolean variable to be used as a toggle flag:
public class MyClass {
boolean toggle = false;
/*
other relative class code
*/
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
// If button is selected the first time.
if (e.getSource() == button && !toggle){
toggle = true;
/* my output when button is pressed the first time.
.
.
. */
e.setSource(false);
}
// If button is selected the second time.
if (e.getSource() == button && toggle){
toggle = false;
/* my output when button is pressed the second time.
.
.
. */
e.setSource(false);
}
});

Related

Trying to perform an action when a button is pressed

I am trying to make a game and I made a Button class using the JButton library.
This code is in the button class:
#Override public void mouseClicked(MouseEvent e) { pressed = true; }
public boolean getPressed(){
return pressed;
}
Then in the main java file:
Button playButton = new Button("PLAY", frame);
frame.add(playButton);
while (true){
if (playButton.getPressed())
System.out.println("test");
}
It never seems to print test even though I checked and the boolean value is being changed
I am unfamiliar with JButton. But it seems that in your if statement in your while loop, there is no condition. Please reply if this helps!

Event handling in Java (JTree + JButton)

private void createEvents()
{
menuFileExit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
System.exit(0);
}
});
////// Events on tree selection
jtStoryViewer.addTreeSelectionListener(new TreeSelectionListener()
{
public void valueChanged(TreeSelectionEvent arg0)
{
DefaultMutableTreeNode selection = (DefaultMutableTreeNode) jtStoryViewer.getLastSelectedPathComponent();
Object nodeObject = selection.getUserObject();
////// Checks if selected node is a String (only story title is a string)
if(selection.getUserObject().getClass().getName() == "java.lang.String" )
{
tfTitle.setText(nodeObject.toString());
////// Action listener for Change Button
btnChange.addActionListener(new ActionListener()
{
////// Title text swap
public void actionPerformed(ActionEvent arg0)
{
selection.setUserObject(tfTitle.getText());
((DefaultTreeModel)jtStoryViewer.getModel()).nodeChanged(selection);
}
});
}
///// checks if the object is a chapter object
if(selection.getUserObject().getClass().getName() == "ISW.common.Chapter")
{
Chapter chapter = (Chapter) selection.getUserObject();
tfTitle.setText(chapter.toString());
////// Action listener for Change Button
btnChange.addActionListener(new ActionListener()
{
////// Title text swap
public void actionPerformed(ActionEvent arg0)
{
chapter.setTitle(tfTitle.getText());
((DefaultTreeModel)jtStoryViewer.getModel()).nodeChanged(selection);
}
});
}
}
});
}
I am using JTree to display and modify some objects. I added a TreeSelectionListener to get the object data on selection. For now I want to be able to change the title of an object, it works fine on first selection on the tree , I change the value in the text box and the "Change" button works just fine, but when I move on to next objects, the change button also modifies the value of all previously selected objects.
I guess it is caused due to my improper usage of the ActionListeners but I can't tell for sure and at this point I'm stuck.
Will be grateful for any hints.
Don't keep adding an ActionListener to the btnChange JButton within the TreeSelectionListener#valueChanged method.
This will cause the button to call EVERY ActionListener you have previously
Instead, give the btnChange a single ActionListener, when clicked, can act on the currently selected node (by checking the JTree it self). You could have the TreeSelectionListener#valueChanged method enable or disable the btnChange based on the validity of the selection
Also, if(selection.getUserObject().getClass().getName() == "ISW.common.Chapter") isn't how String comparison is done in Java, instead you should use something more like if("ISW.common.Chapter".equals(selection.getUserObject().getClass().getName()))

How to avoid to work two JButton at the same time

I'm writing a simple paint program with Java. As all paint applications there are buttons for brushTool, sprayTool, sprayTool... This tools have their own class which extends to MouseAdapter. They are working as they should. However, the problem starts when I choose a tool after choose another tool, both buttons and their ActionListeners keep executing and they do what they are written for at the same time. I mean if I choose lineTool(which draws straight line) with rectangleTool I hava a diagonal too. here is example of my two button. What I'm tring to do is stop the current action when I click another button. Can you guys help me
brushBotton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
pen = new PenTool(mainDrawArea);
mainDrawArea.addMouseListener(pen);
mainDrawArea.addMouseMotionListener(pen);
}
});
rectangleButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
shapeToolbar.setVisible(false);
rect = new RectangleTool(mainDrawArea);
rect.setStrokeSize(strokeInt);
mainDrawArea.addMouseListener(rect);
mainDrawArea.addMouseMotionListener(rect);
}
});
You can't keep adding a MouseListener to the drawing area every time you click a button.
Instead you need to keep track of the current MouseListener. Then when you click a button you need to:
remove the current MouseListener
add the new MouseListener
I would replace the button action listener for a set of Toggle Buttons in a group
https://docs.oracle.com/javase/tutorial/uiswing/components/buttongroup.html
Then you move everything in a single mouse listener.
public void mousePressed(MouseEvent e) {
this.drawingState = !this.drawingState
if ( isRightCLick(e) ) resetAllPendingOperation();
if (drawingState) {
this.startPoint = getPointFromEvent(e);
switch(toolbarGetCurrentTool()) {
case "line":
registerMouseLineListener(startPoint);//here you draw live preview
break
case "rectangle":
registerMouseRectangleListener(startPoint); //here you draw live preview
break;
}
} else {
//user clicked the second time, commit changes
//same switch as above
this.endPoint = getPointFromEvent(e);
switch(toolbarGetCurrentTool()) {
case "line":
commitLine(startPoint, endpoint);//here you draw live preview
break
case "rectangle":
commitRectangle(startPoint, endpoint); //here you draw live preview
break;
}
}
}
You are currently binding the listeners to the mainDrawArea, not setting an action for each individual button.
Note that the codes you write within actionPerformed() for each button's actionListener is the action you want to trigger everytime that button is clicked. You do not want to add a new listener to the mainDrawArea everytime we click the buttons.
You can a create a state for your current action, for example:
brushBotton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
state = BRUSH;
}
});
lineBotton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
state = LINE;
}
});
state can be an integer and BRUSH and LINE are constant such as 0 and 1.
Then in the listener (for the mainDrawArea), check the current state
switch (state){
case BRUSH: //trigger action needed for brushing;
break;
case LINE: //trigger action needed for drawing line;
break;
}

set button condition based on other button condition

currently my program have a selection page which contain 4 action button with one terminate button and after the user click into one of the action button the button will set enabled (false) and i want to set terminate button in false mode when those 4 buttons are enabled but when 4 button is diabled than the terminate button will be enabled
do {
if (SIG.isEnabled() && RG.isEnabled() && AaCG.isEnabled() && SRG.isEnabled()) {
Terminate.setEnabled(false);
} else {
Terminate.setEnabled(true);
}
} while (Terminate.equals(false));
}
try to use do while loop but i dont know how to code it properly
Add an ActionListener to the button. The code it contains will be executed everytime the button is pressed.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Do your check here
if (SIG.isEnabled() && RG.isEnabled() && AaCG.isEnabled() && SRG.isEnabled()){
Terminate.setEnabled(false);
} else {
Terminate.setEnabled(true);
}
}
});
PD: According to the Java Naming Conventions, your variable, fields and method names should start with a lowercase letter, to not confuse them with a Class or an Interface.

Count number of button clicks in given time

JButton btnNewButton = new JButton("CLICK ME!");
btnNewButton.setBounds(134, 142, 274, 77);
btnNewButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
clicked++;
String x=Integer.toString(clicked);
textArea.setText(x);
}
});
I'm stuck here I want to create a program in GUI that counts the number of button click in specific time for example the timer start then count the number of clicks when the loop stop the button click is not working or stop counting the clicks
There are two possible solution
1.Make the button clickable when timer starts and unclickable when timer stops
Or
2.also u can use flag to check whether timer is running Or not.If timer is running make flag true when gets over make it false. Somthing like below snipet
public void actionPerformed(ActionEvent e) {
if (flag) {
clicked++;
String x=Integer.toString(clicked);
textArea.setText(x);
}
else
{
// doSomething
}
}
You can have some boolean variable which says if it's time for clicking (set on true when timer is started and on false when time's up). Then count clicks when this variable is true:
public void actionPerformed(ActionEvent e) {
if (timeIsRunning) {
clicked++;
String x=Integer.toString(clicked);
textArea.setText(x);
}
}
https://stackoverflow.com/a/9413767/1306811
Have a click counter.
private int clickCounter = 0; // as an example
Create get/set methods for it.
Add a MouseListener to your JButton so you can effectively track click events (MouseEvent arg0, arg0.getClickCount(), etc). At the end of each call to mouseClicked increment the clickCounter (clickCounter += arg0.getClickCount(), as an example).
Modify the answer linked so that clickCounter is set to 0 at every "time step" (however long you want it to be).
Voila.

Categories