How to give multiple buttons different commands - java

I have been trying to make a calculator in Javax swing. I know how to make one button have one command, but I don't know how to give more buttons more commands in Java? I want to give buttons a0-clear actions.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Calculator extends JFrame {
private JButton a0;
private JButton a1;
private JButton a2;
private JButton a3;
private JButton a4;
private JButton a5;
private JButton a6;
private JButton a7;
private JButton a8;
private JButton a9;
private JButton clear;
private JButton plusminus;
private JButton plus;
private JButton minus;
private JButton multiply;
private JButton divide;
private JButton equal;
private JButton decimal;
private JLabel resultLabel;
public Calculator() {
setLayout(new FlowLayout());
a0 = new JButton("0");
add(a0);
a1 = new JButton("1");
add(a1);
a2 = new JButton("2");
add(a2);
a3 = new JButton("3");
add(a3);
a4 = new JButton("4");
add(a4);
a5 = new JButton("5");
add(a5);
a6 = new JButton("6");
add(a6);
a7 = new JButton("7");
add(a7);
a8 = new JButton("8");
add(a8);
a9 = new JButton("9");
add(a9);
decimal = new JButton(".");
add(decimal);
clear = new JButton("C");
add(clear);
plusminus = new JButton("+/-");
add(plusminus);
plus = new JButton("+");
add(plus);
minus = new JButton("-");
add(minus);
multiply = new JButton("X");
add(multiply);
divide = new JButton("/");
add(divide);
equal = new JButton("=");
add(equal);
resultLabel = new JLabel("");
add(resultLabel);
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent event) {
a0.addActionListener(this);
a1.addActionListener(this);
a2.addActionListener(this);
a3.addActionListener(this);
a4.addActionListener(this);
a5.addActionListener(this);
a6.addActionListener(this);
a7.addActionListener(this);
a8.addActionListener(this);
a9.addActionListener(this);
clear.addActionListener(this);
decimal.addActionListener(this);
plusminus.addActionListener(this);
plus.addActionListener(this);
minus.addActionListener(this);
multiply.addActionListener(this);
divide.addActionListener(this);
equal.addActionListener(this);
if (event.getSource() == a1) {
resultLabel.setText("0");
}
}
}
public static void main(String[] args) {
Calculator gui = new Calculator();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(300, 800);
gui.setVisible(true);
gui.setTitle("Caclculator");
}
}

I am going to show you for 1-button, do the same for all other,
public class Calculator extends JFrame implements ActionListener {
JButton a0 = new JButton("0");
a0.addActionListener(this);
add(a0);
public void actionPerformed(ActionEvent event) {
String command = e.getActionCommand();
switch(command){
case "0":
//do whatever want while button '0' press
break;
case "1":
//do whatever want while button '1' press
break;
case "2":
//do whatever want while button '2' press
break;
}
}
}

You will create a class which implements ActionListener.
Then you create and instance of this class and then add this as ActionListener to every button(Code Below):
#SuppressWarnings("serial")
public class Calculator extends JFrame {
// array with the number 0-9
private JButton[] numbers = new JButton[9];
private JButton clear;
private JButton plusminus;
private JButton plus;
private JButton minus;
private JButton multiply;
private JButton divide;
private JButton equal;
private JButton decimal;
private JLabel resultLabel = new JLabel("");
public Calculator() {
//
setSize(300, 300);
setLayout(new FlowLayout());
// The Class which implements the ActionListener
EventListener listener = new EventListener();
// Create each button from 0-9 here
for (int i = 0; i < numbers.length; i++) {
numbers[i] = new JButton(i + "");
numbers[i].addActionListener(listener);
add(numbers[i]);
}
// Create the other Buttons
decimal = new JButton(".");
add(decimal);
clear = new JButton("C");
add(clear);
plusminus = new JButton("+/-");
add(plusminus);
plus = new JButton("+");
add(plus);
minus = new JButton("-");
add(minus);
multiply = new JButton("X");
add(multiply);
divide = new JButton("/");
add(divide);
equal = new JButton("=");
add(equal);
clear.addActionListener(listener);
decimal.addActionListener(listener);
plusminus.addActionListener(listener);
plus.addActionListener(listener);
minus.addActionListener(listener);
multiply.addActionListener(listener);
divide.addActionListener(listener);
equal.addActionListener(listener);
add(resultLabel);
}
public static void main(String[] args) {
Calculator gui = new Calculator();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(300, 800);
gui.setVisible(true);
gui.setTitle("Caclculator");
}
// TODO EventListener
class EventListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
Object v = event.getSource();
if (v == clear) {
// do something..
} else if (v == decimal) {
// do something...
} else if (v == plusminus) {
// do something...
}
// etc continue this.....
}
}
}

