This code not work properly. When I select male, every time it select female automatically?
How to validate radio button for gender?
rbtnmale = new JRadioButton("male");
rbtnmale.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
gender="male";
rbtnmale.setSelected(true);
rbtnmale.setSelected(false);
}
});
rbtnmale.setBounds(116, 127, 58, 23);
frame.getContentPane().add(rbtnmale);
rbtnfemale = new JRadioButton("female");
rbtnfemale.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
gender="female";
rbtnfemale.setSelected(true);
rbtnmale.setSelected(false);
}
});
You should be using ButtonGroup, put all of your JRadioButtons in it and then loop through buttonGroup.getElements() to find which JRadioButton is selected. Here is a complete example:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.util.Enumeration;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class Example {
ButtonGroup group = new ButtonGroup();//used to store all radio buttons.
public Example() {
initComponents();
currentSelectedOption();
}
private void initComponents() {
//Radio buttons
JRadioButton female = new JRadioButton("Female");
JRadioButton male = new JRadioButton("Male");
JRadioButton other = new JRadioButton("Other");
female.setSelected(true);//by default, select female.
//Add all radio buttons to a group.
//It will allow to only have one selected at a time.
group.add(male);
group.add(female);
group.add(other);
//Add your components to a panel, it's a good practice.
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
panel.add(female);
panel.add(male);
panel.add(other);
JFrame frame = new JFrame("Example");
frame.setLayout(new BorderLayout());
frame.setLocationRelativeTo(null);
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
/**
* Getting the current selected radio button.
*
* #return Text of the radio button currently selected.
*/
public String getSelectedOption() {
Enumeration<AbstractButton> radioButtons = group.getElements();
while (radioButtons.hasMoreElements()) {
AbstractButton currentRadioButton = radioButtons.nextElement();
if (currentRadioButton.isSelected()) {
return currentRadioButton.getText();
}
}
return null;
}
private void currentSelectedOption() {
String selected = getSelectedOption();
if (selected == null) {
System.out.println("There is something wrong! Nothing is selected");
return;
}
switch (selected.toLowerCase()) {
case "male":
System.out.println("male is selected");
break;
case "female":
System.out.println("female is selected");
break;
case "other":
System.out.println("other is selected");
break;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Example();
}
});
}
rbtnmale.setSelected(true);
rbtnmale.setSelected(false);
Based on your current code you want:
//rbtnmale.setSelected(false);
rbtnfemale.setSelected(false);
However you don't even need the above code in the ActionListener for either of the radio buttons.
Instead you should be using a ButtonGroup and the ButtonGroup will manage the selected state of each radio button for you:
ButtonGroup group = new ButtonGroup();
group.add(btnMale);
group.add(btnFemale);
Read the section from the Swing tutorial on How Use Buttons for more information
Related
i have java swing Class that create JButton
it is working but what i need is when i pressed a JButton lets seed that it is number 1 the code in the ActionEvent is to change the Background of the JButton but what i need is if i pressed another JButton the first one i need it to go back to red Color :
Example :
package Classes;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class testbtn {
public JFrame frame = new JFrame();
public int copcounter = 5;
public testbtn() {
JPanel jdb = new JPanel();
jdb.setLayout(new FlowLayout());
for (int x = 1; x <= copcounter; x++) {
JButton btn = new JButton();
btn.setText(String.valueOf(x));
if (x == 1) {
btn.setBackground(Color.yellow);
} else {
btn.setBackground(Color.red);
}
btn.putClientProperty("id", x);
btn.addActionListener((ActionEvent e) -> {
btn.setBackground(Color.yellow);
System.out.println(e.getID());
});
jdb.add(btn);
}
frame.add(jdb);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new testbtn();
}
});
}
}
this code will show form like this :
when i press JButton 4 the output become like this :
but i need it to be like this so the other button will become red color but what i pressed i need it to become yellow ! :
i know that i can use id but how to get the id for them ! or if there is better way ?
No need for an id, simply put all the JButtons into a List<JButton>, say called buttonList, and then iterate through the list in the button's ActionListener, turning backgrounds red for all the buttons in the list, and then turn the current button's background yellow.
And then in the code that uses it:
public void actionPerformed(ActionEvent e) {
// iterate through the list
for (JButton button : buttonList) {
button.setBackground(Color.RED);
}
// then set *this* button's color yellow:
((JButton) e.getSource).setBackground(Color.YELLOW);
}
That's it
or for your code...
public class TestBtn {
public JFrame frame = new JFrame();
public int copcounter = 5;
private List<JButton> buttonList = new ArrayList<>();
public TestBtn() {
JPanel jdb = new JPanel();
jdb.setLayout(new FlowLayout());
for (int x = 1; x <= copcounter; x++) {
JButton btn = new JButton();
// add this
buttonList.add(btn);
btn.setText(String.valueOf(x));
if (x == 1) {
btn.setBackground(Color.yellow);
} else {
btn.setBackground(Color.red);
}
// btn.putClientProperty("id", x);
btn.addActionListener((ActionEvent e) -> {
// iterate through the list
for (JButton button : buttonList) {
button.setBackground(Color.RED);
}
// then set *this* button's color yellow:
((JButton) e.getSource).setBackground(Color.YELLOW);
// show button text
System.out.println(e.getActionCommand());
});
jdb.add(btn);
}
frame.add(jdb);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new testbtn();
}
});
}
}
Also, the ActionEvent's actionCommand String should match the button's text (with some exceptions).
Below is a short snippet of my code used in my Swing Application, Its an mcq application where I've used radioButtons as the mean to select the chosen option, However when I try selecting any option from 1-4, It automatically selects the last one. Now I've tried putting the last button in the else if condition as well but I dont know what I should write in the else condition then.
JButton btnNext_1 = new JButton("Next");
btnNext_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
/* if(db_ans.equals(studentAnswer))
{
tmarks=tmarks+db_marks;
System.out.println("correct-second");
}*/
buttonGroup.clearSelection();
if(radioButton.isSelected())
{
studentAnswer=radioButton.getText();
radioButton_1.setSelected(false);
radioButton_2.setSelected(false);
radioButton_3.setSelected(false);
System.out.println(studentAnswer);
}
else if(radioButton_1.isSelected())
{
studentAnswer=radioButton_1.getText();
System.out.println(studentAnswer);
radioButton.setSelected(false);
radioButton_2.setSelected(false);
radioButton_3.setSelected(false);
}
else if(radioButton_2.isSelected())
{
studentAnswer=radioButton_2.getText();
System.out.println(studentAnswer);
radioButton.setSelected(false);
radioButton_1.setSelected(false);
radioButton_3.setSelected(false);
}
else if {
studentAnswer=radioButton_3.getText();
System.out.println(studentAnswer);
radioButton.setSelected(false);
radioButton_1.setSelected(false);
radioButton_2.setSelected(false);
}
if(db_ans.equals(studentAnswer))
{
tmarks=tmarks+db_marks;
System.out.println("correct-second");
}
});
As said in comments you would want to use a ButtonGroup this will allow only 1 JRadioButton to be selected at a time, see below for a simple example:
TestApp.java:
import java.awt.event.ActionEvent;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class TestApp {
public TestApp() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TestApp::new);
}
private void initComponents() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JRadioButton option1 = new JRadioButton("Option 1");
option1.setSelected(true);
JRadioButton option2 = new JRadioButton("Option 2");
ButtonGroup group = new ButtonGroup();
group.add(option1);
group.add(option2);
panel.add(option1);
panel.add(option2);
JButton button = new JButton("What did I choose?");
button.addActionListener((ActionEvent e) -> {
if (option1.isSelected()) {
JOptionPane.showMessageDialog(frame, "You chose option 1");
} else if (option2.isSelected()) {
JOptionPane.showMessageDialog(frame, "You chose option 2");
}
});
panel.add(button);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
Essentially each JRadioButton is added to the same ButtonGroup and each JRadioButton is then added to the panel. Now you will only be able to select 1 option from within the same group, and there is no need to set any other JRadioButton in the same group to false.
you have all radio button selected so android is last one read means radioButton_2 this read last so radioButton2 selected
Im using blue j for a project which is a java framework (not through my choice)
I cant get it to print out what seat they have chosen because it always selects the 1st value A1.
Its a seating plan that displays and image and a combo box in which you can select your seat for exmaple A1 and upon the button click save it prints out the seat you have chosen in a dialog box.
Help!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.lang.String;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class SeatingChart extends JFrame
{
private JLabel infoLabel;
// Get the list of field names, used for ordering.
String[] ordering =
{"A1","A2","A3","A4",
"B1","B2","B3","B4",
"C1","C2","C3","C4","D1","D2","D3","D4"};
String chosenSeat;
String ticket= "1" ;
int ticketValue = Integer.parseInt(ticket);
/**
* Main method for starting the system from a command line.
*/
public static void main(String[] args)
{
SeatingChart gui = new SeatingChart();
}
/**
* Create a visual aspect and display its GUI on screen.
*/
public SeatingChart()
{
super("Choose Your seats");
makeFrame();
}
/**
* Quit function: quit the application.
*/
private void quit()
{
System.exit(0);
}
private void play()
{
JFrame frames = new JFrame("Sample frame");
frames.setSize(400, 400);
frames.setVisible(false);
frames.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(frames, "You have chosen the seat " +chosenSeat);
}
/**
* Create the complete application GUI.
*/
public void makeFrame ()
{
// the following makes sure that our application exits when
// the user closes its window
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel contentPane = (JPanel) getContentPane();
contentPane.setBorder(new EmptyBorder(6, 10, 10, 10));
makeMenuBar(); //calls the menu bar method
// Create the center with image
JPanel centerPane = new JPanel();
{
centerPane.setLayout(new BorderLayout(8, 8));
JLabel image = new JLabel(new ImageIcon("SeatingChart.jpg"));
image.setSize (20,20);//dont work
centerPane.add(image, BorderLayout.NORTH);
centerPane.setBackground(Color.WHITE);
infoLabel = new JLabel("Please use the chart to select where you would like to sit and save it. Do this for how many tickets you have");
infoLabel.setHorizontalAlignment(SwingConstants.CENTER);
centerPane.add(infoLabel, BorderLayout.CENTER);
}
contentPane.add(centerPane, BorderLayout.EAST);
JPanel leftPane = new JPanel();
{
leftPane.setLayout(new BorderLayout(8, 8));
// Set up components for ordering the list
JPanel orderingPanel = new JPanel();
orderingPanel.setLayout(new BorderLayout());
orderingPanel.add(new JLabel("Choose your seat:"), BorderLayout.NORTH);
// Create the combo box.
JComboBox formatList = new JComboBox(ordering);
orderingPanel.add(formatList, BorderLayout.CENTER);
leftPane.add(orderingPanel, BorderLayout.NORTH);
formatList.setSelectedIndex(0);
chosenSeat = formatList.getSelectedItem().toString();
//formatList.removeItemAt(formatList.getSelectedIndex());
}
contentPane.add(leftPane, BorderLayout.CENTER);
JPanel toolbar = new JPanel();
{
toolbar.setLayout(new GridLayout(1, 0));
JButton button = new JButton("Save");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
play();
}
});
toolbar.add(button);
button = new JButton("Next");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// This button would allow the use to go to the next step
}
});
toolbar.add(button);
}
contentPane.add(toolbar, BorderLayout.SOUTH);
// building is done - arrange the components
pack();
// place this frame at the center of the screen and show
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(d.width/2 - getWidth()/2, d.height/2 - getHeight()/2);
setVisible(true);
}
/**
* Create the main frame's menu bar.
*/
private void makeMenuBar()
{
final int SHORTCUT_MASK =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
JMenuBar menubar = new JMenuBar();
setJMenuBar(menubar);
JMenu menu;
JMenuItem item;
// create the File menu
menu = new JMenu("File");
menubar.add(menu);
item = new JMenuItem("Quit");
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
quit();
}
});
menu.add(item);
}
}
You set the chosenSeat field immediately after creating the formatList combo box. At that moment, the user has not even had a chance to pick a seat and seat A1 is selected by default. If you set chosenSeat in the play method, it should reflect the seat picked by your user.
I think the new JFrame in the play method - as already mentioned by mKorbel - is not needed, since you can use the application frame (this) as the parent component for the call to the JOptionPane.showMessageDialog method:
private void play() {
// todo: frames is not needed.
//JFrame frames = new JFrame("Sample frame");
//frames.setSize(400, 400);
//frames.setVisible(false);
//frames.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
chosenSeat = formatList.getSelectedItem().toString();
// todo: use the application frame as the parent.
//JOptionPane.showMessageDialog(frames, "You have chosen the seat " + chosenSeat);
JOptionPane.showMessageDialog(this, "You have chosen the seat " + chosenSeat);
}
I have learnt to create a menu with radio buttons using java, but I want to know how to make radio buttons WITHIN radio buttons. The real problem is that I have finally created the radio buttons 'within' a radio button by displaying a new menu with a new group of buttons, but whenever I click on these new radio buttons, nothing happens. It is as if the buttons are not being listened to. Here is my code (example, but still the same idea):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestRadioButtons extends JPanel implements ActionListener
{
private String test = "Test Button 1";
private String random = "RANDOM";
private String test2 = "Button to Click";
private String random2 = "RANDOM MK. 2";
private static boolean menu = false;
public TestRadioButtons()
{
super(new BorderLayout());
//creates first set of radio buttons
JRadioButton testButton = new JRadioButton(test);
testButton.setMnemonic(KeyEvent.VK_T);
testButton.setActionCommand(test);
JRadioButton randomButton = new JRadioButton(random);
randomButton.setMnemonic(KeyEvent.VK_R);
randomButton.setActionCommand(random);
//groups the first set of buttons
ButtonGroup group1 = new ButtonGroup();
group1.add(testButton);
group1.add(randomButton);
//register listener for first radio buttons
testButton.addActionListener(this);
randomButton.addActionListener(this);
//put first radio buttons into a column in a panel
JPanel radioPanel1 = new JPanel(new GridLayout(0, 1));
radioPanel1.add(testButton);
radioPanel1.add(randomButton);
//set first menu border
add(radioPanel1, BorderLayout.LINE_START);
setBorder(BorderFactory.createEmptyBorder(20,20,20,250));
//I also have it so that if the a boolean value equals true, the following menu appears:
if (menu == true)
{
JRadioButton test2Button = new JRadioButton(test2);
test2Button.setMnemonic(KeyEvent.VK_A);
test2Button.setActionCommand(test2);
JRadioButton random2Button = new JRadioButton(random2);
random2Button.setMnemonic(KeyEvent.VK_B);
random2Button.setActionCommand(random2);
ButtonGroup group2 = new ButtonGroup();
group2.add(test2Button);
group2.add(random2Button);
test2Button.addActionListener(this);
random2Button.addActionListener(this);
JPanel radioPanel2 = new JPanel(new GridLayout(0, 1));
radioPanel2.add(test2Button);
radioPanel2.add(random2Button);
add(radioPanel2, BorderLayout.LINE_START);
setBorder(BorderFactory.createEmptyBorder(20,20,20,250));
}
}
public static void menu2()
{
JFrame innerMenu = new JFrame();
innerMenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent innerComponent = new TestRadioButtons();
innerComponent.setOpaque(true);
innerMenu.setContentPane(innerComponent);
innerMenu.pack();
innerMenu.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (test.equals(e.getActionCommand()))
{
menu = true;
menu2();
if (test2.equals(e.getActionCommand()))
{
JOptionPane.showMessageDialog(null, "This is just a TEST!");
}
}
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Radio Button Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent component = new TestRadioButtons();
component.setOpaque(true);
frame.setContentPane(component);
frame.pack();
frame.setVisible(true);
}
public static void main (String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
If anyone is able to help me (as well as fix up my code in the part where I create the new menu), I would be grateful.
Just a } problem
Change your public void actionPerformed(ActionEvent e) like this
public void actionPerformed(ActionEvent e)
{
if (test.equals(e.getActionCommand()))
{
menu = true;
menu2();
}
if (test2.equals(e.getActionCommand()))
{
JOptionPane.showMessageDialog(null, "This is just a TEST!");
}
}
So I have a JPanel with a CardLayout.
this CardLayout, as expected, manages the switching of panels in the frame.
The switching is done by two buttons: "Back" and "Next".
I want to know if there is a way to close the whole application (i.e. call System.exit(0)) when it is on the last card and "Next" is pressed again.
I have looked for a solution everywhere, but I can't find anything.
The problem is: I don't know how to check which is the last one.
Here is the listener excerpt of my code:
public void actionPerformed(ActionEvent arg0) {
CardLayout l = (CardLayout) holder.getLayout();
if(arg0.getSource() == opt[1]){ //opt[1] is the "Next" button
//Insert if statement here to check if
//the CardLayout is on the last card
{
System.exit(0);
} else {
l.next(holder); //holder is the JPanel with the CardLayout
}
}
}
What about dispose() which is inherited from Window? Make sure you set:
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFrame frame = ...
// ...
frame.setVisible(false); // hide the GUI
frame.dispose(); // destroy and release the GUI resources
For example:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class CardLayoutGUI
{
private JFrame frame;
private JButton btnBack;
private JButton btnNext;
private CardLayout cLayout;
private JPanel panUp;
private JPanel panDown;
private static final String[] cards =
{"card1", "card2", "card3", "card4", "card5"};
private int currentCard = 0;
public void init()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
((JPanel)frame.getContentPane()).setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
btnBack = new JButton("Back");
btnNext = new JButton("Next");
btnBack.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
btnNext.setText("Next");
currentCard--;
cLayout.show(panUp, cards[currentCard]);
if(currentCard == 0) btnBack.setVisible(false);
}
});
btnNext.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
btnBack.setVisible(true);
currentCard++;
if(currentCard == cards.length - 1) // last card
{
btnNext.setText("Exit");
cLayout.show(panUp, cards[currentCard]);
}
else if(currentCard >= cards.length)
{
frame.setVisible(false);
frame.dispose();
}
else
{
cLayout.show(panUp, cards[currentCard]);
}
}
});
cLayout = new CardLayout();
panUp = new JPanel(cLayout);
panDown = new JPanel();
frame.add(panUp, BorderLayout.CENTER);
frame.add(panDown, BorderLayout.SOUTH);
panDown.add(btnBack);
panDown.add(btnNext);
for(int i = 0; i < cards.length; i++) createPanels(panUp, cards[i]);
frame.pack();
frame.setLocationRelativeTo(null);
btnBack.setVisible(false);
}
public void showGUI()
{
frame.setVisible(true);
}
private void createPanels(JPanel container, String label)
{
JPanel pan = new JPanel();
pan.add(new JLabel(label));
container.add(pan, label);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
CardLayoutGUI clg = new CardLayoutGUI();
clg.init();
clg.showGUI();
}
});
}
}
I extended CardLayout to add a few features. One of the features is an isNextCardAvailable() method. See Card Layout Focus for all the features.
The issue is determining which card is the last one. You could use a card String array index to manage the current position of the and use the show method to display the next "card". When you exceed the card array index you can then dispose your JFrame.
If you run the System.exit(0), that close all aplication, but if you only close the JFrame you can use JFrameObject.dispose().