I would like to set editable option of a text box based on the selection of a radio button? How to code the action listener on the radio button?
This is the solution that I would use in this case.
//The text field
JTextField textField = new JTextField();
//The buttons
JRadioButton rdbtnAllowEdit = new JRadioButton();
JRadioButton rdbtnDisallowEdit = new JRadioButton();
//The Group, make sure only one button is selected at a time in the group
ButtonGroup editableGroup = new ButtonGroup();
editableGroup.add(rdbtnAllowEdit);
editableGroup.add(rdbtnDisallowEdit);
//add allow listener
rdbtnAllowEdit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setEditable(true);
}
});
//add disallow listener
rdbtnDisallowEdit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setEditable(false);
}
});
My Java is a little rusty, but this should be what you're looking for.
Here is your listener:
private RadioListener implements ActionListener{
private JTextField textField;
public RadioListener(JTextField textField){
this.textField = textField;
}
public void actionPerformed(ActionEvent e){
JRadioButton button = (JRadioButton) e.getSource();
// Set enabled based on button text (you can use whatever text you prefer)
if (button.getText().equals("Enable")){
textField.setEditable(true);
}else{
textField.setEditable(false);
}
}
}
And here is the code that sets it up.
JRadioButton enableButton = new JRadioButton("Enable");
JRadioButton disableButton = new JRadioButton("Disable");
JTextField field = new JTextField();
RadioListener listener = new RadioListener(field);
enableButton.addActionListener(listener);
disableButton.addActionListener(listener);
Another answer for this question. Modify a little code from zalpha314 's answer.
You could know which radio button is selected by the text of this button, and you could also know it by Action Command. In the oracle's radio button demo code http://docs.oracle.com/javase/tutorial/uiswing/examples/components/RadioButtonDemoProject/src/components/RadioButtonDemo.java , I learnt how to use action command.
First, define two action command
final static String ON = "on"
final static String OFF = "off"
Then add action command to buttons
JRadioButton enableButton = new JRadioButton("Enable");
enableButton.setActionCommand(ON);
JRadioButton disableButton = new JRadioButton("Disable");
disableButton.setActionCommand(OFF);
So in actionPerformed, you could get the action command.
public void actionPerformed(ActionEvent e){
String ac = e.getActionCommand();
if (ac.equals(ON)){
textField.setEditable(true);
}else{
textField.setEditable(false);
}
}
Action command maybe better when the button.getText() is a very long string.
Try this:
JRadioButton myRadioButton = new JRadioButton("");
myRadioButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// Do something here...
}
});
Try this:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class NewStudent {
public static void main(String[] args){
NewStudent st=new NewStudent();
}
public NewStudent(){
JFrame frame=new JFrame("STUDENT REGISTRATION FORM");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
frame.setVisible(true);
JPanel p1=new JPanel();
p1.setLayout(null);
p1.setBackground(Color.CYAN);
frame.add(p1);
ButtonGroup buttonGroup=new ButtonGroup();
JRadioButton male=new JRadioButton("MALE");
male.setBounds(100,170,100,20);
buttonGroup.add(male);
p1.add(male);
JRadioButton female=new JRadioButton("FEMALE");
female.setBounds(250,170,100,20);
buttonGroup.add(female);
p1.add(female);
JLabel sex =new JLabel("SEX:");
sex.setBounds(10,200,100,20);
p1.add(sex);
final JTextField gender= new JTextField();
gender.setBounds(100,200,300,20);
p1.add(gender);
male.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ie){
gender.setText("MALE");
}
});
female.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ie){
gender.setText("FEMALE");
}
});
}
Related
I don't get the result I want in this code, which is when I click on the checkbox then the JTextField's text should be bold, but It doesn't happen. Help me please.
public class GUI extends JFrame{
//CheckBoxs
private JCheckBox box1;
private JCheckBox box2;
//Buttons
private JButton button1;
private JButton button2;
//Text
private JTextField fnam;
private JTextField snam;
public GUI(){
//basic
super("Program");
setLayout(new FlowLayout());
//add
box1 = new JCheckBox("Button 1 Activate");
box2 = new JCheckBox("Button 2 Activate");
add(box1);
add(box2);
button1 = new JButton("Select First Name");
button2 = new JButton("Select Second Name");
add(button1);
add(button2);
fnam = new JTextField("Mena Farid",10);
snam = new JTextField("Malak Mamdoh",12);
fnam.setEditable(false);
snam.setEditable(false);
fnam.setFont(new Font("Serif",Font.PLAIN,10));
snam.setFont(new Font("Serif",Font.PLAIN,12));
add(fnam);
add(snam);
//ActionListener and Events
Handler Handle = new Handler();
Handler2 Handle2 = new Handler2();
box1.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(box1.isSelected())
button1.addItemListener(Handle);
}
}
);
box2.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(box2.isSelected())
button2.addItemListener(Handle2);
}
}
);
}
private class Handler implements ItemListener{
public void itemStateChanged(ItemEvent f){
Font font = null;
font = new Font("Serif",Font.BOLD,10);
fnam.setFont(font);
}
}
private class Handler2 implements ItemListener{
public void itemStateChanged(ItemEvent f){
Font font2 = null;
font2 = new Font("Serif",Font.BOLD,12);
snam.setFont(font2);
}
}
}
The problem is The JTextField format is supposed to be turned into bold after I tick the checkbox and click the button but It doesn't happen.
#LuxxMiner ow.. Thanks you fixed my problem . I have been using ItemListener for button instead of ActionListener all the time and that was the problem.
Basically, this is what needs to happen:
Submit button is clicked, the actionlistener picks it up and prints what is in the textfield at the time of submission.
For some reason, it isn't picking up the text inside the textbox?
The "Submit Button Pressed" is getting printed by the way!
This is a silly problem but I am not used to anonymous classes. I believe the problem is the variable modifier. Here is my code simplified:
public class MainWindw extends JFrame {
public static JTextField txt1;
final JButton submit;
public MainWindw()
{
//add panel...add textfield etc..
txt1 = new JTextField();
submit = new JButton("Submit");
submit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Submit button pressed" + txt1.getText());}
}
});
}
}
I have tried this solution, and it works. i honestrly don't see any problem in your code except some Compilation Error but i think is cause you have simplified the code
public static JTextField txt1;
final JButton submit;
public MainWindw()
{
JFrame panel = new JFrame();
txt1 = new JTextField();
submit = new JButton("Submit");
panel.setLayout(new FlowLayout());
panel.add(txt1);
panel.add(submit);
submit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Submit button pressed" + txt1.getText());
}
});
panel.setSize(300, 300);
panel.setVisible(true);
}
I am trying to get the value of the selected radio button on button click. This is what I managed to do but I am getting null as a result.
//Buttons Declared
JRadioButton choice1 = new JRadioButton("Choice 1");
JRadioButton choice2 = new JRadioButton("Choice 2");
JRadioButton choice3 = new JRadioButton("Choice 3");
JRadioButton choice4 = new JRadioButton("Choice 4");
choice1.setSelected(true);
//Buttons Grouped
ButtonGroup group = new ButtonGroup();
group.add(choice1);
group.add(choice2);
group.add(choice3);
group.add(choice4);
JPanel radioPanel = new JPanel();
radioPanel.add(choice1);
radioPanel.add(choice2);
radioPanel.add(choice3);
radioPanel.add(choice4);
JButton button = new JButton("Check Choice");
button.addActionListener(new ClickListener(group));
frame.add(button, BorderLayout.SOUTH);
//Calling Action Listener to read Radio Button Selected
static class ClickListener implements ActionListener{
ButtonGroup group = new ButtonGroup();
public ClickListener(ButtonGroup group){
super();
this.group = group;
}
public void actionPerformed(ActionEvent e){
System.out.println(group.getSelection().getActionCommand());
}
}
You never set the action commands of your JRadioButtons. So, when you ask for it, you're getting null.
Solution:
Where you first make the buttons:
choice1.setActionCommand("1");
choice2.setActionCommand("2");
choice3.setActionCommand("3");
choice4.setActionCommand("4");
then in your actionPerformed method:
String cmd = group.getSelection().getActionCommand();
if(cmd.equalsIgnoreCase("1")) {
// Button 1 Action
} else if(cmd.equalsIgnoreCase("2")) {
// Button 2 Action
} else if(cmd.equalsIgnoreCase("3")) {
// Button 3 Action
} else if(cmd.equalsIgnoreCase("4")) {
// Button 4 Action
}
This allows you to use the action commands to differentiate between the buttons. It isn't the cleanest way, but it should work.
Hope this helped!
Your ActionListener can query your four JRadioButton instances and check which one is selected with JRadioButton's isSelected() method.
If you want an event to occur when you click a JRadioButton and wish to know what JRadioButton was clicked, you could add an ActionListener to your JRadioButtons and then check if the ActionEvent originated from a specific JRadioButton with something like, e.getSource() == radioButton1.
You should make all the JRadioButton's static including the ButtonGroup.
Then you need to change the button listener:
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(java.awt.event.ActionEvent arg0) {
System.out.println(group.getSelection().getActionCommand());
}
});
And to fix the NullPointerException, use this for all your radiobuttons:
choice1.setActionCommand("Choice 1");
This should work for you:
public class Example extends JFrame implements ActionListener {
private ButtonGroup group = null;
private JRadioButton choice1 = new JRadioButton("Choice 1");
private JRadioButton choice2 = new JRadioButton("Choice 2");
private JRadioButton choice3 = new JRadioButton("Choice 3");
private JRadioButton choice4 = new JRadioButton("Choice 4");
public Example() {
choice1.addActionListener(this);
choice2.addActionListener(this);
choice3.addActionListener(this);
choice4.addActionListener(this);
group = new ButtonGroup();
group.add(choice1);
group.add(choice2);
group.add(choice3);
group.add(choice4);
JPanel radioPanel = new JPanel(new FlowLayout());
radioPanel.add(choice1);
radioPanel.add(choice2);
radioPanel.add(choice3);
radioPanel.add(choice4);
add(radioPanel);
setSize(400, 400);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
JRadioButton radio = null;
if (e.getSource() instanceof JRadioButton) {
radio = (JRadioButton) (e.getSource());
}
if (radio.equals(choice1)) {
System.out.println(choice1.getText());
}
}
I am wanting to get a return from a gui instance
The code i run to create the GUI:
JFrame frame = new JFrame();
frame.getContentPane().add(new ChatPopup());
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
My GUI (ChatPopUp code is as follows:
public class ChatPopup extends javax.swing.JPanel {
private JButton cancelButton;
private JTextField textFieldchatRoomName;
private JLabel jLabel1;
private JButton okButton;
public ChatPopup() {
super();
initGUI();
}
private void initGUI() {
try {
this.setPreferredSize(new java.awt.Dimension(294, 85));
{
jLabel1 = new JLabel();
this.add(jLabel1);
jLabel1.setText("Please enter the new chat room name:");
}
{
textFieldchatRoomName = new JTextField();
this.add(textFieldchatRoomName);
textFieldchatRoomName.setPreferredSize(new java.awt.Dimension(263, 22));
}
{
cancelButton = new JButton();
this.add(cancelButton);
cancelButton.setText("Cancel");
cancelButton.setPreferredSize(new java.awt.Dimension(84, 22));
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Cancel PRESSED");
}
});
}
{
okButton = new JButton();
this.add(okButton);
okButton.setText("Ok");
okButton.setPreferredSize(new java.awt.Dimension(60, 22));
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("OK PRESSED");
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is a pretty simple GUI which has a text field and 2 buttons one "Ok" one "Chancel".
When i click "Ok" i want the textField value to be sent to the class where the GUI instance is originally run.
Any ideas how to do this??
The JPanel you posted should be added to a modal JDialog content pane. In the same class, you can provide some methods to return the values the user entered into the text fields.
In the original window, you open the dialog.
SomeDialog dialog = new SomeDialog(parent);
dialog.setVisible(true);
The code after setVisible() will only be executed after the modal dialog is closed. At this point you can call the methods I mentioned above for getting the text field values.
I have a program where I calculate for either 1 of 2 variables depending on the radio button selected. For some reason, isSelected() is not returning true or false. I will post my code below:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
public class FutureValueFrame extends JFrame {
public FutureValueFrame() {
setTitle("Sample App");
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
JFrame f = new FutureValueFrame();
//GUI and BUTTONS
JRadioButton monthlyRadioButton = new JRadioButton("Monthly Payment");
JRadioButton loanAmountButton = new JRadioButton("Loan Amount");
ButtonGroup selection = new ButtonGroup();
selection.add(monthlyRadioButton);
selection.add(loanAmountButton);
JFormattedTextField loanAmountField = new JFormattedTextField(new DecimalFormat("####.##"));
JFormattedTextField interestRateField = new JFormattedTextField(new DecimalFormat("####.##"));
JFormattedTextField yearField = new JFormattedTextField(new DecimalFormat("####.##"));
JFormattedTextField monthlyPaymentField = new JFormattedTextField(new DecimalFormat("####.##"));
JPanel menuPanel = new JPanel();
menuPanel.setLayout(new GridLayout(1,2));
//ACTION LISTENER FOR RADIO BUTTONS
monthlyRadioButton.addActionListener(new SelectionListener(monthlyRadioButton, loanAmountButton, loanAmountField, monthlyPaymentField));
loanAmountButton.addActionListener(new SelectionListener(monthlyRadioButton, loanAmountButton, loanAmountField, monthlyPaymentField));
JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(1,2));
topPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
topPanel.add(monthlyRadioButton);
topPanel.add(loanAmountButton);
JPanel botPanel = new JPanel();
botPanel.setLayout(new GridLayout(4,2));
botPanel.add(new JLabel("Loan Amount:"));
botPanel.add(loanAmountField);
botPanel.add(new JLabel("Yearly Interest Rate:"));
botPanel.add(interestRateField);
botPanel.add(new JLabel("Number of Years:"));
botPanel.add(yearField);
botPanel.add(new JLabel("Monthly Payment:"));
botPanel.add(monthlyPaymentField);
JPanel container = new JPanel();
container.setLayout(new GridLayout(3,1));
container.add(topPanel);
container.add(botPanel);
container.add(menuPanel);
f.add(container);
JButton calculateButton = new JButton("Calculate");
if (monthlyRadioButton.isSelected()){
calculateButton.addActionListener(new CalculateMonthlyListener(loanAmountField, interestRateField, yearField, monthlyPaymentField));
}
if (loanAmountButton.isSelected()){
calculateButton.addActionListener(new CalculateLoanListener(loanAmountField, interestRateField, yearField, monthlyPaymentField));
}
JButton exitButton = new JButton("Exit");
exitButton.addActionListener(new ExitListener());
menuPanel.add(calculateButton);
menuPanel.add(exitButton);
f.setVisible(true);
f.setLocationRelativeTo(null);
}
class CalculateMonthlyListener implements ActionListener {
private JFormattedTextField loanAmountField;
private JFormattedTextField monthlyPaymentField;
private JFormattedTextField interestRateField;
private JFormattedTextField yearField;
private float result;
public CalculateMonthlyListener (JFormattedTextField loanAmountField, JFormattedTextField interestRateField, JFormattedTextField yearField, JFormattedTextField monthlyPaymentField)
{
this.interestRateField = interestRateField;
this.yearField = yearField;
this.loanAmountField = loanAmountField;
this.monthlyPaymentField = monthlyPaymentField;
}
public void actionPerformed(ActionEvent event){
monthlyPaymentField.setValue(new Double(12.22));
System.out.println("You selected monthly");
}
}
class CalculateLoanListener implements ActionListener {
private JFormattedTextField loanAmountField;
private JFormattedTextField monthlyPaymentField;
private JFormattedTextField interestRateField;
private JFormattedTextField yearField;
private float result;
public CalculateLoanListener (JFormattedTextField loanAmountField, JFormattedTextField interestRateField, JFormattedTextField yearField, JFormattedTextField monthlyPaymentField)
{
this.interestRateField = interestRateField;
this.yearField = yearField;
this.loanAmountField = loanAmountField;
this.monthlyPaymentField = monthlyPaymentField;
}
public void actionPerformed(ActionEvent event){
loanAmountField.setValue(new Double(12.22));
System.out.println("You selected loan");
}
}
class ExitListener implements ActionListener {
public void actionPerformed(ActionEvent event){
//f.dispose();
System.exit(0);
//System.out.println("You clicked exit");
}
}
class SelectionListener implements ActionListener {
private JRadioButton monthlyRadioButton;
private JRadioButton loanAmountButton;
private JFormattedTextField loanAmountField;
private JFormattedTextField monthlyPaymentField;
public SelectionListener (JRadioButton monthlyRadioButton, JRadioButton loanAmountButton, JFormattedTextField loanAmountField, JFormattedTextField monthlyPaymentField)
{
this.monthlyRadioButton = monthlyRadioButton;
this.loanAmountButton = loanAmountButton;
this.loanAmountField = loanAmountField;
this.monthlyPaymentField = monthlyPaymentField;
}
public void actionPerformed(ActionEvent event){
if(event.getSource() == monthlyRadioButton){
loanAmountField.setEditable(false);
monthlyPaymentField.setEditable(true);
}
else {
monthlyPaymentField.setEditable(false);
loanAmountField.setEditable(true);
}
}
}
}
I believe the problem occurs at this snippet:
if (monthlyRadioButton.isSelected()){
calculateButton.addActionListener(new CalculateMonthlyListener(loanAmountField, interestRateField, yearField, monthlyPaymentField));
}
if (loanAmountButton.isSelected()){
calculateButton.addActionListener(new CalculateLoanListener(loanAmountField, interestRateField, yearField, monthlyPaymentField));
}
isSelected is not returning true. I've tried creating an int i and setting it to 1. I checked for i==1 in each condition and they executed correctly.
Any insights?
You should put selection checking code in a single action listener attached to your button, not decide which action listener to attach to the button based on the selection.
Replace the code you think is the source of your problem with this:
calculateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (selection.getSelection().equals(monthlyRadioButton.getModel())) {
monthlyPaymentField.setValue(new Double(12.22));
System.out.println("You selected monthly");
} else {
loanAmountField.setValue(new Double(12.22));
System.out.println("You selected loan");
}
}
});
In order for this to compile you'll have to make the variables accessed in the above action listener final. Or replace both CalculateMonthlyListener and CalculateLoanListener with a single class which does the same as shown above.
Note that I did not use JRadioButton.isSelected() directly but instead used your ButtonGroup.getSelection(). You could also check the radio buttons themselves.
isSelected is fired from JRadioButton after ActionListener is done
then
use ItemListener (always fired twice) with to check for SELECTED / DESELECTED
and
put JRadioButtons to the ButtonGroup, ActionCommand returns String value
calculateButton has no assigned listener due to two things:
At the beginning both radio buttons are not selected. Set one as selected then the proper calculateButton listener will be assigned in proper if statements.
In actionPerformed method of SelectionListener you don't set a new calculateButton listener. Change that.