Selecting radio buttons to make text appear - java

Using radio buttons displayed on a panel, is it possible to select the radio button and then display some text on the panel explaining what the user has selected?
So here is a list of radio buttons
public void RadioButtons() {
btLdap = new JRadioButton ("Ldap");
btLdap.setBounds(60,85,100,20);
panelHolder.add(btLdap);
btKerbegos = new JRadioButton ("Kerbegos");
btKerbegos.setBounds(60,115,100,20);
panelHolder.add(btKerbegos);
btSpnego =new JRadioButton("Spnego");
btSpnego.setBounds(60,145,100,20);
panelHolder.add(btSpnego);
btSaml2 = new JRadioButton("Saml2");
btSaml2.setBounds(60,175,100,20);
panelHolder.add(btSaml2);
}
User selects btLdap
btLdap.setSelected(true);
Now how do you make the text appear on the panel not a message box

If you want to display a text when a radio button is selected you could use ActionListener.
final JTextArea textArea = new JTextArea();
add(textArea);
JRadioButton radioButton = new JRadioButton();
add(radioButton);
radioButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
textArea.setText("Selected");
}
});
JRadioButton radioButton2 = new JRadioButton();
add(radioButton2);
radioButton2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
textArea.setText("Selected 2");
}
});
radioButton.setSelected(true);
When the first is selected it will change the text of the JTextArea with The first is selected!, same the second radio button but with The second is selected.
As you said, radioButton.setSelected(true); setSelected is used to select/deselect a radio button.
In this example i used textArea, but you can use everything which have a method to change the text it contains (an image too!)
Official DOC, here.
Anyway, actionPerformed is not called when setSelected is used so i would go to something like a method
private void updateText(int index)
{
String text = null;
switch (index)
{
case 0:
text = "Selected";
break;
case 1:
text = "Selected 2";
break;
}
textArea.setText(text);
}
And then call updateText(0 or 1 etc.) when you want to select setSelected another radio button and update the text too.
All this is useful, if you want to show a "what happens if you press it" message, but if you just want to change the text of the area with the text of the radio button, just use
textArea.setText(e.getActionCommand());

Here is some Example how to use an ActionListener on a JRadioButton:
public class ListenerExample extends JFrame implements ActionListener {
private JRadioButton check = new JRadioButton("hello");
private JLabel label = new JLabel();
public ListenerExample() {
check.addActionListener(this);
add(check);
add(label);
setLayout(new FlowLayout());
setSize(800, 600);
setVisible(true);
}
public static void main(String[] args) {
new ListenerExample();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JRadioButton) {
JRadioButton button = (JRadioButton) e.getSource();
label.setText(String.valueOf(check.isSelected()));
}
}
}

Using an anonymous inner class you will have something like:
yourRadioButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
// here you will write the code that you want to
// be executed when your radio is clicked
yourLabel.setText( "Some text..." );
// if you want to exeute it onlye when it is selected
// you will need to do this
if ( yourRadioButton.isSelected() ) {
// some code here
}
}
});
In Java 8, recently released, you can use a lambda expression to register your listener. Something like:
yourRadioButton.addActionListener( event -> {
// here you will write the code that you want to
// be executed when your radio is clicked
yourLabel.setText( "Some text..." );
// if you want to exeute it onlye when it is selected
// you will need to do this
if ( yourRadioButton.isSelected() ) {
// some code here
}
});

Related

Have a Button Group in Java where all buttons can be deselected?

I want to have a Button Group in which either only one option is selected or none of them are. At the moment, I can get it to have no options ticked by default, and then if one of them is ticked only one of them can be ticked, but I also want to be able to untick the button that was selected. Is this possible?
EDIT: Ideally without having a clear all button, as it would ruin the symmetry of my GUI. Also, here is my code thus far:
ButtonGroup option = new ButtonGroup();
for(int i = 0; i < n; i++) {
JCheckBox check = new JCheckBox("", false);
option.add(check);
row3b.add(check);
}
Just use the clearSelection() method of ButtonGroup :
ButtonGroup.clearSelection()
Clears the selection such that none of the buttons in the ButtonGroup
are selected.
This snippet demonstrates how you can clear selections using ButtonGroup.clearSelection():
//The buttons
JFrame frame = new JFrame("Button test");
JPanel panel = new JPanel();
JRadioButton btn1 = new JRadioButton("Button1");
JRadioButton btn2 = new JRadioButton("Button2");
JButton clearbutton = new JButton("Clear");
panel.add(btn1);
panel.add(btn2);
panel.add(clearbutton);
frame.add(panel);
frame.setVisible(true);
frame.pack();
//The Group, make sure only one button is selected at a time in the group
ButtonGroup btngroup = new ButtonGroup();
btngroup.add(btn1);
btngroup.add(btn2);
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Do whatever you want here
}
});
btn2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Do whatever you want here
}
});
clearbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Clear all selections
btngroup.clearSelection();
}
});
As you can see, this creates two JRadioButtons and adds them to group then makes a button that clears selections. Really simple. Or you could create your own radio button class that allows for the unchecking of the button, which is also doable relatively easily.

