Why isn't this printing? (output of radio button) - java

So I have a radio button and after that I have an if/else statement that is based upon the outcome. But the if/else statements are supposed print things to the console, but they don't. Is something wrong with the Radio Buttons?
If you could, please provide thorough answers, as I'm not very good with Java. Thanks a ton :D
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioButton extends JPanel {
int xDisplacement = 8;
int xVAvg = 8;
int xTime = 8;
static JFrame frame;
JLabel pic;
RadioListener myListener = null;
protected JRadioButton displacement;
protected JRadioButton vAvg;
protected JRadioButton time;
public RadioButton() {
// Create the radio buttons
displacement = new JRadioButton("Displacement");
displacement.setMnemonic(KeyEvent.VK_N);
displacement.setActionCommand("displacement")
//Displacement Button, set to automatically be clicked
vAvg = new JRadioButton("Average Velocity");
vAvg.setMnemonic(KeyEvent.VK_A);
vAvg.setActionCommand("averagevelocity");
//Acceleration Button
time = new JRadioButton("Change in time");
time.setMnemonic(KeyEvent.VK_S);
time.setActionCommand("deltaT");
//The change in time button
// Creates the group of buttons
ButtonGroup group = new ButtonGroup();
group.add(displacement);
group.add(vAvg);
group.add(time);
myListener = new RadioListener();
displacement.addActionListener(myListener);
vAvg.addActionListener(myListener);
time.addActionListener(myListener);
// Set up the picture label
pic = new JLabel(new ImageIcon(""+"numbers" + ".jpg")); //Set the Default Image
pic.setPreferredSize(new Dimension(177, 122));
// Puts the radio buttons down
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1));
panel.add(displacement);
panel.add(vAvg);
panel.add(time);
setLayout(new BorderLayout());
add(panel, BorderLayout.WEST);
add(pic, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(40,40,40,40));
}
//Listening to the buttons
class RadioListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
pic.setIcon(new ImageIcon(""+e.getActionCommand() + ".jpg"));
}
}
public static void main(String s[]) {
frame = new JFrame("∆x = Vavg * time");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
frame.getContentPane().add(new RadioButton(), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public void running() {
if ( displacement.isSelected()) {
//Option 1
System.out.println("The distance traveled on the x axis in meters is " + xDisplacement);
System.out.println("You can find the Average Velocity by dividing this number by time or find the time by dividing this number by the Average Velocity");
}
if ( vAvg.isSelected()) {
//Option 2
System.out.println("The average velocity in Meters per Second is " + xVAvg);
System.out.println("You can find the displacement by multiplying the time and this number together or to find the time, just divide the displacement by this number");
}
else {
//Option 3
System.out.println("The time in seconds is " + xTime);
System.out.println("You can find the displacement by multiplying the velocity times this number or you can find the average velocity by dividing the displacement by this number");
}
}
}

you are missing ; at this line of your code
displacement.setActionCommand("displacement")
and as MadProgrammer said call your running method in RadioListner class that implements ActionListner
class RadioListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
pic.setIcon(new ImageIcon(""+e.getActionCommand() + ".jpg"));
running();
}
}

Call running from your RadioListener's actionPerformed method

Related

Click counter keeps resetting to 0

This program is supposed to count mouse clicks but it only counts the first one. The code is nothing complicated but I don't get why it only counts the first click.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class swing {
private JLabel label;
public swing() {
JFrame frame = new JFrame("exemple");
frame.setBounds(200, 200, 200, 200);
JButton button = new JButton("clic clic");
button.addActionListener(new MyActionListener());
label = new JLabel("0");
JPanel pane = new JPanel();
pane.add(button);
pane.add(label);
frame.getContentPane().add(pane,
BorderLayout.CENTER);
frame.show();
}
private class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
int count = 0;
count++;
label.setText("Number of Mouse Clicks = "+ count);
}
}
public static void main(String[] args) {
new swing();
}
}
Thank you to user WJS who has commented with an answer, I had to simply Move count =0 outside the actionPerformed method but inside the listener class.
on every click you are setting the counter again to zero and then showing the incremented value and after each click value of counter is reset to zero.
you need to move the count outside of actionPerformed
int count = 0;
private class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
count++;
label.setText("Number of Mouse Clicks = " + count);
}
}

