ActionListener nested within an ActionListener? [duplicate] - java

This question already has answers here:
Detect enter press in JTextField
(10 answers)
Closed 7 years ago.
I have a program that has three functions; to read a file, write to a file and search for specific text within a file. I'm currently working on creating a GUI to use with it so that I will no-longer rely on the console. I've already created a fully functional "main window" and functional buttons with respect to the three aforementioned functions, as well as an exit button. Now I'm working on the GUI window for my Search function - the window is created as the response to the Search button being clicked. I have the window and components layed out the way I want but I'm having trouble setting up the action listener for when the user presses Enter after inputting the string they wish to search for. I've looked at a number of different sources including SOverflow, the javadoc and actionlistener tutorials; but I'm getting nowhere fast.
Here is the base code to draw the Search button in the main window and link to the Search GUI (I linked to this through main):
public class SimpleDBGUI{
static File targetFile; //Declare File var to be used in methods below for holding user's desired file
static JTextField sdbTarget;
static JTextField searchTerm;
public void mainWindow(){
//Create main window for Program
JFrame mainWindow = new JFrame("Simple Data Base"); //Init frame
mainWindow.setSize(500, 180); //Set frame size
mainWindow.setVisible(true); //Make frame visible
//Create panel for the main window of the GUI
JPanel simpleGUI = new JPanel( new GridBagLayout());
GridBagConstraints gbCons = new GridBagConstraints();
mainWindow.getContentPane().add(simpleGUI); //Adds JPanel container to the ContentPane of the JFrame
//Create button linking to the search function
JButton searchButton = new JButton("Search"); //Init button with text
gbCons.fill = GridBagConstraints.BOTH;
gbCons.gridx = 1;
gbCons.gridy = 2;
gbCons.weightx = .1;
searchButton.setActionCommand("Search");
searchButton.addActionListener( new ButtonClickListener());
simpleGUI.add(searchButton, gbCons); //Adds the "Search" button to the JPanel
//Create TextField for user to input a desired file
sdbTarget = new JTextField();
gbCons.fill = GridBagConstraints.BOTH;
gbCons.gridx = 0;
gbCons.gridy = 1;
gbCons.gridwidth = 3;
simpleGUI.add(sdbTarget, gbCons); //Adds TextField to GUI
}
public class ButtonClickListener implements ActionListener{ //Sets the EventListener for every function
public void actionPerformed(ActionEvent event){
targetFile = new File(sdbTarget.getText());
String function = event.getActionCommand(); //Reads the ActionCommand into a string for use in performing desired function
if( function.equals("Search")){ //Search Function, draws search window and components
JFrame searchWindow = new JFrame("SimpleDB Search"); //Draw window
searchWindow.setSize(500, 200);
searchWindow.setVisible(true);
JPanel searchGUI = new JPanel( new GridBagLayout()); //Create container and add to window
GridBagConstraints gb1Cons = new GridBagConstraints();
searchWindow.getContentPane().add(searchGUI);
JLabel searchPrompt = new JLabel("Please input the word/phrase you wish to find:"); //Prompt user to specify string to search for
gb1Cons.fill = GridBagConstraints.BOTH;
gb1Cons.gridy = 0;
gb1Cons.gridx = 0;
//gb1Cons.weighty = .1;
searchGUI.add(searchPrompt, gb1Cons); //Add prompt to container
JTextField searchTerm = new JTextField(); //Create JTextField for user input and add to container
gb1Cons.fill = GridBagConstraints.BOTH;
gb1Cons.gridy = 1;
gb1Cons.gridx = 0;
//gb1Cons.weighty = .1;
searchGUI.add(searchTerm, gb1Cons);
searchTerm.addActionListener(this); //Assign ActionListener to JTextField
JTextArea searchResult = new JTextArea(); //Create search output box and add to container
gb1Cons.fill = GridBagConstraints.BOTH;
gb1Cons.gridy = 2;
gb1Cons.gridx = 0;
//gb1Cons.weighty = .1;
searchGUI.add(searchResult, gb1Cons);
public void actionPerformed( ActionEvent event){ //Tried this as one event handler, supposed to execute the following upon the user pressing Enter, failed of course
boolean stringFound = false; //Set flag false
try{
Scanner searchFile = new Scanner(targetFile); //Read file to be searched into a scanner
String searchInput = searchTerm.getText(); //Read term to search for into a string
while( searchFile.hasNextLine()){ //Check that specified file has a next line and:
String searchLine = searchFile.nextLine(); //Read line into string
if( searchLine.contains(searchInput)){ //Check that Line contains searched term and:
stringFound = true; //If line contains term, set flag to true
searchResult.append("**" + searchLine + "**"); //Append line with term to output box
}
}searchFile.close(); //Close scanner
if(!stringFound){
searchResult.append("The term(s) you searched for does not exist in this file"); //Output if line does not contain term
}
}catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}

You should try to re-structure your code some
I would not create the GUI within an actionPerformed, create it outside (or make a class for it extend JFrame), and in actionPerformed, just display it setVisible(true).
Even if this suggestion is not your problem, it would probably solve it.
Your current situation is:
Your are adding the actionListener to JTextField searchTerm, the actionListener that your are adding is actually the ButtonClickListener so you already have an actionPerformed method,hence same method!!!
So outcome is:
when you press enter in your searchTerm the ButtonClickListener.actionPerformed will be called and if you try to write "Search" in the textfield you will see something interesting!!
A short code for adding a new actionListener would be
searchTerm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//DO YOUR STUFF
}
});

Just paste this code in your constructor.
Hope it'll help. Remember your searchTerm should be of jtextfield as the code for jtextxarea is bit different.
searchTerm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionPerformed(e);
}
});