Related

Trying to create a calculator with Java. Button inputs won't print in the textfield

I'm trying to create a scientific calculator for class. I'm not sure where I'm going wrong, but it will not print any button inputs into the textfield. Does anybody know where I'm going wrong? Problems come from the 'calc' class at the bottom of the code. I've only coded the calculator to respond to number inputs, so no other buttons will work, but the number buttons should work and I don't know how to fix it. I'm still very new to programming
package scientificcalc;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ScientificCalc extends JFrame {
JFrame Frame;
JPanel Panel;
JTextField Text;
JButton Button[]= new JButton[25]; // Array holds all calculator buttons
String val0, val1, val2; // Each val records a button pressed
public ScientificCalc() {
val0 = val1 = val2 = "";
Frame = new JFrame("Scientific Calculator");
Panel = new JPanel();
Panel.setBackground(Color.RED);
Text = new JTextField(20);
Text.setEditable(false);
Frame.setVisible(true);
Frame.setSize(400,400);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ActionListener a = null;
// Following Lines create each button
Button[0] = new JButton("0");
Button[0].addActionListener(a);
Button[1] = new JButton("1");
Button[1].addActionListener(a);
Button[2] = new JButton("2");
Button[2].addActionListener(a);
Button[3] = new JButton("3");
Button[3].addActionListener(a);
Button[4] = new JButton("4");
Button[4].addActionListener(a);
Button[5] = new JButton("5");
Button[5].addActionListener(a);
Button[6] = new JButton("6");
Button[6].addActionListener(a);
Button[7] = new JButton("7");
Button[7].addActionListener(a);
Button[8] = new JButton("8");
Button[8].addActionListener(a);
Button[9] = new JButton("9");
Button[9].addActionListener(a);
Button[10] = new JButton("+");
Button[10].addActionListener(a);
Button[11] = new JButton("-");
Button[11].addActionListener(a);
Button[12] = new JButton("*");
Button[12].addActionListener(a);
Button[13] = new JButton("/");
Button[13].addActionListener(a);
Button[14] = new JButton("SQRT");
Button[14].addActionListener(a);
Button[15] = new JButton("Sin");
Button[15].addActionListener(a);
Button[16] = new JButton("Cos");
Button[16].addActionListener(a);
Button[17] = new JButton("Tan");
Button[17].addActionListener(a);
Button[18] = new JButton("1/x");
Button[18].addActionListener(a);
Button[19] = new JButton("x^2");
Button[19].addActionListener(a);
Button[20] = new JButton("log");
Button[20].addActionListener(a);
Button[21] = new JButton("!");
Button[21].addActionListener(a);
Button[22] = new JButton(".");
Button[22].addActionListener(a);
Button[23] = new JButton("=");
Button[23].addActionListener(a);
Button[24] = new JButton("Clear");
Button[24].addActionListener(a);
// Following Lines add everything to Panel and Frame
Panel.add(Text);
Panel.add(Button[0]);
Panel.add(Button[1]);
Panel.add(Button[2]);
Panel.add(Button[3]);
Panel.add(Button[4]);
Panel.add(Button[5]);
Panel.add(Button[6]);
Panel.add(Button[7]);
Panel.add(Button[8]);
Panel.add(Button[9]);
Panel.add(Button[10]);
Panel.add(Button[11]);
Panel.add(Button[12]);
Panel.add(Button[13]);
Panel.add(Button[14]);
Panel.add(Button[15]);
Panel.add(Button[16]);
Panel.add(Button[17]);
Panel.add(Button[18]);
Panel.add(Button[19]);
Panel.add(Button[20]);
Panel.add(Button[21]);
Panel.add(Button[22]);
Panel.add(Button[23]);
Panel.add(Button[24]);
Frame.add(Panel);
}
public class calc implements ActionListener {
public void actionPerformed(ActionEvent e) {
String i = e.getActionCommand();
if ((i.charAt(0) >= '0' && i.charAt(0) <= '9') || i.charAt(0) == '.') {
if (!val1.equals("")) {
val2 = val2 + i;
} else {
val0 = val0 + i; // Sets location of each digit when button is pressed
}
Text.setText(val0+val1+val2);
}
}
}
public static void main(String[] args) {
new ScientificCalc();
}
}
You're currently adding your ActionListener a which you set to null to all of your buttons. Change ActionListener a = null to ActionListener a = new calc();
You forgot to initialize calc object by ActionListener a = new calc();
Use field names starting with small letters!
Use loops instead of repetitive code!
Start class names with capital letters!
Name calc class by CustomActionListener
Below there is pretty code!
Question: why do you check it if it's always false? if (!val1.equals(""))
package scientificcalc;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ScientificCalc extends JFrame {
JFrame frame;
JPanel panel;
JTextField textField;
JButton[] buttonArray = new JButton[25]; // Array holds all calculator buttons
String val0, val1, val2; // Each val records a button pressed
public ScientificCalc() {
val0 = val1 = val2 = "";
frame = new JFrame("Scientific Calculator");
panel = new JPanel();
panel.setBackground(Color.RED);
textField = new JTextField(20);
textField.setEditable(false);
frame.setVisible(true);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CustomActionListener actionListener = new CustomActionListener();
// Following Lines create each button
buttonArray[0] = new JButton("0");
buttonArray[1] = new JButton("1");
buttonArray[2] = new JButton("2");
buttonArray[3] = new JButton("3");
buttonArray[4] = new JButton("4");
buttonArray[5] = new JButton("5");
buttonArray[6] = new JButton("6");
buttonArray[7] = new JButton("7");
buttonArray[8] = new JButton("8");
buttonArray[9] = new JButton("9");
buttonArray[10] = new JButton("+");
buttonArray[11] = new JButton("-");
buttonArray[12] = new JButton("*");
buttonArray[13] = new JButton("/");
buttonArray[14] = new JButton("SQRT");
buttonArray[15] = new JButton("Sin");
buttonArray[16] = new JButton("Cos");
buttonArray[17] = new JButton("Tan");
buttonArray[18] = new JButton("1/x");
buttonArray[19] = new JButton("x^2");
buttonArray[20] = new JButton("log");
buttonArray[21] = new JButton("!");
buttonArray[22] = new JButton(".");
buttonArray[23] = new JButton("=");
buttonArray[24] = new JButton("Clear");
for (int i = 0; i < buttonArray.length; i++) {
buttonArray[i].addActionListener(actionListener);
}
// Following Lines add everything to Panel and Frame
panel.add(textField);
for (JButton jButton : buttonArray) {
panel.add(jButton);
}
frame.add(panel);
}
class CustomActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String i = e.getActionCommand();
if ((i.charAt(0) >= '0' && i.charAt(0) <= '9') || i.charAt(0) == '.') {
if (!val1.equals("")) {
val2 = val2 + i;
} else {
val0 = val0 + i; // Sets location of each digit when button is pressed
}
textField.setText(val0 + val1 + val2);
}
}
}
public static void main(String[] args) {
new ScientificCalc();
}
}

