JRadioButton java - java

I'm new to java GUI programming and while working on the project I'm getting the error cannot find symbol on my addActionListener for my JRadioButtons, I'm not quite sure what I'm doing wrong since I didn't receive the same error when working with JButtons.
Here's my code:
public void SouthPanel() {
JRadioButton greenButton = new JRadioButton("Green");
JRadioButton blueButton = new JRadioButton("Blue");
JRadioButton cyanButton = new JRadioButton("Cyan");
ButtonGroup group = new ButtonGroup();
group.add(greenButton);
group.add(blueButton);
group.add(cyanButton);
greenButton.addActionListener(new RadioButtonListener());
blueButton.addActionListener(new RadioButtonListener());
cyanButton.addActionListener(new RadioButtonListener());
SouthPanel = new JPanel();
add(greenButton);
add(blueButton);
add(cyanButton);
add(SouthPanel);
setVisible(true);
}
private class RadioButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String actionRadio = e.getActionCommand();
if (actionRadio.equals("Green")) {
label.setForeground(Color.GREEN);
}
else if (actionRadio.equals("Blue")) {
label.setForeground(Color.BLUE);
}
else if (actionRadio.equals("Cyan")) {
label.setForeground(Color.CYAN);
}
}

To my knowledge, the error "cannot find symbol" usually refers to a variable that can't be resolved by the compiler.
On what line does the error occur?
What seems a bit odd at first glance is following statement:
SouthPanel = new JPanel();
and add(SouthPanel);
since SouthPanel is the name of your method and you didn't give a name to your SouthPanel (?) object.

To use getActionCommand() on a Button or RadioButton, you should have previously set the ActionCommand
button.setActionCommand(String val);
You'd be able to get it back when you make a call to:
button.getActionCommand(); //This would return the string you previously set.
For a TextField, ActionCommand would give you the text in the TextField by default if you do not set it.
That's where you are probably missing the line.

You have created an instance of the JPanel and inserted into SouthPanel class. How can it be done.
SouthPanel = new JPanel();
add(greenButton);
add(blueButton);
add(cyanButton);
add(SouthPanel);
setVisible(true);
Into where are you adding the buttons and adding the SouthPanel.! Please check this one.Seems the error is from here.3 buttons are added,for 3 times and error is shown for 3 times.right.Seems error is from here. Check here.

See the complete code here.
class SouthPanel extends JPanel {
JLabel label = new JLabel("label");
public SouthPanel() {
JRadioButton greenButton = new JRadioButton("Green");
JRadioButton blueButton = new JRadioButton("Blue");
JRadioButton cyanButton = new JRadioButton("Cyan");
ButtonGroup group = new ButtonGroup();
group.add(greenButton);
group.add(blueButton);
group.add(cyanButton);
greenButton.addActionListener((ActionListener) new
RadioButtonListener());
blueButton.addActionListener(new RadioButtonListener());
cyanButton.addActionListener(new RadioButtonListener());
JPanel SouthPanel = new JPanel();
add(label);
add(greenButton);
add(blueButton);
add(cyanButton);
add(SouthPanel);
setVisible(true);
JFrame frame = new JFrame();
frame.setContentPane(this);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new SouthPanel();
}
private class RadioButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String actionRadio = e.getActionCommand();
if (actionRadio.equals("Green")) {
label.setForeground(Color.GREEN);
} else if (actionRadio.equals("Blue")) {
label.setForeground(Color.BLUE);
} else if (actionRadio.equals("Cyan")) {
label.setForeground(Color.CYAN);
}
}
}
}

Related

JRadioButton toggle unexpectedly in CardLayout panels

