I have five RadionButtons with values from 1 to 5. According to my selection i want to print out the value.
JRadioButton rOneStar = new JRadioButton();
rOneStar.setActionCommand(Integer.toString(1));
JRadioButton rTwoStars = new JRadioButton();
rTwoStars.setActionCommand(Integer.toString(2));
JRadioButton rThreeStar s= new JRadioButton();
rThreeStars.setActionCommand(Integer.toString(3));
JRadioButton rFourStars = new JRadioButton();
rFourStars.setActionCommand(Integer.toString(4));
JRadioButton rFiveStars = new JRadioButton();
rFiveStars.setActionCommand(Integer.toString(5));
// group stars
ButtonGroup starGroup = new ButtonGroup();
starGroup.add(rOneStar);
starGroup.add(rTwoStars);
starGroup.add(rThreeStars);
starGroup.add(rFourStars);
starGroup.add(rFiveStars);
Now I have multiple ActionListeners that print out the value. But in my opinion it's way too much code.
rOneStar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
e.getActionCommand();
System.out.println(starGroup.getSelection().getActionCommand());
}
});
rTwoStars.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
e.getActionCommand();
System.out.println(starGroup.getSelection().getActionCommand());
}
});
... and so on
Can anyone give me a hint please how I can shorten my code?
Depends what you want to do further but with the code snippet given by you, you could refactor a bit by extracting two methods:
private JRadioButton createJRadioButton(int x){
final JRadioButton rXStar = new JRadioButton();
rXStar.setActionCommand(Integer.toString(x));
return rXStar;
}
private ActionListener createActionListener(){
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
e.getActionCommand();
System.out.println(starGroup.getSelection().getActionCommand());
}
};
}
This would reduce your code and make it a bit nicer, like so:
JRadioButton rOneStar = createJRadioButton(1);
JRadioButton rTwoStars = createJRadioButton(2);
JRadioButton rThreeStar = createJRadioButton(3);
JRadioButton rFourStars = createJRadioButton(4);
JRadioButton rFiveStars = createJRadioButton(5);
// group stars
ButtonGroup starGroup = new ButtonGroup();
starGroup.add(rOneStar);
starGroup.add(rTwoStars);
starGroup.add(rThreeStars);
starGroup.add(rFourStars);
starGroup.add(rFiveStars);
rOneStar.addActionListener(createActionListener());
rTwoStars.addActionListener(createActionListener());
rThreeStars.addActionListener(createActionListener());
rFourStars.addActionListener(createActionListener());
rFiveStars.addActionListener(createActionListener());
Related
I'm new to java GUI programming and while working on the project I'm getting the error cannot find symbol on my addActionListener for my JRadioButtons, I'm not quite sure what I'm doing wrong since I didn't receive the same error when working with JButtons.
Here's my code:
public void SouthPanel() {
JRadioButton greenButton = new JRadioButton("Green");
JRadioButton blueButton = new JRadioButton("Blue");
JRadioButton cyanButton = new JRadioButton("Cyan");
ButtonGroup group = new ButtonGroup();
group.add(greenButton);
group.add(blueButton);
group.add(cyanButton);
greenButton.addActionListener(new RadioButtonListener());
blueButton.addActionListener(new RadioButtonListener());
cyanButton.addActionListener(new RadioButtonListener());
SouthPanel = new JPanel();
add(greenButton);
add(blueButton);
add(cyanButton);
add(SouthPanel);
setVisible(true);
}
private class RadioButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String actionRadio = e.getActionCommand();
if (actionRadio.equals("Green")) {
label.setForeground(Color.GREEN);
}
else if (actionRadio.equals("Blue")) {
label.setForeground(Color.BLUE);
}
else if (actionRadio.equals("Cyan")) {
label.setForeground(Color.CYAN);
}
}
To my knowledge, the error "cannot find symbol" usually refers to a variable that can't be resolved by the compiler.
On what line does the error occur?
What seems a bit odd at first glance is following statement:
SouthPanel = new JPanel();
and add(SouthPanel);
since SouthPanel is the name of your method and you didn't give a name to your SouthPanel (?) object.
To use getActionCommand() on a Button or RadioButton, you should have previously set the ActionCommand
button.setActionCommand(String val);
You'd be able to get it back when you make a call to:
button.getActionCommand(); //This would return the string you previously set.
For a TextField, ActionCommand would give you the text in the TextField by default if you do not set it.
That's where you are probably missing the line.
You have created an instance of the JPanel and inserted into SouthPanel class. How can it be done.
SouthPanel = new JPanel();
add(greenButton);
add(blueButton);
add(cyanButton);
add(SouthPanel);
setVisible(true);
Into where are you adding the buttons and adding the SouthPanel.! Please check this one.Seems the error is from here.3 buttons are added,for 3 times and error is shown for 3 times.right.Seems error is from here. Check here.
See the complete code here.
class SouthPanel extends JPanel {
JLabel label = new JLabel("label");
public SouthPanel() {
JRadioButton greenButton = new JRadioButton("Green");
JRadioButton blueButton = new JRadioButton("Blue");
JRadioButton cyanButton = new JRadioButton("Cyan");
ButtonGroup group = new ButtonGroup();
group.add(greenButton);
group.add(blueButton);
group.add(cyanButton);
greenButton.addActionListener((ActionListener) new
RadioButtonListener());
blueButton.addActionListener(new RadioButtonListener());
cyanButton.addActionListener(new RadioButtonListener());
JPanel SouthPanel = new JPanel();
add(label);
add(greenButton);
add(blueButton);
add(cyanButton);
add(SouthPanel);
setVisible(true);
JFrame frame = new JFrame();
frame.setContentPane(this);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new SouthPanel();
}
private class RadioButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String actionRadio = e.getActionCommand();
if (actionRadio.equals("Green")) {
label.setForeground(Color.GREEN);
} else if (actionRadio.equals("Blue")) {
label.setForeground(Color.BLUE);
} else if (actionRadio.equals("Cyan")) {
label.setForeground(Color.CYAN);
}
}
}
}
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 creating a GUI, and can't figure out how to store the JList user selections in an array. I tried List<<Sting>>, Object[] etc... JRadioButtons and other GUIs are fine, only JList is not working...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame {
private JTextField num3;
private JLabel label3;
private JButton button;
private JRadioButton radio2;
private JRadioButton radio3;
private ButtonGroup radioGroup;
private JList statesList;
String[] states = {"Alabama", "Alaska", "Wyoming"};
String expression;
String frequency;
// no args constructor
public Test() {
createUI();
}
private void createUI() {
Container contentPane = getContentPane();
contentPane.setLayout(null);
label3 = new JLabel();
label3.setText("Search Expression");
label3.setBounds(16, 120, 200, 21);
contentPane.add(label3);
num3 = new JTextField();
num3.setText("(any expression)");
num3.setBounds(16, 144, 150, 21);
num3.setHorizontalAlignment(JTextField.LEFT);
contentPane.add(num3);
button = new JButton("Start!");
button.setBounds(90,430,126,24);
contentPane.add(button);
button.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event)
{
buttonActionPerformed(event);
}
}
);
// States Selection
statesList = new JList(states);
statesList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
statesList.setVisibleRowCount(5);
statesList.setBounds(400, 16, 100, 50);
JScrollPane statesScroll = new JScrollPane(statesList);
statesScroll.setBounds(180, 16, 135, 400);
contentPane.add(statesScroll);
// Radio Buttons
radio2 = new JRadioButton();
radio3 = new JRadioButton();
radio3.setSelected(true);
radioGroup = new ButtonGroup();
radioGroup.add(radio2);
radioGroup.add(radio3);
radio2.setText("Quarterly");
radio3.setText("Yearly");
radio2.setBounds(16,360,90,23);
radio3.setBounds(16,385,75,23);
contentPane.add(radio2);
contentPane.add(radio3);
// set the content Pane window
setTitle("Search Engine");
setSize(750,500);
setVisible(true);
}
// Getting the user's TextField and JRadioButton input
private void buttonActionPerformed(ActionEvent event) {
expression = num3.getText();
if (radio2.isSelected())
frequency = "quarterly";
else frequency = "yearly";
System.out.println(expression+","+frequency);
// The above "expression" and "frequency" work fine. But JList does not
// work. What am I doing wrong? I tried Object[] instead of List<String>...
List<String> values = statesList.getSelectedValues();
return values==null ? null : values.toArray(new String[values.size()]);
}
// main thread
public static void main(String[] args) {
Test application = new Test();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
This variant iterates the Object[] returned by getSelectedValues() to show expected values in the console. Next thing to fix is the layouts.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//public class Test extends JFrame {
public class Test {
private JTextField num3;
private JLabel label3;
private JButton button;
private JRadioButton radio2;
private JRadioButton radio3;
private ButtonGroup radioGroup;
private JList statesList;
String[] states = {"Alabama", "Alaska", "Wyoming"};
String expression;
String frequency;
// no args constructor
public Test() {
createUI();
}
private void createUI() {
JFrame f = new JFrame("Search Engine");
Container contentPane = f.getContentPane();
// This needs fixing NEXT!
contentPane.setLayout(null);
label3 = new JLabel();
label3.setText("Search Expression");
label3.setBounds(16, 120, 200, 21);
contentPane.add(label3);
num3 = new JTextField();
num3.setText("(any expression)");
num3.setBounds(16, 144, 150, 21);
num3.setHorizontalAlignment(JTextField.LEFT);
contentPane.add(num3);
button = new JButton("Start!");
button.setBounds(90,430,126,24);
contentPane.add(button);
button.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
buttonActionPerformed(event);
}
});
// States Selection
statesList = new JList(states);
statesList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
statesList.setVisibleRowCount(5);
statesList.setBounds(400, 16, 100, 50);
JScrollPane statesScroll = new JScrollPane(statesList);
statesScroll.setBounds(180, 16, 135, 400);
contentPane.add(statesScroll);
// Radio Buttons
radio2 = new JRadioButton();
radio3 = new JRadioButton();
radio3.setSelected(true);
radioGroup = new ButtonGroup();
radioGroup.add(radio2);
radioGroup.add(radio3);
radio2.setText("Quarterly");
radio3.setText("Yearly");
radio2.setBounds(16,360,90,23);
radio3.setBounds(16,385,75,23);
contentPane.add(radio2);
contentPane.add(radio3);
// set the content Pane window
f.setSize(750,500);
//f.pack();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setVisible(true);
}
// Getting the user's TextField and JRadioButton input
private void buttonActionPerformed(ActionEvent event) {
expression = num3.getText();
if (radio2.isSelected())
frequency = "quarterly";
else frequency = "yearly";
System.out.println(expression+","+frequency);
Object[] values = statesList.getSelectedValues();
for (Object state : values) {
System.out.println(state);
}
}
// main thread
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
Test application = new Test();
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
Tips
Don't extend frame, just use an instance.
J2SE GUIs (Swing & AWT) should be created and updated on the EDT. See Concurrency in Swing - Initial Threads especially.
contentPane.setLayout(null); This will not work in the real world (read probably the next PC as 'the real world'). Use layout managers for a robust GUI. See Laying Out Components Within a Container for details, and also this nested layout example for grouping layouts according to need.
According to the documentation, getSelectedValues returns an object array.
Object[] values = statesList.getSelectedValues();
If you're positive they're all strings, you can just type cast them.
String[] values = (String[]) statesList.getSelectedValues();
Edit: Try this:
Object[] values = statesList.getSelectedValues();
String[] strings = new String[values.length];
for(int i = 0; i < values.length; i++) {
if(values[i] instanceof String) {
strings[i] = ((String) values[i]);
}
}
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");
}
});
}
I am having some issues with my code, I cant see whats wrong with the logic, but here it is. I want them to have the radio button to choose either or, and when one is selected(radio button) the text area isn't available and vise versa. Here is the segment of the code. When I go back and forth on the radio buttons, both become not selectable, and I am unsure why.
private void PriceTab()
{
pricePanel = new JPanel(new FlowLayout());
final JRadioButton poolPrice= new JRadioButton("Pool");
final JRadioButton tubPrice = new JRadioButton("Hot Tub");
poolPrice.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(poolPrice);
group.add(tubPrice);
pricePanel.add(poolPrice);
pricePanel.add(tubPrice);
final JLabel poolLabel = new JLabel("Enter the pool's volume: ");
final JTextField poolField = new JTextField(10);
pricePanel.add(poolLabel);
pricePanel.add(poolField);
final JTextField tubField = new JTextField(10);
final JLabel tubLabel = new JLabel ("Enter the tub's volume: ");
pricePanel.add(tubLabel);
pricePanel.add(tubField);
JButton calculatePrice = new JButton("Calculate Price");
calculatePrice.setMnemonic('C');
pricePanel.add(calculatePrice);
pricePanel.add(createExitButton());
pricePanel.add(new JLabel("The price is: "));
final JTextField priceField = new JTextField(10);
priceField.setEditable(false);
pricePanel.add(priceField);
final JTextArea messageArea = createMessageArea(1, 25,
"*Please only select one section");
pricePanel.add(messageArea);
calculatePrice.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double pool = Double.parseDouble (poolField.getText());
double tub = Double.parseDouble(tubField.getText());
double price;
if (poolPrice.isSelected()) {
price = pool * 100;
} else {
price = tub * 75;
}
priceField.setText(df.format(price));
}
});
ActionListener priceListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == poolPrice) {
tubLabel.setEnabled(false);
tubField.setEnabled(false);
messageArea.setVisible(false);
} else if (e.getSource() == tubPrice) {
poolLabel.setEnabled(false);
poolField.setEnabled(false);
messageArea.setVisible(false);
}
}
};
poolPrice.addActionListener(priceListener);
tubPrice.addActionListener(priceListener);
}
ActionListener priceListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == poolPrice) {
tubLabel.setEnabled(false);
tubField.setEnabled(false);
// Re-enable the previously disabled labels
poolLabel.setEnabled(true);
poolField.setEnabled(true);
messageArea.setVisible(false);
} else if (e.getSource() == tubPrice) {
poolLabel.setEnabled(false);
poolField.setEnabled(false);
// Re-enable disabled labels
tubLabel.setEnabled(true);
tubField.setEnabled(true);
messageArea.setVisible(false);
}
}
};
You need to re-enable the buttons you disabled.