The getSource() method in an action listener does not recognize the buttons i'm referring to

all, I'm a newbie to Java and I'm working on the Lab 12 on the Java textbook, Starting out with Java (Ed.5).
After written the code for constructor, I have created a method to build a panel and add some radio buttons to it. I have registered these radio buttons to an Action Listener called RadioButtonListener. Then I wrote an inner class for RadioButtonListener.
Here is the problem, as I used the getSource() method to determine which button is clicked, the compiler does not recognize the button I indicated.
Here is my coding:
private void buildBottomPanel()
{
bottomPanel = new JPanel();
JRadioButton greenButton = new JRadioButton("Green");
JRadioButton blueButton = new JRadioButton("Blue");
JRadioButton cyanButton = new JRadioButton("Cyan");
ButtonGroup bottomButtonGroup = new ButtonGroup();
bottomButtonGroup.add(greenButton);
bottomButtonGroup.add(blueButton);
bottomButtonGroup.add(cyanButton);
greenButton.addActionListener(new RadioButtonListener());
blueButton.addActionListener(new RadioButtonListener());
cyanButton.addActionListener(new RadioButtonListener());
bottomPanel.add(greenButton);
bottomPanel.add(blueButton);
bottomPanel.add(cyanButton);
}
private class RadioButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent f)
{
if (f.getSource() == greenButton)
{
messageLabel.setForeground(Color.GREEN);
}
else if (f.getSource() == blueButton)
{
messageLabel.setForeground(Color.BLUE);
}
else if (f.getSource() == cyanButton)
{
messageLabel.setForeground(Color.CYAN);
}
}
}
try to use getActionCommand() instead of getSource() as Below :-
if (f.getActionCommand().equals("green"))
{
messageLabel.setForeground(Color.GREEN);
}
or you can use anonymous inner classes as below :-
greenButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e)
{
messageLabel.setForeground(Color.GREEN);
}
});

How do I trigger a textbox with a button

I have the following code. How would I make a textbox displaying the text on each button come up when that button is pushed? I'm taking a beginning java class online that gives little to no instruction and then asks me to do stuff like this, so any and all help is very much appreciated. I want to learn! Thank You!
import java.awt.*;
public class FinalProj2 extends Frame
{
FinalProj2()
{
setTitle("Buttons");
setSize(600,600);
show();
}
public static void main(String args[])
{
Frame objFrame;
Button objButton1;
Button objButton2;
Button objButton3;
Label objLabel2;
objFrame= new FinalProj2();
objButton1= new Button("Submit");
objButton2= new Button("Cancel");
objButton3= new Button("What Now");
objLabel2= new Label();
objButton1.setBounds(60,200,80,80);
objButton2.setBounds(150,300,80,80);
objButton3.setBounds(60,400,80,80);
objFrame.add(objButton2);
objFrame.add(objButton1);
objFrame.add(objButton3);
objFrame.add(objLabel2);
}
}
Attach an ActionListener using addActionListener() method on each of the buttons instances you need. In actionPerformed()method text in textbox
btn.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
lbl.setText(btn.getLabel());
}
});
If I understand you correctly, You want that when you press any button then the button label should be displayed in TextField
For this you have to create an object of TextField like:
final TextField box = new TextField();
Then you can add ActionListener on that TextField like:
objButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
box.setText(objButton1.getLabel());
}
});
Same for other buttons.

Input Verifier effect not work by click, just work by tab button

