How to find Next Prime Number in Java presented by GUI Label - java

I want to find the next (larger) prime number which will displayed on the label in GUI
But the code below is not okay.
Maybe the problem is d++, however I cannot think of other way to let the loop continue.
Can anyone help?
Thanks so much.
public class PrimeNumber extends JFrame implements ActionListener {
private JLabel label = new JLabel("2");
private JButton button = new JButton("Next Prime");
public PrimeNumber() {
FlowLayout layout = new FlowLayout();
this.setLayout(layout);
label = new JLabel("2");
button = new JButton("Next Prime");
this.add(label);
this.add(button);
button.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
#Override
public void actionPerformed(ActionEvent e) {
int d = 2;
do {
String t = String.valueOf(d);
label.setText(t);
d++;
}
while (d % 2 != 0);
}
}
public class TestPrimeNumber {
public static void main(String args[]) {
PrimeNumber frame = new PrimeNumber();
frame.setVisible(true);
}
}

Related

How to change images with a JButton

How can I change between the pictures with help of clicking the button.
I made a x variable because then I could make different if-statements but that didn't work for me, probably because I did something wrong... Here is my code so far:
public class Main extends JFrame{
private JButton changePic;
private JPanel panel;
private JLabel pic1;
private JLabel pic2;
private JLabel pic3;
private JLabel picture;
private int x = 0;
public Main(){
panel = new JPanel();
add(panel);
changePic = new JButton("Change Button");
panel.add(changePic);
pic1 = new JLabel(new ImageIcon("pic1.png"));
pic2 = new JLabel(new ImageIcon("pic.png"));
pic3 = new JLabel(new ImageIcon("pic3.png"));
panel.add(pic1);
panel.add(pic2);
panel.add(pic3);
changePic.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(e.getSource() == changePic){
}
}
});
getContentPane().setBackground(Color.white);
setSize(300, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){
Main fr = new Main();
}
}
public class Main extends JFrame{
private JButton changePic;
private JPanel panel;
private JLabel pic1;
private int x = 0;
public Main(){
panel = new JPanel();
add(panel);
changePic = new JButton("Change Button");
panel.add(changePic);
pic1 = new JLabel();
panel.add(pic1);
ImageIcon icon1 = new ImageIcon("pic1.gif");
ImageIcon icon2 = new ImageIcon("pic2.gif");
ImageIcon icon3 = new ImageIcon("pic3.gif");
changePic.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(e.getSource() == changePic){
if(x == 0){
pic1.setIcon(icon1);
}else if(x == 1){
pic1.setIcon(icon2);
}else if(x == 2){
pic1.setIcon(icon3);
}
Main.this.pack();
x++;
if(x > 2) x = 0;
}
}
});
getContentPane().setBackground(Color.white);
setSize(300, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){
Main fr = new Main();
}
}
you don't need multiple JLabels, use 3 ImageIcons instead.
you need to call JFrame's pack() every time you had UI Changes (in
this case, changing image)

Java swing: managing integers/doubles with Listeners and J*Fields