So the problem is: I'm trying to make a wizard-like CardLayout. In each card panel, I put back & next JButton and 3 JRadioButton to switch between 3 pages.
Now, when I select the radio buttons the 1st time, it works normally. However, the 2nd time I select the radio button, they don't get selected as expected. For example, I want to select page 2, the card panel 2 does show up, but the radio button 2 state does not show that it's being selected, instead either radio button 1 or 3 gets selected. Button 2 only gets selected when I click it again. Same thing happens when I try to select the others.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutWizardDemo extends JFrame{
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
CardLayoutWizardDemo frame= new CardLayoutWizardDemo();
frame.init();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
private static final long serialVersionUID = 1L;
private JPanel cardPanel, panel1, panel2, panel3, btnPanel1, btnPanel2, btnPanel3;
private JLabel label1, label2, label3;
private JRadioButton step1, step2, step3;
private ButtonGroup bg;
private CardLayout cl = new CardLayout();
private void init(){
setTitle("CardLayoutWizardDemo");
cardPanel = new JPanel();
cardPanel.setLayout(cl);
panel1 = new JPanel(new BorderLayout());
panel2 = new JPanel(new BorderLayout());
panel3 = new JPanel(new BorderLayout());
label1 = new JLabel("label 1");
label2 = new JLabel("label 2");
label3 = new JLabel("label 3");
panel1.add(label1, BorderLayout.NORTH);
panel2.add(label2, BorderLayout.NORTH);
panel3.add(label3, BorderLayout.NORTH);
btnPanel1 = new JPanel();
btnPanel2 = new JPanel();
btnPanel3 = new JPanel();
btnPanel1.setName("panel1");
btnPanel2.setName("panel2");
btnPanel3.setName("panel3");
btnPanel1 = initTutBtn(btnPanel1);
btnPanel2 = initTutBtn(btnPanel2);
btnPanel3 = initTutBtn(btnPanel3);
panel1.add(btnPanel1, BorderLayout.SOUTH);
panel2.add(btnPanel2, BorderLayout.SOUTH);
panel3.add(btnPanel3, BorderLayout.SOUTH);
cardPanel.add(panel1, "1");
cardPanel.add(panel2,"2");
cardPanel.add(panel3,"3");
getContentPane().add(cardPanel, BorderLayout.CENTER);
setPreferredSize(new Dimension(350,500));
setMinimumSize(new Dimension(240,320));
pack();
setLocationByPlatform(true);
}
/**create new set of 3 step buttons
*/
private JPanel initTutBtn(JPanel btnPanel){
btnPanel.setLayout(new BoxLayout(btnPanel,BoxLayout.X_AXIS));
step1 = new JRadioButton();
step2 = new JRadioButton();
step3 = new JRadioButton();
step1.setActionCommand("step1");
step2.setActionCommand("step2");
step3.setActionCommand("step3");
bg = new ButtonGroup();
bg.add(step1);
bg.add(step2);
bg.add(step3);
if (btnPanel.getName().equals("panel1")){
step1.setSelected(true);
}else if (btnPanel.getName().equals("panel2")){
step2.setSelected(true);
}else if (btnPanel.getName().equals("panel3")){
step3.setSelected(true);
}
step1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
goToStep(e);
}
});
step2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
goToStep(e);
}
});
step3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
goToStep(e);
}
});
btnPanel.add(step1);
btnPanel.add(step2);
btnPanel.add(step3);
return btnPanel;
}
private void goToStep(ActionEvent evt){
if(evt.getActionCommand().equals("step1")){
cl.show(cardPanel, "1");
}else if(evt.getActionCommand().equals("step2")){
cl.show(cardPanel, "2");
}else if(evt.getActionCommand().equals("step3")){
cl.show(cardPanel, "3");
}
}
}
I think maybe the problems lie where I create new radio buttons within initButton() and goToStep(ActionEvent evt)but I can't figure out what I did wrong