I have a delicate problem!
I have a form that set input verifier to text fields, and when user type a incorrect value, other text fields and radio buttons should be disable.
In second text filed (last name), When user type a incorrect value, other components disable perfectly, But when user edit that value to correct it, (for e.x by removing digit), user should user keyboard tab button to enable other components (radio buttons) and I want to enable with clicking to radio buttons too.
Here is my code:
public class UserDialog3 extends JDialog implements ActionListener {
JButton cancelBtn, okBtn;
JTextField fNameTf, lNameTf;
JRadioButton maleRb, femaleRb;
ButtonGroup group;
JLabel fNameLbl, lNameLbl, genderLbl, tempBtn, temp3, temp2, temp1;
public UserDialog3() {
add(createForm(), BorderLayout.CENTER);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocation(400, 100);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new UserDialog3();
}
});
}
public JPanel createForm() {
JPanel panel = new JPanel();
okBtn = new JButton("Ok");
cancelBtn = new JButton("Cancel");
tempBtn = new JLabel();
fNameLbl = new JLabel("First Name");
lNameLbl = new JLabel("Last Name");
genderLbl = new JLabel("Gender");
temp2 = new JLabel();
temp1 = new JLabel();
maleRb = new JRadioButton("Male");
femaleRb = new JRadioButton("Female");
temp3 = new JLabel();
group = new ButtonGroup();
group.add(maleRb);
group.add(femaleRb);
fNameTf = new JTextField(10);
fNameTf.setName("FnTF");
fNameTf.setInputVerifier(new MyVerifier(new JComponent[]{maleRb, femaleRb, okBtn}));
lNameTf = new JTextField(10);
lNameTf.setName("LnTF");
lNameTf.setInputVerifier(new MyVerifier(new JComponent[]{maleRb, femaleRb, okBtn}));
panel.add(fNameLbl);
panel.add(fNameTf);
panel.add(temp1);
panel.add(lNameLbl);
panel.add(lNameTf);
panel.add(temp2);
panel.add(genderLbl);
JPanel radioPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
radioPanel.add(maleRb);
radioPanel.add(femaleRb);
panel.add(radioPanel);
panel.add(temp3);
panel.add(okBtn);
panel.add(cancelBtn);
panel.add(tempBtn);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 4, 3, 50, 10, 80, 60);
return panel;
}
#Override
public void actionPerformed(ActionEvent e) {
}
public class MyVerifier extends InputVerifier {
private JComponent[] component;
public MyVerifier(JComponent[] components) {
component = components;
}
#Override
public boolean verify(JComponent input) {
String name = input.getName();
if (name.equals("FnTF")) {
String text = ((JTextField) input).getText().trim();
if (text.matches(".*\\d.*") || text.length() == 0) {
//disable dependent components
for (JComponent r : component) {
r.setEnabled(false);
}
return false;
}
} else if (name.equals("LnTF")) {
String text = ((JTextField) input).getText();
if (text.matches(".*\\d.*") || text.length() == 0) {
//disable dependent components
for (JComponent r : component) {
r.setEnabled(false);
}
return false;
}
}
//enable dependent components
for (JComponent r : component) {
r.setEnabled(true);
}
return true;
}
}
}
The purpose of InputVerifier class is to help clients support smooth focus navigation through GUIs with text fields. Before focus is transfered to another Swing component that requests it, the input verifier's shouldYieldFocus method is called(which ask the verify function to validate data). Focus is transfered only if that method returns true.
Please Try to fix the issues about using InutVerifier, verify and shouldYieldFunction as mentioned in your previous post. If you are not going to change your practice, you will be danger in future. Remove you components enabling and disabling code from verify function.
Your Problem in this post: In this case, what really happening is that, when your data is invalid and you try to lose your input text field focus by clicking another component, your JRadioButtons get disabled. A disabled cant be focused until it is re-enabled. As input-verifier responds with focus-lose event, clicking on the disabled RadioButton isn't resulting in focus navigation, and thus ShouldYieldFocus(which calls verify) is not being called to re-enable your components.
Pressing the tab works, because it is sending the Focus to your second text input field according to swing's focus traversal policy. Hence a focus lose event occur on first input text field and this time InputVerifier's verify function get called which eventually enables your component. To understand the problem better, try rewriting your own example with one JRadioButton and one JTextFeild.
Try using a DocumentListener with your text Field. upon data insertion and removal event, check your data validity using InputVerifier and then, enable/disable related components.
I am writing a sample code snippets to demonstrate, how adding DocumentListener to your fNameTF and lNameTF text fields will resolve your problem:
fNameTF.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
doOnDataValidity(verifier.verify(fNameTF));
}
#Override
public void removeUpdate(DocumentEvent e) {
doOnDataValidity(verifier.verify(fNameTF));
}
#Override
public void changedUpdate(DocumentEvent e) {}
});
doOnValidity(boolean isValid) function is as follows:
public void doOnDataValidity(boolean isDataValid)
{
if(isDataValid)
{
//enable your components
}else
{
//disable your components
}
}
Add a DocumentListener to your lNameTf.getDocument() the same way.
Tutorial Resources: How to use DocumentListener.

Text Field disabling in NetBeans

I want to ask if there is a way to make the text field active and inactive according to the radio button.
For example, the textfield will be inactive and when the user click on the radio button, the textfield will be active.
I am using Java language and NetBeans program
You could have two radio buttons for representing the active/inactive state. Add an action listener to each and when the 'active' one is pressed you call setEditable(true) on the JTextField and when the 'inactive' JRadioButton is called you call setEditable(false).
JTextField textField = new JTextField();
JRadioButton activeButton = new JRadioButton("Active");
JRadioButton inactiveButton = new JRadioButton("Inactive");
activeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
textField.setEditable(true);
}
});
inactiveButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
textField.setEditable(false);
}
});

Categories

Resources