JTextField.setText() does not work in method as an array - java

new Java programmer here so I might have a basic question here. I am making an array of JTextFields. I want to use setText outside of the class in a public method but it does not work. However, I am able to use setText in the class (not in a method). I am not sure why. Here is some code as a SSCCE to show what I am experiencing.
import java.awt.BorderLayout;
import javax.swing.*;
public class testSetText extends JFrame
{
private JPanel panel;
private JTextField[] arrayField;
private JTextField singleField;
public testSetText()
{
// Specify an action for close button
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make a panel
panel = new JPanel();
// Make array of JTextField components
JTextField[] arrayField = new JTextField[2];
for (int i = 0; i < 2; i++)
{
arrayField[i] = new JTextField(10);
arrayField[i].setEditable(false);
arrayField[i].setText("<>!");
panel.add(arrayField[i]);
}
// Make just one JTextField component
singleField = new JTextField(10);
singleField.setText("Works here");
panel.add(singleField);
// Add to panel to frame
add(panel);
// Pack the contents of the window and display it
pack();
setVisible(true);
// This will work!
arrayField[0].setText("Array index in class");
// This won't? Why?
setInMethodWithArray();
// Is this a problem with JTextField itself? Let me try a single element
setInMethodWithSingleElement();
// Hmmm so an element in an array of JTextFields can be addressed with setText in a class but not
// in a method in same class with same statement. But a single JTextField can be used in a method
// by that same class. Why do arrays behave so differently?
// EDIT: So I misunderstood, it does not work with a non array as well either!!
}
public void setInMethodWithArray()
{
arrayField[1].setText("This text will never show up");
}
public void setInMethodWithSingleElement()
{
//singleField.setText("Works here as non-array"); <--- before edit
singleField.setText("nevermind, it does not work here either");
}
public static void main(String[] args)
{
new testSetText();
}
}

you should declare arrayField[] in class area so array Field is accessible from setInMethodWithArray() method.
JTextField[] arrayField = new JTextField[2]; //class area
in constructor initial it
arrayField[i]= new JTextField(10);
arrayField[i].setEditable(false);
yes this is work
arrayField[0].setText("Array index in class");
because arrayField in the constructor scope ..and you are accessing arrayField Within constructor .so it works..
This won't? Why?
setInMethodWithArray();
because method setInMethodWithArray() can't access arrayField[] because it's not in method scope or in class scope.that's because you have declare it in the constructor so after constructor code block execute arrayField doesn't exist .it's reference lost because it's local variable ..
public void setInMethodWithArray()
{
arrayField[1].setText("This text will never show up");
}
now set can access arratField[] so now your code will work
import java.awt.BorderLayout;
import javax.swing.*;
public class testSetText extends JFrame
{
private JPanel panel;
private JTextField singleField;
// Make array of JTextField components
private JTextField[] arrayField = new JTextField[2];
public testSetText()
{
// Specify an action for close button
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make a panel
panel = new JPanel();
for (int i = 0; i < 2; i++)
{
arrayField[i] = new JTextField(10);
arrayField[i].setEditable(false);
arrayField[i].setText("<>!");
panel.add(arrayField[i]);
}
// Make just one JTextField component
singleField = new JTextField(10);
singleField.setText("Works here");
panel.add(singleField);
// Add to panel to frame
add(panel);
// Pack the contents of the window and display it
pack();
setVisible(true);
// This will work!
arrayField[0].setText("Array index in class");
// This won't? Why?
setInMethodWithArray();
// Is this a problem with JTextField itself? Let me try a single element
setInMethodWithArray();
// Hmmm so an element in an array of JTextFields can be addressed with setText in a class but not
// in a method in same class with same statement. But a single JTextField can be used in a method
// by that same class. Why do arrays behave so differently?
}
public void setInMethodWithArray()
{
arrayField[1].setText("This text will never show up");
}
public void setInMethodWithSingleElement()
{
singleField.setText("Works here as non-array");
}
public static void main(String[] args)
{
new testSetText();
}
}
output>>

Related

JButton's actionPerformed doesn't change JTextField's text by using .setText() method