How and where to use javax.swing Timer

Please help, I'm trying to use javax.swing.Timer in my program. I have looked at lots of examples, but it still doesn't make sense to me. I am writing a program that has the user guessing the price. What I can't seem to figure out is how to have a timer that counts down from 30 seconds after the "new Game" button is clicked. If the user has not guessed the correct answer, then I want the game to display "You lose", but I also want the timer to stop if they get the correct answer in under 30 seconds and display that time. I believe I'm suppose to use
timer = new Timer(Speed, this);
timer.start();
timer.end();
but, I'm not sure what else I need for the timer or where to place these within my code. Any help would be much appreciated. Below is the code for my program...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class ClockGame extends JFrame {
//Declare fields for GUI components
private JTextField guessField;
private JButton newGameButton;
private JLabel messageLabel;
private JLabel guessLabel;
private ImageIcon clockImage;
private int countTotal;
private Random rand;
private JLabel title;
private int number;
private Timer timer;
public ClockGame() {
//Build GUI
super ("Clock Game");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set layout
this.setLayout(new BorderLayout());
//Create the main panel
JPanel mainPanel = new JPanel();
//Create components and place them in the panel
rand = new Random();
guessLabel = new JLabel("Guess: ");
guessField = new JTextField(20);
messageLabel = new JLabel(" Click New Game to Begin");
clockImage = new ImageIcon("clock.jpg");
newGameButton = new JButton("New Game");
title = new JLabel("The Clock Game", clockImage, SwingConstants.CENTER);
//Set font for clockGameLabel
title.setFont(new Font("Calibri", Font.BOLD, 24));
//Set messageLabel Color
messageLabel.setOpaque(true);
messageLabel.setBackground(Color.yellow);
newGameButton.addActionListener(new ButtonListener());
guessField.addActionListener(new AnswerListener());
//Add components to the panel
mainPanel.add(guessLabel);
mainPanel.add(guessField);
mainPanel.add(newGameButton);
this.add(title, BorderLayout.NORTH);
this.add(messageLabel, BorderLayout.SOUTH);
//Add the panel to this JFrame
this.add(mainPanel, BorderLayout.CENTER);
//Sizes this JFrame so that it is just big enough to hold the components
this.setSize(340,225);
//Make the JFrame visible on the screen
this.setVisible(true);
}
private class AnswerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//Code to check to see if answer is correct
int sum = number;
int answer = Integer.parseInt(guessField.getText());
Color purple = new Color(153, 153, 253);
countTotal++;
if (sum < answer)
{
messageLabel.setText("Too High");
messageLabel.setBackground(Color.red);
}
else if (sum > answer)
{
messageLabel.setText("Too Low");
messageLabel.setBackground(purple);
}
else
{
messageLabel.setText("Correct! It took you " + countTotal + " tries, in " +
timer + " seconds");
messageLabel.setBackground(Color.yellow);
}
}
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
number = rand.nextInt(1001);
messageLabel.setText(" The price is between $1 and $1000, begin.");
messageLabel.setBackground(Color.green);
countTotal = 0;
}
}
public static void main(String[] args) {
ClockGame frame = new ClockGame();
}
}
timer.end();
There is no end() method. First you need to read the API for the appropriate method to use.
counts down from 30 seconds after the "new Game" button is clicked.
So in the ActionListener you add to the button you need to start the Timer and schedule it to fire every second. When the Timer fires you decrement your count by 1.
I also want the timer to stop if they get the correct answer
So when they get the correct answer you stop the Timer. So in your code where you update the text of the label you stop the Timer.
If the user has not guessed the correct answer, then I want the game to display "You lose",
So when the timer count reaches 0, you 1) stop the timer and 2) display the message.
In the constructor of you class you would actually create the Timer, so that the above methods in your class have a reference to the Timer so it can be started and stopped as required.
What you really need to do is forget about your game and learn how to use a Timer. So you create a frame with a label and two buttons. The label will display the initial count of 30. Then you have a "Start" button that decrements the label by 1 each time the Timer fires. Then you have a "Stop" button that stops the Timer so the count is not decremented.
Once you understand the basic concept of starting and stopping the Timer, then you add the code to your real program.
Well to begin... you would need a JLabel that is assigned to print "You lose" and another one that prints the Time that it took the player to answer the question. Add these to your Frame however you want.
JLabel outcome = new JLabel(); //setText to win or lose.
JLabel countdown = new JLabel(); //setTime as Timer counts down.
After you have instantiated these Labels. The Timer needs to be instantiated.
Timer timer = new Timer(1000, new ActionListener() { //Change parameters to your needs.
int count = 30;
public void actionPerformed(ActionEvent e) {
count--;
if(count == 0) //They lose
{
countdown.setText("CountDown: " + count);
outcome.setText("You Lose");
timer.stop(); //ends the countdown.
}
else if(userGotAnswer) // You need to create a boolean value that changes when a user gets the answer right.
{
countdown.setText("CountDown: " + count);
outcome.setText("You win");
timer.stop(); //ends the countdown
}
else
{
countdown.setText("CountDown: " + count); //default
}
}
});
Then call
timer.start();
when you want the timer to start.