NullPointerException error and cardlayout [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
The NullPointerException only comes about when I click the 'next' button.
I'm trying to get the frame to transition to another panel using cardlayout, but I have failed to do so.
Second question: How do I get my current panel to transition to the next panel (LoginPanel) in another class? I've already created an instance of it
public class InsuranceMain extends JFrame {
private CardLayout cardPanel;
private JPanel buttonPanel;
private JButton next;
private JLabel label;
public InsuranceMain() {
buttonPanel = new JPanel();
JPanel card1 = new JPanel();
JPanel cards = new JPanel(cardPanel);
LoginPanel loginPanelA = new LoginPanel(this);
CardLayout cardLayout = new CardLayout();
cards.setLayout(cardLayout);
next = new JButton("Next"); // Button
label = new JLabel("Test");
// Main frame settings
setTitle("Travel Insurance Application");
setSize(300, 300);
setLayout(new FlowLayout());
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonPanel.add(next);
add(buttonPanel);
card1.add(label);
cards.add(card1, "card1");
cards.add(loginPanelA, "loginPanelA");
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == next) {
cardLayout.show(cards, "loginPanelA");
}}
});
}
public static void main(String[] args) {
InsuranceMain test = new InsuranceMain();
}
}
Here's my LoginPanel code. I apologize if it's very disorganized
public class LoginPanel extends JPanel {
private JButton loginB, registerB, clearB;
private JTextField nricTextField, passwordTextField;
private JLabel nric, password, loginTitle;
private JPanel centerPanel, southPanel;
private InsuranceMain main;
public LoginPanel(InsuranceMain main){
this.main = main;
// JLabels
loginTitle = new JLabel("Insurance Login", JLabel.CENTER);
nric = new JLabel("NRIC: ");
password = new JLabel("Password: ");
// JTextField
nricTextField = new JTextField("");
passwordTextField = new JTextField("");
// JButton
loginB = new JButton("Login");
loginB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == loginB) {
//cardLayout.show(cards, "card1");
}}
});
registerB = new JButton("Register");
clearB = new JButton("Clear");
// North Panel
setLayout(new BorderLayout()); // main panel's layout
add(loginTitle, BorderLayout.NORTH);
// Center Panel
centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(2,2));
centerPanel.add(nric);
centerPanel.add(nricTextField);
centerPanel.add(password);
centerPanel.add(passwordTextField);
add(centerPanel, BorderLayout.CENTER);
// South Panel
southPanel = new JPanel();
southPanel.setLayout(new FlowLayout());
southPanel.add(loginB);
southPanel.add(registerB);
southPanel.add(clearB);
add(southPanel, BorderLayout.SOUTH);
}
}
A NPE in the actionPerformed method can only be caused by cardLayout being null. So instead of
CardLayout cardLayout = (CardLayout) cards.getLayout(); // yields null
You should create the layout you need.
CardLayout cardLayout = new CardLayout();
See also
Cannot refer to a non-final variable inside an inner class defined in a different method
See also Erwin's comment.
//change to
final CardLayout cardLayout = new CardLayout();
final JPanel cards = new JPanel(cardPanel);
cards.setLayout(cardLayout);
You have to declare the variables final so you can refer to them from an anonymus inner class
new ActionListener() {}
Also use the naming convention of java for naming classes => start with capital letter i.e InsuranceMain, LoginPanel

Trying to use cards layout, but cant make show work