I want to change combobox color while clicking on their names in java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class combodemo implements ActionListener {
JFrame f;
JPanel p;
JTextField tf;
JButton b1;
JButton b2;
JRadioButton rb1;
JRadioButton rb2;
JLabel l;
JComboBox cb;
JCheckBox c1, c2, c3;
ButtonGroup bg;
combodemo() {
String[] h = {
"red",
"yellow",
"green"
};
cb = new JComboBox(h);
f = new JFrame();
p = new JPanel();
tf = new JTextField(30);
b1 = new JButton("OK");
b2 = new JButton("Clear");
rb1 = new JRadioButton("male");
rb2 = new JRadioButton("Female");
l = new JLabel("Enter Text");
c1 = new JCheckBox("java");
c2 = new JCheckBox("C++");
c3 = new JCheckBox("Microsoft");
bg = new ButtonGroup();
f.add(p);
p.add(l);
p.add(tf);
b1.addActionListener(this);
b2.addActionListener(this);
p.add(b1);
p.add(b2);
bg.add(rb1);
bg.add(rb2);
p.add(rb1);
p.add(rb2);
p.add(cb);
p.add(c1);
p.add(c2);
p.add(c3);
f.setVisible(true);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
String str = (String) cb.getSelectedItem();
'
if (str.equals("red"))
p.setBackground(Color.red);
if (str.equals("green"))
p.setBackground(Color.green);
if (str.equals("yellow"))
p.setBackground(Color.yellow);
if (ae.getActionCommand() == "OK") {
tf.setText("This is example of swing");
}
if (ae.getActionCommand() == "Clear") {
tf.setText("");
}
}
public static void main(String[] args)
{
combodemo cd = new combodemo();
}
}
Actually when I run this code and to change the color of panel when I click on "RED", "GREEN" or "YELLOW", it requires me to click on "OK" in order to change the color of panel. I want to change the color while clicking on the name on "RED", "GREEN" or "Yellow" please help me to get rid of this problem.
I learn this code from NIIT in today's lecture and when I coded it then many errors has occurred. But now I have completed the code but the problem I'm facing now I already written above.
Help will be appreciated.
You need to do two things..
first add actionlistner to jcombobox
cb.addActionListener(this);
second, implement logic for handling the event.
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() instanceof JComboBox) {
String str = (String)cb.getSelectedItem();
if(str.equals("red"))
p.setBackground(Color.red);
if(str.equals("green"))
p.setBackground(Color.green);
if(str.equals("yellow"))
p.setBackground(Color.yellow);
}
/////
Complete code
package test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class combodemo implements ActionListener
{
JFrame f;
JPanel p;
JTextField tf;
JButton b1;
JButton b2;
JRadioButton rb1;
JRadioButton rb2;
JLabel l;
JComboBox cb;
JCheckBox c1,c2,c3;
ButtonGroup bg;
combodemo()
{
String []h = {"red","yellow","green"};
cb = new JComboBox(h);
f = new JFrame();
p = new JPanel();
tf = new JTextField(30);
b1 = new JButton("OK");
b2 = new JButton("Clear");
rb1 = new JRadioButton("male");
rb2 = new JRadioButton("Female");
l = new JLabel("Enter Text");
c1 = new JCheckBox("java");
c2 = new JCheckBox("C++");
c3 = new JCheckBox("Microsoft");
bg = new ButtonGroup();
f.add(p);
p.add(l);
p.add(tf);
b1.addActionListener(this);
b2.addActionListener(this);
cb.addActionListener(this);
p.add(b1);
p.add(b2);
bg.add(rb1);
bg.add(rb2);
p.add(rb1);
p.add(rb2);
p.add(cb);
p.add(c1);
p.add(c2);
p.add(c3);
f.setVisible(true);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() instanceof JComboBox) {
String str = (String)cb.getSelectedItem();
if(str.equals("red"))
p.setBackground(Color.red);
if(str.equals("green"))
p.setBackground(Color.green);
if(str.equals("yellow"))
p.setBackground(Color.yellow);
}
if(ae.getActionCommand()=="OK")
{
tf.setText("This is example of swing");
}
if(ae.getActionCommand()=="Clear")
{
tf.setText("");
}
}
public static void main (String [] args)
{
combodemo cd = new combodemo();
}
}