Using Enter key to use JButton instead of just mouse click?

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.

How do I update a JLabel everytime a JComboBox changes?

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

How to change a JLabel dynamically

I have one JLabel and one button, the JLabel displays the number of times the button has been pressed, however, I cant figure how to update the JLabel displaying the number of button presses.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class SimpleGui {
private JFrame f = new JFrame("Basic GUI"); // create Frame
int pressed = 0; // tracks number of button presses.
JLabel label1 = new JLabel("You have pressed button " + pressed + "times.");
private JButton start = new JButton("Click To Start!");
public SimpleGui() {
// Setup Main Frame
f.getContentPane().setLayout(new GridLayout(0, 1));
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculate();
}
});
// Add components
f.add(label1);
f.add(start);
// Allows the Swing App to be closed
f.addWindowListener(new ListenCloseWdw());
}
public class ListenMenuQuit implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
public class ListenCloseWdw extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
public void launchFrame() {
// Display Frame
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack(); // Adjusts panel to components for display
f.setVisible(true);
}
public static void main(String args[]) {
PrimeTime gui = new PrimeTime();
gui.launchFrame();
}
public void calculate() {
pressed++;
label1 = new JLabel("You have pressed button " + pressed + "times.");
// update the GUI with new jLabel
f.repaint();
}
}
The issue is that you are creating a new, different JLabel that is not show in the panel.
do
public void calculate(){
pressed++;
this.label1.setText("You have pressed button " + pressed + "times.");
}
Change label1 = new JLabel("You have pressed button " + pressed + "times."); to label1.setText("You have pressed button " + pressed + "times.");
You only call calculate() when the button start is clicked. So you can move that method into the ActionListener for the button. And by calling setText on the JLabel, you don't have to call repaint. Normally you don't have to call repaint in Swing. E.g. change your code to something like this instead:
final JLabel label1 = new JLabel("You have pressed button " + pressed + "times.");
private JButton start = new JButton(new AbstractAction("Click To Start!") {
public void actionPerformed(ActionEvent e) {
pressed++;
label1.setText("You have pressed button " + pressed + "times.");
}
});
Try and understand this code, here i use an icon to set the label's image and the getIcon method of Label's to change the icon of previous label using setIcon method.
Icon picLabelicon new ImageIcon(img); /* setting the icon initially */
JLabel picLabel = new JLabel();
picLabel.setIcon(picLabelicon);
Now you have set the icon initially now lets change it dynamically
JLabel modify = new JLabel(new ImageIcon(newimg)); /* new label you wanted to use */
picLabelicon=modify.getIcon();
picLabel.setIcon(picLabelicon);
revalidate();
repaint();

Categories

Resources