So I want to store a string value in a variable, the value is given through a JTextField and after a confirm button is clicked, I want it to store what's written in the text field in a string variable.
This is the relevant part of the code:
public class Window {
private JButton confirm;
private JTextField textfield;
private JLabel label;
public void drawWindow() {
JFrame window = new JFrame("CountryQuiz");
ClickChecker click = new ClickChecker();
JPanel panel = new JPanel();
panel.setBounds(40, 80, 200, 200);
panel.setBackground(Color.green);
JTextField t1 = new JTextField("Enter country...");
t1.setBounds(50, 100, 200, 30);
window.add(t1);
JButton confirm = new JButton("Confirm");
confirm.setBounds(50, 50, 95, 30);
confirm.addActionListener(click);
window.add(confirm);
window.setSize(400, 400);
window.setLayout(null);
window.setVisible(true);
window.add(panel);
}
private class ClickChecker implements ActionListener {
public void actionPerformed(ActionEvent e) {
String answer = textfield.getText();
System.out.println(answer);
}
}
}
Results in the following error:
Cannot invoke "javax.swing.JTextField.getText()" because "this.this$0.textfield" is null
Your textfield variable is only declared but never used.
Replace the below
JTextField t1 = new JTextField("Enter country...");
t1.setBounds(50, 100, 200, 30);
window.add(t1);
With
textfield = new JTextField("Enter country...");
textfield.setBounds(50, 100, 200, 30);
window.add(textfield);
Related
My too simple Swing code is causing the whole system to freeze. I'm learning java still :)
this is the actionEvent that is causing the problem
#Override
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = passwordField.getText();
System.out.println("hej");
}
I haven't wrote anything in there yet(still testing) because obviously it is in the code here in the class xD
public class NewAccount implements ActionListener {
static JFrame frame = new JFrame();
static JButton createAccountButton = new JButton();
static JButton haveAnAccount = new JButton();
static JLabel usernameLabel = new JLabel();
static JLabel passwordLabel = new JLabel();
static JTextField usernameField = new JTextField();
static JPasswordField passwordField = new JPasswordField();
NewAccount() {
frame = new JFrame();
createAccountButton = new JButton("Create account");
haveAnAccount = new JButton("Already have an account?");
usernameLabel = new JLabel("New username");
passwordLabel = new JLabel("New Password");
usernameField = new JTextField(20);
passwordField = new JPasswordField(20);
//Frame
frame.setLayout(null);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(400, 250);
frame.setTitle("Create new account");
//Buttons
frame.add(createAccountButton);
createAccountButton.setLocation(20, 130);
createAccountButton.setSize(230, 30);
createAccountButton.setFocusable(false);
createAccountButton.addActionListener(new NewAccount());
frame.add(haveAnAccount);
haveAnAccount.setLocation(20, 170);
haveAnAccount.setSize(230, 30);
haveAnAccount.setFocusable(false);
//Labels
frame.add(usernameLabel);
usernameLabel.setLocation(20, 20);
usernameLabel.setSize(130, 30);
frame.add(passwordLabel);
passwordLabel.setLocation(20, 50);
passwordLabel.setSize(130, 30);
//Fields
frame.add(usernameField);
usernameField.setLocation(150, 20);
usernameField.setSize(165, 25);
frame.add(passwordField);
passwordField.setLocation(150, 50);
passwordField.setSize(165, 25);
}
#Override
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = passwordField.getText();
System.out.println("hej");
}
}
I have no idea what is wrong with it but when I delete the actionlistener it works without freezing my whole system.
createAccountButton.addActionListener(new NewAccount());
Congratulations, you created an infinite loop. That eats your memory.
Maybe you mean to pass this?
Change this line
createAccountButton.addActionListener(new NewAccount());
to
createAccountButton.addActionListener(this);
Solved:
it was a simple mistake but took me so many hours that I had to make a question here. the only problem was to put this
createAccountButton.addActionListener(new NewAccount());
before setting it's bounds and location. hope if anyone had the same problem sees this.
this button does nothing what would be the mistake?
its a login, I dont know why it doesnt work seems pretty well, could somebody help me to indentify the issue?.....................................................................................................................
package Operaciones_Logicas;
import Mainargs.FirstClass;
import java.awt.event.*;
import javax.swing.*;
public class Main1 extends JFrame implements ActionListener {
private JLabel usuario;
private JLabel contraseña;
public JButton blogin;
public JTextField jtusuario, jtcontra;
public static String susuario = "", scontra = "";
public Main1() {
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Cajero Automatico");
JLabel usuario = new JLabel();
usuario.setVisible(true);
usuario.setBounds(20, 100, 100, 50);
add(usuario);
JLabel contraseña = new JLabel();
contraseña.setBounds(20, 300, 100, 50);
add(contraseña);
JButton blogin = new JButton("Login");
blogin.setBounds(50, 400, 100, 30);
blogin.addActionListener(this);
add(blogin);
JTextField jtusuario = new JTextField();
jtusuario.setBounds(20, 120, 150, 30);
add(jtusuario);
JTextField jtcontra = new JTextField();
jtcontra.setBounds(20, 150, 150, 30);
add(jtcontra);
}
//control para el login
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == blogin) {
susuario = jtusuario.getText();
scontra = jtcontra.getText();
if (susuario.equals("josmart96") && (scontra.equals("rojo2000"))) {
FirstClass secondwindow = new FirstClass();
secondwindow.setBounds(0, 0, 600, 360);
secondwindow.setVisible(true);
secondwindow.setResizable(false);
secondwindow.setLocationRelativeTo(null);
this.setVisible(false);
} else {
JOptionPane.showMessageDialog(null, "Usuario y/o Contraseña
incorrectas");
}
}
}
public static void main(String[] args) {
Main1 firstwindow = new Main1();
firstwindow.setBounds(0, 0, 360, 600);
firstwindow.setVisible(true);
firstwindow.setResizable(false);
firstwindow.setLocationRelativeTo(null);
}
}
no erros just doesnt work, when hit button does nothing I can compile it and everything is good I think it could be the IDE itself
You are using local variable blogin instead of using instance variable blogin
Inside the contructor, change
JButton blogin = new JButton("Login");
to
blogin = new JButton("Login");
you also need to use other declared instance variables rather than declaring local variables inside the constructor
Im developing an little "clicker" but, if i press the button, and i should get 1+ Score, it dont work! Is there any way to reload or anything else?
Heres my code: (ClickEvent)
public class event implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("PRESS");
game.timesClicked.add(1);
points.setText(game.seePoints);
}
}
And there is my JFrame:
public class game extends JFrame
{
public static JButton buttonStart;
JButton buttonCredits;
JButton buttonBack;
JButton buttonLeave;
public static JFrame panel = new game();
public static ArrayList<Integer> timesClicked = new ArrayList<Integer>();
public static JLabel label1;
public static JLabel points;
public static String seePoints = "Deine Knöpfe: " + timesClicked.size();
public game()
{
setLayout(null);
label1 = new JLabel("ButtonClicker");
points = new JLabel(seePoints);
points.setFont(new Font("Tahoma", Font.BOLD, 15));
points.setBounds(0, 0, 200, 200);
label1.setFont(new Font("Tahoma", Font.BOLD, 50));
label1.setBounds(315, 50, 500, 200);
event e1 = new event();
JButton b = new JButton("KNOPF");
b.setBackground(new Color(96, 140, 247));
b.setForeground(Color.WHITE);
b.setFocusPainted(false);
b.setFont(new Font("Tahoma", Font.BOLD, 15));
b.setBounds( 402, 380, 180, 50 );
b.addActionListener(e1);
add(b);
add(label1);
add(points);
}
}
(Sorry For My Bad English)
public static String seePoints = "Deine Knöpfe: " + timesClicked.size();
This is only being called once at the start of your program. When you add to timesClicked, it does not recalculate seePoints.
You will need to set this variable to the correct value every time you click.
I tried to implement a simple user interface of my programm.It is the first time that I used swing designer plugin.
1st problem :User enters start and end date and program automatically calculates the duration. But i dont know how i can write the restriction of the yyyy/MM/dd. I mean that user begins to enter year then skip the another block without make anything.
Here is my code:
public class MyFrame extends JFrame {
public MyFrame() {
}
private static JLabel labelBegin;
private static JLabel labelEnd;
private static JLabel labelDuration;
private static JLabel labelA;
private static JLabel labelB;
private static JLabel labelC;
private static JLabel labelD;
private static JLabel labelTotal;
private static JLabel labelSafety;
private static JLabel labelSpeed;
private static JLabel labelEfficiency;
private static JLabel message;
private static JTextField textFieldBegin;
private static JTextField EndingField;
private static JTextField DurationField;
private static JTextField AField;
private static JTextField BField;
private static JTextField CField;
private static JTextField DField;
private static JTextField TotalField;
private static JTextField SafetyField;
private static JTextField SpeedField;
private static JTextField EfficiencyField;
private static JButton clear;
private static JButton buttonNext;
private static JButton buttonBack;
private static JRadioButton PlacementResult;
private static JRadioButton Collision;
private static JPanel panelOptions;
private static JPanel panelLogin;
private static JFrame frame;
private static JButton Mybutton;
private static JPanel panelCons;
private static void mydesign() {
frame = new JFrame("Placement Tool V1.0");
frame.getContentPane().setLayout(new GridLayout(1, 1));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panelLogin = new JPanel();
panelLogin.setLayout(null);
message = new JLabel ("In order to begin your testing, please enter the data");
labelBegin = new JLabel("Enter Begin Date :");
textFieldBegin = new JTextField(10);
labelEnd = new JLabel("Test Duration :");
EndingField = new JTextField(10);
labelDuration = new JLabel ("Enter End Date :");
DurationField = new JTextField(10);
labelA = new JLabel ("Enter Group A :");
AField = new JTextField (10);
labelB = new JLabel ("Enter Group B:");
BField = new JTextField (10);
labelC = new JLabel ("Enter Group C:");
CField = new JTextField (10);
labelD = new JLabel ("Enter Group D:");
DField = new JTextField (10);
labelTotal = new JLabel ("Total Test Devices :");
TotalField = new JTextField (10);
labelSafety = new JLabel ("Enter Safety (%) : ");
SafetyField = new JTextField (10);
labelSpeed = new JLabel ("Enter Speed (kpbs)");
SpeedField = new JTextField (10);
labelEfficiency = new JLabel ("Enter Efficiency (%)");
EfficiencyField = new JTextField (10);
buttonNext = new JButton("Next");
clear = new JButton("Cancel");
panelLogin.add(buttonNext);
panelLogin.add(clear);
panelLogin.add(labelBegin);
panelLogin.add(message);
panelLogin.add(textFieldBegin);
panelLogin.add(labelEnd);
panelLogin.add(EndingField);
panelLogin.add(labelDuration);
panelLogin.add(DurationField);
panelLogin.add (labelA);
panelLogin.add(labelB);
panelLogin.add(labelC);
panelLogin.add(labelD);
panelLogin.add(labelTotal);
panelLogin.add(AField);
panelLogin.add(BField);
panelLogin.add(CField);
panelLogin.add(DField);
panelLogin.add(TotalField);
panelLogin.add(labelSafety);
panelLogin.add(labelSpeed);
panelLogin.add(labelEfficiency);
panelLogin.add(SpeedField);
panelLogin.add(EfficiencyField);
panelLogin.add(SafetyField);
message.setBounds(50, 70, 500, 20);
textFieldBegin.setBounds(200, 120, 100, 20);
labelBegin.setBounds(50, 120, 120, 20);
EndingField.setBounds(200, 140, 100, 20);
labelEnd.setBounds(50, 160, 120, 20);
DurationField.setBounds(200, 160, 100, 20);
labelDuration.setBounds(50, 140, 120, 20);
AField.setBounds(200, 180, 100, 20);
labelA.setBounds(50, 180, 120, 20);
BField.setBounds(200, 200, 100, 20);
labelB.setBounds(50, 200, 120, 20);
CField.setBounds(200, 220, 100, 20);
labelC.setBounds(50, 220, 120, 20);
DField.setBounds(200, 240, 100, 20);
labelD.setBounds(50, 240, 120, 20);
TotalField.setBounds(200, 260, 100, 20);
labelTotal.setBounds(50, 260, 120, 20);
SafetyField.setBounds(200, 280, 100, 20);
labelSafety.setBounds(50, 280, 120, 20);
SpeedField.setBounds(200, 300, 100, 20);
labelSpeed.setBounds(50, 300, 120, 20);
EfficiencyField.setBounds(200, 320, 100, 20);
labelEfficiency.setBounds(50, 320, 120, 20);
buttonNext.setBounds(70, 350, 100, 20);
clear.setBounds(200, 350, 100, 20);
buttonNext.addActionListener(actionEvent);
clear.addActionListener(actionEvent);
frame.getContentPane().add(panelLogin);
//frame ends.
//Options frame starts.
panelOptions = new JPanel();
panelOptions.setLayout(null);
PlacementResult = new JRadioButton ("Show the placement result.");
Collision = new JRadioButton ("Show the collision (%)");
buttonBack = new JButton("Back");
buttonNext = new JButton("Next");
panelOptions.add(buttonBack);
panelOptions.add(buttonNext);
panelOptions.add(Collision);
panelOptions.add(PlacementResult);
Collision.setBounds(150, 25, 200, 25);
PlacementResult.setBounds(150, 50, 200, 25);
buttonBack.setBounds(150, 100, 200, 25);
buttonNext.setBounds(150, 150, 200, 25);
buttonBack.addActionListener(actionEvent);
buttonNext.addActionListener(actionEvent);
//Options Frame ends.
panelCons = new JPanel();
panelCons.setLayout(null);
Mybutton = new JButton("Button");
panelCons.add(Mybutton);
Mybutton.setBounds(180, 180, 150, 25);
Mybutton.addActionListener(actionEvent);
frame.setSize(500, 500);
frame.setVisible(true);
}
public static void main(String args[]) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
mydesign();
}
});
}
private static ActionListener actionEvent = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(frame == null)
frame = new JFrame();
else {
//remove the previous JFrame
frame.setVisible(false);
frame.dispose();
//create a new one
frame = new JFrame();
}
String action = e.getActionCommand();
if ("Login".equals(action)) {
System.out.println("Login action" + e.getActionCommand());
if ("".equals(textFieldBegin.getText()) || "".equals(EndingField.getText()) ||"".equals(DurationField.getText()) ) {
JOptionPane.showMessageDialog(null,
"Enter Both begin test date and end test date");
} else if ("admin".equals(textFieldBegin.getText())&&"admin".equals(AField.getText())&&
"admin".equals(BField.getText())&&
"admin".equals(CField.getText())&&"admin".equals(DField.getText())&& "admin".equals(TotalField.getText())&&
"admin".equals(EfficiencyField.getText()) && "admin".equals(SafetyField.getText()) &&
"admin".equals(SpeedField.getText()) && "admin".equals(EndingField.getText()))
{
System.out.println("Test begin date" + textFieldBegin.getText() + " Test end date" + EndingField.getText()
//+" Test duration" + (EndingField.getText() - textFieldBegin.getText())
+" Group A devices" + AField.getText() +" Group B devices"+ BField.getText()
+ " Group C devices "+ CField.getText()
+ "Group D devices"+ DField.getText()
+ "Total devices" + (AField.getText() + BField.getText() + CField.getText() + DField.getText())
+"Max speed (kbps)" + SpeedField.getText()
+ "Efficiency (%)" + EfficiencyField.getText() + "Safety (%)" + SafetyField.getText()
);
frame.remove(panelLogin);
frame.getContentPane().add(panelOptions);
frame.setVisible(true);
} else {
JOptionPane.showMessageDialog(null,
"Date format that you entered is not appropriate! Hint: YYYY/MM/DD");
}
} else if ("Cancel".equals(action)) {
System.out.println(e.getActionCommand());
System.exit(0);
}
{
frame.remove(panelOptions);
frame.getContentPane().add(panelCons);
frame.setVisible(true);
}
}
;
};
}
2nd problem is i want to make my program user friendly so i want to make a group every component that are similar each other.Here is output:
Advance thanks for all helps
SOLUTION :
Use TF(For 4 digits) + LB(For Slash) + TF(For 2 digits) + LB(For Slash) + TF(For 2 digits) to achive that format in date [TF : TextField and LB : Label] OR you can simply validate on Next button click whether date format match the specific format or not or even precisely date is valid or not.
Use JPanel and set border of it for grouping. (Hint : Use BorderFactory)
I didn't get you in this specific problem.SO can't say anything.
Is there any code that I can use to pass value of selected radio button to another frame?
This is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class bookBatman extends JFrame implements ActionListener {
private JLabel jlbName, jlbTime, jlbPic, jlbDate, jlbDescription, jlbAuthor, jlbDateProduce, jlbDirector, jlbActor, jlbRate, jlbNoOfTicket, jlbPrice, jlbTotal;
private JTextField jtfNoOfTicket;
private JRadioButton jr1, jr2, jr3, jr4, jr5, jr6, jr7, jr8, jr9, jr10;
private JButton jTotal, jBook, jCancel;
Font f = new Font("Times",Font.BOLD,30);
public bookBatman () {
setLayout(null); //set LayoutManager
// initialized the label
jlbName = new JLabel ("Batman The Dark Knight");
jlbTime = new JLabel ("Time :");
jlbPrice = new JLabel ("RM 9.00");
jlbPic = new JLabel ();
jlbPic.setIcon(new ImageIcon("C:\\Users\\User\\Desktop\\OOP project\\img\\icon\\Batman.jpg"));
jlbTotal = new JLabel (" Total : RM 9.00");
// add all the label on the frame
add(jlbName);
add(jlbPic);
add(jlbTime);
add(jlbPrice);
add(jlbTotal);
// set all the label positions
jlbName.setBounds(85, 78, 300, 18); //(int x, int y, int width, int height)
jlbPic.setBounds(74, 101, 180, 288);
jlbTime.setBounds(74, 400, 60, 18);
jlbPrice.setBounds (270, 477, 60, 18);
jlbTotal.setBounds (339, 475, 300, 22);
// initialized the textfield
jlbAuthor = new JLabel ("Directed by Christopher Nolan");
jlbDateProduce = new JLabel ("Date : 17 July 2008");
jlbDirector = new JLabel ("Author : Jonathan Nolan, Christopher Nolan");
jlbActor = new JLabel ("Main Actor : Christian Bale");
jlbRate = new JLabel ("Movie Rate : 13 PG (Parental Guidance)");
jlbNoOfTicket = new JLabel ("Number of Ticket :");
// add all the textfield on the frame
add(jlbAuthor);
add(jlbDateProduce);
add(jlbDirector);
add(jlbActor);
add(jlbRate);
add(jlbNoOfTicket);
// set the textfield position
jlbAuthor.setBounds (273, 102, 300, 18);
jlbDateProduce.setBounds (273, 132, 300, 18);
jlbDirector.setBounds (273, 162, 300, 18);
jlbActor.setBounds (273, 192, 300, 18);
jlbRate.setBounds (273, 222, 300, 18);
jlbNoOfTicket.setBounds (77, 478, 150, 18);
// initialize the Radio Button
jr1 = new JRadioButton ("11.40 AM");
jr2 = new JRadioButton ("12.00 PM");
jr3 = new JRadioButton ("1.40 PM");
jr4 = new JRadioButton ("3.40 PM");
jr5 = new JRadioButton ("5.40 PM");
jr6 = new JRadioButton ("7.00 PM");
jr7 = new JRadioButton ("9.00 PM");
jr8 = new JRadioButton ("10.40 PM");
jr9 = new JRadioButton ("11.40 PM");
jr10 = new JRadioButton ("12.40 AM");
// add all the radion button
add(jr1);
add(jr2);
add(jr3);
add(jr4);
add(jr5);
add(jr6);
add(jr7);
add(jr8);
add(jr9);
add(jr10);
// set the radion button positions
jr1.setBounds (75, 423, 100, 24);
jr2.setBounds (172, 423, 100, 24);
jr3.setBounds (269, 423, 100, 24);
jr4.setBounds (366, 423, 100, 24);
jr5.setBounds (463, 423, 100, 24);
jr6.setBounds (75, 447, 100, 24);
jr7.setBounds (172, 447, 100, 24);
jr8.setBounds (269, 447, 100, 24);
jr9.setBounds (366, 447, 100, 24);
jr10.setBounds (463, 447, 100, 24);
// group the button
ButtonGroup group = new ButtonGroup ();
group.add(jr1);
group.add(jr2);
group.add(jr3);
group.add(jr4);
group.add(jr5);
group.add(jr6);
group.add(jr7);
group.add(jr8);
group.add(jr9);
group.add(jr10);
jr1.setActionCommand("radio1"); // for ButtonGroup
String sel = group.getSelection().getActionCommand();
// initialize all the button
jTotal = new JButton ("Total");
jBook = new JButton ("Book Now");
jCancel = new JButton ("Cancel");
// add all the button
add (jTotal);
add (jBook);
add (jCancel);
// set the button positions
jTotal.setBounds (191, 519, 83, 28);
jBook.setBounds (285, 519, 93, 28);
jCancel.setBounds (389, 519, 83, 28);
// add actionlistener
jTotal.addActionListener (this);
jBook.addActionListener (this);
jCancel.addActionListener (this);
// initialize all text field
jtfNoOfTicket = new JTextField (15);
// add all the text field
add (jtfNoOfTicket);
// set the text field positions
jtfNoOfTicket.setBounds (200, 477, 56, 22);
}
public void actionPerformed(ActionEvent e){
if((e.getSource() == jTotal)) {
double price = 12.00;
double number = (Integer.parseInt(jtfNoOfTicket.getText().trim()));
double total = 0.0;
total = price * number;
jlbTotal.setText(" Total : RM" + total +"0");
}
if((e.getSource() == jBook)) {
String name = jlbName.getText ();
String date = jlbDateProduce.getText ();
String time = jr1.getText ();
int number = (Integer.parseInt(jtfNoOfTicket.getText().trim()));
String total = jlbTotal.getText ();
String price = jlbPrice.getText ();
//Passing
ticketReservation frame = new ticketReservation(name, date, time, price, total, String.valueOf(number));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Ticket Reservation"); //set title of the window
frame.setSize(800,600); //size of the window
frame.setVisible(true); //visible the window
frame.setLocationRelativeTo (null); //center the window
}
if((e.getSource() == jCancel)) {
listOfMovies frame = new listOfMovies ();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("List of Movies"); //set title of thewindow
frame.setSize(800,600); //size of the window
frame.setVisible(true); //visible the window
frame.setLocationRelativeTo (null); //center the window
}
}
public static void main (String [] args) {
bookBatman frame = new bookBatman ();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Book Batman : The Dark Knight"); //set title of thewindow
frame.setSize(800,600); //size of the window
frame.setVisible(true); //visible the window
frame.setLocationRelativeTo (null); //center the window
}
}
Don't think of it as passing information from one GUI to another, but rather think of it in its most basic OOP form: as passing object state from one object to another. Often we use public accessor methods (i.e., "getter" methods) for this purpose and this can work here too.
Your ButtonGroup object will hold the ButtonModel of the selected JRadioButton (or null if none are selected) and so you can get the information from the model and return it from your getter method.
As an aside, your code has a lot of redundancies that can be reduced by using arrays and by using appropriate layout managers.
edit 1:
For Example
Say we create a JPanel that holds a bunch of JRadioButtons:
import java.awt.GridLayout;
import javax.swing.*;
class RadioBtnDialogPanel extends JPanel {
private static final String[] BUTTON_TEXTS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
private ButtonGroup buttonGroup = new ButtonGroup();
public RadioBtnDialogPanel() {
setLayout(new GridLayout(0, 1)); // give JPanel a decent layout
// create radio buttons, add to button group and to JPanel
for (String buttonText : BUTTON_TEXTS) {
JRadioButton radioBtn = new JRadioButton(buttonText);
radioBtn.setActionCommand(buttonText); // set the actionCommand here
buttonGroup.add(radioBtn);
add(radioBtn);
}
}
// getter or accessor method to get selected JRadioButton's actionCommand text
public String getSelectedButtonText() {
ButtonModel model = buttonGroup.getSelection();
if (model == null) { // no radiobutton selected
return "";
} else {
return model.getActionCommand();
}
}
}
We also give it a public getter method that queries the state of the ButtonGroup to find out which button model has been selected and then return its actionCommand, a String that holds the text that describes the radio button (here it's the same as the text of the radio button).
We can then show this JPanel in a JOptionPane in our main GUI and after the JOptionPane is done, query the object above by calling its getSelectedButtonText() method:
import java.awt.event.*;
import javax.swing.*;
public class RadioButtonInfo extends JPanel {
private RadioBtnDialogPanel radioBtnDlgPanel = new RadioBtnDialogPanel();
private JTextField textfield = new JTextField(10);
public RadioButtonInfo() {
JButton getDayOfWeekBtn = new JButton("Get Day Of Week");
getDayOfWeekBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getDayOfWeekActionPerformed();
}
});
textfield.setFocusable(false);
add(getDayOfWeekBtn);
add(textfield);
}
private void getDayOfWeekActionPerformed() {
// display a JOptionPane that holds the radioBtnDlgPanel
int result = JOptionPane.showConfirmDialog(this, radioBtnDlgPanel, "Select Day Of Week", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) { // if use presses "OK" get the selected radio button text
// here we call the getter method to get the selected button text
String selectedButtonText = radioBtnDlgPanel.getSelectedButtonText();
textfield.setText(selectedButtonText); // and put it into a JTextField
}
}
private static void createAndShowUI() {
JFrame frame = new JFrame("RadioButtonInfo");
frame.getContentPane().add(new RadioButtonInfo());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}