One JButton can do many action - java

Why when I press the button it doesn't do anything?. It won't go to the next frame I want on a certain condition I put
if(e.getSource()==btn2)
{
if (txt5.getText=="20")
{
Accept a = new Accept();
a.setAccept();
dispose();
//}
if (txt5.getText=="5")
{
Reject a = new Reject();
a.setReject();
dispose();
}
if(txt.getText=="10")
{
Reserve a = new Reserve();
a.setReserve();
dispose();
}
}

Related

infinite loop if pause java game

I have a part of my code:
while(_running){
// render screens
if( _input.escape) {
if( isPaused ) {
pauseDialog.setVisible(false);
remuse(); // set isPaused = false, _running = true and render screens
}
else {
pause(); // set isPaused = true and _running = false and render screens
pauseDialog.setVisible(true);
}
}
}
and _input like this
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
}
#Override
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
}
and pauseDialog
public class PauseDialog extends JDialog{
JButton b1,b2;
public PauseDialog() {
setLayout(new GridLayout(2, 1,8,8));
setSize(new Dimension(85, 180));
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
b1 = new JButton("resume");
b2 = new JButton("exit");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("resume");
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("exit");
}
});
add(b1); add(b2);
}
but if i setvisible(true) for pauseDialog when escape key is released, variable _input.escape is always set true value, so dialog appears and disappears and appears again ... like an infinite loop. what should i do next? thanks.
Set "_input.escape" to False, after Escape is pressed?
Or does "_input.escape" need to be True for pausing to happen?
If so, that implies something's wrong, 'cause you shouldn't need to hold down Escape to keep the game paused?
It just seems you need a good logic system so that the dialog isn't being triggered more than once.
Maybe check if it's already triggered and don't trigger it again?

wait for a jbutton click to continue with program execution java

how can I know in main method that one button is click to continue with the execution because the code doesn't work inside the actionperfomed button.
For example this is my main method
public static void main(String args[]) {
jwindows jw = new jwindows ();
//stop until a button inside the jwindows is clicked
// codeExecuteAfterButtonClick
}
The wait and notify methods is Object exist to handle this sort of situation
final JButton button = new JButton('click to continue');
button.setAction(new AbstractAction() {
public void actionPerformed(ActionEvent ae) {
synchronized (button) {
button.notify();
}
}
});
JFrame jf = new JFrame("Window");
jf.getContentPane().add(button, BorderLayout.CENTER);
jf.setDefaultCloseOperation(...);
jf.pack();
jf.setVisible();
synchronized(button) {
try {
button.wait();
} catch (InterruptedException ex) {
System.out.println("Interrupted");
}
}
System.out.println("After button clicked");

javafx: bug when trying to close window properly