im trying to to use cards layout, and i have 2 buttons at the the top that supoose to change the card but for some reason it wont work, the next method works but the show or first\last doesnt, ofcourse i cant use next, cause i want a specific card for every button, here is my code:
cards = new CardLayout();
cardPanel = new JPanel();
cardPanel.setLayout(cards);
cards.show(cardPanel, "gapas");
JPanel firstCard = new JPanel();
firstCard.setBackground(Color.WHITE);;
JPanel secondCard = new JPanel();
secondCard.setBackground(Color.blue);
cardPanel.add(firstCard, "kalam");
cardPanel.add(secondCard, "gapan");
guiFrame.add(tabsPanel,BorderLayout.NORTH);
guiFrame.add(cardPanel,BorderLayout.CENTER);
guiFrame.setVisible(true);
}
ActionListener action = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().matches("kalam")){
cards.show(cardPanel,"kalam");
System.out.println("kalam");
}
else{
cards.show(cardPanel, "gapas");
System.out.println("gapas");
}
}
};
I think you want something like this.
public class TestCard extends JFrame implements ActionListener {
CardLayout cards;
JPanel cardPanel, tabsPanel;
JButton b1, b2;
public TestCard() {
b1= new JButton("kalam");
b2= new JButton("gapas");
tabsPanel = new JPanel();
cards = new CardLayout();
cardPanel = new JPanel();
cardPanel.setLayout(cards);
JPanel firstCard = new JPanel();
firstCard.setBackground(Color.WHITE);
JPanel secondCard = new JPanel();
secondCard.setBackground(Color.blue);
cardPanel.add(firstCard, "kalam");
cardPanel.add(secondCard, "gapas");
tabsPanel.add(b1);
tabsPanel.add(b2);
add(tabsPanel, BorderLayout.NORTH);
add(cardPanel, BorderLayout.CENTER);
b1.addActionListener(this);
b2.addActionListener(this);
setSize(800, 600);
cards.show(cardPanel, "gapas");
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().matches("kalam")) {
cards.show(cardPanel, "kalam");
System.out.println("kalam");
} else {
cards.show(cardPanel, "gapas");
System.out.println("gapas");
}
}
public static void main(String[] args) {
new TestCard();
}
}
Documentation states:
show (Container parent, String name) Flips to the component that was added to this layout with the specified name, using the addLayoutComponent method.
You add two items:
kalam
gapan
but you try to show: gapas.
Additionally I would add first and then try 2 show.

Action Listener does not work on swing

I have a form , That when i click to save button, "Yes" String should display on my console!
(I use "Yes" String for test!)
But does not work when clicked.
My code:
public final class NewUserFrame1 extends JFrame implements ActionListener {
UserInformation userinfo;
JLabel fnamelbl;
JLabel lnamelbl;
JTextField fntf;
JTextField lntf;
JLabel gndlnl;
JRadioButton malerb;
JRadioButton femalerb;
ButtonGroup bgroup;
JLabel registnm;
JButton savebt;
JButton cancelbt;
JLabel showreglbl;
public NewUserFrame1() {
add(rowComponent(), BorderLayout.CENTER);
setLocation(200, 40);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public JPanel rowComponent() {
JPanel panel = new JPanel();
fnamelbl = new JLabel("First name");
lnamelbl = new JLabel("Last Name");
JLabel fntemp = new JLabel();
JLabel lntemp = new JLabel();
fntf = new JTextField(10);
lntf = new JTextField(10);
gndlnl = new JLabel("Gender");
malerb = new JRadioButton("Male");
femalerb = new JRadioButton("Female");
bgroup = new ButtonGroup();
bgroup.add(malerb);
bgroup.add(femalerb);
registnm = new JLabel("Registration ID is:");
showreglbl = new JLabel("");
JLabel regtemp = new JLabel();
savebt = new JButton("Save");
cancelbt = new JButton("Cancell");
JLabel buttontemp = new JLabel();
panel.add(fnamelbl);
panel.add(fntf);
panel.add(fntemp);
panel.add(lnamelbl);
panel.add(lntf);
panel.add(lntemp);
panel.add(gndlnl);
JPanel radiopanel = new JPanel();
radiopanel.setLayout(new FlowLayout(FlowLayout.LEFT));
radiopanel.add(malerb);
radiopanel.add(femalerb);
panel.add(radiopanel);
panel.add(new JLabel());
panel.add(registnm);
panel.add(showreglbl);
panel.add(regtemp);
panel.add(savebt);
panel.add(cancelbt);
panel.add(buttontemp);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 5, 3, 50, 10, 80, 60);
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
NewUserFrame1 newUserFrame1 = new NewUserFrame1();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == savebt) {
System.out.print("Yes");
}
}
}
You need to add an ActionListener to your button like so:
savebt.addActionListener(this);
or with an anonymous class, like so:
savebt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// your code.
}
});
Using anonymous classes (or inner classes) is better because you can't have more than one actionPerformed() method in a given class.
You need to tell the button to invoke the ActionListener:
savebt = new JButton("Save");
savebt.addActionListener(this);
Note if you intend to use the same method for the save and cancel buttons, you'll need to differentiate, perhaps by comparing the source of the ActionEvent against the two buttons.