I have this code... in it it has a problem as in title: JTextField's text doesn't change when clicking the button. I don't know what the problem is, but I think actionPerformed is executed as the message dialog appears. I tried to use a constructor (of class Start) (instead of function "doIt") but it doesn't work either.
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.*;
import java.awt.event.*;
public class PalTransfer
{
public static void main(String[] args)
{
Starter starter = new Starter();
starter.doIt();
}
}
class Starter
{
JFrame PTMainFrame = new JFrame("In/Out - arch - access, ...");
JTextField TextFieldOfIP = new JTextField(20);
//String string = "I AM START OF STARTER";
void doIt()
{
PTMainFrame.setSize(900, 400); // Set the frame size
PTMainFrame.setLocationRelativeTo(null);
PTMainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField TextFieldOfIP = new JTextField(20);
JButton jBtn = new JButton("I AM A BUTTON!");
PTMainFrame.add(jBtn);
PTMainFrame.add(TextFieldOfIP);
FlowLayout layoutManager = new FlowLayout(0,10,5);
PTMainFrame.setLayout(layoutManager);
TextFieldOfIP.setText("I am doIt() method!"); //+++++++++++++++++++++++++++
jBtn.addActionListener(new ButtonListener());
PTMainFrame.setVisible(true); // to do // put later
}
class ButtonListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null, "hello?");
TextFieldOfIP.setText("I am actionPerformed of JButton!");
}
}
}
Why have you defined this twice.
JTextField TextFieldOfIP = new JTextField(20);
Remove it from the DoIt() method it will work.
You have your class attribute TextFieldOfIP that your ButtonListeners is doing the setText on. But additional you have a local variable called TextFieldOfIP in your doIt() method. And thats the object you are placing on your JFrame.
Remove this redefinition line: JTextField TextFieldOfIP = new JTextField(20); of your doIt() method. Then you are placing the same object on your JFrame that your ButtonListener is doing the setText on and everything will work as expected.

.getText(); not working for textField variable that is declared in another class