I am designing the close window functionality for my desktop application. A high level explanation of the functionality is listed:
If I click the Exit menuItem, it prompts a ConfirmBox the user to confirm whether he wants to save or not before closing the application.
If the user click on the CloseButton on the window to force close the window (i.e. setOnCloseRequest function), the Exit menuItem event is fire off, which brings the user to case (1) again.
Within my ConfirmBoxcode, I have bind ENTER key to save things, N key to not save things and ESCAPE key to close confirmBox.
I have also set accelerator for the Exit menuItem (METAKEY + E).
Everything works fine. However, there is a minor bug if I follow this special sequence of steps. Whenever I use the accelerator for the Exit menuItem (i.e. METAKEY + E) and then I press either one of the 3 keys(ENTER, ESCAPE, N), the confirmBox closes but it pops up again.
I am wondering why is this happening only in this very special case?
public class ConfirmBox {
// answer[0] determines the need to Save
// answer[1] determines whether to close the application or not
private static boolean[] answer = new boolean[]{false,false};
private static Stage window;
public static boolean[] displayWarning(String title, String message){
window = new Stage();
window.initModality(Modality.APPLICATION_MODAL);
window.setTitle(title);
window.setMinWidth(300);
Label label = new Label();
label.setText(message);
Button yesButton = new Button("Yes");
Button noButton = new Button("No");
// needToSave = true, close Application = true and close this confirmbox
yesButton.setOnAction(ey ->{
answer[0] = true;
answer[1] = true;
window.close();
});
// needToSave = false, close Application = true and close this confirmbox
noButton.setOnAction(en -> {
answer[0] = false;
answer[1] = true;
window.close();
});
// needToSave = false, close Application = false and close this confirmbox
window.setOnCloseRequest(e -> {
answer[0] = false;
answer[1] = false;
closeConfirmBox();
});
// key binding
window.addEventHandler(KeyEvent.KEY_PRESSED, e -> {
if ( e.getCode() == KeyCode.N){
noButton.fire();
e.consume();
}
});
// bind enter key to yesButton
window.addEventHandler(KeyEvent.KEY_PRESSED, ev -> {
if (ev.getCode() == KeyCode.ENTER ){
yesButton.fire();
ev.consume();
}
});
window.addEventFilter(KeyEvent.KEY_PRESSED, ev ->{
if(ev.getCode()==KeyCode.ESCAPE){
ev.consume();
answer[0] = false;
answer[1] = false;
closeConfirmBox();
}
});
VBox layout = new VBox(20);
layout.setPadding(new Insets(20,5,20,5));
HBox bottomLayout = new HBox(50);
bottomLayout.setPadding(new Insets(20,5,20,5));
bottomLayout.getChildren().addAll(yesButton,noButton);
bottomLayout.setAlignment(Pos.CENTER);
layout.getChildren().addAll(label,bottomLayout);
layout.setAlignment(Pos.CENTER);
Scene scene = new Scene(layout);
window.setScene(scene);
window.showAndWait();
return answer;
}
public static void closeConfirmBox(){
window.close();
}
}
Within my controller class, this is how I designed my MenuItem menuItemExit.
menuItemExit.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e){
//System.out.println("set stage" + primaryStage);
boolean[] answer;
boolean needToSave = false;
boolean closeApplication = false;
if(saved.get() == false){
answer = ConfirmBox.displayWarning("Warning", "Do you want to save your stuff?");
needToSave = answer[0];
closeApplication = answer[1];
}
if(needToSave == true){
menuItemSave.fire();
}
if(closeApplication== true){
Platform.runLater(new Runnable() {
public void run() {
close();
}
});
}
}
});
primaryStage.setOnCloseRequest(e -> {
e.consume();
menuItemExit.fire();
});
menuItemExit.setAccelerator(new KeyCodeCombination(KeyCode.E, KeyCombination.META_DOWN));
public void close(){
this.primaryStage.close();
}

Java throwing exception when criteria not met

I've been working on this program for the last week or so and have had this particular block of code running smoothly up until a little while ago. I haven't changed it at all, and all of a sudden it started throwing an exception for every option picked once the button was pushed. I've tested it for each option by putting a "System.out.println(activityMultiplier);" statement in each block, and it prints the correct value, so the item listener seems to be working. And when I select "Choose an Activity Level" (the optin which is supposed to throw an exception) the exception is thrown properly: the JOptionPane goes away once I click okay, and the JComboBox is still there so I can make another selection. However, I get the JOptionPane error message for EVERY option now, I've included the noActivity() method at the bottom so you can see what I'm calling.
public void setActivity() //JComboBox
{
final JFrame activityWindow = new JFrame();
activityWindow.setTitle("Question No 6 of 6");
activityWindow.setLocationRelativeTo(null);
JPanel activityPanel = new JPanel();
activityPanel.setLayout(new BorderLayout(10, 10));
activityPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
JLabel activityLabel = new JLabel("Please select your activity level:");
final JComboBox activityList = new JComboBox(activityString);
activityList.setSelectedIndex(5);
activityList.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
activityLevel = (String) activityList.getSelectedItem();
}
});
JButton submitBtn = new JButton("Submit");
submitBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
if (activityLevel.equals("Choose an activity level"))
throw new Exception();
else if (activityLevel.equals("Sedentary (little or no exercise)"))
{
activityMultiplier = 1.2;
activityWindow.dispose();
setBMR();
}
else if (activityLevel.equals("Lightly active (light exercise/sports 1-3 days/week)"))
{
activityMultiplier = 1.375;
activityWindow.dispose();
System.out.println(activityMultiplier);
setBMR();
}
else if (activityLevel.equals("Moderatetely active (moderate exercise/sports 3-5 days/week)"))
{
activityMultiplier = 1.55;
activityWindow.dispose();
System.out.println(activityMultiplier);
setBMR();
}
else if (activityLevel.equals("Very active (hard exercise/sports 6-7 days a week"))
{
activityMultiplier = 1.725;
activityWindow.dispose();
System.out.println(activityMultiplier);
setBMR();
}
else if (activityLevel.equals("Extra active (very hard exercise/sports & physical job or 2x/day training)"))
{ activityMultiplier = 1.9;
activityWindow.dispose();
System.out.println(activityMultiplier);
setBMR();
}
}
catch(Exception e1)
{
noActivity();
}
}
});
private void noActivity()
{
JOptionPane.showMessageDialog(null, "Please select an activity level.", "No Selection Made", JOptionPane.ERROR_MESSAGE);
JOptionPane.getRootFrame().dispose();
}
why not simply change it to:
if (activityLevel.equals("Choose an activity level"))
noActivity();
the rest of the options are in else if blocks anyway
i don't think that is a proper use for an Exception

