how to use options from showMessageDialog to do things? - java

I am making a game on Java and i am doing a character selection menu. Within that menu i have the characters and if the user clicks on certain character a JOptionPane.showMessageDialog appears shows the stats of the character. So my question is if the person clicks "ok" which is automatically created when using the function how to i get that to select the character?
JButton chuck = new JButton(new ImageIcon("8bitChuckNorris.jpg"));//this part of program runs this if user picks lizard
chuck.setSize(210,175); //sets size of button
chuck.setLocation(300,317); //sets location of button
chuck.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
JOptionPane.showMessageDialog(null, "\t\tSTATS\nAttack\ndefence\nspecial");
}
});

The simplest method would probably be to provide a method that the ActionListener can call after the
the option pane is closed, for example...
chuck.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
JOptionPane.showMessageDialog(null, "\t\t STATS\nAttack\ndefence\nspecial");
characterSelected("chuck"); // Pass whatever you need to identify the character
}
});
Updated
It would be easier to use JOptionPane.showConfirmDialog as it will actually return a int result representing the option that the user selected (or -1 if they dismissed the dialog without selecting anything)
switch (JOptionPane.showConfirmDialog(null, "\t\t STATS\nAttack\ndefence\nspecial", "Character", JOptionPane.OK_CANCEL_OPTION)) {
case JOptionPane.OK:
// Process selection...
break;
}

Related

Handling exit button which is create automatically?

I am building a text editor and I don't know how to handle a listener on Swing exit button, which is create automatically.
I want to use dialogs when user doesn't save file, for example press exit button.
final JFrame f = new JFrame("Good Location & Size");
// make sure the exit operation is correct.
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent we) {
// pop the dialog here, and if the user agrees..
System.exit(0);
}
});
As seen in this answer to Best practice for setting JFrame locations, which serializes the frame location & size before exiting.
Assuming you have a handle on your window, assuming it's a Window object (e.g. a JFrame or other kind of window), you can listen to WindowEvent events. Here is an example with windowClosed, you can replace it with windowClosing if you need to intercept it before.
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
// do something here
}
});
Go stepwise:
Declare a boolean variable saved and set its default value to false.
When user saves the file, change it to true
When exit button is pressed, check the variable.
If true, exit, else, prompt user for saving file.
So, finally this code snippet looks like:
public boolean saved = false;
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saved = true;
//Code to save file
}
});
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(saved)
System.exit(0);
else {
//Code to prompt user to save file
}
}
});

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.

JFrame-JDialog comunication

I have a JFrame main window wich has a Register button on in.Click the register button and the JDialog windows pops out.
public void mouseClicked(MouseEvent e) {
Reg new1=new Reg(users);
new1.setVisible(true);
}
The JDialog window has 2 buttons->Register,Cancel.Both of them must do something and close the Dialog window.
This is what I tried.
In the Reg(Dialog window)---> btnCancel:
public void mouseClicked(MouseEvent e) {
dialog.dispose();
System.out.println("Reg disposed by cancel button");
}
This closes the D window when run just the D window but I guess when executed from the main window(Button clicked) it still exists like an object in the main fraim"class" and doesn't close.What should I do ?How do I make it close ?
You need some way for the frame to determine how the dialog was closed
// Why are you using a `MouseListener` on buttons??
// User use keyboards to, use an ActionListener instead
public void mouseClicked(MouseEvent e) {
Reg new1=new Reg(users);
new1.setVisible(true);
switch (new1.getDisposeState()) {
case Reg.OK:
// Clicked Ok
break;
case Reg.CANCEL:
// Clicked cancel or was closed by press [x]
break;
}
}
Then in your Reg class, you need to maintain information about the state...
public class Reg extends JDialog {
public static final int OK = 0;
public static final int CANCEL = 1;
private int disposeState = CANCEL;
//...
public int getDisposeState() {
return disposeState
}
public void setDisposeState(int state) {
disposeState = state;
}
Then you change the state
// Why are you using a `MouseListener` on buttons??
// User use keyboards to, use an ActionListener instead
public void mouseClicked(MouseEvent e) {
setDisposeState(CANCEL);
dialog.dispose();
System.out.println("Reg disposed by cancel button");
}
This all assumes that your dialog is modal of course...
Now, having said all that, personally, I would make your Reg class a JPanel and add it to a JOptionPane instead or use a CardLayout
Take a look at:
How to Use Buttons, Check Boxes, and Radio Buttons
How to Write an Action Listeners
How to Make Dialogs
How to Use CardLayout
...for more details

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