Java throwing exception when criteria not met - java

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

Related

How to prevent that closing a JDialog closes the entire application

I have a main(screen) gui window and need to open a few "multi input" windows (jdialog or when not possible jframe), for example to add preferences (4 textfields with 2 filechoosers and 2 radiobuttons).
When pressing OK/Cancel in these JDialogs (or JFrames), my entire application closes.
I don't want that. How can I prevent that?
First try: I tried the intelliJ option "New -> Create Dialog class", which gives me a JDialog with OK/Cancel button. Pressing one of the buttons closes the JDialog and my entire application.
Second try: I wrote a class "by hand" which creates a JDialog (and also tried JFrame). Again: Pressing one of the buttons closes the JDialog and my entire application.
I removed "dispose()" and "setVisible(false)" options from theJDialog (JFrame), but still my entire application is closed.
main class method
public class mainScreen {
// Menu action listener (only relevant options)
class MenuActionListener implements ActionListener {
// menuListener
public void actionPerformed(ActionEvent ev) {
//myVariables myVars = new myVariables();
String[] dummy = null;
System.out.println("Selected: " + ev.getActionCommand());
switch(ev.getActionCommand()) {
case "Preferences":
showPreferencesDialog();
case "Exit":
System.exit(0);
break;
}
// method that opens the external class (see below in following code block)
private void showPreferencesDialog() {
prefJDialog myprefs = new prefJDialog(prefsPanel);
myprefs.showDialog();
boolean okPressed = myprefs.isOkPressed();
if (okPressed) {
JOptionPane.showMessageDialog(mainScreen.this.rootPanel,"OK pressed","About jExifToolGUI",JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(mainScreen.this.rootPanel,"Cancel pressed","About jExifToolGUI",JOptionPane.INFORMATION_MESSAGE);
}
}
// This is the class which is mention in the manifest
public mainScreen(JFrame frame) {
boolean preferences = false;
Preferences prefs = Preferences.userRoot();
createmyMenuBar(frame);
groupRadiobuttonsandListen();
fileNamesTableListener();
try {
myUtils.DisplayLogo(mainScreen.this.iconLabel);
} catch(IOException ex) {
System.out.println("Error reading Logo");
}
preferences = check_preferences();
if (!preferences) {
myUtils.checkExifTool(mainScreen.this.rootPanel);
}
programButtonListeners();
}
// main method in my main class for my project
public static void main(String[] args) {
JFrame frame = new JFrame("jExifToolGUI");
frame.setContentPane(new mainScreen(frame).rootPanel);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
The JDialog class/method that is called from the main class
package org.hvdw.jexiftoolgui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class prefJDialog extends JDialog {
private JButton okButton;
private JButton cancelButton;
private JPanel prefsPanel;
private boolean okPressed;
public prefJDialog(JPanel prefsPanel) {
super(JOptionPane.getFrameForComponent(prefsPanel), true);
this.prefsPanel = prefsPanel;
setTitle("Preferences");
initDialog();
}
public void showDialog() {
setSize(800, 768);
double x = getParent().getBounds().getCenterX();
double y = getParent().getBounds().getCenterY();
setLocation((int) x - getWidth() / 2, (int) y - getHeight() / 2);
setVisible(true);
}
private void initDialog() {
JPanel pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
pane.setBorder(BorderFactory.createEmptyBorder(10, 10, 5, 10));
add(pane);
pane.add(Box.createVerticalGlue());
FlowLayout l = new FlowLayout(FlowLayout.RIGHT);
JPanel buttonsPane = new JPanel(l);
okButton = new JButton("Save"); //$NON-NLS-1$
buttonsPane.add(okButton);
pane.getRootPane().setDefaultButton(okButton);
cancelButton = new JButton("CANCEL"); //$NON-NLS-1$
buttonsPane.add(cancelButton);
buttonsPane.setMaximumSize(new Dimension(Short.MAX_VALUE, (int) l.preferredLayoutSize(buttonsPane).getHeight()));
pane.add(buttonsPane);
addListeners();
}
private void addListeners() {
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//saveProperties();
setVisible(false);
okPressed = true;
//close();
// dispose();
}
});
cancelButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
//dispose();
//close();
okPressed = false;
}
});
}
public boolean isOkPressed() {
return okPressed;
}
/*public void close() {
WindowEvent winClosingEvent = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
}*/
}
So how do I prevent that upon clicking OK or Cancel in the JDialog, the entire application closes. That needs to stay open until the user clicks the "window close" X in the top-right, or from the menu "File -> Exit"
I have searched Google for several days, but can't find a solution (and one same question without answer).
Edit:
After Patrick's answer I changed the close method to
public void close() {
this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
}
And removed the /* and */.
I also activated the close(); in the listeners again, but it doesn't make a difference. My main app is still closed.
switch(ev.getActionCommand()) {
case "Preferences":
showPreferencesDialog();
case "Exit":
System.exit(0);
break;
And the problem is that you don't have a break statement in your switch case so the code falls through to the "Exit" logic and does a System.exit(0)
This is why we need a proper "MCVE" with every question. When you post random pieces of code we can't see the entire logic flow.

Return value from custom JDialog

I see this has been asked multiple times and apologize in advance if I'm just missing something simple...
I've created a custom JDialog with the examples provided in the Java docs here and from a similar question asked here.
My main application is a JFrame that contains a JPanel with an array of JButtons that display various employee names. I've added a custom ActionListener to each JButton that calls the mentioned JDialog:
//inner class for handling user button pushes
private class UserButtonHandler implements ActionListener
{
//handle button event
#Override
public void actionPerformed(ActionEvent event)
{
statusDialog = new ChangeDialog(statusWindow);
statusDialog.setVisible(true);
statusDialog.setLocationRelativeTo(null);
//set title for dialog box
String dialogTitle = "Status change for " + event.getActionCommand();
statusDialog.setTitle(dialogTitle);
statNum = ((ChangeDialog) statusDialog).getInputStatus();
System.out.println("Current num is: " + statNum);
//statNum = statusDialog.getInputStatus();
}
}
Here is the class for the custom JDialog (ChangeDialog):
class ChangeDialog extends JDialog implements ActionListener, PropertyChangeListener
{
//create panel where users can modify their status
private final ChangePanel empStatusChangePanel;
//text of buttons in dialog
private String btnString1 = "OK";
private String btnString2 = "Cancel";
private String btnString3 = "Clear Time-Off";
private JOptionPane statusPane;
//determines message to return for user input
private int inputStatus;
public ChangeDialog(JFrame statusFrame)
{
empStatusChangePanel = new ChangePanel();
//create an array specifying the number
//of dialog buttons and their text
Object[] options = {btnString1, btnString2, btnString3};
//create the JOptionPane
statusPane = new JOptionPane(empStatusChangePanel,
JOptionPane.PLAIN_MESSAGE,
JOptionPane.YES_NO_CANCEL_OPTION,
null,
options,
options[0]);
//set contents of dialog
setContentPane(statusPane);
//handle window closing
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
//register event handler for changes in status pane state
statusPane.addPropertyChangeListener(this);
pack();
}
#Override
public void actionPerformed(ActionEvent e)
{
statusPane.setValue(btnString1);
}
#Override
public void propertyChange(PropertyChangeEvent e)
{
String prop = e.getPropertyName();
if (isVisible()
&& (e.getSource() == statusPane)
&& (JOptionPane.VALUE_PROPERTY.equals(prop)))
{
Object value = statusPane.getValue();
if (value == JOptionPane.UNINITIALIZED_VALUE)
{
//ignore reset
return;
}
//Reset the JOptionPane's value. If this is not done,
//then if the user presses the same button next time,
//no property change event will be fired
statusPane.setValue(JOptionPane.UNINITIALIZED_VALUE);
if(value.equals(btnString1)) //user clicked "OK"
{
//validation of user input
inputStatus = empStatusChangePanel.validateUserInput();
//handle validation results
switch (inputStatus)
{
case 0: //user input is good
JOptionPane.showMessageDialog(this, "Good input given");
dispose();
break;
case 1: //one (or both) of the date pickers are empty
JOptionPane.showMessageDialog(this, "PTO pickers can't be empty.",
"ERROR", JOptionPane.ERROR_MESSAGE);
break;
case 2:
case 3: //bad date range (start before end or visa-versa)
JOptionPane.showMessageDialog(this, "Bad date range.",
"ERROR", JOptionPane.ERROR_MESSAGE);
break;
case 99: //dates are equal
JOptionPane.showMessageDialog(this, "Single-day PTO");
dispose();
break;
}
}
else if(value.equals(btnString3)) //user clicked "Clear Input"
{
JOptionPane.showMessageDialog(this, "User clicked 'clear input");
//more processing should be done here
empStatusChangePanel.recycle();
//dispose();
}
else //user clicked "Cancel" or closed dialog
{
JOptionPane.showMessageDialog(this, "User closed status window");
dispose();
}
}
}
//returns value from user validation
public int getInputStatus()
{
return inputStatus;
}
}
I need to access the method getInputStatus from the custom dialog but each attempt I've tried comes back stating that:
getInputStatus is undefined for the type JDialog
I have looked at several other similar posts but feel that I'm missing something fundamental in trying to solve this problem (or I've been looking at the code too long).
Another thing that has me stumped (and why I left it in the first snippet) is that if I cast the method to the type ChangeDialog
statNum = ((ChangeDialog) statusDialog).getInputStatus();
It suddenly has access (this was a suggestion from Eclipse and doesn't make sense to me). Thanks again for any and all help.
That is how inheritance works, you have defined statusDialog as a JDialog reference and JDialog doesn't have a getInputStatus method.
To access the members of ChangeDialog, you have to define statusDialog as variable of ChangeDialog.

One JButton can do many action

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();
}
}