In trying to read the text that is entered into a textField, I used the actionlistener for a button right next to it. In this actionlistener class, I had an action performed method in which I created a string that was set equal to the textField.getText();. This class however has a problem recognizing textField variable from the previous class.
It is necessary for the .getText() or reading of the textField entry to be in the actionlistener class. I do not know what to try besides the code that I have listed down below.
public class MainClass {
public static void main(String args[]) {
JFrame frame = new JFrame ("Welcome");
frame.setVisible(true);
frame.setSize(500, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JLabel label = new JLabel("...");
panel.add(label);
JTextField text = new JTextField(20);
panel.add(text);
JButton SubmitButton = new JButton("Analyze");
panel.add(SubmitButton);
SubmitButton.addActionListener(new Action1());
}
static class Action1 implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
JFrame frame1 = new JFrame("Word Commonality");
frame1.setVisible(true);
frame1.setSize(500,200);
String ReceivedPath = text.getText();
System.out.println(ReceivedPath);
Error is present at second to bottom line of code. The error is "text cannot be resolved"
I expect that the text can be read and printed out in the console.
Your problem is revolved around function scoping to fix it you need a direct access to the JTextField object you can do so by instantiating a new action performed straight in the MainClass like this:
public class Main {
public static void main(String args[]) {
new MainClass();
}
}
Here I created a class only used to instantiate the window class
For the main class I suggest extending JFrame so you can inherit all of it methods.
//Imports
public class MainClass extends JFrame {
private JPanel panel;
private JLabel label;
private JTextField text;
private JButton SubmitButton;
public MainClass(){
super("Welcome");
setSize(500, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
add(panel);
label = new JLabel("...");
panel.add(label);
text = new JTextField(20);
panel.add(text);
SubmitButton = new JButton("Analyze");
panel.add(SubmitButton);
SubmitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String ReceivedPath = text.getText();
System.out.println(ReceivedPath);
}
});
setVisible(true);
}
}
This is how your class should look like.
Side notes:
Set visible is at the end otherwise the items will not be see able.
The MainClass is inheriting from JFrame so it can use all its methods without instatiating it look at inheritance(https://www.w3schools.com/java/java_inheritance.asp)
The action performed now can acces the text JTextField because it is a class attribute.
If the solution is correct please think of marking this answer as final. Thank you
If you place the getText() outside the ActionListener, it will be read immediately after creating the panel. That is why it is empty. You can make the ActionListener assign a value to a variable, but it will be empty until the action is performed.
Also see here: Swing GUI doesn't wait for user input

How to change a JLabel with a button from another class?

I have two classes and a text file database, The JLabel in the first class, let's call it class1 automatically set it self to the number in the database. Now, in class2 I have this little JFrame and a text field and of course a button, the value I put in the text field overwrites the one in the database, but here's the problem. The label in the first class wont update while running, but if I restart it it will show me the value that I want.
How do I update it while the program is running?
I've tried to change the label in the buttonActionperformed in the other class but it gives me a NullPointException every time.
How do I fix this?
THE MAIN CLASS ( JUST THE JFRAME )
package BankrollG;
import java.awt.Graphics;
import javax.swing.JFrame;
public class BGbrain {
BGbody body = new BGbody();
JFrame Frame = new JFrame();
public BGbrain() {
Frame.setSize(body.width, body.height);
Frame.setTitle(body.title);
Frame.setResizable(false);
Frame.setDefaultCloseOperation(Frame.EXIT_ON_CLOSE);
Frame.add(body.panel);
Frame.setLocationRelativeTo(null);
Frame.setFocusable(true);
Frame.setVisible(true);
}
public static void main(String[] args ) {
new BGbrain();
}
}
Then you got the class with the components:
private JLabel bankroll_label
public BGbody(){
panel.setLayout(null);
windowComponents();
}
public void windowComponents() {
// Bankroll database access
try {
FileReader fr = new FileReader("Bankroll.txt");
BufferedReader br = new BufferedReader(fr);
set_bankroll = br.readLine();
} catch(IOException e) {
System.out.println("FEL MED LĂ„SNING AV DATABAS /// BGBODY");
}
}
}
THEN you got the JFrame class that I created with the netbeans function
private void AddcurrencyActionPerformed(java.awt.event.ActionEvent evt) {
String CBR = txt_bankroll.getText();
try {
FileWriter fw = new FileWriter("Bankroll.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println(CBR);
pw.close();
} catch(IOException e) {
System.out.println("FEL MED INSKRIVNINGEN I DATABASEN");
}
}
Now, everything goes as plan, but I can't update my JLabel "bankroll_label" from the button class because it just returns nullpointsexceptions. The data is there, because the JLabel reads from the database but it wont update when changes has been made from the button class. So a getter setter method wont work because the value IS there but it wont update the JLabel.
I hope this made it easier to understand my problem.
It's ALOT more code, that dont have to do with this, I hope I simplified it at least some.
Your question is a specific example of a basic problem in programming in Java -- how to transfer information between classes. There are several ways to do this, one of the most elegant being giving to use a "model" class that holds your program's logic code and key data, having one class change the model's state by changing a text String that it holds. Then using a listener or observer pattern, have the model notify the other class that it has been changed so the other class can extract the new information, its new String from the model. While this is likely the best solution, it may be a bit of overkill and likely is above your current level of coding, so for you, I'm not going to recommend this.
Instead, I'm going to recommend a simpler less elegant solution, that you instead have one class call a setter method of the other to push the new String into it.
One problem we have as volunteer answerers here is that your question is hard to answer because it lacks critical code, making it hard for us to guess why your code is misbehaving, why specifically you're running into a NullPointerException (or NPE) when you try to run it. So all I can do is guess, but guess I will try nevertheless.
For simplicity's sake, let's call one class the, the one that holds the JLabel, the LabelClass and the other class the ButtonTextFieldClass.
One possible reason is that you've got a NullPointerException is because your ButtonTextFieldClass may have a LabelClass variable, but never initialized the variable, something like so:
// this guy is null because it is never initialized
private LabelClass labelClass;
A simple solution could be to try to initialize it like so:
private LabelClass labelClass = new LabelClass();
But this won't work because while it does create and assign a LabelClass instance, it's likely not the LabelClass instance that is visualized in the running GUI.
A better solution is to give the ButtonTextFieldClass a setter method that allows other classes to set the ButtonTextFieldClass with the proper LabelClass instance.
e.g.,
public void setLabelClass(LabelClass labelClass) {
this.labelClass = labelClass;
}
This way the code that sets up both classes can pass the visualized LabelClass to the first class, and it can call methods on it.
A simple example of LabelClass could look like so:
class LabelClass extends JPanel {
private JLabel label = new JLabel("");
public LabelClass() {
setBorder(BorderFactory.createTitledBorder("Label Panel"));
add(label);
}
public void setLabelText(String text) {
label.setText(text);
}
}
I have it extend JPanel because this way it gives me the freedom of placing it into a JFrame or JDialog or other JPanel as I see fit. Note that I've made the JLabel private and have given the class a public setter method, setLabelText(String text), that allows outside classes the ability to set the JLabel's text.
The ButtonTextFieldClass could look something like:
class ButtonTextFieldClass extends JPanel {
private JTextField textField = new JTextField(10);
private JButton button = new JButton(new ButtonAction("Send Text"));
private LabelClass labelClass;
public ButtonTextFieldClass() {
setBorder(BorderFactory.createTitledBorder("Button TextField Panel"));
add(textField);
add(button);
}
// here we allow other classes to set instances of our LabelClass
public void setLabelClass(LabelClass labelClass) {
this.labelClass = labelClass;
}
// ....
I've also given the button an AbstractAction in place of an ActionListener since it is like a super ActionListener on steroids. Inside of it, I'd get the text from the JTextField and then call the LabelClass's setter method (if the variable is not null) to set the label's text:
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
if (labelClass != null) {
labelClass.setLabelText(text);
}
}
Then to set everything up, in another class I'd create instances of both LabelClass and ButtonTextFieldClass, and then "hook them up" by calling the setter method:
LabelClass labelClass = new LabelClass();
ButtonTextFieldClass buttonTextFieldClass = new ButtonTextFieldClass();
buttonTextFieldClass.setLabelClass(labelClass); // set our reference
The whole thing could look like so:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class TransferData {
private static void createAndShowGui() {
LabelClass labelClass = new LabelClass();
ButtonTextFieldClass buttonTextFieldClass = new ButtonTextFieldClass();
buttonTextFieldClass.setLabelClass(labelClass); // set our reference
JPanel mainPanel = new JPanel(new GridLayout(0, 1));
mainPanel.add(buttonTextFieldClass);
mainPanel.add(labelClass);
JFrame frame = new JFrame("TransferData");
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();
}
});
}
}
class LabelClass extends JPanel {
private JLabel label = new JLabel("");
public LabelClass() {
setBorder(BorderFactory.createTitledBorder("Label Panel"));
add(label);
}
public void setLabelText(String text) {
label.setText(text);
}
}
class ButtonTextFieldClass extends JPanel {
private JTextField textField = new JTextField(10);
private JButton button = new JButton(new ButtonAction("Send Text"));
// one possible solution -- give this class a variable
// of the LabelClass -- but don't initialize the variable
// here, but rather do it in a setter
private LabelClass labelClass;
public ButtonTextFieldClass() {
setBorder(BorderFactory.createTitledBorder("Button TextField Panel"));
add(textField);
add(button);
}
// here we allow other classes to set instances of our LabelClass
public void setLabelClass(LabelClass labelClass) {
this.labelClass = labelClass;
}
// an AbstractAction is like a "super" ActionListener
private class ButtonAction extends AbstractAction {
public ButtonAction(String name) {
super(name); // set the button's text and actionCommand
int mnemonic = (int) name.charAt(0); // get first char
putValue(MNEMONIC_KEY, mnemonic); // set mnemonic
}
#Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
if (labelClass != null) {
labelClass.setLabelText(text);
}
}
}
}
For simplicity's sake, I've displayed both JPanels within the same GUI, but it could work just as well if one JPanel were in one JFrame and the other within a JDialog.