Why do I get a nullPointerException in my program? And how would I possibly remove the error? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Here is my program:
The language is obviously Java. Thank you for taking your time to help is you did. I greatly appreciate your services.
The code is used to create a calculator that shall have functions like squaring ,rooting , subtracting , adding , multiplying , dividing , and more if I feel like is necessary in the future.
This program is purely for personal use not for commercial use.
//04-11-15
//This program is a JFrame Calculator
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calc extends JFrame{
public static void main(String[] acalc){
Calc cal = new Calc();
}
public Calc(){
super("Calculator");
setSize(350,400);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocation(10,50);
setResizable(false);
Clanel z = new Clanel();
setContentPane(z);
setVisible(true);
}
}
class Clanel extends JPanel{
Bon bons;
public Clanel(){
setLayout(new BorderLayout());
bons = new Bon();
add(bons,BorderLayout.CENTER);
}
}
class Bon extends JPanel{
Disp dis = new Disp();
Funk fun = new Funk();
Numbers nus = new Numbers();
public Bon(){
setLayout(new BorderLayout());
add(dis,BorderLayout.NORTH);
add(fun,BorderLayout.EAST);
add(nus,BorderLayout.CENTER);
}
class Funk extends JPanel implements ActionListener{
private JButton plus;
private JButton minus;
private JButton multiply;
private JButton divide;
private JButton square;
private JButton r;
public Funk(){
setLayout(new GridLayout(5,1));
JButton plus = new JButton("+");
plus.addActionListener(this);
JButton minus = new JButton("-");
minus.addActionListener(this);
JButton divide = new JButton("/");
divide.addActionListener(this);
JButton square = new JButton("Square");
square.addActionListener(this);
JButton r = new JButton("Root");
r.addActionListener(this);
add(plus);
add(minus);
add(divide);
add(square);
add(r);
}
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("+")){
}
}
}
class Numbers extends JPanel implements ActionListener{
private JButton plus;
private JButton minus;
private JButton multiply;
private JButton divide;
private JButton square;
private JButton r;
private JLabel t;
private String number=" ";
public Numbers(){
setLayout(new GridLayout(4,3));
JButton plus = new JButton("0");
plus.addActionListener(this);
JButton minus = new JButton("1");
minus.addActionListener(this);
JButton divide = new JButton("2");
divide.addActionListener(this);
JButton square = new JButton("3");
square.addActionListener(this);
JButton r = new JButton("4");
r.addActionListener(this);
JButton fiv = new JButton("5");
fiv.addActionListener(this);
JButton si = new JButton("6");
si.addActionListener(this);
JButton se = new JButton("7");
se.addActionListener(this);
JButton ei = new JButton("8");
ei.addActionListener(this);
JButton ni = new JButton("9");
ni.addActionListener(this);
JButton clear = new JButton("Clear");
clear.addActionListener(this);
add(plus);
add(minus);
add(divide);
add(square);
add(r);
add(fiv);
add(si);
add(se);
add(ei);
add(ni);
add(clear);
}
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("0")){
number=number + "0";
}
if(e.getActionCommand().equals("Clear")){
number="0";
}
if(e.getActionCommand().equals("1")){
number=number+"1";
}
if(e.getActionCommand().equals("2")){
number=number+"2";
}
if(e.getActionCommand().equals("3")){
number=number+"3";
}
if(e.getActionCommand().equals("4")){
number=number+"4";
}
if(e.getActionCommand().equals("5")){
number=number+"5";
}
if(e.getActionCommand().equals("6")){
number=number+"6";
}
if(e.getActionCommand().equals("7")){
number=number+"7";
}
if(e.getActionCommand().equals("8")){
number=number+"8";
}
if(e.getActionCommand().equals("9")){
number=number+"9"; }
}
}
class Disp extends JPanel implements ActionListener{
private JLabel t;
private String numb=nus.number;
public Disp(){
t = new JLabel(numb);
add(t);
}
public void actionPerformed(ActionEvent e){
}
}
}
nus has not been initialised when your Disp class tries to access it
The order that the fields are defined also defines the order in which they are initialised
// dis is been initialised BEFORE nus
Disp dis = new Disp();
Funk fun = new Funk();
Numbers nus = new Numbers();
If you change the order to something more like...
Numbers nus = new Numbers();
Disp dis = new Disp();
Funk fun = new Funk();
It should work.
You have to treat it like any normal variable initialisation, if variable A relies on something from variable B, B must be initialised before A