Related

Have a phone keypad and I want to make it a simple addition calculator

I made a simple phone keypad and I want to change a button to add numbers. Right now, the + button simply adds a + to the displayed numbers at the top, but I want that to add the inputted numbers. Like on a calculator, exactly what the + does. And I would like to change the clear button to be an enter button. Here's my partner's and I code so far to make the keypad:
public class Keypad extends JPanel implements ActionListener {
JLabel display;
JButton numButton;
JButton clearButton;
String displayContent = "";
String[] numPadContent = {"1","2","3","4","5","6","7","8","9","+","0"};
ArrayList<JButton> buttonList;
// Keypad constructor class
public Keypad(Container pane) {
// sets the size of the Keypad display
pane.setPreferredSize(new Dimension(320, 335));
// initialize display to hold displayContent
display = new JLabel(displayContent);
display.setPreferredSize(new Dimension(320, 25));
// create lowered bevel border around the display
display.setBorder(BorderFactory.createLoweredBevelBorder());
// add the display to the panel
pane.add(display, BorderLayout.PAGE_START);
// initialize the buttonList
buttonList = new ArrayList<JButton>(12);
JPanel numberPanel = new JPanel();
// set the numberPanel to have a 4row by 3col grid layout
numberPanel.setLayout(new GridLayout(4,3,0,0));
// set the size of the numberPanel
numberPanel.setPreferredSize(new Dimension(320,260));
// create the buttons and add them to the buttonList, properly displaying the numbers
for (int i = 0; i < numPadContent.length; i++) {
numButton = new JButton(numPadContent[i]);
buttonList.add(numButton);
}
// add the buttonList to the number panel
for (int n = 0; n < buttonList.size(); n++) {
buttonList.get(n).addActionListener(this);
numberPanel.add(buttonList.get(n));
}
// create black border around the number panel
numberPanel.setBorder(BorderFactory.createMatteBorder(5, 5, 5, 5, Color.black));
// add number panel to center part of display
pane.add(numberPanel, BorderLayout.LINE_END);
// create Clear button that is actionable
clearButton = new JButton("Clear");
clearButton.setPreferredSize(new Dimension(320, 30));
clearButton.addActionListener(this);
// add Clear button to bottom of display
pane.add(clearButton, BorderLayout.PAGE_END);
}
// update the display depending on clicked button(s)
public void actionPerformed(ActionEvent e) {
String textThere = display.getText();
String additionalText = "";
// add clicked number button text to display
for (int a = 0; a < buttonList.size(); a++) {
if (e.getSource().equals(buttonList.get(a))) {
additionalText = buttonList.get(a).getText();
}
}
// clear display if "Clear" button is clicked
if (e.getSource().equals(clearButton)) {
textThere = "";
}
display.setText(textThere.concat(additionalText));
}
public static void main(String[] args) {
//create and set up the window.
JFrame frame = new JFrame("Keypad");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//set up the content pane.
frame.getContentPane().add(new Keypad(frame));
frame.pack();
frame.setVisible(true);
}
See this link: Is there an eval() function in Java?
You can import javax.script and use the ScriptEngine's eval() method to evaluate your expression.

try and catch java with files in a GUI

private class PrintButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == radio){
try{
File file = new File("Birds.txt");
Scanner inputFile = new Scanner(file);
area.setText(inputFile.toString());
}
catch(Exception ex){
System.out.println("File not found!");
}
}
}
}
I need to display 2 different files. Each file has an associated radio button. The content of the files must display on the GUI interface once the button is clicked. I really need help with this one!
private JRadioButton radio; // first radio button
private JRadioButton radio2; // second radio button
private JRadioButton radio3; // third radio button
private JButton button; // button to gain access to whatever option was selected
private JPanel panel; // the panel
private JTextArea area;
private ButtonGroup buttonGroup;
public BirdTest2(){ // GUI constructor
super();
setSize(2000,950);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
buildPanel();
add(panel);
}
public void buildPanel(){ // building the panel for the GUI
panel = new JPanel();
radio = new JRadioButton("Display all birds!");
radio2 = new JRadioButton("Display foreign birds only!");
radio3 = new JRadioButton("Display non-foreign birds only!");
button = new JButton("Click me!");
button.addActionListener(new PrintButtonListener());
buttonGroup = new ButtonGroup();
buttonGroup.add(radio);
buttonGroup.add(radio2);
buttonGroup.add(radio3);
area = new JTextArea();
panel.add(radio);
panel.add(radio2);
panel.add(radio3);
panel.add(button);
panel.add(area);
}
Here is the code I have above the previous for my window, button, radio buttons. Help would be greatly appreciated! Please let me know if you need any additional info :)
The content of the files must display on the GUI interface once the button is clicked.
To read a File using Scanner, you have to explicitly iterate over all the lines of the file using the methods defined by the Scanner object you are using (the toString currently used in actionPerformed will only return a String representing the Scanner object, which isn't necessarily the contents of the File).
Scanner inputFile = new Scanner(file);
while ( inputFile.hasNextLine() ){
area.append(inputFile.nextLine());//append the line to the JTextArea
area.append("\n");//append any new lines as they are ommitted with Scanner.nextLine
}
You can check which JCheckBox is selected in the actionPerformed method to determine which File to open based upon which JCheckBox is selected.

Java Swing: disable typeahead for JDialog?

I have an application that uses JDialog popups. I'm using 1.6 (compatibility requirement for the customer.) The ENTER key dismisses the dialog, taking previous results. The problem is that the user can type-ahead on hitting the ENTER key (or any other text for that matter).
Here's a snippet:
private void promptForCredentials(final GenericSwitch sw) {
final JDialog jd = new JDialog();
jd.setModal(true);
jd.getContentPane().setLayout(new FlowLayout());
final JLabel l_user = new JLabel("Username: ");
final JLabel l_pass = new JLabel("Password: ");
final JTextField tf_user = new JTextField(25);
final JTextField tf_pass = new JPasswordField(25);
JButton b_ok = new JButton("OK");
JButton b_same = new JButton("Same as previous");
JButton b_cancel = new JButton("Cancel");
final JLabel l_authfail = new JLabel("Authentication failed, try again.");
ActionListener okSameListener = new ActionListener() {
public void actionPerformed(ActionEvent ev) {
// if (((JButton) ev.getSource()).isVisible()) {
// return; // always returns for 'OK' button!
// }
String name = ((JButton) ev.getSource()).getText();
if (name.equals("OK")) {
// If user hits OK, save user/pw, unless they're both empty
// (treat that as "use last")
if (! tf_user.getText().isEmpty()
&& ! tf_pass.getText().isEmpty()) {
mLastUsername = tf_user.getText();
mLastPassword = tf_pass.getText();
}
}
jd.dispose();
sw.setUsername(mLastUsername, true);
sw.setPassword(mLastPassword, true);
if (!sw.checkLogin()) {
// auth failed so don't save for next time
mLastUsername = "";
mLastPassword = "";
}
display(sw.mIndex);
poll();
}
};
b_ok.addActionListener(okSameListener);
b_same.addActionListener(okSameListener);
b_cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
System.out.print("Poll cancelled\n");
abort();
jd.dispose();
}
});
Box box0 = Box.createHorizontalBox();
Box box1 = Box.createHorizontalBox();
Box box2 = Box.createHorizontalBox();
Box box3 = Box.createHorizontalBox();
box0.add(l_authfail);
box1.add(l_user);
box1.add(tf_user);
box2.add(l_pass);
box2.add(tf_pass);
box3.add(b_ok);
box3.add(Box.createHorizontalStrut(10));
if (!mLastUsername.isEmpty() && !mLastPassword.isEmpty()) {
box3.add(b_same);
box3.add(Box.createHorizontalStrut(10));
}
box3.add(b_cancel);
if (sw.authFailed()) {
jd.add(box0);
}
jd.add(box1);
jd.add(box2);
jd.add(box3);
SwingUtilities.getRootPane(b_ok).setDefaultButton(b_ok);
jd.setTitle("Login for " + sw.mShortname);
jd.setPreferredSize(new Dimension(400, 150));
jd.setSize(new Dimension(400, 150));
jd.setLocationRelativeTo(getContentPane());
jd.setVisible(true);
}
Since this app polls a number of external resources, most of which usually have the same username/pw, it's nice to just hit "enter" to cycle through the lot, the first time. All good. (And yeah, I know I should have "use same for subsequent" checkbox. Maybe later.)
However, I noticed to my surprise that I can type ahead. Frankly, I like this, but I don't think it's really appropriate for general users. How can I disable it?
Would it work to consume all actions prior to setting the JDialog visible? I tried checking if the button is visible, but while the Cancel button is, the OK button isn't! (commented out above)
Thanks