Unchecking checkbox does not undo command?

Its my first time programming checkboxes; I figured out how to make a checkbox appear, and do a command when checked. However, when the box is unchecked, instead of undoing the command, it instead does the command a second time. How can I undo the command when unchecking the box?
Code: (instantiation of checkboxes)
negA = new JCheckBox("Neg");
negA.addActionListener(this);
negA.setActionCommand("A-5");
tossupA = new JCheckBox("Tossup");
tossupA.addActionListener(this);
tossupA.setActionCommand("A10");
powerA = new JCheckBox("Power");
powerA.addActionListener(this);
powerA.setActionCommand("A05");
Command:
public void actionPerformed(ActionEvent e)
{
//get the String value from the button pressed
String result = e.getActionCommand();
char team = result.charAt(0);
//set text on screen to reflect new score
String screenText = "Team "+(team)+"'s total score for this tossup: ";
//add score to subtotal and show on screentext
if(team=='A'){
teamATempScore += Integer.parseInt(result.substring(1));
screenText += teamATempScore;
}
//and now for B
else if(team=='B'){
teamBTempScore += Integer.parseInt(result.substring(1));
screenText += teamBTempScore;
}
When the box is unchecked, I want the score to decrement by the amount that it was incremented, but instead the score just increments again :(
Thanks!
(yes, if you were wondering, this is a scorekeeping program for a game of Quizbowl) :D
The listener just checks to see if the checkBox was clicked -- It doesn't check if it went from unchecked to checked, or vice versa.
Use the .isSelected() method to determine whether the checkbox is checked or not after it becomes clicked.
For example:
if (negA.isSelected())
{
//the checkbox was checked after they clicked it, do something
}
else
{
//the checkbox was unchecked after they clicked it, do something else
}
You have to check the state of the control and then either increment or decrement. The compiler cannot auto generate the reverse of your code.
To check the state of the checkbox, you call the isSelected() method on it like in the example below.
import javax.swing.JOptionPane;
public class CheckboxExample extends javax.swing.JFrame {
private javax.swing.JCheckBox jCheckBox1;
public CheckboxExample() {
jCheckBox1 = new javax.swing.JCheckBox();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.FlowLayout());
jCheckBox1.setText("CheckMe");
jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBox1ActionPerformed(evt);
}
});
getContentPane().add(jCheckBox1);
pack();
}
// this will get called when the state of the checkbox changes
private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jCheckBox1.isSelected()) {
JOptionPane.showMessageDialog(this, "Checked", "Message",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(this, "Unchecked", "Message",
JOptionPane.INFORMATION_MESSAGE);
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CheckboxExample().setVisible(true);
}
});
}
}

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