How would one bind the "Enter" key on a keyboard to press a JButton? Currently trying to figure this out but have no idea on what to do.
Here is my code for reference. What it's supposed to do is create a guessing game (which it does) but I want to add the ability to press enter to click the "Enter" button (jButtonEnter in this case).
package day21;
import java.awt.*;
import java.awt.event.*;
//import java.applet.*;
import javax.swing.*;
//import javax.swing.border.*;
public class Day21 extends JApplet implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
//All important Variables
JTextArea outTextArea = new JTextArea(10,20);
JScrollPane scroller = new JScrollPane(outTextArea);
static int GuessMe = (int) Math.ceil(Math.random()*1000);//randomizes the number
JPanel jPanelTop = new JPanel();
JPanel jPanelMid = new JPanel();
JPanel jPanelLow = new JPanel();
JLabel jLabelTop = new JLabel("Guess a number between 1 and 1000");
static JTextField jTextFieldInput = new JTextField("Guess Here",25);
JButton jButtonEnter = new JButton("Enter");
JButton jButtonReset = new JButton("Reset");
JButton jButtonClose = new JButton("Close");
public void init(){
this.getContentPane().setBackground(Color.white);
this.setSize(new Dimension(400, 120));
//Top Panel
jPanelTop.setBackground(Color.cyan);
jPanelTop.setBorder(BorderFactory.createRaisedBevelBorder());
jPanelTop.setPreferredSize(new Dimension(14, 40));
jPanelTop.setToolTipText("Top Panel");
this.getContentPane().add(jPanelTop, BorderLayout.NORTH);
jPanelTop.add(jLabelTop);
//Middle Panel
jPanelMid.setBackground(Color.orange);
jPanelMid.setBorder(BorderFactory.createRaisedBevelBorder());
jPanelMid.setPreferredSize(new Dimension(14, 40));
jPanelMid.setToolTipText("Center Panel");
this.getContentPane().add(jPanelMid, BorderLayout.CENTER);
jPanelMid.add(jTextFieldInput);
jPanelMid.add(jButtonEnter);
jButtonEnter.addActionListener(this);
//Lower Panel
jPanelLow.setBackground(Color.black);
jPanelLow.setBorder(BorderFactory.createRaisedBevelBorder());
jPanelLow.setPreferredSize(new Dimension(14, 40));
jPanelLow.setToolTipText("Lower Panel");
this.getContentPane().add(jPanelLow, BorderLayout.SOUTH);
jPanelLow.add(jButtonReset);
jPanelLow.add(jButtonClose);
jButtonClose.addActionListener(this);
jButtonReset.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
double input = 0;
boolean Error = false;
String ErrorMSG = "Error: Please Enter a Number";
try{
input = Double.parseDouble(jTextFieldInput.getText().trim());;
}
catch(NumberFormatException n){
Error = true;
}
if(Error){
JOptionPane.showMessageDialog(rootPane, ErrorMSG); //If variable entered is not a number
}
String correctAnswer = "Hooray! You guessed Correctly! \n Press Reset to play again";
String tooHigh = input + " is too high";
String tooLow = input + " is too low";
if(!Error){
if(e.getSource() == jButtonEnter){
if (input == GuessMe){
jPanelLow.setBackground(Color.green);
JOptionPane.showMessageDialog(rootPane, correctAnswer);
}
if (input > GuessMe){
jPanelLow.setBackground(Color.red);
JOptionPane.showMessageDialog(rootPane, tooHigh);
}
if (input < GuessMe){
jPanelLow.setBackground(Color.red);
JOptionPane.showMessageDialog(rootPane, tooLow);
}
}
}
if(e.getSource() == jButtonReset){
Day21.reset(); //runs the reset() method which resets the window back to it's normal state
}
if(e.getSource() == jButtonClose){
System.exit(1); //exits the program
}
}
public static void reset(){
GuessMe = (int) Math.ceil(Math.random()*1000);//randomizes the number
jTextFieldInput.setText("Guess Here");
}
}
Check out Enter Key and Button for a discussion on this topic and a couple of solutions depending on your exact requirement:
use the root pane to set a default button
use the UIManager to have focus follow the button
use Key Bindings to invoke the default Action
Define a method - processEnterButton() and put all the necessary logic there. Call the method from actionPerformed() if the button was clicked. Also define key binding for the ENTER key and call the processEnterButton() from the binding as well.
Related
I'm trying to make a program that will do some fairly simple calculations in a JPanel. One of the requirements is that it will repeat until the user says otherwise. Unfortunately when the JPanel opens it does not wait for any user input, but instead moves right on to the next thing (as I have yet written the part that asks the user if he would like to continue or quit, it's currently in an infinite while loop which means that new JPanels just keep opening continually until I stop the program). My question is: Why isn't the program waiting until the user presses the Okay button to move on?
Here is my main():
public class Driver extends JFrame{
public static void main(String args[]){
do{
new GUI();
while (!GUI.isButtonPressed()){
}
//int choice = JOptionPane.showConfirmDialog(null, "Default tax rate is 7.5%\nDefault discount rate is 10%.\nKeep these default values?", "Choose an Option", JOptionPane.YES_NO_OPTION);
//switch (choice){
//case JOptionPane.YES_OPTION: {
//SaleItem newItem = new SaleItem();
//break;
//}
//case JOptionPane.NO_OPTION: {
//new GUI();
//break;
//}
//}
}while(true);
}
and here is my GUI:
import javax.swing.*;
import java.awt.event.*;
public class GUI extends JFrame {
JPanel panel;
JLabel priceLabel;
JLabel discountLabel;
JLabel taxLabel;
JTextField taxTextField;
JTextField priceTextField;
JTextField discountTextField;
JButton okayButton;
JButton defaultsButton;
final int WINDOW_WIDTH = 300;
final int WINDOW_HEIGHT = 250;
boolean buttonPressed = false;
public boolean isButtonPressed() {
return buttonPressed;
}
public void setButtonPressed(boolean buttonPressed) {
this.buttonPressed = buttonPressed;
}
public GUI(){
super("Item Properties");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
private void buildPanel(){
priceLabel = new JLabel("Enter the item price:");
priceTextField = new JTextField(10);
discountTextField = new JTextField(10);
discountLabel = new JLabel("Enter the discount percent:");
taxLabel = new JLabel("Enter the tax percent:");
taxTextField = new JTextField(10);
okayButton = new JButton("Okay");
okayButton.addActionListener(new ButtonListener());
defaultsButton = new JButton("Use Defaults");
defaultsButton.addActionListener(new ButtonListener());
panel = new JPanel();
panel.add(priceLabel);
panel.add(priceTextField);
panel.add(discountLabel);
panel.add(discountTextField);
panel.add(taxLabel);
panel.add(taxTextField);
panel.add(okayButton);
panel.add(defaultsButton);
}
private class ButtonListener implements ActionListener {
private boolean buttonPressed = false;
public void actionPerformed(ActionEvent event){
GUI.setButtonPressed(true);
SaleItem newItem = new SaleItem(Double.parseDouble(priceTextField.getText()), Double.parseDouble(discountTextField.getText()), Double.parseDouble(taxTextField.getText()));
}
}
The stuff about getButtonPressed() and isButtonPressed() and all that was me trying (unsuccessfully) to solve the problem on my own.
Thanks in advance for any help!
Unfortunately when the JPanel opens it does not wait for any user input,
Panels don't open. You add a panel to a frame or dialog. If you want something to "open" or "popup" then you use a JDialog.
SaleItem newItem = new SaleItem(...);
SaleItem should be a modal JDialog. Then the dialog will not close until the user clicks on button that you create to close the dialog. A dialog is created exactly the same way as you create a JFrame.
Here is a run down of the program:
Three JLables are made.
Three buttons are made corresponding to the labels.
When a button is pressed it calls a random generator that picks a number between 0-9.
Depending on what button is pressed the corresponding JLabel is changed to the number that was generated.
Once all three numbers (in each label) are the same it automatically changes the main label to "You Win!".
Number 5 is the part I am having trouble with. I cant seem to be able to compare or tell when all three are the same. I would love if someine could point me in the right direction or provide any kind of help.
Here is the code for the action listener
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class SlotMachinePanel extends JPanel
{
private JRadioButton button1, button2, button3;
private JLabel instr, first, second, third;
private int check1, check2, check3;
//-----------------------------------------------------------------
// Constructor: Sets up the GUI.
//-----------------------------------------------------------------
public SlotMachinePanel()
{
// First Panel
instr = new JLabel ("Please spin a wheel");
JPanel one = new JPanel();
one.setPreferredSize (new Dimension(200,50));
one.setBackground(Color.green);
one.add(instr);
// Second Panel
button1 = new JRadioButton("Spin me!",false);
first = new JLabel ("1");
JPanel two = new JPanel();
two.setPreferredSize (new Dimension(200,50));
two.setBackground(Color.cyan);
two.add(first);
two.add(button1);
// Third Panel
button2 = new JRadioButton("Spin me!",false);
second = new JLabel ("2");
JPanel three = new JPanel();
three.setPreferredSize (new Dimension(200,50));
three.setBackground(Color.green);
three.add(second);
three.add(button2);
// Fourth Panel
button3 = new JRadioButton("Spin me!",false);
third = new JLabel ("3");
JPanel four = new JPanel();
four.setPreferredSize (new Dimension(200,50));
four.setBackground(Color.cyan);
four.add(third);
four.add(button3);
ButtonGroup group = new ButtonGroup();
group.add(button1);
group.add(button2);
group.add(button3);
button1.addActionListener(new ButtonListener());
button2.addActionListener(new ButtonListener());
button3.addActionListener(new ButtonListener());
add(one);
add(two);
add(three);
add(four);
setPreferredSize(new Dimension(200, 210));
setBackground(Color.green);
}
//*****************************************************************
// listener for button pushes
//*****************************************************************
private class ButtonListener implements ActionListener
{
//--------------------------------------------------------------
//
//--------------------------------------------------------------
public void actionPerformed(ActionEvent event)
{
int num;
Random generator1 = new Random();
num = generator1.nextInt(9);
Object source = event.getSource();
if(source == button1){
check1 = num;
first.setText(Integer.toString(num));
}
if(source == button2){
check2 = num;
second.setText(Integer.toString(num));
}
if(source == button3){
check3 = num;
third.setText(Integer.toString(num));
}
if((check1 == check2) && (check2 == check3)){
instr.setText("You Win");
}
}
}
}
Its run using this
import javax.swing.JFrame;
import java.awt.*;
import javax.swing.*;
public class SlotMachine
{
//-----------------------------------------------------------------
// Creates the main program frame.
//-----------------------------------------------------------------
public static void main(String[] args)
{
JFrame frame = new JFrame("Slot Machine");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SlotMachinePanel());
frame.pack();
frame.setVisible(true);
}
}
Seems to be working to me..
I just compiled and ran the code and when all three have the same number, this if succeeds :
if((check1 == check2) && (check2 == check3)){
and the jlabel instr shows the message:
You Win
if you want to add another message where not all three are the same, use the following code
if((check1 == check2) && (check2 == check3)){
instr.setText("You Win");
}
else {
instr.setText("You Did Not Win Yet");
}
Orelse, what is the problem exactly?
You can do something like this:
if (label1.text.equals(l2.text) && label1.text.equals(l3.text)) doSomething();
There are 2 ways to check whether the player wins.
First way of doing:
Check whether the text on all 3 labels are the same.
if (label1.getText().equals(label2.getText()) && label2.getText().equals(label3.getText()))
instr.setText("Win!");
You can place the above codes in the listener when you click the button to generate the random number. This way, every click on the buttons, it checks for a win.
Second way of doing:
Every time a random number was generated, you can store that number in 3 int variables. Compare the int variables instead of the text of the 3 labels.
if ((val1 == val2) && (val2 == val3))
instr.setText("Win");
i'm trying to make enter key react instead of the mouse click.
i have no idea how to do that using java.
here is the code and the output.
import java.util.Random;
import javax.swing.*;
import java.util.Arrays;
import java.text.DecimalFormat;
import java.awt.event.*;
import java.awt.*;
public class PayRate extends JFrame
{
private JPanel panel;
private JLabel rateLabel;
private JLabel hoursLabel;
private JLabel payLabel;
private JTextField rateTextField;
private JTextField hoursTextField;
private JTextField payTextField;
private JButton calcButton;
private JButton clearButton;
private final int WINDOW_WIDTH = 350;
private final int WINDOW_HEIGHT = 160;
public PayRate()
{
setTitle("PAY RATE");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
private void buildPanel()
{
rateLabel = new JLabel("RATE");
hoursLabel = new JLabel("HOUR");
payLabel = new JLabel("");
rateTextField = new JTextField(8);
hoursTextField = new JTextField(8);
payTextField = new JTextField(27);
calcButton = new JButton("CALCULATE PAY");
clearButton = new JButton(" CLEAR ");
calcButton.addActionListener(new CalcButtonListener());
clearButton.addActionListener(new clearButtonListener());
getRootPane().setDefaultButton(calcButton); // make the enter key react instead of mouse click
//calcButton.setMnemonic(KeyEvent.VK_E); // make (ALT + E) response as an enter key
panel = new JPanel();
payTextField.setBackground(Color.ORANGE);
rateTextField.setBackground(Color.LIGHT_GRAY); // Set the Background of rateTextField to LIGHT_GRAY
hoursTextField.setBackground(Color.LIGHT_GRAY);// Set the Background of hoursTextField to LIGHT_GRAY
calcButton.setBackground(Color.GREEN); // Set the background of CalcButton to GREEN
rateLabel.setForeground(Color.BLUE); // set the Foreground of rate label to blue
hoursLabel.setForeground(Color.BLUE); // set the Foreground of hours label to blue
payLabel.setForeground(Color.BLUE); // set the Foreground of pay label to blue
panel.setBackground(Color.PINK);// Set the background of the panel to yellow
panel.add(rateLabel); // Add rate label to the panel
panel.add(rateTextField); // add rate text field to the panel
panel.add(hoursLabel); // add hour label to the panel
panel.add(hoursTextField); // add hours text field to the panel
panel.add(calcButton); // add calculate button to the panel
panel.add(payLabel); // add the pay label to the panel
panel.add(payTextField); // add pay text field to the panel
panel.add(clearButton);
}
private class CalcButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double rt ;
String input;
String display ="";
String output = " Your total pay for this week is: ";
double hrs;
double sum = 0;
DecimalFormat formatter = new DecimalFormat("#0.00");
input = rateTextField.getText();
rt = Double.parseDouble(input);
input = hoursTextField.getText();
hrs = Double.parseDouble(input);
sum = hrs * rt;
display = display + output.toUpperCase() + formatter.format(sum);
payTextField.setText(display);
}
}
private class clearButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
payTextField.setText("");
hoursTextField.setText("");
rateTextField.setText("");
}
}
public static void main(String[] args)
{
new PayRate();
}
}
Here is the output.
I Want the the calculate pay button to react to enter key instead of clicking on it using the mouse.
Thank You in advance.
Option 1: make the JButton of interest the default button for your JFrame's JRootPane:
calcButton = new JButton("CALCULATE PAY");
calcButton.addActionListener(new CalcButtonListener());
getRootPane().setDefaultButton(calcButton); // **** add this line ****
Option 2: add the same ActionListener to your JTextFields:
CalcButtonListener calcListener = new CalcButtonListener();
calcButton.addActionListener(calcListener);
rateTextField.addActionListener(calcListener);
payTextField.addActionListener(calcListener);
Edit
You ask in comment:
what if i want another key (such as space key) to react as the enter key? is that possible?
Answer:
A JButton is already wired to respond to space key press if the button has the focus. Otherwise, 1) set the button's mnemonic to respond to an alt-key combination, or 2) use key bindings to bind the button to any key or key combination.
An example of a mnemonic:
calcButton.setMnemonic(KeyEvent.VK_C);
If you add this to your program, you'll see that the first "C" in the button's text is underlined. Your button will also respond to alt-c presses.
Add this code
public PayRate(){
setTitle("PAY RATE");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
getRootPane().setDefaultButton(calcButton);// here it is
}
I am building a simple JFrame GUI requiring user input. If the user clicks the submit button, it checks for input then either renders a JOptionPane message telling the user to completely fill out the form, or it tells the user that the form submitted and closes the program. The problme is that if the user left blank fields, the message dialog box renders and only adds to the loop count if you try to close it and does not allow the user to return to the JFrame to apply input to the form.
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.util.Scanner.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* #author joel.ramsey
*/
public class JRStarPhase5 extends JFrame{
public static void main (String [] args) throws IOException {
JFrame window = new JRStarPhase5();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}//end main method
private boolean validationError;
private final JTextField fNameInput;
private final JTextField miInput;
private final JTextField lNameInput;
private final JTextField productChoiceInput;
private final JTextField licenseQuantityInput;
private final JTextField streetAddressInput;
private final JTextField cityInput;
private final JTextField stateInput;
private final JTextField zipInput;
private final JTextField phoneInput;
//constructor for JFrame
public JRStarPhase5(){
setTitle("JRStar Star Gaze Order Processing");
setSize (800,800);
Container pane = getContentPane();
GridLayout grid = new GridLayout(0,2);
pane.setLayout(grid);
JLabel fNameLabel = new JLabel ("First name:");
JLabel mi = new JLabel ("Middle initial:");
JLabel lNameLabel = new JLabel ("Last name:");
JLabel productChoice = new JLabel ("Star Gaze version:");
JLabel licenseQuantity = new JLabel ("License quantity:");
JLabel streetAddress = new JLabel ("Street address:");
JLabel city = new JLabel ("City:");
JLabel state = new JLabel ("State abbrev:");
JLabel zip = new JLabel ("Zip code:");
JLabel phone = new JLabel ("Phone Number:");
this.fNameInput = new JTextField(15);
this.miInput = new JTextField (1);
this.lNameInput = new JTextField (15);
this.productChoiceInput = new JTextField (1);
this.licenseQuantityInput = new JTextField (2);
this.streetAddressInput = new JTextField (20);
this.cityInput = new JTextField (20);
this.stateInput = new JTextField (2);
this.zipInput = new JTextField (5);
this.phoneInput = new JTextField (10);
//add as last buttons
JButton submit = new JButton("Submit");
SubmitButtonHandler sbh = new SubmitButtonHandler();
submit.addActionListener(sbh);
JButton clear = new JButton("Clear");
ClearButtonHandler cbh = new ClearButtonHandler();
clear.addActionListener(cbh);
pane.add(fNameLabel);
pane.add(fNameInput);
pane.add(mi);
pane.add(miInput);
pane.add(lNameLabel);
pane.add(lNameInput);
pane.add(productChoice);
pane.add(productChoiceInput);
pane.add(licenseQuantity);
pane.add(licenseQuantityInput);
pane.add(streetAddress);
pane.add(streetAddressInput);
pane.add(city);
pane.add(cityInput);
pane.add(state);
pane.add(stateInput);
pane.add(zip);
pane.add(zipInput);
pane.add(phone);
pane.add(phoneInput);
//add last
pane.add(submit);
pane.add(clear);
}//end constructor
private class SubmitButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
validationError = (fNameInput.getText().equals("")||
miInput.getText().equals("")||
lNameInput.getText().equals("")||
streetAddressInput.getText().equals("")||
cityInput.getText().equals("")||
stateInput.getText().equals("")||
zipInput.getText().equals("")||
phoneInput.getText().equals(""));
for (int n=1; n<3; n++){
if (validationError){
if (n == 3){
System.exit(0);
}
JOptionPane.showMessageDialog(null,"Please complete each field within the order form.");
}
else break;
}
if (validationError = false)
JOptionPane.showMessageDialog(null,"Your order has been submitted!");
System.exit(0);
}
}//end submit
private class ClearButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
fNameInput.setText("");
miInput.setText("");
lNameInput.setText("");
productChoiceInput.setText("");
licenseQuantityInput.setText("");
streetAddressInput.setText("");
cityInput.setText("");
stateInput.setText("");
zipInput.setText("");
phoneInput.setText("");
}
}//end clear
}//end main class
I honestly don't know what else you expected (no offense).
Swing is a event driven environment. An event occurs, you react to it...
The loop will execute within the context of the EDT to start with, meaning that there is no way a user could actually close the dialog, correct the error and try to re-submit.
Even if it did, the loop does not allow for any opportunity for the validationError variable to be re-evaluated, meaning it will always be what it was originally set to earlier in the method (lets assume true for now)...
for (int n = 1; n < 3; n++) {
if (validationError) {
if (n == 3) {
System.exit(0);
}
JOptionPane.showMessageDialog(null, "Please complete each field within the order form.");
} else {
break;
}
}
if (validationError = false) {
JOptionPane.showMessageDialog(null, "Your order has been submitted!");
}
System.exit(0);
So basically you have a death trap, there is simply no way to escape...
Let's take another approach. Rather than using a hard-loop, like for or while, we can create a soft loop, whereby, each time the method is executed and the form is invalid, we update a counter, until that counter runs out...
// How many times retries has the user used...
private int retries = 0;
/*...*/
public void actionPerformed(ActionEvent e) {
validationError = (fNameInput.getText().equals("")
|| miInput.getText().equals("")
|| lNameInput.getText().equals("")
|| streetAddressInput.getText().equals("")
|| cityInput.getText().equals("")
|| stateInput.getText().equals("")
|| zipInput.getText().equals("")
|| phoneInput.getText().equals(""));
if (validationError) {
retries++;
if (retries < 3) {
JOptionPane.showMessageDialog(this, "Please complete each field within the order form.");
} else {
JOptionPane.showMessageDialog(this, "You've used up all your tries...");
System.exit(0);
}
} else {
JOptionPane.showMessageDialog(this, "Your order has been submitted!");
System.exit(0);
}
}
You may also like to have a read of Validating Input from the How to use the focus subsystem tutorial...
I have a JComboBox with 12 different selections, and depending on what is selected I want the question (JLabel) to change matching the selection. I've tried an if statement to see what is selected and if it matches what should be selected, then the question changes accordingly, but the JLabel never really changes under an circumstance.
Code
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Window extends JFrame{
private static final long serialVersionUID = 1L;
public Window(){
super("Area Finder v1.0");
BufferedImage image = null;
try {
image = ImageIO.read(getClass().getClassLoader().getResource("images/areafinder.png"));
} catch (IOException e) {
e.printStackTrace();
}
super.setIconImage(image);
setSize(400, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JLabel Instr = new JLabel("What would kind of area would you like to find?");
String[] areaChoices = {"Circle", "Square", "Rectangle", "Triangle", "Trapezoid", "Parallelogram", "Hexagon", "Rhombus", "Pentagon", "Polygon", "Ellipse", "Sector"};
final JComboBox<?> choiceBox = new JComboBox(areaChoices);
final Object isSelected = choiceBox.getSelectedItem();
choiceBox.setToolTipText("Select which one you want to find the area of!");
choiceBox.setSelectedIndex(0);
final JLabel q = new JLabel("");
final JTextField inputFromUser = new JTextField("");
JButton findArea = new JButton("Find Area");
/* Question Changer*/
/*End of Question Changer*/
findArea.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0){
if(isSelected == "Circle"){
double radius = Double.parseDouble(inputFromUser.getText());
double area = 3.14 * (radius * radius);
JOptionPane.showMessageDialog(null, "Your Area is " + area);
}else if(isSelected == "Square"){
}
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(15,15,15,15);
panel.add(Instr);
panel.add(choiceBox);
panel.add(findArea);
panel.add(q);
panel.add(inputFromUser);
add(panel);
}
}
EDIT: So I did a few tests with System.out.println(); and I figured out it's calling all the items at once, but the one that's selected is being called first.
Example:
choiceBox.addItemListener(new ItemListener(){
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getItem() == "Circle"){
System.out.println("Circle selected");
}else if(e.getItem() == "Square"){
System.out.println("Square selected");
}
}
});
Prints out "Circle Selected Square Selected" if you select circle, but "Square Selected Circle Selected" if you select Square.
Add an ItemListener to the JComboBox to react when the selection changes.
Also, when you do this:
Object isSelected = choiceBox.getSelectedItem();
... you are just getting the selected value at that time; you aren't magically binding the isSelected variable to update whenever the combobox updates. You need to call getSelectedItem() again if you want the new value.
try adding an action listener to the JComboBox
choiceBox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//put the code here
}
});
Change the text of the JLabel
label.setText("Changed text");
Tell the container to relayout.
frame.invalidate();
frame.repaint();
This makes sure that the frame is redrawn to show the changed label. To know when the combo box has changed it's selection, add an ActionListener like this.
combo.addActionListener (new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
label.setText(combo.getText());
frame.invalidate();
}
});