I am creating a basic GUI frame. The frame has 10 radio buttons and a Submit button. The user selects one option(JRadioButtons) and clicks on the Submit(JButton) button. On clicking the Submit button, the option selected by the user appears on a different frame.
I want the Submit button to recognize the JRadioButton selected by the user.
I have put my bit of code here for reference.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Frame2 extends JFrame{
private JFrame frame2;
private JLabel label2;
private JButton button2;
private JRadioButton r1;
private JRadioButton r2;
private JRadioButton r3;
private JRadioButton r4;
private JRadioButton r5;
private JRadioButton r6;
private JRadioButton r7;
private JRadioButton r8;
private JRadioButton r9;
private JRadioButton r10;
public ButtonGroup group;
Frame2(){
setLayout(new BorderLayout());
setSize(new Dimension(1304,690));
getContentPane().setBackground(Color.DARK_GRAY);
label2= new JLabel(" Choose a topic: ");
label2.setFont(new Font("Seriff",Font.BOLD, 14));
label2.setForeground(Color.WHITE);
button2=new JButton("Submit");
add(label2, BorderLayout.NORTH);
JPanel centerPanel = new JPanel(new GridLayout(2, 5));
centerPanel.add(r1=new JRadioButton("Introduction"));
centerPanel.add(r2=new JRadioButton("Class and Objects"));
centerPanel.add(r3=new JRadioButton("Object Oriented Programming Concepts"));
centerPanel.add(r4=new JRadioButton("JAVA literals, constants, variables"));
centerPanel.add(r5=new JRadioButton("Loops"));
centerPanel.add(r6=new JRadioButton("Functions/Methods"));
centerPanel.add(r7=new JRadioButton("Strings"));
centerPanel.add(r8=new JRadioButton("Arrays"));
centerPanel.add(r9=new JRadioButton("Time Complexity"));
centerPanel.add(r10=new JRadioButton("Data Structures"));
add(centerPanel, BorderLayout.CENTER);
group= new ButtonGroup();
group.add(r1);
group.add(r2);
group.add(r3);
group.add(r4);
group.add(r5);
group.add(r6);
group.add(r7);
group.add(r8);
group.add(r9);
group.add(r10);
add(button2, BorderLayout.SOUTH);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==button2) {
Layouts l=new Layouts();
l.main(null);
dispose();
}
}
});
}
public static void main(String[] args) {
Frame2 fr2=new Frame2();
}
}`
Thanks in advance.
It's a lot easier if you put the JRadioButtons in an array.
Here are the changes I made to your code to make it easier to modify and understand.
I added a call to the SwingUtilities invokeLater method to ensure the creation and execution of the Swing components happens on the Event Dispatch Thread.
I created the individual JPanels in methods. By separating the JPanel code, I could more easily focus on one part of the GUI at a time.
The methods to construct a JFrame must be called in the proper order. You have to create all the Swing components before you make the JFrame visible.
Here's one way to connect a JButton with a group of JRadioButtons.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class RadioButtonTest {
private JButton button2;
private JRadioButton[] rb;
private ButtonGroup group;
public RadioButtonTest() {
JFrame frame = new JFrame("Java Tutorials");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.DARK_GRAY);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
JLabel label2 = new JLabel(" Choose a topic: ");
label2.setFont(new Font("Seriff", Font.BOLD, 14));
label2.setForeground(Color.WHITE);
panel.add(label2, BorderLayout.NORTH);
panel.add(createButtonPanel(), BorderLayout.CENTER);
button2 = new JButton("Submit");
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button2) {
for (int i = 0; i < rb.length; i++) {
if (rb[i].isSelected()) {
String text = rb[i].getText();
System.out.println(text);
// Do your second JFrame
}
}
}
}
});
panel.add(button2, BorderLayout.SOUTH);
return panel;
}
private JPanel createButtonPanel() {
JPanel centerPanel = new JPanel(new GridLayout(0, 2));
String[] titles = { "Introduction", "Class and Objects",
"Object Oriented Programming Concepts",
"JAVA literals, constants, variables", "Loops",
"Functions/Methods", "Strings", "Arrays",
"Time Complexity", "Data Structures" };
rb = new JRadioButton[titles.length];
group = new ButtonGroup();
for (int i = 0; i < titles.length; i++) {
rb[i] = new JRadioButton(titles[i]);
group.add(rb[i]);
centerPanel.add(rb[i]);
}
return centerPanel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RadioButtonTest();
}
});
}
}
Related
I have to get a String input in one JFrame and display in another.
My second task is to flash the given string in a larger font in the second frame, at an interval of 1sec.
How to proceed?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Input{
String hinput;
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private void prepareGUI(){
mainFrame = new JFrame("STRING");
mainFrame.setSize(500,100);
headerLabel = new JLabel("", JLabel.CENTER);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.setVisible(true);
}
private void showTextField(){
JLabel stringlabel= new JLabel("String ", JLabel.RIGHT);
final JTextField userText = new JTextField(20);
JButton submitButton = new JButton("Submit");
submitButton.addActionListener(new mylistener());
submitButton.setActionCommand("open");
controlPanel.add(stringlabel);
controlPanel.add(userText);
controlPanel.add(submitButton);
mainFrame.setVisible(true);
}
private class mylistener implements ActionListener{
public void actionPerformed(ActionEvent e){
String cmd = e.getActionCommand();
if(cmd.equals("open")){
mainFrame.dispose();
NewJFrame nj= new NewJFrame(hinput);
}
}
}
public static void main(String args[]){
Input Inp = new Input();
Inp.prepareGUI();
Inp.showTextField();
}
}
class NewJFrame{
JFrame mainFrame;
String text;
JLabel l1;
JTextField tb1;
public NewJFrame(String t){
text=t;
mainFrame=new JFrame("STRING");
mainFrame.setSize(800,800);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l1=new JLabel("Entered string");
tb1.setText(text);
mainFrame.add(l1);
mainFrame.add(tb1);
mainFrame.setVisible(true);
}
}
I am getting traceback after i click 'submit' button.
Please point out the errors.
You can get rid of the error by instatiating tb1 in your NewJFrame class like so:
class NewJFrame{
JFrame mainFrame;
String text;
JLabel l1;
JTextField tb1;
public NewJFrame(String t){
text=t;
mainFrame=new JFrame("STRING");
mainFrame.setSize(800,800);
// *** must init tb1!!! ***///
JTextField tb1 = new JTextField();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l1=new JLabel("Entered string");
tb1.setText(text);
mainFrame.add(l1);
mainFrame.add(tb1);
mainFrame.setVisible(true);
}
}
As for getting text typed in one JFrame to open in another, I have a slightly modified solution. Maybe have text entered in a JTextField on one JPanel display in another JPanel. To do that, you could use the following code:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.FlowLayout;
public class SimpleGUI extends JFrame {
private final JPanel firstPanel;
private final JPanel secondPanel;
private final JButton submitButton;
private final JTextField textField;
private final JLabel secondPanelLabel;
public SimpleGUI() {
// sets the title of the JFrame
super("SimpleGUI");
setLayout(new FlowLayout());
// inits both JPanels
firstPanel = new JPanel();
secondPanel = new JPanel();
// inits empty second JLabel and adds to the secondPanel
secondPanelLabel = new JLabel();
secondPanel.add(secondPanelLabel);
// makes the secondPanel invisible for the time being
secondPanel.setVisible(false);
// inits the submit button
submitButton = new JButton("Submit");
// event-handler for submit button, will set the text in the
// secondPanelLabel to the text in the JTextField the user types
// into. It then makes the firstPanel (with the text field and button),
// invisible, and then makes the second panel visible.
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
secondPanelLabel.setText(textField.getText());
firstPanel.setVisible(false);
secondPanel.setVisible(true);
}
});
// inits the textField
textField = new JTextField(10);
// adds the button and the text field to the firstPanel
firstPanel.add(submitButton);
firstPanel.add(textField);
// adds both panels to this JFrame
this.add(firstPanel);
this.add(secondPanel);
}
}
And here is a class with a main method that constructs the SimpleGUI so you can test it out for yourself:
import javax.swing.JFrame;
public class SimpleGUITest {
public static void main(String[] args) {
SimpleGUI frame = new SimpleGUI();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
I am having trouble finding a way to invoke an action listener that returns the value of the button clicked in the text area at the bottom.
I made the buttons using a for loop and did not expressly give the buttons a name so I do not know how to reference them when trying to incorporate an ActionListener.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class buttoner implements ActionListener {
//JFrame
JFrame frame = new JFrame("Button Game");
//Make JPanels
JPanel panelLabel = new JPanel();
JPanel buttonGrid = new JPanel(new GridLayout(0,10));
JPanel bottomPanel = new JPanel();
//JLabel
private JLabel label1 = new JLabel("The Button Game");
public buttoner() {
//set layout
frame.setLayout(new BorderLayout());
frame.add(panelLabel, BorderLayout.NORTH);
frame.add(buttonGrid, BorderLayout.CENTER);
frame.add(bottomPanel, BorderLayout.SOUTH);
//Set stuff
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,700);
frame.setVisible(true);
//Change label color
label1.setForeground(Color.RED);
//add Label
panelLabel.add(label1);
//add Buttons
for (int i = 1; i <= 60; i++) {
String val = Integer.toString(i);
buttonGrid.add(new JButton(val));
}
//Add JText Area to bottom JPanel
String num = "value";
JTextArea jta = new JTextArea(num, 1, 1);
bottomPanel.add(jta);
frame.pack();
}
public static void main(String args[]){
buttoner gui = new buttoner();
}
public void actionPerformed(ActionEvent a) {
}
}
I created an action listener to put the value in the text area at the bottom of the GUI.
I fixed a few problems with your code.
In the main method, I called the SwingUtilities invokeLater method to put the Swing GUI on the Event Dispatch thread (EDT). Swing components must be created and updated on the EDT.
The name of a Java class must start with a capital letter.
It's safer to put your Swing components on a JPanel, rather than add them directly to a JFrame.
I separated the code that creates the JFrame from the code that creates the JPanels. It should be easier for any reader of your code, including yourself, to understand what's going on.
In the createMainPanel method, I grouped the code so that everything having to do with the buttonGrid JPanel, to take one instance, is in one place in the code.
I added the action listener to the code that creates the buttonGrid JPanel.
I wrote action listener code that updates the JTextArea with the left clicked button label.
Here's the corrected code.
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class Buttoner implements ActionListener {
// JFrame
private JFrame frame = new JFrame("Button Game");
// Make JPanels
private JPanel panelLabel = new JPanel();
private JPanel buttonGrid = new JPanel(new GridLayout(0, 10));
private JPanel bottomPanel = new JPanel();
// JLabel
private JLabel label1 = new JLabel("The Button Game");
private JTextArea jta;
public Buttoner() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
// Change label color
label1.setForeground(Color.RED);
// add Label
panelLabel.add(label1);
panel.add(panelLabel, BorderLayout.NORTH);
// add Buttons
for (int i = 1; i <= 60; i++) {
String val = Integer.toString(i);
JButton button = new JButton(val);
button.addActionListener(this);
buttonGrid.add(button);
}
panel.add(buttonGrid, BorderLayout.CENTER);
// Add JText Area to bottom JPanel
String num = "value";
jta = new JTextArea(num, 1, 1);
jta.setEditable(false);
bottomPanel.add(jta);
panel.add(bottomPanel, BorderLayout.SOUTH);
return panel;
}
public static void main(String args[]) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new Buttoner();
}
};
SwingUtilities.invokeLater(runnable);
}
public void actionPerformed(ActionEvent a) {
JButton button = (JButton) a.getSource();
jta.setText(button.getText());
}
}
Try creating an array of buttons and add the newly created button to the array. See comments.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class buttoner implements ActionListener {
//JFrame
JFrame frame = new JFrame("Button Game");
//Make JPanels
JPanel panelLabel = new JPanel();
JPanel buttonGrid = new JPanel(new GridLayout(0,10));
JPanel bottomPanel = new JPanel();
//JLabel
private JLabel label1 = new JLabel("The Button Game");
private JButton buttons[] = new JButton[60]; //create an array of button for future reference
public buttoner() {
//set layout
frame.setLayout(new BorderLayout());
frame.add(panelLabel, BorderLayout.NORTH);
frame.add(buttonGrid, BorderLayout.CENTER);
frame.add(bottomPanel, BorderLayout.SOUTH);
//Set stuff
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,700);
frame.setVisible(true);
//Change label color
label1.setForeground(Color.RED);
//add Label
panelLabel.add(label1);
//add Buttons
for (int i = 1; i <= 60; i++) {
String val = Integer.toString(i);
JButton btn = new JButton(val);
btn.addActionListener(this); //add an actionListener right away
buttons[i] = btn; //add the button in the array for future reference
buttonGrid.add(btn);
}
//Add JText Area to bottom JPanel
String num = "value";
JTextArea jta = new JTextArea(num, 1, 1);
bottomPanel.add(jta);
frame.pack();
}
public static void main(String args[]){
buttoner gui = new buttoner();
}
public void actionPerformed(ActionEvent a) {
}
}
I'm having trouble with this JApplet. At the moment I have a CardLayout JPanel which contains two BorderLayout JPanels. Whenever I run it, the components added to each 'card' (a JButton to go back to the other JPanel) don't display unless I use setVisible(true) for each LayoutManager. Furthermore, none of my ActionListeners work. I'm assuming because they only use show() and there's something else I have to do that's alluding me.
Must I use setVisible(true)? It seems from other questions that there's a way of doing this without that. Here's the code I'm having trouble with:
/*
*Java Version: 1.8.0_25
*Author: Peadar Ó Duinnín
*Student Number: R00095488
*/
package As1;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AUIJApplet extends JApplet implements ActionListener {
private final int WIDTH = 600;
private final int HEIGHT = 400;
private int highScore;
private int currentScore;
JPanel panelCont = new JPanel();
JPanel startPanel = new JPanel();
JPanel gamePanel = new JPanel();
JButton newGameButton = new JButton("New Game");
JButton endGameButton = new JButton("End Game");
JLabel highScoreLabel;
JLabel currentScoreLabel;
CardLayout cl = new CardLayout();
BorderLayout bl = new BorderLayout();
public AUIJApplet() {
highScore = 0;
}
#Override
public void init() {
setSize(WIDTH, HEIGHT);
panelCont.setLayout(cl);
startPanel.setLayout(bl);
gamePanel.setLayout(bl);
startPanel.add(newGameButton, BorderLayout.SOUTH);
gamePanel.add(endGameButton, BorderLayout.SOUTH);
startPanel.setBackground(Color.BLUE);
gamePanel.setBackground(Color.GREEN);
panelCont.add(startPanel, "Start Applet Screen");
panelCont.add(gamePanel, "New Game Screen");
newGameButton.addActionListener((e) -> {
newGame();
});
endGameButton.addActionListener((e) -> {
quitGame();
});
cl.show(panelCont, "Start Applet Screen");
this.add(panelCont);
}
public void newGame() {
cl.show(panelCont, "New Game Screen");
showScores(gamePanel);
}
public void quitGame() {
cl.show(panelCont, "Start Applet Screen");
if (currentScore > highScore) {
highScore = currentScore;
}
currentScore = 0;
}
public void showScores(JPanel currentPanel) {
currentPanel.add(new JLabel("High Score:") , BorderLayout.EAST);
currentPanel.add(highScoreLabel, BorderLayout.EAST);
currentPanel.add(new JLabel("Current Score:"), BorderLayout.EAST);
currentPanel.add(currentScoreLabel, BorderLayout.EAST);
}
#Override
public void actionPerformed(ActionEvent ae) {
}
}
I have made the a little similar code to perform same operation it works for me try to write the code from scratch. Here is my code.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.JApplet;
import javax.swing.*;
public class Example extends JApplet {
JPanel panel1,panel2,mainPanel;
JButton start,stop;
CardLayout cl = new CardLayout();
#Override
public void init() {
panel1 = new JPanel();
panel1.setBackground(Color.red);
panel1.setLayout(new BorderLayout());
panel2 = new JPanel();
panel2.setBackground(Color.blue);
panel2.setLayout(new BorderLayout());
start = new JButton("Start");
stop = new JButton("stop");
panel1.add(start,BorderLayout.SOUTH);
panel2.add(stop,BorderLayout.SOUTH);
mainPanel = new JPanel();
mainPanel.setLayout(cl);
mainPanel.add(panel1,"First Panel");
mainPanel.add(panel2, "Second Panel");
start.addActionListener((ActionEvent e) -> {
newGame();
});
stop.addActionListener((ActionEvent e) ->{
endGame();
});
this.add(mainPanel);
}
public void newGame()
{
cl.show(mainPanel, "Second Panel");
}
public void endGame()
{
cl.show(mainPanel,"First Panel");
}
}
I am working on my HOMEWORK (please don't do my work for me). I have 95% of it completed already. I am having trouble with this last bit though. I need to display the selected gender in the JTextArea. I must use the JRadioButton for gender selection.
I understand that JRadioButtons work different. I set up the action listener and the Mnemonic. I think I am messing up here. It would seem that I might need to use the entire group to set and action lister maybe.
Any help is greatly appreciated.
Here is what I have for my code (minus parts that I don't think are needed so others can't copy paste schoolwork):
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.TitledBorder;
public class LuisRamosHW3 extends JFrame {
private JLabel WelcomeMessage;
private JRadioButton jrbMale = new JRadioButton("Male");
private JRadioButton jrbFemale = new JRadioButton("Female");
public LuisRamosHW3(){
setLayout(new FlowLayout(FlowLayout.LEFT, 20, 30));
JPanel jpRadioButtons = new JPanel();
jpRadioButtons.setLayout(new GridLayout(2,1));
jpRadioButtons.add(jrbMale);
jpRadioButtons.add(jrbFemale);
add(jpRadioButtons, BorderLayout.AFTER_LAST_LINE);
ButtonGroup gender = new ButtonGroup();
gender.add(jrbMale);
jrbMale.setMnemonic(KeyEvent.VK_B);
jrbMale.setActionCommand("Male");
gender.add(jrbFemale);
jrbFemale.setMnemonic(KeyEvent.VK_B);
jrbFemale.setActionCommand("Female");
//Set defaulted selection to "male"
jrbMale.setSelected(true);
//Create Welcome button
JButton Welcome = new JButton("Submit");
add(Welcome);
Welcome.addActionListener(new SubmitListener());
WelcomeMessage = (new JLabel(" "));
add(WelcomeMessage);
}
class SubmitListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e){
String FirstName = jtfFirstName.getText();
String FamName = jtfLastName.getText();
Object StateBirth = jcbStates.getSelectedItem();
String Gender = gender.getActionCommand(); /*I have tried different
variations the best I do is get one selection to print to the text area*/
WelcomeMessage.setText("Welcome, " + FirstName + " " + FamName + " a "
+ gender.getActionCommmand + " born in " + StateBirth);
}
}
} /*Same thing with the printing, I have tried different combinations and just can't seem to figure it out*/
I have done a similar kind of a problem on JTable where we get the selection from the radio group and then act accordingly. Thought of sharing the solution.
Here, I have grouped the radio buttons using the action listener and each radio button will have an action command associated with it. When the user clicks on a radio button then an action will be fired subsequently an event is generated where we deselect other radio button selection and refresh the text area with the new selection.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
public class RadioBtnToTextArea {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new RadioBtnToTextArea().createUI();
}
};
EventQueue.invokeLater(r);
}
private void createUI() {
JFrame frame = new JFrame();
JPanel panel = new JPanel(new BorderLayout());
JPanel radioPnl = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel textPnl = new JPanel();
JRadioButton radioMale = new JRadioButton();
JRadioButton radioFemale = new JRadioButton();
JTextArea textArea = new JTextArea(10, 30);
ActionListener listener = new RadioBtnAction(radioMale, radioFemale, textArea);
radioPnl.add(new JLabel("Male"));
radioPnl.add(radioMale);
radioMale.addActionListener(listener);
radioMale.setActionCommand("1");
radioPnl.add(new JLabel("Female"));
radioPnl.add(radioFemale);
radioFemale.addActionListener(listener);
radioFemale.setActionCommand("2");
textPnl.add(textArea);
panel.add(radioPnl, BorderLayout.NORTH);
panel.add(textPnl, BorderLayout.CENTER);
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class RadioBtnAction implements ActionListener {
JRadioButton maleBtn;
JRadioButton femaleBtn;
JTextArea textArea;
public RadioBtnAction(JRadioButton maleBtn,
JRadioButton femaleBtn,
JTextArea textArea) {
this.maleBtn = maleBtn;
this.femaleBtn = femaleBtn;
this.textArea = textArea;
}
#Override
public void actionPerformed(ActionEvent e) {
int actionCode = Integer.parseInt(e.getActionCommand());
switch (actionCode) {
case 1:
maleBtn.setSelected(true);
femaleBtn.setSelected(false);
textArea.setText("Male");
break;
case 2:
maleBtn.setSelected(false);
femaleBtn.setSelected(true);
textArea.setText("Female");
break;
default:
break;
}
}
}
Suggestions:
Make your ButtonGroup variable, gender, a field (declared in the class) and don't declare it in the constructor which will limit its scope to the constructor only. It must be visible throughout the class.
Make sure that you give your JRadioButton's actionCommands. JRadioButtons are not like JButtons in that if you pass a String into their constructor, this does not automatically set the JRadioButton's text, so you will have to do this yourself in your code.
You must first get the selected ButtonModel from the ButtonGroup object via getSelection()
Then check that the selected model is not null before getting its actionCommand text.
For example
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class RadioButtonEg extends JPanel {
public static final String[] RADIO_TEXTS = {"Mon", "Tues", "Wed", "Thurs", "Fri"};
// *** again declare this in the class.
private ButtonGroup buttonGroup = new ButtonGroup();
private JTextField textfield = new JTextField(20);
public RadioButtonEg() {
textfield.setFocusable(false);
JPanel radioButtonPanel = new JPanel(new GridLayout(0, 1));
for (String radioText : RADIO_TEXTS) {
JRadioButton radioButton = new JRadioButton(radioText);
radioButton.setActionCommand(radioText); // **** don't forget this
buttonGroup.add(radioButton);
radioButtonPanel.add(radioButton);
}
JPanel bottomPanel = new JPanel();
bottomPanel.add(new JButton(new ButtonAction("Press Me", KeyEvent.VK_P)));
setLayout(new BorderLayout());
add(radioButtonPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
add(textfield, BorderLayout.PAGE_START);
}
private class ButtonAction extends AbstractAction {
public ButtonAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
ButtonModel model = buttonGroup.getSelection();
if (model == null) {
textfield.setText("No radio button has been selected");
} else {
textfield.setText("Selection: " + model.getActionCommand());
}
}
}
private static void createAndShowGui() {
RadioButtonEg mainPanel = new RadioButtonEg();
JFrame frame = new JFrame("RadioButtonEg");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I'm writing a simple program using CardLayout. The main screen should display a button which when pressed would go to the next screen which contains another button for another screen. My problem is that when I run my program the screen is black. I tried following tutorials online to write my own program but I don't seem to find the problem with my code. I don't get any errors when run. Here is my code
//using CardLayout to change screen when action is performed
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.Popup;
import javax.swing.JOptionPane;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.FlowLayout;
public class CL extends JFrame {
JPanel cardPanel;
JPanel cardPanelA;
JPanel cardPanelB;//to set different screens
CardLayout cl;
private JButton button1;
private JButton button2;
private JButton change;
private JLabel label;
private JTextField textField1;
private JTextField textField2;
JButton button;
public CL() {
super("This is a sample");
cardPanel = new JPanel();
cardPanelA = new JPanel();
cardPanelB = new JPanel();
cl = new CardLayout();
cardPanel.setLayout(cl);
button1 = new JButton("button1");
button2 = new JButton("button2");
change = new JButton("change screen");
label = new JLabel("this is a label");
textField1 = new JTextField(10);
textField2 = new JTextField("enter text", 6);
cardPanelA.add(change);
cardPanelA.add(label);
cardPanelA.add(textField1);
cardPanelA.add(textField2);
cardPanelB.add(button1);
cardPanelB.add(button2);
cardPanel.add(cardPanelA);
cardPanel.add(cardPanelB);
JPanel panel1 = new JPanel();
button = new JButton("initial button");
panel1.add(button);
theHandler handler = new theHandler();//make action listener
change.addActionListener(handler);
button1.addActionListener(handler);
button2.addActionListener(handler);
button.addActionListener(handler);
/*
getContentPane().add(panel1, BorderLayout.NORTH);
getContentPane().add(cardPanelA, BorderLayout.NORTH);
getContentPane().add(cardPanelB, BorderLayout.NORTH);
*/
}
private class theHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == button) {
cl.show(cardPanel, "Panel A");
}
if (event.getSource() == change) {
cl.show(cardPanelB, "panelB");
}
if (event.getSource() == button2) {
cl.show(cardPanel, "PanelA");
}
if (event.getSource() == button1) {
JOptionPane.showMessageDialog(null, "this is the second screen");
}
}
}
}
/*way to use CardLayout: create a CardLayout manager and create a bunch of different JPanels which
* would each be a different screen. Make a panel that stores the CardLayout as the layout.
* Add the different elements to each Panel(buttons, textfields) and then add the panels to the JPanel that stores
* the CardLayout
*/
import javax.swing.JFrame;
public class CardTest {
public static void main(String[] args) {
CL object = new CL();
object.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
object.setSize(400, 400);
object.setVisible(true);
}
}
It might be something simple but I'm not sure of what it is. Some advice would be appreciated.
Make sure you add your panels to the frame
add(cardPanel);
Without that no components will be shown