Question

I'm currently working in a simple calculator project and I found myself in a small problem. I'm not able to write on the text field using the buttons. I want to be able to write on the text using the buttons on the frame.

Can someone please help me?

Here's my code:

import javax.swing.*;
import java.awt.*;


public class Calculator extends JFrame{
JPanel NumberPanel = new JPanel();
String [] ButtonString = {"7","8","9","4","5","6","1","2","3","0",".","+/-"};
JButton ButtonArray [] = new JButton[ButtonString.length];
JPanel OperationPanel = new JPanel();
String [] OperationString = {"Erase","Ac","*","/","+","-","Ans","="};
JButton [] OperationArray = new JButton [OperationString.length];
Calculator(){

    for (int a = 0 ; a < ButtonArray.length ; a++){
        ButtonArray[a]= new JButton (ButtonString[a]);
    }
    NumberPanel.setLayout(new GridLayout(4,3,5,5));
    for (int a = 0 ; a < ButtonArray.length ; a++){
        NumberPanel.add(ButtonArray[a]);
    }

    for (int a = 0 ; a < OperationArray.length ; a++){
        OperationArray[a]= new JButton(OperationString[a]);
    }
    OperationPanel.setLayout(new GridLayout(4,2,5,5));
    for (int a = 0 ; a < OperationArray.length ; a++){
        OperationPanel.add(OperationArray[a]);
    }

    JPanel Finalpanel = new JPanel();
    Finalpanel.setLayout(new FlowLayout());
    Finalpanel.add(NumberPanel);Finalpanel.add(OperationPanel);

    JTextField WritingZone = new JTextField(27);
    WritingZone.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    WritingZone.setBorder(BorderFactory.createLoweredSoftBevelBorder());
    WritingZone.setEditable(false);
    JPanel TextPanel = new JPanel();
    TextPanel.add(WritingZone);


    JPanel AllPanel = new JPanel();
    AllPanel.setLayout(new BorderLayout(5,5));
    AllPanel.add(BorderLayout.NORTH, TextPanel);
    AllPanel.add(BorderLayout.CENTER, Finalpanel);
    AllPanel.setBorder(BorderFactory.createTitledBorder("Simple Calculator"));
    add(AllPanel);
}
public static void main (String [] arg){
    JFrame frame = new Calculator();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setSize(400,250);
    frame.setResizable(false);

}
}
Was it helpful?

Solution 2

Implement ActionPerformed methode.

  @Override
   public void ActionPerformed(ActionEvent e){
        JButton btn = (JButton)e.getSource();
        if(btn == btnName){
           String state = WritingZone.getText();
            WritingZone.setText(state+btnNum(operation));
        } else if(btn==otherButton)...
   }

-And then add listener to every button. btn.addListener(this);

-this is one way to do it.

OTHER TIPS

First of all, follow Java naming conventions. Variable name should NOT start with an upper case character. I have never seen a tutorial, text book or example posted in the forum that does this, so don't make up your own conventions. Learn by example.

If you want the buttons to do something then you need to add an ActionListener to the button. Or even better is to create an Action that can be shared by the button and by the keyboard so you can use Key Bindings.

Simple example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class CalculatorPanel extends JPanel
{
    private JTextField display;

    public CalculatorPanel()
    {
        Action numberAction = new AbstractAction()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                display.setCaretPosition( display.getDocument().getLength() );
                display.replaceSelection(e.getActionCommand());
            }
        };

        setLayout( new BorderLayout() );

        display = new JTextField();
        display.setEditable( false );
        display.setHorizontalAlignment(JTextField.RIGHT);
        add(display, BorderLayout.NORTH);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout( new GridLayout(0, 5) );
        add(buttonPanel, BorderLayout.CENTER);

        for (int i = 0; i < 10; i++)
        {
            String text = String.valueOf(i);
            JButton button = new JButton( text );
            button.addActionListener( numberAction );
            button.setBorder( new LineBorder(Color.BLACK) );
            button.setPreferredSize( new Dimension(50, 50) );
            buttonPanel.add( button );

            InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
            inputMap.put(KeyStroke.getKeyStroke(text), text);
            inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
            button.getActionMap().put(text, numberAction);
        }
    }

    private static void createAndShowUI()
    {
//      UIManager.put("Button.margin", new Insets(10, 10, 10, 10) );

        JFrame frame = new JFrame("Calculator Panel");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.add( new CalculatorPanel() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

You need an actionlistener..

I edited your code so that button 1 will work.

 import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class Calculator extends JFrame{

JPanel NumberPanel = new JPanel();

ButtonHandler handler = new ButtonHandler();
    JButton button;

JTextArea textArea;
Calculator(){

JPanel AllPanel = new JPanel();

AllPanel.setBorder(BorderFactory.createTitledBorder("Simple Calculator"));
getContentPane().add(AllPanel);
AllPanel.setLayout(null);

button = new JButton("1");
button.setBounds(10, 129, 89, 23);
button.addActionListener(handler);
AllPanel.add(button);

JButton button_1 = new JButton("2");
button_1.setBounds(109, 129, 89, 23);
AllPanel.add(button_1);

JButton button_2 = new JButton("3");
button_2.setBounds(208, 129, 89, 23);
AllPanel.add(button_2);

JButton button_3 = new JButton("4");
button_3.setBounds(10, 95, 89, 23);
AllPanel.add(button_3);

JButton button_4 = new JButton("5");
button_4.setBounds(109, 95, 89, 23);
AllPanel.add(button_4);

JButton button_5 = new JButton("6");
button_5.setBounds(208, 95, 89, 23);
AllPanel.add(button_5);

JButton button_6 = new JButton("7");
button_6.setBounds(10, 61, 89, 23);
AllPanel.add(button_6);

JButton button_7 = new JButton("8");
button_7.setBounds(109, 61, 89, 23);
AllPanel.add(button_7);

JButton button_8 = new JButton("9");
button_8.setBounds(208, 61, 89, 23);
AllPanel.add(button_8);

JButton button_9 = new JButton("0");
button_9.setBounds(109, 163, 89, 23);
AllPanel.add(button_9);

JButton btnClear = new JButton("Clear");
btnClear.setBounds(298, 163, 89, 23);
AllPanel.add(btnClear);

JButton btnAdd = new JButton("Add");
btnAdd.setBounds(298, 129, 89, 23);
AllPanel.add(btnAdd);

JButton btnSub = new JButton("Sub");
btnSub.setBounds(298, 95, 89, 23);
AllPanel.add(btnSub);

textArea = new JTextArea();
textArea.setBounds(43, 29, 253, 22);
AllPanel.add(textArea);
}

private class ButtonHandler implements ActionListener 
{
    public void actionPerformed (ActionEvent e)
    {
        if (e.getSource() == button)
        {
            textArea.insert("1",0);
        }
    }
}
public static void main (String [] arg){
    JFrame frame = new Calculator();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setSize(400,250);
    frame.setResizable(false);

}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top