Using Jinput to pop up a JFrame WIndow alarm

Using Jinput and Java in Netbeans, I'm working on a very small project that simply Pops up a JFrame alarm window when lets say a user presses down on the 'K' on the keyboard and terminates the JFrame alarm window when the user lets go of 'k'. In my code, I seemed to get stuck in the while loop as the JFrame opened on the first press down and couldn't seem to close. I researched and I found that using javax.swing.Timer was the better way to do it. However, since I'm a newbie at this, all the different ways to use timer just made me even more confused. Could someone please see my code and point me in the right direction?
Here is my code;
public void startPolling() {
while(true) {
ControllerEnvironment.getDefaultEnvironment().getControllers();
ca[index].poll();
EventQueue queue = ca[index].getEventQueue();
Event event = new Event();
while(queue.getNextEvent(event)) {
StringBuffer buffer = new StringBuffer(ca[index].getName());
buffer.append(" at ");
buffer.append(event.getNanos()).append(", ");
Component comp = event.getComponent();
buffer.append(comp.getName()).append(" changed to ");
float value = event.getValue();
if(comp.isAnalog()) {
buffer.append(value);
} else {
if(value==1.0f) {
buffer.append("On");
if ("K".equals(comp.getName())){
alarmBox();
}
} else {
buffer.append("Off");
if ("K".equals(comp.getName())){
alarmBox.setVisible(false);
}
}
}
System.out.println(buffer.toString());
}
}
}
alarmBox() is my JFrame.
I was working on it and here is my updated code:
public void startPolling() {
Timer timer = new Timer(50, new ActionListener() {
public void actionPerformed(ActionEvent e) {
ca[index].poll();
EventQueue queue = ca[index].getEventQueue();
Event event = new Event();
while(queue.getNextEvent(event)) {
StringBuffer buffer = new StringBuffer(ca[index].getName());
buffer.append(" at ");
buffer.append(event.getNanos()).append(", ");
Component comp = event.getComponent();
buffer.append(comp.getName()).append(" changed to ");
float value = event.getValue();
if(comp.isAnalog()) {
buffer.append(value);
} else {
if(value==1.0f) {
buffer.append("On");
if ("K".equals(comp.getName())){
alarmBox();
}
} else {
buffer.append("Off");
if ("K".equals(comp.getName())){
alarmBox.dispose();
}
}
}
System.out.println(buffer.toString());
}
try {
Thread.sleep(20);
} catch (InterruptedException f) {
f.printStackTrace();
}
}
}); timer.start();
if you just want to open and close window,y to use timer?
you have a very complicated code,for a simple task.
you can add a ComponentListener to your JFrame to hide,somthing like this:
frame.addComponentListener(new ComponentAdapter(){
public void componentMoved(ComponentEvent e) {
if (popup.isVisible()){
popup.setVisible(false);
}
}
});

Categories

Resources