How do I pause a method until a button is pressed?

I am designing a software with multiple components - each with its own actionlistener.
For an example, I have a JPanel with a cardlayout that holds 10 cards - each its own JPanel and purpose.
On one side, there are multiple buttons, I.E. Login, Logout, Settings, etc.
When I click Login, it will switch to the card using the Login() method to the Login JPanel object where I want it to wait for a button to click I.E. Login, New User, or Cancel before continuing the Login() method and setting the current user.
Is there a method to pause the program until one of the buttons are clicked to retrieve the data from it? (Kind of like how JOptionPane.showInputMessage(null,"INPUT STRING") waits for you)
My Code is below:
FRAME:
/**
* Frame design
*/
public class Frame extends JFrame{
JPanel LeftSide, UpperRightSide;
EmployeeAdder employAdd;
ArrayList<ServiceView> serviceViewers;
ChartViewer viewChart;
PayByView viewPayBy;
SettingsViewer viewSettings;
LoginViewer viewLogin;
CategoryView viewCategory;
ServiceAdder serviceAdd;
Directory directory;
Employee currentEmployee;
ChargeViewer viewCharge;
JButton Login, Logout, Settings;
CardLayout LeftCard,RightCard;
String currentCard,currentRightCard;
ButtonListen listen;
public static String CARDCAT = "Category View";
public static String CARDPAY = "Pay By";
public static String CARDCHART = "Chart View";
public static String CARDLOGIN = "Log-in View";
public static String CARDSERVICEADD = "Service Adder";
Frame(){
listen = new ButtonListen();
//-------Current Card--------------------
currentCard = CARDCAT;
currentRightCard = "CHARGE";
//-----First Find Directory Folder-------
startDirectory();
//-----User Interface--------------------
//-------Left Side-----------------------
LeftSide = new JPanel();
LeftCard = new CardLayout();
LeftSide.setLayout(LeftCard);
viewPayBy = new PayByView();
viewLogin = new LoginViewer();
viewChart = new ChartViewer();
viewCategory = new CategoryView();
employAdd = new EmployeeAdder();
serviceAdd = new ServiceAdder();
LeftSide.add(viewCategory,"CAT");
LeftSide.add(viewChart, "CHA");
LeftSide.add(viewLogin,"LOG");
LeftSide.add(viewPayBy,"PAY");
LeftSide.add(employAdd,"EMA");
LeftSide.add(serviceAdd,"SEA");
LeftCard.show(LeftSide, "CAT");
viewCategory.setEnabled(false);
LeftSide.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK),currentCard));
serviceViewers = new ArrayList<ServiceView>();
//--------Right Side---------------------
JPanel RightSide = new JPanel();
RightSide.setLayout(new BorderLayout());
UpperRightSide = new JPanel();
RightCard = new CardLayout();
UpperRightSide.setLayout(RightCard);
viewSettings = new SettingsViewer();
viewCharge = new ChargeViewer();
viewCharge.setEnabled(false);
UpperRightSide.add(viewCharge,"CHARGE");
UpperRightSide.add(viewSettings,"SETTINGS");
UpperRightSide.setPreferredSize(new Dimension(350,500));
RightSide.add(UpperRightSide,BorderLayout.NORTH);
//--------Buttons at the bottom Panel---
JPanel Buttons = new JPanel();
Buttons.setLayout(new GridLayout(3,1));
Login = new JButton("LOG-IN");
Login.addActionListener(listen);
Logout = new JButton("LOG OUT");
Logout.addActionListener(listen);
Settings = new JButton("Settings");
Settings.addActionListener(listen);
Buttons.add(Login);
Buttons.add(Logout);
Buttons.add(Settings);
Buttons.setPreferredSize(new Dimension(350,150));
RightSide.add(Buttons,BorderLayout.SOUTH);
RightSide.setSize(new Dimension(400,200));
//------Other Stuff--------------------------
//-----add Panels----------------------------
setLayout(new BorderLayout());
add(LeftSide,BorderLayout.WEST);
add(RightSide,BorderLayout.EAST);
}
private void Login(){
LeftCard.show(LeftSide, "LOG");
//----I WANT IT TO WAIT HERE FOR AN ACTION-------
int clicked = viewLogin.getClicked();
if (clicked==LoginViewer.NEWUSER){
NewUser();
}else if (clicked==LoginViewer.LOGIN){
if (viewLogin.checkPassword()){
currentEmployee = directory.getEmployee(viewLogin.getSelectedName());
viewCategory.setEnabled(true);
viewCharge.setEnabled(true);
viewCharge.refreshName(currentEmployee.getName());
LeftCard.show(LeftSide, "CAT");
}
}else if (clicked==LoginViewer.CANCEL){
LeftCard.show(LeftSide, "CAT");
}
}
public class ButtonListen implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if (!viewLogin.isWaiting()){
if (e.getSource()==Login){
if (currentCard.equals(CARDLOGIN)){
LeftCard.show(LeftSide,"CAT");
currentCard = CARDCAT;
}else{
Login();
currentCard = CARDLOGIN;
}
}else{
//Don't change the screen
}
}
}
}
}
My Code for LoginViewer:
public class LoginViewer extends JPanel{
JComboBox User;
JPasswordField passField;
JButton NewUser, Login, Cancel;
Hashtable<String,String> namespass; //names and password
private int clicked = -1;
ButtonListen listen;
public static int NEWUSER = 1;
public static int LOGIN = 0;
public static int CANCEL = 2;
boolean waiting;
LoginViewer(){
waiting = false;
//---------------------------------------
setPreferredSize(new Dimension(100,100));
listen = new ButtonListen();
namespass = new Hashtable<String,String>();
//----------Panel Design-------------------
JPanel Center = new JPanel();
Center.setLayout(new GridLayout(3,3));
User = new JComboBox();
passField = new JPasswordField();
NewUser = new JButton("New User");
NewUser.addActionListener(listen);
Login = new JButton("Login");
Login.addActionListener(listen);
Cancel = new JButton("Cancel");
Cancel.addActionListener(listen);
Center.add(new JLabel("Choose User"));
Center.add(User);
Center.add(new JLabel(""));
Center.add(new JLabel("Type Password"));
Center.add(passField);
Center.add(new JLabel(""));
Center.add(Login);
Center.add(NewUser);
Center.add(Cancel);
Center.setPreferredSize(new Dimension(300,300));
Center.setMaximumSize(new Dimension(100,100));
Center.setAlignmentX(CENTER_ALIGNMENT);
setAlignmentX(CENTER_ALIGNMENT);
setLayout(new BoxLayout(this,BoxLayout.X_AXIS));
add(Box.createHorizontalGlue());
add(Center);
add(Box.createHorizontalGlue());
}
public void uploadUserNames(Hashtable<String,String> names){
namespass.clear();
namespass.putAll(names);
User.removeAllItems();
Enumeration<String> name = names.keys();
while (name.hasMoreElements()){
User.addItem(name.nextElement());
}
}
public boolean checkPassword(){
boolean value = false;
String key = User.getSelectedItem().toString();
if (passField.getPassword().length==4){
if (namespass.get(key).equals(String.valueOf(passField.getPassword()))){
value = true;
}
}
return value;
}
public String getSelectedName(){
return User.getSelectedItem().toString();
}
public boolean isWaiting(){
return waiting;
}
public int getClicked(){
waiting = true;
return clicked;
}
public class ButtonListen implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
waiting = false;
if (e.getSource()==NewUser){
clicked = 1;
}else if (e.getSource()==Login){
clicked = 0;
}else if (e.getSource()==Cancel){
clicked = 2;
}
}
}
}
Or is it easier to just use an actionlistener to listen to ALL of the objects' buttons?
There are a LOT of buttons...
NOTE: Some of the methods are incomplete or test methods until I know how to make it work...
You don't want to use linear console-type code in a Swing GUI. Instead, with event-driven GUI programs you will want to have user interactions change a program's state, and then have the behavior of the program depend on the state. For instance, rather than have the login method pause, have it do some housekeeping -- change the state of the program to be ready to accept a login attempt -- and then where you plan to "wait", exit the login method. Then have the rest of the code for logging in reside in the login button's ActionListener.
As an aside, you've posted a lot of code, 95% of it unrelated to your problem and thus only serving as a distraction to us and preventing us from reading the code and understanding the specifics of your problem. In the future, consider creating and posting an sscce, where you condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem for us.
the way the Swing framework works is that you already "wait" for everything to happen, and it only happens once the users triggers the action corresponding to your listener.
So yes, basically you only have to wait for buttons to be clicked.
HOWEVER:
Designing responsive GUIs means that you won't let your user wait 10 seconds on a frozen interface until you do yout 10000 calculations and 10 million SELECT statements. Thus in case your action listeners (or whatever specific listeners you've got) have to perform heavy duty calculations, do them on a separate Thread, and inform the user if a task is done one way or another.

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