how to select JRadioButton depending on button

see my problem start form this piece of code i add all the addActionListener for the button
but when it come to the Radio button it use addItemListenet but i implements ActionListener only how i will implements ItemListener so i can set Law when ever the user Select sw form the radio button and click on add item~ it will add the item to the right array i made before
exitButton.addActionListener(new ButtonWatcher());
addButton.addActionListener(new ButtonWatcher());
copyButton.addActionListener(new ButtonWatcher());
showButton.addActionListener(new ButtonWatcher());
rButton.addItemListenet(new ButtonWatcher());
}
private class ButtonWatcher implements ActionListener{
public void actionPerformed(ActionEvent a){
Object buttonPressed=a.getSource();
if(buttonPressed.equals(exitButton))
{
System.exit(0);
}
if(buttonPressed.equals(addButton) && rButton1.isSelected())
{
//do the action
}
full code
package item;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
*
* #author isslam
*/
public class MyFrameMain extends JFrame{
Equipment newq = new Equipment();
private final JLabel iLabel;
private final JLabel nLabel;
private final JTextField iJTextField;
private final JTextField nJTextField;
private final JTextField swTextField;
private final JTextField hwTextField;
private final JLabel jItemCounter;
private final JTextArea reSoulte;
private final JButton addButton;
private final JButton showButton;
private final JButton copyButton;
private final JButton exitButton;
public MyFrameMain(String title){
setSize(500, 500);
setTitle(title);
setDefaultCloseOperation(MyFrameMain.EXIT_ON_CLOSE);
iJTextField = new JTextField();
nJTextField = new JTextField();
swTextField = new JTextField();
hwTextField = new JTextField();
nLabel = new JLabel("ID: ");
iLabel = new JLabel("Name: ");
jItemCounter = new JLabel("Number of current Item");
reSoulte = new JTextArea(15,20);
reSoulte.setEditable(false);
reSoulte.setText("Array is empty");
addButton = new JButton("Add an item into the Array");
showButton = new JButton("Show all items in the Array");
copyButton = new JButton("Copy Array into File");
exitButton = new JButton("Exite");
JRadioButton rButton1 = new JRadioButton("SW Version",false);
JRadioButton rButton2 = new JRadioButton("HW Type",false);
JRadioButton rButton3 = new JRadioButton("General",true);
ButtonGroup BGroup = new ButtonGroup();
BGroup.add(rButton1);
BGroup.add(rButton2);
BGroup.add(rButton3);
JPanel rbPanel = new JPanel(new GridLayout(5,1));
rbPanel.add(nLabel);
rbPanel.add(iLabel);
rbPanel.add(rButton1);
rbPanel.add(rButton2);
rbPanel.add(rButton3);
JPanel bpanel = new JPanel(new GridLayout(2,2));
bpanel.add(addButton);
bpanel.add(showButton);
bpanel.add(copyButton);
bpanel.add(exitButton);
JPanel jtfPanel = new JPanel(new GridLayout(5,1));
jtfPanel.add(iJTextField);
jtfPanel.add(nJTextField);
jtfPanel.add(swTextField);
jtfPanel.add(hwTextField);
jtfPanel.add(jItemCounter);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(rbPanel, BorderLayout.WEST);
topPanel.add(jtfPanel, BorderLayout.CENTER);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(bpanel, BorderLayout.SOUTH);
mainPanel.add(reSoulte, BorderLayout.CENTER);
mainPanel.add(topPanel, BorderLayout.NORTH);
Container pane = getContentPane();
pane.add(mainPanel);
exitButton.addActionListener(new ButtonWatcher());
addButton.addActionListener(new ButtonWatcher());
copyButton.addActionListener(new ButtonWatcher());
showButton.addActionListener(new ButtonWatcher());
//rButton.addItemListenet(new ButtonWatcher());
}
private class ButtonWatcher implements ActionListener{
public void actionPerformed(ActionEvent a){
Object buttonPressed=a.getSource();
if(buttonPressed.equals(exitButton))
{
System.exit(0);
}
if(buttonPressed.equals(addButton) && rButton1.isSelected())
{
//do the action
}
}
}
}
I'm not sure what array you want to fill but get the text with getText()
if(buttonPressed.equals(addButton) && rButton1.isSelected())
{
String s1 = iJTextField.getText();
String s2 = nJTextField.getText();
String s3 = swTextField.getText();
String s4 = hwTextField.getText();
// something with these strings
}
If any of the inputs are numbers and you want the numerical value, you need to parse.
Also, these need to be declared as class memebers. You have them declared in the constructor
JRadioButton rButton1 = new JRadioButton("SW Version",false);
JRadioButton rButton2 = new JRadioButton("HW Type",false);
JRadioButton rButton3 = new JRadioButton("General",true);
Declared in the constructor, they are not within the scope of the listener class
public class MyFrameMain extends JFrame{
private final JLabel iLabel;
private final JLabel nLabel;
private final JTextField iJTextField;
private final JTextField nJTextField;
private final JTextField swTextField;
private final JTextField hwTextField;
private final JLabel jItemCounter;
private final JTextArea reSoulte;
private final JButton addButton;
private final JButton showButton;
private final JButton copyButton;
private final JButton exitButton;
JRadioButton rButton1 = new JRadioButton("SW Version",false);
JRadioButton rButton2 = new JRadioButton("HW Type",false);
JRadioButton rButton3 = new JRadioButton("General",true);
public MyFrameMain(String title){
Also, doesn't really look like you need a listener for the radio button, since an event is not necessary. The JButton listens for an event, and in the actionPerformed, it checks if the radio button is selected. Therefore no need for the radio button to listen for any event, the JButton does that.
Try following code. I ahve added a List item and adding values from swTextField TextFiled to item when user select rButton1 and click on addButton button
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
/**
*
* #author isslam
*/
public class Test extends JFrame {
private final JLabel iLabel;
private final JLabel nLabel;
private final JTextField iJTextField;
private final JTextField nJTextField;
private final JTextField swTextField;
private final JTextField hwTextField;
private final JLabel jItemCounter;
private final JTextArea reSoulte;
private final JButton addButton;
private final JButton showButton;
private final JButton copyButton;
private final JButton exitButton;
JRadioButton rButton1;
java.util.List<String> item = new ArrayList<String>();
public Test(String title) {
setSize(500, 500);
setTitle(title);
setDefaultCloseOperation(Test.EXIT_ON_CLOSE);
iJTextField = new JTextField();
nJTextField = new JTextField();
swTextField = new JTextField();
hwTextField = new JTextField();
nLabel = new JLabel("ID: ");
iLabel = new JLabel("Name: ");
jItemCounter = new JLabel("Number of current Item");
reSoulte = new JTextArea(15, 20);
reSoulte.setEditable(false);
reSoulte.setText("Array is empty");
addButton = new JButton("Add an item into the Array");
showButton = new JButton("Show all items in the Array");
copyButton = new JButton("Copy Array into File");
exitButton = new JButton("Exite");
rButton1 = new JRadioButton("SW Version", false);
JRadioButton rButton2 = new JRadioButton("HW Type", false);
JRadioButton rButton3 = new JRadioButton("General", true);
ButtonGroup BGroup = new ButtonGroup();
BGroup.add(rButton1);
BGroup.add(rButton2);
BGroup.add(rButton3);
JPanel rbPanel = new JPanel(new GridLayout(5, 1));
rbPanel.add(nLabel);
rbPanel.add(iLabel);
rbPanel.add(rButton1);
rbPanel.add(rButton2);
rbPanel.add(rButton3);
JPanel bpanel = new JPanel(new GridLayout(2, 2));
bpanel.add(addButton);
bpanel.add(showButton);
bpanel.add(copyButton);
bpanel.add(exitButton);
JPanel jtfPanel = new JPanel(new GridLayout(5, 1));
jtfPanel.add(iJTextField);
jtfPanel.add(nJTextField);
jtfPanel.add(swTextField);
jtfPanel.add(hwTextField);
jtfPanel.add(jItemCounter);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(rbPanel, BorderLayout.WEST);
topPanel.add(jtfPanel, BorderLayout.CENTER);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(bpanel, BorderLayout.SOUTH);
mainPanel.add(reSoulte, BorderLayout.CENTER);
mainPanel.add(topPanel, BorderLayout.NORTH);
Container pane = getContentPane();
pane.add(mainPanel);
exitButton.addActionListener(new ButtonWatcher());
addButton.addActionListener(new ButtonWatcher());
copyButton.addActionListener(new ButtonWatcher());
showButton.addActionListener(new ButtonWatcher());
//rButton.addItemListenet(new ButtonWatcher());
}
private class ButtonWatcher implements ActionListener {
public void actionPerformed(ActionEvent a) {
Object buttonPressed = a.getSource();
if (buttonPressed.equals(exitButton)) {
System.exit(0);
}
if (buttonPressed.equals(addButton) && rButton1.isSelected()) {
item.add(swTextField.getText());
System.out.println(item);
}
}
}
public static void main(String args[]) {
Test t = new Test("Test");
t.setVisible(true);
}
}
Use ButtonGroup with the JRadioButton of your context.
Use jRadioButton.setActionCommand(String) to set their corresponding action name: for your context "SW Version" and anything such.
Make use of an ArrayList to add the item of your context. Try mapping each such array list using a HashMap<Key, Val> i.e., HashMap<String, ArrayList<Equipment>> where the "SW Version" or anything such name will be the key
Try adding listeners to each action button in-line using the means of anonymous class.
So a sample coding for add action would become depicting the usage(usefulness) of ButtonGroup:
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String actionCommand = buttonGroup1.getSelection()
.getActionCommand();
// actionCommand = "SW Version"
map.get(actionCmmand).add(equipment);
}
});
Tutorial and reference:
How to use Radio Button, check the demo for ButtonGroup
ButtonGroup class
HashMap

Can't figure out how to output result to JLabel instead of System.out.println

I'm stuck again trying to figure out how to out the button clicked to label1.
When I click button01 I get A printed out. I need it to print to the label1 though and say Folder A when A is pressed and B when B is pressed and so on. Any nudge in the right direction?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JFileCabinet extends JFrame {
private JButton button01 = new JButton("A");
private JButton button02 = new JButton("B");
private JButton button03 = new JButton("C");
private JButton button04 = new JButton("D");
private JButton button05 = new JButton("E");
private JButton button06 = new JButton("F");
private JButton button07 = new JButton("G");
private JButton button08 = new JButton("H");
private JButton button09 = new JButton("I");
private JButton button10 = new JButton("J");
private JButton button11 = new JButton("K");
private JButton button12 = new JButton("L");
private JButton button13 = new JButton("M");
private JButton button14 = new JButton("N");
private JButton button15 = new JButton("O");
private JButton button16 = new JButton("P");
private JButton button17 = new JButton("Q");
private JButton button18 = new JButton("R");
private JButton button19 = new JButton("S");
private JButton button20 = new JButton("T");
private JButton button21 = new JButton("U");
private JButton button22 = new JButton("V");
private JButton button23 = new JButton("W");
private JButton button24 = new JButton("X");
private JButton button25 = new JButton("Y");
private JButton button26 = new JButton("Z");
private JButton button27 = new JButton(" ");
private JButton button28 = new JButton(" ");
private JButton button29 = new JButton(" ");
private JButton button30 = new JButton(" ");
private static JLabel label1 = new JLabel("Folder ");
private JPanel panel01 = new JPanel(new GridLayout(1, 6));
private JPanel panel02 = new JPanel(new GridLayout(1, 6));
private JPanel panel03 = new JPanel(new GridLayout(1, 6));
private JPanel panel04 = new JPanel(new GridLayout(1, 6));
private JPanel panel05 = new JPanel(new GridLayout(1, 2));
private GridLayout layout = new GridLayout(5, 1, 5, 5);
public JFileCabinet() {
setLayout(layout);
add(panel01);
add(panel02);
add(panel03);
add(panel04);
add(panel05);
button01.addActionListener(new ButtonListener());
panel01.add(button01);
panel01.add(button02);
panel01.add(button03);
panel01.add(button04);
panel01.add(button05);
panel01.add(button06);
panel02.add(button07);
panel02.add(button08);
panel02.add(button09);
panel02.add(button10);
panel02.add(button11);
panel02.add(button12);
panel03.add(button13);
panel03.add(button14);
panel03.add(button15);
panel03.add(button16);
panel03.add(button17);
panel03.add(button18);
panel04.add(button19);
panel04.add(button20);
panel04.add(button21);
panel04.add(button22);
panel04.add(button23);
panel04.add(button24);
panel05.add(button25);
panel05.add(button26);
panel05.add(button27).setVisible(false);
panel05.add(button28).setVisible(false);
//panel05.add(button29).setVisible(false);
panel05.add(label1);
panel05.add(button30).setVisible(false);
setSize(400, 350);
setVisible(true);
}
public static void main(String[] args) {
JFileCabinet frame = new JFileCabinet();
}
String selection;
class ButtonListener implements ActionListener {
private String e;
public void actionPerformed(ActionEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
String clicked = null;
if (e.getActionCommand().equals("A")) { //clicked.equals("A");
System.out.println("A");
}
}
}
}
label1.setText("Folder " + e.getActionCommand());
The nudge - and not the full blown answer is this:
Go and read the public API for JLabel
Identify the method that sets the text on JLabel
Instead of checking for an A string value, just set the value of folder to the value of e.getActionCommand().

Categories