EDITED
I've probably just stared at the screen for WAYYY too long but I feel the need to submit this question prior to going to sleep incase my delirium remains true...
The problem I'm having is I'm trying to get an int/double from the JTextField textField and convert it to a(n) int/double to use later in a listener, after retrieving it from a listener... ListenForText implements KeyListener, specifically KeyTyped, to obtain, through toString(), and store it in a String txtFldAmnt. After which I will store the result of Integer.parseInt(txtFldAmnt) into fldAmnt (fldAmnt = Integer.pareseInt(txtFldAmnt)) LINE 99 if copied to an editor. Once it's converted into an int I want to be able to manipulate it and then use it again, at LINE 173, to display, in a new window, the fldAmnt. Honestly, I don't really care about whether it's an int or String displayed, but I know a String is required for JTextField. What magic am I missing? Answers are always welcome but I prefer a chance to learn. Also, as I'm fairly new to Java, off topic pointers, criticism, and better ways to implement this code is greatly welcomed :)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JFrame{
/**
* wtf is the serial version UID = 1L
*/
private static final long serialVersionUID = 1L;
private JButton wdBtn;
private JButton dpBtn;
private JButton xferBtn;
private JButton balBtn;
private JRadioButton chkRadio;
private JRadioButton savRadio;
private JTextField textField;
private static String txtFldAmnt;
private static int fldAmnt = 0;
private static Double chkBal = 0.00;
private static Double savBal = 0.00;
public static void main(String[] args){
new GUI();
}
public GUI() {
//default location and size
this.setSize(300,182);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("ATM Machine");
//add buttons
wdBtn = new JButton("Withdraw");
dpBtn = new JButton("Deposit");
xferBtn = new JButton("Transfer");
balBtn = new JButton("Show Balance");
chkRadio = new JRadioButton("Checking");
chkRadio.setSelected(false);
savRadio = new JRadioButton("Savings");
savRadio.setSelected(false);
textField = new JTextField("", 20);
final JLabel textLabel = new JLabel("Enter amount: ");
textField.setToolTipText("Enter amount");
//Listener class to pass button listeners
ListenForButton lForButton = new ListenForButton();
wdBtn.addActionListener(lForButton);
dpBtn.addActionListener(lForButton);
xferBtn.addActionListener(lForButton);
balBtn.addActionListener(lForButton);
chkRadio.addActionListener(lForButton);
savRadio.addActionListener(lForButton);
ListenForText textFieldListener = new ListenForText();
textField.addKeyListener(textFieldListener);
//Configure layouts
JPanel PANEL = new JPanel();
PANEL.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(2,2, 5, 10));
JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayout(1,2,10,10));
panel2.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayout(2,1));
//add buttons to their panels
panel1.add(wdBtn);
panel1.add(dpBtn);
panel1.add(xferBtn);
panel1.add(balBtn);
panel2.add(chkRadio);
panel2.add(savRadio);
panel3.add(textLabel);
panel3.add(textField);
PANEL.add(panel1);
PANEL.add(panel2);
PANEL.add(panel3);
this.add(PANEL);
//this.setAlwaysOnTop(true);
this.setVisible(true);
}
//implement listeners
private class ListenForText implements KeyListener {
#Override
public void keyTyped(KeyEvent e) {
txtFldAmnt = (e.toString());
fldAmnt = Integer.parseInt(txtFldAmnt);
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
private class ListenForButton implements ActionListener {
public void actionPerformed(ActionEvent e){
//maybe do case/switch statements
if (e.getSource() == wdBtn) {
JFrame newFrame = new JFrame("Withdraw Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Withdraw Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == dpBtn) {
JFrame newFrame = new JFrame("Deposit Title");
/*
* Set the newFrame.setSize(300,182); to this comment in the if statement to place
* the window directly over current window
*/
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Deposit Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == xferBtn) {
JFrame newFrame = new JFrame("Transfer Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JLabel newLbl = new JLabel("Transfer Frame", JLabel.CENTER);
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
if (e.getSource() == balBtn){
JFrame newFrame = new JFrame("Balance Title");
newFrame.setResizable(false);
newFrame.setLocationRelativeTo(null);
newFrame.setSize(300, 91);
JPanel panel = new JPanel();
JTextField newLbl = new JTextField(Integer.toString(fldAmnt));
panel.add(newLbl);
newFrame.add(panel);
newFrame.setVisible(true);
}
}
}
}
-cheers
EDITED BELOW
Thank for the answers, and I'm sorry for the horrible description... but I found a work around, thoguh I'm not sure if it's appropriate.
with the above example:
fldAmnt = Integer.pareseInt(txtFldAmnt)
i just added a .getText() //Though I rewrote the entire source code
fldAmnt = Integer.pareseInt(txtFldAmnt.getText())
it's worked for me for my entire program.
I wish I didn't have to post my entire code below but I haven't decided on a great place to store all of my code yet.
(SUGGESTIONS ARE WELCOME :D)
but here it is:
import javax.swing.;
import java.awt.GridLayout;
import java.awt.event.;
import javax.swing.border.*;
public class ATM extends JFrame{
//buttons needed
JButton wBtn;
JButton dBtn;
JButton xBtn;
JButton bBtn;
//radios needed
JRadioButton cRadio;
JRadioButton sRadio;
//Text field needed
JTextField txt;
JLabel txtLabel;
static int withdraw = 0;
Double amount = 0.00;
Double cBal = 100.00;
Double sBal = 100.00;
double number1, number2, totalCalc;
public static void main(String[] args){
new Lesson22();
}
public ATM(){
this.setSize(400, 200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("My Third Frame");
wBtn = new JButton("Withdraw");
dBtn = new JButton("Deposit");
xBtn = new JButton("Transfer");
bBtn = new JButton("Show Balance");
cRadio = new JRadioButton("Checking");
sRadio = new JRadioButton("Savings");
txtLabel = new JLabel("Amount: $");
txt = new JTextField("", 10);
JPanel thePanel = new JPanel();
// Create an instance of ListenForEvents to handle events
ListenForButton lForButton = new ListenForButton();
wBtn.addActionListener(lForButton);
dBtn.addActionListener(lForButton);
xBtn.addActionListener(lForButton);
bBtn.addActionListener(lForButton);
// How to add a label --------------------------
// Creates a group that will contain radio buttons
// You do this so that when 1 is selected the others
// are deselected
ButtonGroup operation = new ButtonGroup();
// Add radio buttons to the group
operation.add(cRadio);
operation.add(sRadio);
// Create a new panel to hold radio buttons
JPanel operPanel = new JPanel();
JPanel btnPanel1 = new JPanel();
JPanel btnPanel2 = new JPanel();
btnPanel1.setLayout(new GridLayout(1,2));
btnPanel2.setLayout(new GridLayout(1,2));
Border btnBorder = BorderFactory.createEmptyBorder();
btnPanel1.setBorder(btnBorder);
btnPanel1.add(wBtn);
btnPanel1.add(dBtn);
btnPanel2.setBorder(btnBorder);
btnPanel2.add(xBtn);
btnPanel2.add(bBtn);
Border operBorder = BorderFactory.createBevelBorder(1);
// Set the border for the panel
operPanel.setBorder(operBorder);
// Add the radio buttons to the panel
operPanel.add(cRadio);
operPanel.add(sRadio);
// Selects the add radio button by default
cRadio.setSelected(true);
JPanel txtPanel = new JPanel();
txtPanel.add(txtLabel);
txtPanel.add(txt);
thePanel.add(btnPanel1);
thePanel.add(btnPanel2);
thePanel.add(operPanel);
thePanel.add(txtPanel);
thePanel.setLayout(new GridLayout(4,2));
this.add(thePanel);
this.setVisible(true);
txt.requestFocus();
}
private class ListenForButton implements ActionListener{
// This method is called when an event occurs
public void actionPerformed(ActionEvent e){
/******************************************************
* THIS IS FOR CHECKING
*****************************************************/
// Check if the source of the event was the button
if(cRadio.isSelected()){
if(e.getSource() == wBtn){
try {
amount = Double.parseDouble(txt.getText());
cBal -= amount;
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number in multiples of 20",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == bBtn){
JFrame bFrame = new JFrame();
bFrame.setSize(300, 182);
bFrame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel cLabel = new JLabel(Double.toString(cBal));
JLabel CLBL = new JLabel("Checking: ");
panel.add(CLBL);
panel.add(cLabel);
bFrame.add(panel);
bFrame.setVisible(true);
}
if(e.getSource() == dBtn){
amount = Double.parseDouble(txt.getText());
cBal += amount;
}
if(e.getSource() == xBtn){
amount = Double.parseDouble(txt.getText());
if (sBal >= 0 && sBal >= amount){
cBal += amount;
sBal -= amount;
}
else if (sBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
}
/******************************************************
* THIS IS FOR SAVINGS
*****************************************************/
if(sRadio.isSelected()){
if(e.getSource() == wBtn){
try {
amount = Double.parseDouble(txt.getText());
if(sBal >= 0 && sBal >= amount){
sBal -= amount;
}
else if (sBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number in multiples of 20",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == bBtn){
JFrame bFrame = new JFrame();
bFrame.setSize(300, 182);
bFrame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel sLabel = new JLabel(Double.toString(sBal));
JLabel SLBL = new JLabel("Savings: ");
panel.add(SLBL);
panel.add(sLabel);
bFrame.add(panel);
bFrame.setVisible(true);
}
if(e.getSource() == dBtn){
try{
amount = Double.parseDouble(txt.getText());
sBal += amount;
}
catch(NumberFormatException excep){
JOptionPane.showMessageDialog(ATM.this,
"Please enter a valid number!",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if(e.getSource() == xBtn){
amount = Double.parseDouble(txt.getText());
if (cBal >= 0 && cBal >= amount){
sBal += amount;
cBal -= amount;
}
else if (cBal < amount) {
JOptionPane.showMessageDialog(ATM.this,
"INSUFFICENT FUNDS", "ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
}
...and by the way can anyone explain this warning message:
The serializable class ATM does not declare a static final serialVersionUID field of type long
If not simply don't bother. I'll keep researching into it when I have time.
This is still not complete, but thank you all for your help!
KeyListener on any JTextComponent is a bad idea.
To monitor changes to a text component, use a DocumentListener, to filter the content that a text component can handle, use a DocumentFilter. See Listening for Changes on a Document, Implementing a Document Filter and DocumentFilter Examples for more details.
In your case, it'd probably better to use a JSpinner or JFormattedTextField as they are designed to handle (amongst other things) numbers
See How to Use Spinners and How to Use Formatted Text Fields for more details

Cannot find a way to create a loading screen

I was just messing around with GUI in Java and created a little game. In it, 105 randomly placed buttons are created and then an instruction screen pops up, telling the user which button to find. I've tried to figure out how to program a "Loading..." JDialog, which will pop up while the buttons are being created in the background. The trouble is, when I run the program the JDialog doesn't load until AFTER all the buttons have been created, which kind of defeats the purpose of the box in the first place. How can I force the "Loading..." box to load BEFORE the buttons begin to be created??? Thanks in advance.
Because I've just been tinkering, my code is not perfect but here it is:
import java.util.Scanner;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.ProgressMonitor;
public class ButtonGame {
private static int butNum = 1;
private static JFrame frame;
private static ActionListener notIt;
private static ActionListener it;
private static Random rand = new Random();
private static int butToFind = rand.nextInt(105);
private static JFrame frameToClose;
//private static int mouseClicks;
//private static double time;
public static void main(String[] args) {
//actionlistener for all incorrect buttons (buttons that are "not it")
notIt = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
JFrame frame5 = (JFrame) SwingUtilities.getRoot(component);
frame5.dispose();
}
};
//actionlistener for the correct button (the button that's "it")
it = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame youWin = new JFrame("YOU WON!");
//removes all panels to begin game again
JButton again = new JButton("Play again");
again.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
java.awt.Window windows[] = java.awt.Window.getWindows();
for(int i=0;i<windows.length;i++){
if (windows[i] != frame) { windows[i].dispose(); }
butToFind = rand.nextInt(105);
butNum = 1;
youWin.dispose();
}
frame.setVisible(true);
}
});
//quits game
JButton win = new JButton("Quit");
win.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
//layout
youWin.setSize(775, 300);
youWin.setLayout(new FlowLayout());
JLabel label1 = new JLabel("Fantastic!");
Font font1 = new Font("Courier", Font.BOLD,120);
label1.setFont(font1);
label1.setHorizontalAlignment(JLabel.CENTER);
JLabel label2 = new JLabel("You beat the game!");
Font font2 = new Font("Courier", Font.BOLD,60);
label2.setFont(font2);
label2.setHorizontalAlignment(JLabel.CENTER);
youWin.add(label1);
youWin.add(label2);
JPanel panel = new JPanel();
youWin.add(panel);
panel.add(again);
panel.add(win);
youWin.setLocation(260, 100);
youWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
youWin.setVisible(true);
java.awt.Window windows[] = java.awt.Window.getWindows();
}
};
//start window
frame = new JFrame("Window");
frame.setLocation(400, 200);
JButton button1 = new JButton("Click to begin");
//button to begin game
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// JDialog load = new JDialog();
// load.setAlwaysOnTop(true);
// load.setSize(500,500);
// load.setVisible(true);
// load.add(new Label("Loading..."));
// load.pack();
frame.setVisible(false); // "start" window's visibility
// try {
// Thread.sleep(100000);
// } catch (Exception t) {
// }
// creates buttons
for (int i = 0; i < 105; i++) {
JFrame nextFrame = newFrame(butNum);
nextFrame.setVisible(true);
butNum++;
}
//creates instructions and tells user what button to find
JFrame instructions = new JFrame("How to play");
instructions.setSize(300,175);
instructions.setLayout(new GridLayout(4,1));
JPanel instPanel = new JPanel();
//button to remove instruction panel
JButton ok = new JButton("Ok");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
instructions.dispose();
}
});
instPanel.add(ok);
instructions.setLocation(400,200);
//layout of instruction panel
JLabel find = new JLabel("Your goal is to find Button " + butToFind + ".");
find.setHorizontalAlignment(JLabel.CENTER);
JLabel find2 = new JLabel("Click a button to make it disappear.");
find2.setHorizontalAlignment(JLabel.CENTER);
JLabel find3 = new JLabel("Good luck!");
find3.setHorizontalAlignment(JLabel.CENTER);
instructions.add(find);
instructions.add(find2);
instructions.add(find3);
instructions.add(instPanel);
instructions.setVisible(true);
}
});
frame.add(button1);
frame.setSize(150,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
//creates frame with button in it
public static JFrame newFrame(int num) {
JFrame frame2 = new JFrame();
JButton button = new JButton("Button " + num);
if (num == butToFind) {
button.addActionListener(it);
frameToClose = frame2;
} else {
button.addActionListener(notIt);
}
frame2.add(button);
frame2.setSize(randNum(90,200), randNum(50,100));
frame2.setLocation(rand.nextInt(1200), rand.nextInt(800));
frame2.getContentPane().setBackground(new Color(rand.nextInt(255),
rand.nextInt(255),
rand.nextInt(255)));
frame2.setVisible(true);
return frame2;
}
//provides random number between high and low
public static int randNum(int low, int high) {
int result = -1;
while (result < low || result > high) {
result = rand.nextInt(high);
}
return result;
}
}
Also, as a side-question, which of the variables defined before main should be static? And how can I get the program to compile without being static? Thanks!
First take a look at The Use of Multiple JFrames, Good/Bad Practice? and understand why I freaked out when I ran your code...
Instead of creating a bunch of frames, why not use something like JButton on another JPanel and add it to the current frame (this would also be a good use for a CardLayout)
JPanel panel = new JPanel(new GridLayout(10, 0));
Random rnd = new Random();
// creates buttons
for (int i = 0; i < 105; i++) {
JButton btn = new JButton(String.valueOf(i));
panel.add(btn);
//JFrame nextFrame = newFrame(butNum);
//nextFrame.setVisible(true);
//butNum++;
}
frame.getContentPane().removeAll();
frame.add(panel);
frame.revalidate();
frame.pack();
Alternatively, if you're really hell bent on using "frames", consider using a JDesktopPane and JInternalFrame instead.
See How to Use Internal Frames for more details
Also, as a side-question, which of the variables defined before main should be static? And how can I get the program to compile without being static?
As much as possible, none. Instead of trying to create the whole thing in the main method, use the classes constructor to initialise the UI and use another method to actually get the game rolling...
public class ButtonGame {
private int butNum = 1;
private JFrame frame;
private ActionListener notIt;
private ActionListener it;
private Random rand = new Random();
private int butToFind = rand.nextInt(105);
private JFrame frameToClose;
//private static int mouseClicks;
//private static double time;
public static void main(String[] args) {
ButtonGame game = new ButtonGame();
game.start();
}
public ButtonGame() {
//... All the code that was once in main...
frame.add(button1);
frame.setSize(150, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void start() {
frame.setVisible(true);
}
Answering to your side questions:
a static method can only accept static global variables
You can put all your code in the constructor and use main to only run the program.
Constructor:
public ButtonGame() {
// All of your code goes here - except the static methods
}
You should also make all other methods non-static.
To run the program:
public static void main(String[] args) {
new ButtonGame();
}

comparison of selected option with correct answer in a group of radio buttons

How do I fetch the selected option from a group of radio buttons.What are the possible ways to check the selected option with the correct answer?
(am a beginner)This is the code which am working on.Just included 2 questions with 4 radio buttons each and they were grouped.Now I have to display a score after checking for the correct answer
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class MyRadioButton {
private JFrame frame = new JFrame("RadioRadio");
private JLabel timerl = new JLabel("Press Button to start");
private JPanel butp = new JPanel();
private JPanel panel1=new JPanel();
private JLabel q1=new JLabel("Qn 1:Who is the first President Of India?");
private JLabel q2=new JLabel("Qn 2:Who is the first Prime Minister Of India?");
private JPanel panel2=new JPanel();
private JPanel panel3=new JPanel();
private JLabel label=new JLabel();
private JButton button = new JButton("Start Exam");
private JRadioButton rd1=new JRadioButton("a)Nehru");
private JRadioButton rd2=new JRadioButton("b)R.Prasad");
private JRadioButton rd3=new JRadioButton("c)S.R.Krishnan");
private JRadioButton rd4=new JRadioButton("d)GV.Mavlankar");
private JRadioButton rd5=new JRadioButton("a)Nehru");
private JRadioButton rd6=new JRadioButton("b)R.Prasad");
private JRadioButton rd7=new JRadioButton("c)S.R.Krishnan");
private JRadioButton rd8=new JRadioButton("d)GV.Mavlankar");
ButtonGroup group1 = new ButtonGroup();
ButtonGroup group2 = new ButtonGroup();
public int result=0;
private Timer mytimer;
private String ss = "Time Remaining %02d Seconds!";
private int elapsedSeconds = 0;
private int total = 60;
JLayeredPane pane=new JLayeredPane();
public MyRadioButton() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (mytimer != null && mytimer.isRunning()) {
//String t = String.format("Result:Your Score is %d", result);
//label.setText(t);
mytimer.stop();
elapsedSeconds = 0;
timerl.setText("Exam Terminated");
} else {
panel1.setBounds(0, 100, 500, 100);
panel1.add(q1);
pane.add(panel1,pane.DEFAULT_LAYER);
panel2.setBounds(0,200,500,100);
panel2.add(q2);
pane.add(panel2,pane.DEFAULT_LAYER);
panel3.setBounds(0, 300, 500, 100);
pane.add(panel3,pane.DEFAULT_LAYER);
panel3.add(label);
panel1.add(rd1);
panel1.add(rd2);
panel1.add(rd3);
panel1.add(rd4);
panel2.add(rd5);
panel2.add(rd6);
panel2.add(rd7);
panel2.add(rd8);
group1.add(rd1);
group1.add(rd2);
group1.add(rd3);
group1.add(rd4);
group2.add(rd5);
group2.add(rd6);
group2.add(rd7);
group2.add(rd8);
mytimer = new Timer(1000, new TimerListener());
mytimer.start();
String t = String.format(ss, total);
timerl.setText(t);
}
}
});
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.add(pane);
butp.setBounds(0,0,500,100);
butp.add(button);
butp.add(timerl);
pane.add(butp,pane.DEFAULT_LAYER);
frame.setVisible(true);
}
private class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
elapsedSeconds++;
if (elapsedSeconds == total) {
mytimer.stop();
elapsedSeconds = 0;
timerl.setText("Time Up");
} else {
String t = String.format(ss, total - elapsedSeconds);
timerl.setText(t);
}
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
MyRadioButton r = new MyRadioButton();
}
});
}
}
You can add an ActionListener to each button in which you can set, for example, class field to currently selected radio button value.
...
String firstAnswer;
String secondAnswer;
...
private FirstQuestionActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e) {
firstAnswer = e.getActionCommand();
}
}
private SecondQuestionActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e) {
secondAnswer = e.getActionCommand();
}
}
And use it this way: rb1.addActionListener(new FirstQuestionActionListener());