Trying to create a character counter, but my button is not updating the while loop boolean to do so

so I am trying to make a small java program to count the number of characters in a given string.
Right now, my code works in the console output, but it is not updating the text field I have created in a JFrame and I am unsure why. Can someone please explain this to me?
BTW: I have set "onPress" to true, so the button doesn't really have an effect right now, I'm just trying to test the functionality of the program before I implement button functionality.
Thank you :)! Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class characterCounterTwov2 extends JFrame {
static boolean onPress = true;
public characterCounterTwov2(){
/*******************/
/* Local Variables */
/*******************/
//creates a new Jframe to put our frame objets in
JFrame frame = new JFrame();
//creates a text field frame object
JTextField txtField = new JTextField("Enter your text here", 25);
//stores the string of the the jtextfield into a variable text
String text = txtField.getText();
//creates a text field that is uneditable with the word "characters"
String charString = "Characters: ";
JTextField charField = new JTextField(charString, 25);
charField.setEditable(false);
//integer to count the characters
int charCounter = 0;
//string that will be used in a text field to display the # of chars
String charCount = Integer.toString(charCounter);
//Text field that displays charCount
JTextField charFieldTwo = new JTextField(charCount, 10);
//calculate button
JButton calcButton = new JButton("Calculate");
calcButton.addActionListener(new calcButtonFunc());
/*******************/
/* Frame Setup */
/*******************/
//sets the layout of the frame
frame.setLayout(new BorderLayout());
//add's elements to the frame
frame.add(txtField, BorderLayout.NORTH);
frame.add(charField, BorderLayout.CENTER);
frame.add(charFieldTwo, BorderLayout.SOUTH);
frame.add(calcButton, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
//begin while loop
//infinite while loop
System.out.println("Entering main while loop");
while(true)
{
while(onPress == true)
{
System.out.println("text length is:" + charCount);
for(int i = 0; i < text.length(); i++)
{
charCounter++;
System.out.println("Number of characters:" + charCounter);
}
//charCount = Integer.toString(charCounter);
onPress = false;
}
}
}
static class calcButtonFunc implements ActionListener
{
public void actionPerformed(java.awt.event.ActionEvent event)
{
onPress = true;
}
}
public static void main(String[] args){
new characterCounterTwov2();
System.out.println("End of program. Should not get here");
}
}
~~~~~~~~~
EDIT
I was given a lot of helpful tips by Hovercraft Full of Eels, and cleaned up my code. I am still having a problem with calculating the character count on button press, and having it reflect in the GUI. I am thinking my bug lies within the line "text = txtField.getText();" inside my button listener class.
Here is my updated code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class characterCounterTwov4{
//creates a new Jframe to put our frame objets in
JFrame frame = new JFrame();
//creates a text field frame object
JTextField txtField = new JTextField(25);
//stores the string of the the jtextfield into a variable text
String text = txtField.getText();
//creates a text field that is uneditable with the word "characters"
String charString = "Characters: ";
JTextField charField = new JTextField(charString, 25);
public characterCounterTwov4(){
charField.setEditable(false);
//integer to count the characters
int charCounter = 0;
//string that will be used in a text field to display the # of chars
String charCount = Integer.toString(text.length());
//Text field that displays charCount
JTextField charFieldTwo = new JTextField(charCount, 10);
//calculate button
JButton calcButton = new JButton("Calculate");
calcButton.addActionListener(new ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent event)
{
System.out.println("button pressed");
//stores the string of the the jtextfield into a variable text
text = txtField.getText();
//string that will be used in a text field to display the # of chars
String charCount = Integer.toString(text.length());
//Text field that displays charCount
JTextField charFieldTwo = new JTextField(charCount, 10);
}
});
/*******************/
/* Frame Setup */
/*******************/
//sets the layout of the frame
frame.setLayout(new BorderLayout());
//add's elements to the frame
frame.add(txtField, BorderLayout.NORTH);
frame.add(charField, BorderLayout.CENTER);
frame.add(charFieldTwo, BorderLayout.SOUTH);
frame.add(calcButton, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
new characterCounterTwov4();
System.out.println("End of program. Should not get here");
}
}
Your code is not structured for correct Swing GUI event-driven programming but rather looks like a linear console program that is being shoe-horned into a GUI. Get rid of that while loop, get rid of that static boolean variable. Instead give your class a non-static (instance) int counter variable and a JTextField non-static variable and simply increment your counter in the actionPerformed method and display the results in the JTextField (or JLabel if you prefer).
So the actionPerformed could look something like:
public void actionPerformed(ActionEVent e) {
counter++; // increment the counter variable
charCount.setText("Count: " + counter); // display the results
}
and again, counter and charCount are non-static and are declared and initialized in the class, not inside of the constructor or any method.
Edit
Additional notes:
Why does your class extend JFrame when you don't use it as a JFrame?
In general, it's a good idea to start all Swing proggrams on the Swing Event Dispatch Thread or EDT. This can be done by passing a Runnable with your start-up code in it to the SwingUtilities static method invokeLater(...).
For example:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
// create and display your GUI from in here
MainGui mainGui = new MainGui();
JFrame mainFrame = new JFrame("Main GUI");
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainFrame.add(mainGui);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
Edit 2
Oops, I read your requirements wrong. You need to count the chars in a String, and so you will need another class instance JTextField, one to hold the user's String, get rid of the counter instance field since it no longer will be needed, and then in the actionPerformed method, simply get the String from the JTextField, get its length, and display the length in another JTextField or in a JLabel, again your choice.
Edit 3
Your code is now almost there!
Problems:
The charFieldTwo variable is a non-final local variable. To be able to use it in your anonymous inner class, either make it final, and note that doing this won't harm its ability to work since it is a reference variable, not a primite,
Or you could move its declaration out of the constructor, like you do the other variables.
Once you've done this, it is easy to call charFieldTwo.setText(charCount); on it at the bottom of your ActionListener, and you're pretty much done.

