When displaying a group of JRadioButtons, initially none of them is selected (unless you programmatically enforce that). I would like to be able to put buttons back into that state even after the user already selected one, i.e., none of the buttons should be selected.
However, using the usual suspects doesn't deliver the required effect: calling 'setSelected(false)' on each button doesn't work. Interestingly, it does work when the buttons are not put into a ButtonGroup - unfortunately, the latter is required for JRadioButtons to be mutually exclusive.
Also, using the setSelected(ButtonModel, boolean) - method of javax.swing.ButtonGroup doesn't do what I want.
I've put together a small program to demonstrate the effect: two radio buttons and a JButton. Clicking the JButton should unselect the radio buttons so that the window looks exactly as it does when it first pops up.
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
/**
* This class creates two radio buttons and a JButton. Initially, none
* of the radio buttons is selected. Clicking on the JButton should
* always return the radio buttons into that initial state, i.e.,
* should disable both radio buttons.
*/
public class RadioTest implements ActionListener {
/* create two radio buttons and a group */
private JRadioButton button1 = new JRadioButton("button1");
private JRadioButton button2 = new JRadioButton("button2");
private ButtonGroup group = new ButtonGroup();
/* clicking this button should unselect both button1 and button2 */
private JButton unselectRadio = new JButton("Unselect radio buttons.");
/* In the constructor, set up the group and event listening */
public RadioTest() {
/* put the radio buttons in a group so they become mutually
* exclusive -- without this, unselecting actually works! */
group.add(button1);
group.add(button2);
/* listen to clicks on 'unselectRadio' button */
unselectRadio.addActionListener(this);
}
/* called when 'unselectRadio' is clicked */
public void actionPerformed(ActionEvent e) {
/* variant1: disable both buttons directly.
* ...doesn't work */
button1.setSelected(false);
button2.setSelected(false);
/* variant2: disable the selection via the button group.
* ...doesn't work either */
group.setSelected(group.getSelection(), false);
}
/* Test: create a JFrame which displays the two radio buttons and
* the unselect-button */
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RadioTest test = new RadioTest();
Container contentPane = frame.getContentPane();
contentPane.setLayout(new GridLayout(3,1));
contentPane.add(test.button1);
contentPane.add(test.button2);
contentPane.add(test.unselectRadio);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
Any ideas anyone? Thanks!
You can do buttonGroup.clearSelection().
But this method is available only since Java 6.
The Javadoc of the class ButtonGroup itself gives some hint about how this can be achieved:
From the API doc of class ButtonGroup:
Initially, all buttons in the group are unselected. Once any button is selected, one button is always selected in the group.There is no way to turn a button programmatically to "off", in order to clear the button group. To give the appearance of "none selected", add an invisible radio button to the group and then programmatically select that button to turn off all the displayed radio buttons.
Try adding a third invisible button to the button group. When you want to "deselect", select the invisible one.
Or you can use Darryl's Select Button Group which doesn't require you to use an "invisible button".
You can use a click counter:
private ButtonGroup radioGroup = new javax.swing.ButtonGroup();
private JRadioButton jRadioBtn1 = new javax.swing.JRadioButton();
private int clickCount = 0;
private void jRadioBtn1Clicked(java.awt.event.MouseEvent evt) {
// Remove selection on a second click
if (jRadioBtn1.isSelected()) {
if (++clickCount % 2 == 0) {
radioGroup.clearSelection();
}
}
}
You can use setselected(false) method to unselect the previous selected button.
I don't know if this will help but have you tried to use doClick() method?
jRadioButtonYourObject.doClick();
Input - NONE
Return- void
I had a similar problem and tried everything in this thread to no avail. So I took a look at all the methods of JRadioButton and found that method from JRadioButton's parent class.
In my program, I had two radio button independent of each other and it was programed so that only one was selected.
After the user enters data and hits a button the program clears all text fields and areas and deselects the radio button. The doClick() did the job of deselecting the radio button for me; the method "performs a "click"."
I know yours is different and you probably would have to program the doClick() method for every radio button that is selected.
http://docs.oracle.com/javase/7/docs/api/javax/swing/AbstractButton.html
search for doClick()
When you want to deselect, select invisible. For that you add a third invisible button to the button group.
In my case I use Jgoodies project to bind GUI components to Java model.
The RadioButton component is bound to a field
class Model {
private SomeJavaEnum field; // + getter, setter
}
In such case ButtonGroup.clearSelection doesn't work since the old value still retains in the model. Straightforward solution was to simply setField(null).
Use this helper class SelectButtonGroup.java
direct link to the class source
import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SelectUnselected extends JPanel {
private static String birdString = "Bird";
private static String catString = "Cat";
private static Integer selectedIndex = -1;
private static AbstractButton hiddenButton = new JRadioButton(catString);
private final static AbstractButton birdButton = new JRadioButton(birdString);
private final static AbstractButton catButton = new JRadioButton(catString);
//Group the radio buttons.
private SelectButtonGroup group = new SelectButtonGroup();
public SelectUnselected() {
super(new BorderLayout());
//Create the radio buttons.
hiddenButton.setVisible(false);
hiddenButton.setSelected(true);
group.add(birdButton);
group.add(catButton);
group.add(hiddenButton);
ActionListener sendListener = e -> {
checkSelectedRadioButten();
};
birdButton.addActionListener(sendListener);
catButton.addActionListener(sendListener);
hiddenButton.addActionListener(sendListener);
//Put the radio buttons in a column in a panel.
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
radioPanel.add(birdButton);
radioPanel.add(catButton);
add(radioPanel, BorderLayout.LINE_START);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
public void checkSelectedRadioButten(){
System.out.println("selectedIndex = " + selectedIndex + "\ngroup.getSelectedButton() = " + group.getSelectedIndex());
if(group.getSelectedIndex() == selectedIndex){
hiddenButton.setSelected(true);
selectedIndex = -1;
System.out.println("getText = " + group.getSelectedButton().getText());
}else{
selectedIndex = group.getSelectedIndex();
System.out.println("getText = " + group.getSelectedButton().getText());
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("RadioButtonDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new SelectUnselected();
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
}
You can use your own ButtonGroup (1), or use modified instance (2), like this:
ONLY SINCE JAVA 6:
(1) public class NoneSelectedButtonGroup extends ButtonGroup {
#Override
public void setSelected(ButtonModel model, boolean selected) {
if (selected) {
super.setSelected(model, selected);
} else {
clearSelection();
}
}
}
(2) ButtonGroup chGroup = new ButtonGroup() {
#Override
public void setSelected(ButtonModel m, boolean b) {
if (!b) clearSelection();
else
super.setSelected(m, b);
}
};
take from https://blog.frankel.ch/unselect-all-toggle-buttons-of-a-group/
Related
Alright, so I have a dilemma. I was wondering if there is a way for me to do the following with two text areas:
I. Print the first text area, and only the first text area.
II. Upon closing the first text area, have it so the second text area appears.
III. Do this so that both text areas do not appear at the same time.
Here is my code, sorry for all the comments, I have to teach this to fellow classmates for a project:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*; //Used for events and the Action Listener
public class ActionProgram extends JFrame /*"extends JFrame" will extend the frame into the variable used to call the class*/
{
//Declare fields (Do not require public/private identification)
JTextArea area;
JLabel instructions;
JLabel question;
JLabel ask;
JButton submitt;
JScrollPane sp;
//Create a constructor to start applying these variables in the creation of the Text Area
public ActionProgram()
{
//Create the flow layout
setLayout(new FlowLayout());
//Create the text area and set how long and wide it should be. Add it to the frame
area = new JTextArea(10,30);
add(area);
//Create scroll pane and add it to the frame
sp = new JScrollPane(area);
add(sp);
//Set the line wrap and word wrap to true for the frame
area.setLineWrap(true);
area.setWrapStyleWord(true);
//Create submitt button, and add it to the frame
submitt = new JButton ("Submitt");
add(submitt);
//Create label asking user to answer the question and add it to the frame
instructions = new JLabel("Please Answer the Following Question:");
add(instructions);
//Create label for the question and add it to the frame
question = new JLabel("-----Briefly Describe how to print something in java-----");
add(question);
//Create label telling user what to do when finished, and add it to the frame
ask = new JLabel("Please enter Submitt when you have finished");
add(ask);
//As you can tell, we do not need to put all these parts into the frame, for the class puts it all into the variable calling it
/*In order for the program to take what the user has writen into text area and make it an input, we have to create an
Action Listener. An Action Listener is a piece of code that will do a specific event when an action is done. In this case
we need the action listener to respond when the user presses "Submitt". To do this, we need to create an event class*/
//This will call the action listener class
event action = new event();
//This will add the action listener to the submitt button
submitt.addActionListener(action);
}
/*The class called event will create the aciton listener. There are two different methods for the action event, the action listener
and the action performer. The action performer is the method used to create code when the action listener is activated. The listener
waits for the submitt button to be pressed, and the performer does user-inputed code when the button is pressed*/
public class event implements ActionListener
{
public void actionPerformed(ActionEvent e) //We use a nested method to create the action performer
{
/*The following code is what the performer will do when the listner is activated. It will get the text typed in the
text area when the user hits the submitt button. The performer will then print the text obtained and close the text area*/
String text = area.getText();
System.out.println(text);
//Use System.exit(0) to close the text area
System.exit(0);
}
}
public static void main(String[] args)
{
//Call the class like you usually do, and set a variable to it
ActionProgram display = new ActionProgram();
//display also acts as the frame of the text area since the class set it equal to the JFrame
display.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set the length and width of the text area in pixels
display.setSize(500,300);
//Set it so the text area can be seen
display.setVisible(true);
}
}
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; //Used for events and the Action Listener
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ActionProgram extends JFrame /*
* "extends JFrame" will extend the
* frame into the variable used to call
* the class
*/
{
// Declare fields (Do not require public/private identification)
JTextArea area;
JLabel instructions;
JLabel question;
JLabel ask;
JButton submitt;
JScrollPane sp;
final int TOTAL_QUESTIONS = 5; // assuming you have 5 questions
int quizCounter = 0;
String[] quizQuestions;
// Create a constructor to start applying these variables in the creation of
// the Text Area
public ActionProgram() {
// Create the flow layout
setLayout(new FlowLayout());
// display also acts as the frame of the text area since the class set
// it equal to the JFrame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set the length and width of the text area in pixels
setSize(500, 300);
// Create the text area and set how long and wide it should be. Add it
// to the frame
area = new JTextArea(10, 30);
add(area);
// Create scroll pane and add it to the frame
sp = new JScrollPane(area);
add(sp);
// Set the line wrap and word wrap to true for the frame
area.setLineWrap(true);
area.setWrapStyleWord(true);
// Create submitt button, and add it to the frame
submitt = new JButton("Submit");
add(submitt);
// Create label asking user to answer the question and add it to the
// frame
instructions = new JLabel("Please Answer the Following Question:");
add(instructions);
// Create label for the question and add it to the frame
quizQuestions = questions();
question = new JLabel(quizQuestions[quizCounter]);
add(question);
// Create label telling user what to do when finished, and add it to the
// frame
ask = new JLabel("Please enter Submit when you have finished");
add(ask);
// As you can tell, we do not need to put all these parts into the
// frame, for the class puts it all into the variable calling it
/*
* In order for the program to take what the user has writen into text
* area and make it an input, we have to create an Action Listener. An
* Action Listener is a piece of code that will do a specific event when
* an action is done. In this case we need the action listener to
* respond when the user presses "Submitt". To do this, we need to
* create an event class
*/
// This will call the action listener class
event action = new event();
// This will add the action listener to the submitt button
submitt.addActionListener(action);
}
/*
* The class called event will create the aciton listener. There are two
* different methods for the action event, the action listener and the
* action performer. The action performer is the method used to create code
* when the action listener is activated. The listener waits for the submitt
* button to be pressed, and the performer does user-inputed code when the
* button is pressed
*/
public class event implements ActionListener {
public void actionPerformed(ActionEvent e) // We use a nested method to
// create the action
// performer
{
/*
* The following code is what the performer will do when the listner
* is activated. It will get the text typed in the text area when
* the user hits the submitt button. The performer will then print
* the text obtained and close the text area
*/
if (e.getSource() == submitt) {
String text = area.getText();
System.out.println(text);
dispose();
// increment the amount of times questions were asked - i.e. the frame opened
quizCounter++;
if (quizCounter < TOTAL_QUESTIONS ) {
quizQuestions = questions();
area.setText("");
question.setText(quizQuestions[quizCounter]);
setVisible(true);
} else {
System.exit(0);
}
}
}
}
public String[] questions() {
String[] newQuestion = new String[TOTAL_QUESTIONS];
switch(quizCounter) {
case 0:
newQuestion[0] = "-----Briefly Describe how to print something in java-----";
break;
case 1:
newQuestion[1] = "----- Question 2 -------";
break;
case 2:
newQuestion[2] = "Question 3";
break;
case 3:
newQuestion[3] = "Question 4";
break;
case 4:
newQuestion[4] = "Question 5";
break;
}
return newQuestion;
}
public static void main(String[] args) {
// Call the class like you usually do, and set a variable to it
ActionProgram display = new ActionProgram();
// Set it so the text area can be seen
display.setVisible(true);
}
}
The answer is laid out on the assumption that you are going to ask 5 questions. Please change the quantity for the TOTAL_QUESTIONS variable to fit with your criteria. Also, don't forget to modify the questions() method body.
It is a good practice to set up all your actions for the JFrame in the construction, rather than in the main. I have amended the code accordingly. Also, it is a good habit to use SwingUtilities to run swing applications.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ActionProgram().setVisible(true);
}
});
If you have any queries, feel free to comment.
You can not close a JTextArea, until unless you are wrapping the JTextArea in a JScrollPane and then adding the JScrollPan to JPanel.
If you are able to perform all these steps then you can use FocusListener
which is used to shift the focus from one component to another.
You can read more about them here.
I want to disable certain swing components based on a button group of radio buttons. One of the radio buttons is selected initially, but it doesn't disable the components until one of the buttons is clicked. How can i make it so that a text field is off by default?
I have this of it helps.
private void cCipherActionPerformed(java.awt.event.ActionEvent evt) {
if (cCipher.isSelected()) {
cipherText.setEnabled(false);
cipherLetterSelect.setEnabled(true);
}
}
private void vCipherActionPerformed(java.awt.event.ActionEvent evt) {
if (vCipher.isSelected()) {
cipherLetterSelect.setEnabled(false);
cipherText.setEnabled(true);
}
}
Based on what I understood, it's quite simple: consider cipherText for example, you can create at the start of the class the JTextField instance:
JTextField cipherText = new JTextField();
and then in the constructor of the specific class you set it to disabled
public MyClass(){
cipherText.setEnabled(false);
}
help,
my questions are:
why isn't itemStateChanges triggered, I tried to put it in the inner class ButtonHandler and also in RadioButtonHandler Im having trouble with it, what is the right way to do it?
I want to trigger and check the marked JRadioButtons after the user click the "check" button.
What is the right way to check which button was clicked, I feel like comparing the strings is bad programming practise. Maybe using an ID ?
How should I make a "reset" button(start over), I want to uncheck all radio buttons and run the constructor once again.
Thank you for your help !
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class ExamFrame extends JFrame {
static ArrayList<Question> qArrList;
JRadioButton a1,a2,a3,a4;
public ExamFrame() {
super("Quiz");
setLayout(new GridLayout(0, 1));
GridBagConstraints gbc = new GridBagConstraints();
Exam exam = new Exam();
qArrList = exam.getExam();
int count=0;
for(Question q : qArrList){
count++;
JLabel questionLabel = new JLabel(count+". "+q.getQustion()); //swing constant ?
ArrayList<String> ansRand = q.getAllRandomAns();
a1 = new JRadioButton(ansRand.get(0));
a2 = new JRadioButton(ansRand.get(1));
a3 = new JRadioButton(ansRand.get(2));
a4 = new JRadioButton(ansRand.get(3));
add(questionLabel);
add(a1);add(a2,gbc);add(a3);add(a4);
ButtonGroup radioGroup = new ButtonGroup(); //logical relationship
radioGroup.add(a1);radioGroup.add(a2);radioGroup.add(a3);radioGroup.add(a4);
}
//buttons:
JButton checkMe = new JButton("Check Exam");
JButton refresh = new JButton("Start Over");
ButtonHandler handler = new ButtonHandler();
checkMe.addActionListener(handler);
refresh.addActionListener(handler);
add(checkMe);
add(refresh);
}
/** Listens to the radio buttons. */
public class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e) {
if(e.getActionCommand().equals("Start Over")){ //id?
//how to do this?
}
else{
RadioButtonHandler handler = new RadioButtonHandler();
a1.addItemListener(handler);
System.out.println("success?");
}
JOptionPane.showMessageDialog(ExamFrame.this, String.format("You pressed: %s", e.getActionCommand()));
}
public void itemStateChanged(ItemEvent e) //can i add it here?
{
JOptionPane.showMessageDialog(ExamFrame.this, String.format("yes?"));
System.out.println("success!");
}
}
public class RadioButtonHandler implements ItemListener
{
public void itemStateChanged(ItemEvent e)
{
JOptionPane.showMessageDialog(ExamFrame.this, String.format("radio state changed"));
}
}
}
why "itemStateChanges" isn't triggered, i tried to put it in the inner
class "ButtonHandler" and also in "RadioButtonHandler" Im having
troubles with it, what is the right way to do it? I want to trigger
and check the marked JRadioButtons after the user click the "check"
button.
ButtonHandler is implemented with ActionListener only:
public class ButtonHandler implements ActionListener{}
The itemStateChanged(ItemEvent) function belongs to ItemListener. This function is triggered if state of a source component to which this listener is registered gets changed. So implement the ItemListener. However, one more thing to note, that JButton doesn't respond to ItemListener but JRadioButton will. Because this Item events are fired by components that implement the ItemSelectable interface. Some example of such components are: check boxes, check menu items, toggle buttons and combo boxes including Radio Buttons as mentioned above.
What is the right way to check which button was clicked, i feel like
comparing the strings is wrong programming. Maybe using an ID
Well using the event source function: e.getSource(), check whither the type of the source is your expected type and cast it to appropriate type. And then you can use getName(String) function and check the name you were expecting. Of-course you should assign the name using setName(String) after initialization of component. Or using the component reference directly if it is declared in the Class context and you have direct access to the component.
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getSource() instanceof JCheckBox)
{
JCheckBox checkBox = (JCheckBox)e.getSource();
if(checkBox.getName().equals("expectedName"))
; // do my thing
}
}
How should i make a "reset" button(start over), i want to uncheck all
radio buttons and run the constructor once again.
Well you are working with ButtonGroup. And ButtonGroup has a nice function: clearSelection() to help with whatever(I could not understand the part: run the constructor part) you want.
Edit: As you wanted me to see an ItemListener implemented class, Yes i can see that But:
i can not see that you have actually registered an instance of that class(a1.addItemListener(handler);) to any component before performing any action on the component to which ButtonHandler is registered to: checkMe, refresh
In addition to that, in this action performed function, you are checking with
action command, which you haven't even set with JButton.setActionCommand(String) function. You should not assign a (Item)listener depending on event-occurrence of another (Action)listener.
Tutorial:
How to Write an ItemListener
How to Write an ActionListener
How to Use the ButtonGroup Component
I am trying to deselect JRadio button while clear button is pressed. I have tried googling and gone thru lots of forum the only fix i could find is create an invisible button and while clear button is pressed select invisible one. Is there any other method i can use? My code is as follows
public class deselectRadioBtn extends JFrame {
private JRadioButton[] buttons; // array for JRadio buttons
public deselectRadioBtn() {
super("Deselect Radio");
for (int nbrOfButtons = 0; nbrOfButtons < options.length; nbrOfButtons++) {
//create new JRadioButtons and labels and add ( ) around label
buttons[nbrOfButtons] = new JRadioButton(( nbrOfButtons + radioLabel[nbrOfButtons] ));
//add buttons to eastPanel
rightPanel.add(options[nbrOfButtons]);
}//end for (JRadio)
//Create a ButtonGroup object, add buttons to the group
ButtonGroup optionSelect = new ButtonGroup();
optionSelect.add(buttons[0]);
optionSelect.add(buttons[1]);
optionSelect.add(buttons[2]);
optionSelect.add(buttons[3]);
}
This is just a piece of code and i havent include full code.
Use ButtonGroup.clearSelection().
I am having trouble designing GUI's in an object oriented manner. The following code will help me express my question more clearly:
import javax.swing;
import java.awt.*;
import java.awt.event.*;
public class QuoteOptionsPanel extends JPanel
{
private JLabel quote;
private JRadioButton comedy, philosophy, carpentry;
private String comedyQuote, philosophyQuote, carpentryQuote;
//-----------------------------------------------------------------
// Sets up a panel with a label and a set of radio buttons
// that control its text.
//-----------------------------------------------------------------
public QuoteOptionsPanel()
{
comedyQuote = "Take my wife, please.";
philosophyQuote = "I think, therefore I am.";
carpentryQuote = "Measure twice. Cut once.";
quote = new JLabel (comedyQuote);
quote.setFont (new Font ("Helvetica", Font.BOLD, 24));
comedy = new JRadioButton ("Comedy", true);
comedy.setBackground (Color.green);
philosophy = new JRadioButton ("Philosophy");
philosophy.setBackground (Color.green);
carpentry = new JRadioButton ("Carpentry");
carpentry.setBackground (Color.green);
ButtonGroup group = new ButtonGroup();
group.add (comedy);
group.add (philosophy);
group.add (carpentry);
QuoteListener listener = new QuoteListener();
comedy.addActionListener (listener);
philosophy.addActionListener (listener);
carpentry.addActionListener (listener);
add (quote);
add (comedy);
add (philosophy);
add (carpentry);
setBackground (Color.green);
setPreferredSize (new Dimension(300, 100));
}
//*****************************************************************
// Represents the listener for all radio buttons.
//*****************************************************************
private class QuoteListener implements ActionListener
{
//--------------------------------------------------------------
// Sets the text of the label depending on which radio
// button was pressed.
//--------------------------------------------------------------
public void actionPerformed (ActionEvent event)
{
Object source = event.getSource();
if (source == comedy)
quote.setText (comedyQuote);
else
if (source == philosophy)
quote.setText (philosophyQuote);
else
quote.setText (carpentryQuote);
}
}
}
The above code simply creates a panel with three radio buttons, each corresponding to a quote. It also creates a label which displays a quote. Whenever a button is selected, the text in the label is set to the corresponding quote. I understand this code just fine. I run into trouble trying to modify it. Let's say I want to create the same program, but with the radio buttons stacked vertically on top of one another. Let's also say that I decide to go about this by adding the radio buttons to a panel with a BoxLayout, which I define in its own BoxPanel class. (I would then add the BoxPanel to my QuoteOptionsPanel, which would still contain my quote JLabel.)
So my BoxPanel code might look something like this:
import java.awt.*;
import javax.swing.*;
public class BoxPanel extends JPanel
{
private JRadioButton comedy, philosophy, carpentry;
public BoxPanel()
{
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setBackground (Color.green);
comedy = new JRadioButton ("Comedy", true);
comedy.setBackground (Color.green);
philosophy = new JRadioButton ("Philosophy");
philosophy.setBackground (Color.green);
carpentry = new JRadioButton ("Carpentry");
carpentry.setBackground (Color.green);
ButtonGroup group = new ButtonGroup();
group.add (comedy);
group.add (philosophy);
group.add (carpentry);
QuoteListener listener = new QuoteListener();
comedy.addActionListener (listener);
philosophy.addActionListener (listener);
carpentry.addActionListener (listener);
}
//*****************************************************************
// Represents the listener for all radio buttons.
//*****************************************************************
private class QuoteListener implements ActionListener
{
//--------------------------------------------------------------
// Sets the text of the label depending on which radio
// button was pressed.
//--------------------------------------------------------------
public void actionPerformed (ActionEvent event)
{
Object source = event.getSource();
I do not know what to do here.
}
}
}
So as you can see, I did not know how to define my QuoteListener class. I want it to perform the same function as in the original program I posted, but am unsure of how to make it do so. The label which displays the quote is located in QuoteOptionsPanel, so I do not have access to it. In essence I am asking for the optimal way to change a label on one panel with an event listener belonging to a component on a different panel. I would be immensely grateful for any help you may be able to provide. Please let me know if I have not expressed my question clearly enough.
There are several ways to solve this, but for most all the key is to get and use references. Say the class that holds the JLabel as a private field has a public method,
public void setQuoteLabelText(String text) {
quoteLabel.setText(text);
}
Then you have to pass the reference to the visualized object of this class to your BoxPanel class, either through a constructor parameter or a setXXX(...) setter method. Then your ActionListener can call methods on the object of this class.
1. You can create an instance of the class whose private instance variable you need to
access.
2. Follow the one of the many use of Encapsulation, that is to have private Instance variable
and public getter-setter for that instance variable.
3. Now you can access the private member, by calling the public method on the instance of
the class.
4. One more thing, try using the Group Layout created by NetBeans team in 2005. Use the Window Builder Pro, now free from google.