JOptionPane call stacks

I got a little problem with a JOptionPane which I use to warn user if wrong input is found. It works correct first time. But when I close down the JFrame which calls for that JOptionPane, and open it again it will this time call for it twice. And it will stack for every close down I do.
I have tried to look for the problem without any luck. I can provide the code, but it is quite large though.
Third EDIT: I have found and solved the problem now.
Ok, I provided the code I use. I have cut it down so it only show the necessary one. I dont think it will compile, but this is how I use the addActionListener();
public class BorderLayoutDemo extends JFrame implements ActionListener {
private JButton button1 = new JButton("L?gg till kund");
private JButton button2 = new JButton("Ta bort kund");
private JButton button3 = new JButton("Visa kund");
private JButton button4 = new JButton("Lista alla kunder");
private JButton button5 = new JButton("Avsluta");
private JButton button6 = new JButton("Change");
private JTextArea TextWindow = new JTextArea("Hej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\n");
private JScrollPane scrollPane = new JScrollPane(TextWindow); //l?gger in TextWindow s? att det f?r en scroll-bar
private JPanel aPanel = new JPanel();
private JFrame aFrame = new JFrame();
private JTextField aTextfield1 = new JTextField();
private JTextField aTextfield2 = new JTextField();
private JButton aButton1 = new JButton("L?gg till kund");
private JButton aButton2 = new JButton("St?ng");
public BorderLayoutDemo() {
setTitle("Bankregister");
setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));
panel.setLayout(new GridLayout(6,1,55,5)); //row, cols, hgap, vgap
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button5.addActionListener(this);
button6.addActionListener(this);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
panel.add(button6);
JPanel panel2 = new JPanel();
panel2.add(panel);
add(panel2,BorderLayout.WEST);
add(scrollPane,BorderLayout.CENTER);
setJMenuBar(menu());
setSize(600,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public void addCustomer(boolean status) {
if(status) {
aFrame.setTitle("L?gg till kund");
aFrame.setSize(200,300);
aFrame.setLayout(new GridLayout(3,1));
aPanel.setLayout(new GridLayout(2,1)); //rad, kolumn
aPanel.add(aTextfield1);
aPanel.add(aTextfield2);
aButton1.addActionListener(this);
aButton2.addActionListener(this);
System.out.println("Foo!!!!!!!!!!!!!");
aFrame.add(aPanel);
aFrame.add(aButton1);
aFrame.add(aButton2);
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aFrame.setLocationRelativeTo(null);
aFrame.setVisible(true);
}
else {
aFrame.setVisible(false);
}
}
public static void main(String[] args) {
new BorderLayoutDemo();
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1) {
setEnabled(false);
addCustomer(true);
}
//IFs f?r addCustomer();
else if(e.getSource() == aButton1) {
if((aTextfield1.getText().isEmpty() || aTextfield2.getText().isEmpty())) {
JOptionPane.showMessageDialog(null, "You miss to fill out the fields");
}
else {
JOptionPane.showMessageDialog(null, "Added");
Kund kund = new Kund(aTextfield1.getText(),aTextfield2.getText());
setEnabled(true);
register.add(kund);
}
}
else if(e.getSource() == aButton2) {
setEnabled(true);
addCustomer(false);
}
Sounds like you are adding the "validation listener" every time you open the JFrame. So check your "addListenerXXX" code to make sure it is only added/created once.
Which also leads to the question why are you using a JFrame for this? Typically an application has a single JFrame. Then, if you need a window to enter data you create a JDialog.
By passing null as the first parameter of that method you are creating a default JFrame that the JOptionPane uses as its parent component and not the JFrame you have created in your code. If you provide more detail in your question I'm sure someone here will provide you with a much more detailed answer.

Categories

Resources