Question

I'm trying to code a Java program to take two values from a GUI and add them using text boxes and an add button. I know I have to use actionlisteners and use something to actually get the values from the textboxes, but I'm not quite sure where that all fits into the code that I already have. I've been working on it for about a few hours and just can't figure it out. I have posted what I have so far below, any help would be greatly appreciated!

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

public class Add extends JFrame {
    JLabel num1Label = new JLabel("Number 1: ", JLabel.CENTER); //NUM1LABEL
    JTextField num1Name = new JTextField(15);                   //NUM1BOX
    JLabel num2Label = new JLabel("Number 2: ", JLabel.CENTER); //NUM2LABEL
    JTextField num2Name = new JTextField(15);                   //NUM2BOX
    JButton exitButton = new JButton("Add");                    //ADDBUTTON

    public Add() {
        super("Actions");
        setSize(400, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        GridLayout grid = new GridLayout(3,3);
        setLayout(grid);
        add(num1Label);
        add(num1Name);
        add(num2Label);
        add(num2Name);
        add(exitButton);
        setVisible(true);
    }

    public static void main(String[] arguments) {
        Add ag = new Add();
    }
}
Was it helpful?

Solution

To answer your question in the title...

You need to get the text within the textboxes and parse it as a number:

int num1 = Integer.parseInt(num1Name.getText());
int num2 = Integer.parseInt(num2Name.getText());
int result = num1 + num2;
num3Name.setText(Integer.toString(result));

where num3Name is a JTextField (which you can use to store your result)

This can at least point you in the right direction.

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