Actionlistener java

For my class I need to use my ActionListener. I am having trouble adding my ActionListener to my buttons. I have to use the word "this" like this.buttons to add my ActionListener but Im having trouble doing that. I will get to my actionPerformed method later but my main problem is my ActionListener.
public class TextButtonsHW extends JFrame implements ActionListener {
private JButton[] buttons; //Do not change
private JTextArea textArea; //Do not change
//Assign values for these constants in the constructor
private final int ENTER; //Index of Enter button in buttons
private final int SPACE; //Index of Space button in buttons
private final int CLEAR; //Index of Clear button in buttons
/**
* Set up this frame and its contents.
* #param title Title to appear in JFrame title bar
*/
public TextButtonsHW(String title) {
super(title); //call parent JFrame constructor to set the title
buttons = new JButton[] { new JButton("A"), new JButton("B"), new JButton("C"),
new JButton("1"), new JButton("2"), new JButton("3"),
new JButton("X"), new JButton("Y"), new JButton("Z"),
new JButton("Enter"), new JButton("Space"), new JButton("Clear")};
ENTER = buttons.length-3;
SPACE = buttons.length-2;
CLEAR = buttons.length-1;
textArea = new JTextArea(15, 5);
textArea.setEditable(false);
this.buttons[0].addActionListener(I dont know what to put right here);
//TODO: instantiate all JButtons, add them to the buttons array,
// and register "this" as the ActionListener for each button.
//DONE
//TODO: assign values to ENTER, SPACE, and CLEAR constants to
// indicate the indexes of those buttons in the buttons array
//DONE
//TODO: create the JTextArea textArea
//TODO: set its "editable" property to false
//DONE
//Create a TextButtonsHWPanel to display the buttons and textArea
TextButtonsHWPanel mainPanel = new TextButtonsHWPanel(buttons, textArea);
this.getContentPane().add(mainPanel);
this.pack();
}
public void actionPerformed(ActionEvent e) {
//TODO: update the text of textArea according to which
// button generated the ActionEvent.
}
public static void main(String[] args) {
final TextButtonsHW f = new TextButtonsHW("Text Buttons");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null); //centers frame on screen
f.setVisible(true);
}
}
buttons[0].addActionListener(this);
Since you have 12 buttons you could also go for a for-loop to add ActionListener to all your buttons i.e.
for(int i=0; i<12; i++)
{
buttons[i].addActionListener(this);
}
Instead of a long code i.e.
buttons[0].addActionListener(this);
buttons[1].addActionListener(this);
........................
Though buttons[0].addActionListener(this); will work well, From design perspective I will suggest to have separate class (may be inner class) which implements ActionListner and pass its object reference to the method.
the whole point of Object Oriented programming is to delegate different responsibilities to different Objects(classes), so code becomes more maintainable and reusable.

Categories