How to use variables set in an actionlistener

I am having problems understanding how to use an actionlistener to change the value of variables.
In my program I need to store the choices the user makes by selecting some radio buttons.
I have got a main class with a card layout, then several classes which each are different panels. In one of the panels I have some radio buttons, with an actionlistener as an inner class.
When I try to print the variable value in the main class, it is printed immediately, before the user has made a choice, as I instantiate the panel class and get the variable from it I get the variable before it has been changed by the user.
I know I should not think in a linear manner with Java, but how can I make sure that I fetch the variable after it has been changed by the user and not before? I will not be able to do that will I? I understand there is some flaw in my thinking but I haven't slept properly for ages and I just cannot get my head around this.
public class Screen3 extends JPanel{
JRadioButton addition = new JRadioButton("Addition");
JRadioButton subtraction = new JRadioButton("Subtraction");
JRadioButton multiplication = new JRadioButton("Multiplication");
JRadioButton division = new JRadioButton("Division");
JRadioButton all = new JRadioButton("All");
JRadioButton single = new JRadioButton("Single");
JRadioButton two = new JRadioButton("Double");
JRadioButton triple = new JRadioButton("Triple");
JRadioButton mix = new JRadioButton("Mix");
JRadioButton five = new JRadioButton("5");
JRadioButton ten = new JRadioButton("10");
private int type, digit, rounds;
public Screen3() {
JPanel firstButtonPanel = new JPanel();
JPanel secondButtonPanel = new JPanel();
ButtonGroup myFirstGroup = new ButtonGroup();
ButtonGroup mySecondGroup = new ButtonGroup();
myFirstGroup.add(addition);
myFirstGroup.add(subtraction);
myFirstGroup.add(multiplication);
myFirstGroup.add(division);
//myFirstGroup.add(all);
mySecondGroup.add(single);
mySecondGroup.add(two);
mySecondGroup.add(triple);
//mySecondGroup.add(mix);
firstButtonPanel.setLayout(new FlowLayout());
firstButtonPanel.add(addition);
firstButtonPanel.add(subtraction);
firstButtonPanel.add(multiplication);
firstButtonPanel.add(division);
//firstButtonPanel.add(all);
secondButtonPanel.setLayout(new FlowLayout());
secondButtonPanel.add(single);
secondButtonPanel.add(two);
secondButtonPanel.add(triple);
//secondButtonPanel.add(mix);
JPanel buttons = new JPanel();
buttons.setLayout(new BorderLayout());
buttons.add(selectionLabel, BorderLayout.NORTH);
buttons.add(firstButtonPanel, BorderLayout.CENTER);
buttons.add(secondButtonPanel, BorderLayout.SOUTH);
ButtonGroup myThirdGroup = new ButtonGroup();
JPanel endButtons = new JPanel();
myThirdGroup.add(five);
myThirdGroup.add(ten);
endButtons.add(five);
endButtons.add(ten);
endPanel.setLayout(new BorderLayout());
endPanel.add(rounds, BorderLayout.NORTH);
endPanel.add(endButtons, BorderLayout.CENTER);
setLayout(new BorderLayout());
add(buttons, BorderLayout.NORTH);
Selection sn = new Selection();
addition.addActionListener(sn);
subtraction.addActionListener(sn);
multiplication.addActionListener(sn);
division.addActionListener(sn);
single.addActionListener(sn);
two.addActionListener(sn);
triple.addActionListener(sn);
five.addActionListener(sn);
ten.addActionListener(sn);
}
public int getType() {
return type;
}
public int getDigit() {
return digit;
}
public int getRounds() {
return rounds;
}
public class Selection implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(addition.isSelected()) {
type = 1;
}
else if(subtraction.isSelected()) {
type = 2;
}
else if(multiplication.isSelected())
type = 3;
else if(division.isSelected())
type = 4;
//else if(all.isSelected())
//type = 5;
if(single.isSelected()) {
digit = 1;
System.out.println("single");
}
else if(two.isSelected())
digit = 2;
else if(triple.isSelected())
digit = 3;
if(five.isSelected())
rounds = 5;
else if(ten.isSelected())
rounds = 10;
}
}
}
Here is the main class:
public class Driver {
public JFrame frame = new JFrame("Math Game");
public JPanel screens = new JPanel(new CardLayout());
int digit = 1;
int rounds = 1;
int type = 1;
Driver() {
}
public void show() {
JPanel buttonPanel = new JPanel();
JButton next = new JButton("Next");
JButton previous = new JButton("Previous");
buttonPanel.add(previous);
buttonPanel.add(next);
Screen1 screen1 = new Screen1();
Screen2 screen2 = new Screen2();
Screen3 screen3 = new Screen3();
screens.add(screen1, "welcome");
screens.add(screen2, "next");
screens.add(screen3, "selection");
frame.add(screens);
frame.add(buttonPanel, BorderLayout.PAGE_END);
frame.setSize(400, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
next.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cl = (CardLayout)(screens.getLayout());
cl.next(screens);
}
});
previous.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cl = (CardLayout)(screens.getLayout());
cl.previous(screens);
}
});
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Driver dr = new Driver();
dr.show();
}
});
}
}
I just try a test print of System.out.println(screen3.getType()); either in show() or main
Use JOptionPane/JDialog which has modality.
Have a read on How to Make Dialogs
In example here is only printed after JDialog is closed:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JDialog jd = new JDialog();
jd.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
jd.setModal(true);
jd.pack();
jd.setVisible(true);
System.out.println("Here");
}
});
}
In this example here is only printed after JOptionPane is closed:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JPanel panel=new JPanel();
panel.add(new JLabel("Hello, world!"));
JOptionPane.showMessageDialog(null, panel, "Panel Message",JOptionPane.PLAIN_MESSAGE);
System.out.println("Here");
}
});
}
I know I should not think in a linear manner with Java, but how can I
make sure that I fetch the variable after it has been changed by the
user and not before?
After using a modal JDialog/JOptionPane you would simply use public getters to access the variable contained within the class instance:
public class Test {
public static void main(String[] args) {
X x= new X();//will only return after dialog closed
System.out.println(x.getY());
}
}
class X {
private int y=0;//will be assigned during dialog/joptionpanes life span
public X() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//creates and shows the modal dialog/optionpane which will allow modification of variable y through some input/controls
}
});
}
public int getY() {
return y;
}
}

Categories