I've got a simple Swing GUI and I want to add a new line of text to a JTextArea after a button is pressed, simple right?
The Button and it's ActionListener function correctly (printing stuff to the console works fine), but when I use .append()or .setText() to add text to the textarea, I get a nullpointer exception.
As always, code it below. Any input would be greatly appreciated, thanks!!!
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class GUI extends JFrame implements ActionListener {
private JFrame frame;
private JLabel paneHeader;
public JTextArea ipArea, portArea, outputLog, orderLog, cookLog;
private JButton newServer;
public String ipAddress, portNumber, cashierName, cookName;
public GUI() {
initGUI();
}
public void initGUI() {
frame = new JFrame("Restaurant Overview");
Container contentPane = frame.getContentPane();
JLabel paneHeader = new JLabel("Restaurant Monitoring System");
paneHeader.setBounds(200, 0, 200, 25);
paneHeader.setFont(new Font("Calibri", Font.BOLD, 14));
JLabel ipLabel = new JLabel("IP Address: ");
ipLabel.setBounds(25, 30, 75, 20);
ipLabel.setFont(new Font("Calibri", Font.PLAIN, 12));
final JTextArea ipArea = new JTextArea();
ipArea.setBorder(new LineBorder(Color.GRAY));
ipArea.setBounds(105, 30, 100, 20);
JLabel portLabel = new JLabel("Port Number: ");
portLabel.setBounds(25, 55, 75, 20);
portLabel.setFont(new Font("Calibri", Font.PLAIN, 12));
final JTextArea portArea = new JTextArea();
portArea.setBorder(new LineBorder(Color.GRAY));
portArea.setBounds(105, 55, 100, 20);
JButton newServer = new JButton("Create new Server");
newServer.setBorder(new LineBorder(Color.GRAY));
newServer.setBounds(250, 30, 150, 40);
newServer.setActionCommand("createserver");
newServer.addActionListener(this);
JTextArea outputLog = new JTextArea(" ");
outputLog.setBorder(new LineBorder(Color.GRAY));
outputLog.setBounds(25, 90, 150, 150);
//outputLog.setEditable(false);
JTextArea cashierLog = new JTextArea();
cashierLog.setBorder(new LineBorder(Color.GRAY));
cashierLog.setBounds(185, 90, 150, 150);
//cashierLog.setEditable(false);
JTextArea cookLog = new JTextArea();
cookLog.setBorder(new LineBorder(Color.GRAY));
cookLog.setBounds(345, 90, 150, 150);
//cookLog.setEditable(false);
contentPane.add(paneHeader);
contentPane.add(ipLabel);
contentPane.add(ipArea);
contentPane.add(portLabel);
contentPane.add(portArea);
contentPane.add(outputLog);
contentPane.add(cashierLog);
contentPane.add(cookLog);
contentPane.add(newServer);
frame.setLayout(null);
frame.pack();
frame.setSize(600,400);
frame.setVisible(true);
}
public void test() {
//ipAddress = ipArea.getText() + "\n";
//portNumber = portArea.getText() + "\n";
String text = "lemons";
//System.out.println(text);
outputLog.append(text);
//outputLog.append(portNumber);
}
public void actionPerformed(ActionEvent e) {
if ("createserver".equals(e.getActionCommand())) {
//test();
outputLog.append("lemons");
} else {
//Do Nothing
}
}
}
You are likely shadowing a variable -- declaring it more than once, but initializing a local variable not the class field, and so the class field remains null.
Edit:
Yep, sure enough you do. In your constructor you have
JTextArea outputLog = new JTextArea(" ");
This re-declares the outputLog variable, and so you are initializing only the variable local to the constructor. The solution is not to redeclare the variable but instead initialize the class field. So change the above to
outputLog = new JTextArea(" ");
You will need to do this for every variable that needs to be accessed in the class scope. For those that are OK to declare locally, do so, but in the sake of safety, get rid of their corresponding class declaration so as not to risk causing the same error in the future.
Your error is that the instance variable outputLog is not initialized.
your code not done on EDT, you have to wrap tht into invokeLater()
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
outputLog.setText(outputLog.getText()
+ System.getProperty("line.separator") + text);
}
});
Related
created login class for GUI, added all the GUI construction to a method so I can call it from my main class on startup. Calling method throws error "'GUILoginPage.this' cannot be referenced from a static context".
What are the work arounds for this? I understand the reasoning behind not being able to use .this but I haven't seen any solutions
public static void main() {
JFrame frame = new JFrame();
JButton loginButton = new JButton("Login");
JTextField userIDField = new JTextField();
JPasswordField userPasswordField = new JPasswordField();
JLabel userIDLabel = new JLabel("Username:");
JLabel userPasswordLabel = new JLabel("Password:");
userIDLabel.setBounds(50, 100, 75, 25);
userPasswordLabel.setBounds(50, 150, 75, 25);
userIDField.setBounds(125, 100, 200, 25);
userPasswordField.setBounds(125, 150, 200, 25);
loginButton.setBounds(125, 200, 100, 25);
loginButton.addActionListener(this);
frame.add(userIDLabel);
frame.add(userPasswordLabel);
frame.add(userIDField);
frame.add(userPasswordField);
frame.add(loginButton);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLayout(null);
frame.setVisible(true);
}
this doesn't have any meaning in a static context. your main is Static so it means that there is no instance of a class to work with.
Here you will need to define and use your own action listener that will handle the button click, such as :
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
performLogin();
}
} );
I don't know a whole lot about programming so excuse my messy code, but I'm working on a little choice-based game and my action listeners are throwing a nasty NullPointerException. Let me know what the issue might be.
the error is
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
with a continued list of (Unknown Source) based lines
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class finalproj extends JFrame implements ActionListener
{
private static final int WIDTH = 800, HEIGHT = 800;
private static final Font STANDARD_FONT = new Font("Arial", Font.BOLD, 32);
private JButton startgame, next, endgame;
private JLabel startmenu, question;
private int chanceofdeath = 0;
private JRadioButton q1A, q1B, q1C, q2A, q2B, q2C, q3A, q3B, q3C, q4A, q4B, q4C,
q5A, q5B, q5C, q6A, q6B, q6C, q7A, q7B, q8C, q9A, q9B, q9C, q10A, q10B, q10C, q11A,
q11B, q11C, q12A, q12B, q12C, q13A, q13B, q13C, q14A, q14B, q14C, q15A, q15B, q15C;
public static void main(String[] args)
{
new finalproj();
}
public finalproj()
{
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(WIDTH, HEIGHT);
setTitle("The Wild, Wild West");
getContentPane().setBackground(Color.BLACK);
setLocationRelativeTo(null);
setResizable(false);
JLabel startmenu = new JLabel("");
startmenu.setSize(800, 100);
startmenu.setLocation(35, 100);
startmenu.setFont(STANDARD_FONT);
startmenu.setText("Howdy Pardner! Ready to enter the Wild West?!");
startmenu.setOpaque(true);
startmenu.setBackground(Color.BLACK);
startmenu.setForeground(Color.WHITE);
startmenu.setVisible(true);
JButton startgame = new JButton("press me");
startgame.setFont(new Font("Arial", Font.BOLD, 28));
startgame.setForeground(Color.BLACK);
startgame.setSize(600, 100);
startgame.setLocation(100, 300);
startgame.setVisible(true);
JButton next = new JButton("Continue");
next.setFont(new Font("Arial", Font.BOLD, 28));
next.setForeground(Color.BLACK);
next.setSize(600, 100);
next.setLocation(100, 300);
next.setFocusable(false);
next.setVisible(false);
JLabel question = new JLabel();
question.setFont(new Font("Arial", Font.BOLD, 28));
question.setForeground(Color.BLACK);
question.setSize(600, 100);
question.setLocation(100, 300);
question.setFocusable(false);
question.setVisible(false);
question.setText("AAAAA");
startgame.addActionListener(this);
add(startmenu);
add(startgame);
add(question);
add(next);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("press me"))
{
startmenu.setVisible(false);
}
You are using local variable with the name 'startmenu', while the field 'startmenu' is never assigned.
You should initialize it like this
startmenu = new JLabel("");
instead of
JLabel startmenu = new JLabel("");
The same thing should be done with other fields.
Let me advice you to use IDE highlighting, it will show you what field or variable you are looking at.
First of you declare a variable name with
private JLabel startmenu, question;
in your constructor, you are creating an object using
JLabel startmenu = new JLabel("");
this object scoope only in constructor, not outside the constructor.
so you need to insitalize value of startmenu using above statement.
this.startmenu = new JLabel("");
what to do. replace
JLabel startmenu = new JLabel("");
to
this.startmenu = new JLabel("");
I am currently designing a login screen, but I ran into a strange issue. I already designed my GUI with the help of swing, and it was time to make functional buttons. I wanted to test my login button and if it would take me to the frame I want, but it is unable to. I can set a JOptionPane.showMessageDialog for example, which works just fine, but I am unable to open another frame from the button. I tried with New JFrameName().setVisible(true), and also JFrameName test = new JFrameName(); test.setVisible(true);, but the methods show up in red. Here is my code.
package com.edu4java.swing.tutrial3;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginView {
public static void main(String[] args) {
JFrame frame = new JFrame("Bus Tour Booking System");
frame.setSize(300, 200);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel titleLabel = new JLabel("Bus Tour Booking System");
titleLabel.setBounds(70,15,150,25);
panel.add(titleLabel);
JLabel userLabel = new JLabel("Username: ");
userLabel.setBounds(30, 50, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(120, 50, 130, 25);
panel.add(userText);
JLabel passwordLabel = new JLabel("Password: ");
passwordLabel.setBounds(30, 80, 80, 25);
panel.add(passwordLabel);
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(120, 80, 130, 25);
panel.add(passwordText);
JButton loginButton = new JButton("login");
loginButton.setBounds(100, 125, 80, 25);
panel.add(loginButton);
ActionListener myButtonListener = new MyButtonListener();
loginButton.addActionListener(myButtonListener);
}
private static class MyButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
//can't access a new frame from here :(
}
}
}
I would be very grateful if someone could help me out, I read a lot on Stackoverflow and Reddit, but just can't find the solution. I am also new to Java, so that doesn't help a lot either :D. Thanks in advance!
P.S. As far as the actual functionality for the login screen, I am going to do that in a later stage.
This is your login class. I put the JFrame frame in the global scope, so you can manipulate it from the ButtonListener method. I also created a SomeFrame class, just to demonstrate the new JFrame that would be created when you click the button. When an action is performed(the button is clicked) a new object of SomeFrame is created. Since SomeFrame extends JFrame we can use the method setVisible() to a SomeFrame object. The SomeFrame frame appears and the LoginView is no longer visible.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginView {
public static JFrame frame = new JFrame("Bus Tour Booking System");
public static void main(String[] args) {
frame.setSize(300, 200);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel titleLabel = new JLabel("Bus Tour Booking System");
titleLabel.setBounds(70,15,150,25);
panel.add(titleLabel);
JLabel userLabel = new JLabel("Username: ");
userLabel.setBounds(30, 50, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(120, 50, 130, 25);
panel.add(userText);
JLabel passwordLabel = new JLabel("Password: ");
passwordLabel.setBounds(30, 80, 80, 25);
panel.add(passwordLabel);
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(120, 80, 130, 25);
panel.add(passwordText);
JButton loginButton = new JButton("login");
loginButton.setBounds(100, 125, 80, 25);
panel.add(loginButton);
ActionListener myButtonListener = new MyButtonListener();
loginButton.addActionListener(myButtonListener);
}
private static class MyButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
SomeFrame newFrame = new SomeFrame();
newFrame.setVisible(true);
frame.setVisible(false);
}
}
}
This is the SomeFrame class.
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SomeFrame extends JFrame {
public SomeFrame(){
super("something");
this.setSize(300, 200);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
this.add(panel);
this.setVisible(true);
}
}
I need to build a GUI that will allow users to enter basic details about themselves for a new patient form and have that information saved to a .txt file. This data should then be viewable at a later time, but I can't get the save button to work.
//Import packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
//Main class
public class PatientDetailsWindow{
//Declare variables
public JFrame frame1;
public JPanel panel;
public JButton btnSave, btnExit;
public JLabel lblFirstName, lblSurname, lblGender, lblDOB, lblSmoker, lblMedHistory, lblFSlash1, lblFSlash2, lblImage;
public JTextField txtFirstName, txtSurname, txtGender, txtSmoker, txtMedHistory, txtDOB1, txtDOB2, txtDOB3;
public Insets insets;
public JTextArea textArea = new JTextArea();
public static void main (String args[]){
new PatientDetailsWindow();
}
public PatientDetailsWindow(){
createFrame();
createLabels();
createTextFields();
createButtons();
}
//Create the frame
public void createFrame(){
frame1 = new JFrame ("Personal details");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setSize (600,600);
panel = new JPanel();
panel.setBackground(Color.gray);
panel.setBounds(0, 0, 600, 600);
panel.setLayout(null);
frame1.add(panel);
frame1.setVisible(true);
}
//Creating Labels
public void createLabels(){
lblFirstName = new JLabel ("First Name: ");
lblFirstName.setBounds(50, 50, 500, 20);
lblFirstName.setForeground(Color.blue);
panel.add (lblFirstName);
lblSurname = new JLabel ("Surname: ");
lblSurname.setBounds(50, 100, 500, 20);
lblSurname.setForeground(Color.blue);
panel.add (lblSurname);
lblGender = new JLabel ("Gender: ");
lblGender.setBounds(50, 150, 500, 20);
lblGender.setForeground(Color.blue);
panel.add (lblGender);
lblDOB = new JLabel ("Date of Birth: ");
lblDOB.setBounds(50, 200, 500, 20);
lblDOB.setForeground(Color.blue);
panel.add (lblDOB);
lblFSlash1 = new JLabel ("/");
lblFSlash1.setBounds(440, 200, 20, 20);
lblFSlash1.setForeground(Color.blue);
panel.add (lblFSlash1);
lblFSlash2 = new JLabel ("/");
lblFSlash2.setBounds(490, 200, 40, 20);
lblFSlash2.setForeground(Color.blue);
panel.add (lblFSlash2);
lblSmoker = new JLabel ("Are you a smoker? ");
lblSmoker.setBounds(50, 250, 500, 20);
lblSmoker.setForeground(Color.blue);
panel.add (lblSmoker);
lblMedHistory = new JLabel ("Any other previous medical history? ");
lblMedHistory.setBounds(50, 300, 500, 20);
lblMedHistory.setForeground(Color.blue);
panel.add (lblMedHistory);
/*ImageIcon image= new ImageIcon("heartandstethoscope.jpg");
JLabel lblImage = new JLabel(image);
panel.add(lblImage);
*/
}
//Creating Text Fields
public void createTextFields(){
txtFirstName = new JTextField (10);
txtFirstName.setBounds(400, 50, 100, 20);
txtFirstName.setForeground(Color.blue);
panel.add (txtFirstName);
txtSurname = new JTextField (10);
txtSurname.setBounds(400, 100, 100, 20);
txtSurname.setForeground(Color.blue);
panel.add (txtSurname);
txtGender = new JTextField (10);
txtGender.setBounds(400, 150, 100, 20);
txtGender.setForeground(Color.blue);
panel.add (txtGender);
txtDOB1 = new JTextField (2);
txtDOB1.setBounds(400, 200, 40, 20);
txtDOB1.setForeground(Color.blue);
panel.add (txtDOB1);
txtDOB2 = new JTextField (2);
txtDOB2.setBounds(450, 200, 40, 20);
txtDOB2.setForeground(Color.blue);
panel.add (txtDOB2);
txtDOB3 = new JTextField (4);
txtDOB3.setBounds(500, 200, 80, 20);
txtDOB3.setForeground(Color.blue);
panel.add (txtDOB3);
txtSmoker = new JTextField (3);
txtSmoker.setBounds(400, 250, 100, 20);
txtSmoker.setForeground(Color.blue);
panel.add (txtSmoker);
txtMedHistory = new JTextField (300);
txtMedHistory.setBounds(400, 300, 100, 60);
txtMedHistory.setForeground(Color.blue);
panel.add (txtMedHistory);
JScrollPane areaScrollPane = new JScrollPane(txtMedHistory);
areaScrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textArea.setBounds(400, 300, 100, 80);
JScrollPane scroll = new JScrollPane (textArea);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
textArea.setLineWrap(true);
textArea.setEditable(true);
textArea.setVisible(true);
panel.add(textArea);
}
//Creating buttons
public void createButtons(){
btnSave = new JButton ("Save");
btnSave.setBounds(130, 350, 100, 20);
btnSave.setForeground(Color.blue);
btnSave.addActionListener(new SaveHandler());
panel.add (btnSave);
btnSave.setVisible(true);
btnExit = new JButton ("Exit");
btnExit.setBounds(240, 350, 100, 20);
btnExit.setForeground(Color.blue);
btnExit.addActionListener(new ExitHandler());
panel.add (btnExit);
btnExit.setVisible(true);
}
class ExitHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showConfirmDialog(frame1,
"Are you sure you want to exit?", "Exit?",JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
System.out.println("EXIT SUCCESSFUL");
}
}
}
class SaveHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
try( PrintWriter out = new PrintWriter( "DetailsofPatient.txt" )){
out.println(txtFirstName.getText());
out.println(txtGender.getText());
out.println(txtDOB1.getText());
out.println(txtDOB2.getText());
out.println(txtDOB3.getText());
out.println(txtSmoker.getText());
out.println(txtMedHistory.getText());
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
System.out.println("Save successful");
}
}
}
Alright for starters, you didn't add an ActionListener to your save button, so you need to add it like this.
btnSave = new JButton ("Save");
btnSave.setBounds(130, 350, 100, 20);
btnSave.setForeground(Color.blue);
btnSave.addActionListener(new SaveHandler());
panel.add (btnSave);
btnSave.setVisible(true);
Also, in your SaveHandler, your PrintWriter isn't actually printing anything.
Your Code: out.println( ); would not write anything.
Let's say you wanted to write the contents of txtFirstName, you would need to do
out.println(txtFirstName.getText());
Edit: You also need another closing braces at the end of your ExitHandler class
class ExitHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showConfirmDialog(frame1,
"Are you sure you want to exit?", "Exit?",JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
System.out.println("EXIT SUCCESSFUL");
}
}
}
You will also then need to remove a closing brace at the end of the program.
This is the source code for my calculator that i am building in eclipse windowbuilder, i am trying to make two textFields read input and output the area for a simple rectangle, i can type the numbers into the boxes however the numbers do not compute and i am at a loss as to what i could be doing wrong, please critique my code and let me know why it isn't working. Thank you
*Edit, i have removed and changed a few things and now the Answer box displays 0.0 and nothing else
import java.awt.EventQueue;
public class GUI {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 694, 499);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
tabbedPane.addTab("New tab", null, panel, null);
panel.setLayout(null);
JLabel lblInputBase = new JLabel("Input Base");
lblInputBase.setBounds(0, 0, 57, 39);
panel.add(lblInputBase);
textField = new JTextField();
textField.setBounds(0, 28, 86, 20);
panel.add(textField);
textField.setColumns(10);
double value = Double.parseDouble(textField.getText());
JLabel lblInputHeight = new JLabel("Input Height");
lblInputHeight.setBounds(0, 212, 68, 20);
panel.add(lblInputHeight);
textField_1 = new JTextField();
textField_1.setBounds(0, 230, 86, 20);
panel.add(textField_1);
textField_1.setColumns(10);
double value_1 = Double.parseDouble(textField_1.getText());
double Area = value*value_1;
String finalArea = Double.toString(Area);
JLabel lblArea = new JLabel("Area:");
lblArea.setBounds(244, 119, 75, 68);
panel.add(lblArea);
textField_2 = new JTextField();
textField_2.setBounds(273, 143, 86, 20);
panel.add(textField_2);
textField_2.setColumns(10);
textField_2.setEditable(false);
textField_2.setText(finalArea);
}
}
Your code is really confusing, but here are some problems that I found:
double value = Double.parseDouble(textField.getText());
This is being run before the user has any chance to even look at the gui. textField.getText() will return an empty string here, and the parseDouble method will always throw a NumberFormatException when the program is run, as it does not consider an empty string to be a valid number format.
double Area = Double.parseDouble(value)*Double.parseDouble(value_1);
Here, the variable value is already a double and does not need to be parsed, and the variable value_1 doesn't exist.
Where you meant to assign an actionListener to textField_1, you assigned a second one to textField.
Overall, it seems that all your calculation logic is being run in your initialize() method, and this means that it is only being run once. You'll want your math to be run whenever one of the text fields is updated.
Your field names are horribly confusing. Your textField variable names should give some indication of their function, like areaTextField, baseTextField, heightTextField.
Here is a modification of your code that seems to function as you intended yours to function. Note the addition of a calculate() method that is called by the action listeners that will find the area and display it, or display NaN (Not a Number) if either of the input fields are not valid numbers. All of your GUI code is retained as is, excepting the renaming of the text field variables.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
public class GUI {
private JFrame frame;
private JTextField baseTextField;
private JTextField heightTextField;
private JTextField areaTextField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 694, 499);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
tabbedPane.addTab("New tab", null, panel, null);
panel.setLayout(null);
JLabel lblInputBase = new JLabel("Input Base");
lblInputBase.setBounds(0, 0, 57, 39);
panel.add(lblInputBase);
baseTextField = new JTextField();
baseTextField.setBounds(0, 28, 86, 20);
panel.add(baseTextField);
baseTextField.setColumns(20);
baseTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
calculate();
}
});
JLabel lblInputHeight = new JLabel("Input Height");
lblInputHeight.setBounds(0, 212, 68, 20);
panel.add(lblInputHeight);
heightTextField = new JTextField();
heightTextField.setBounds(0, 230, 86, 20);
panel.add(heightTextField);
heightTextField.setColumns(20);
heightTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
calculate();
}
});
JLabel lblArea = new JLabel("Area:");
lblArea.setBounds(244, 119, 75, 68);
panel.add(lblArea);
areaTextField = new JTextField();
areaTextField.setBounds(273, 143, 86, 20);
panel.add(areaTextField);
areaTextField.setColumns(20);
areaTextField.setEditable(false);
}
private void calculate() {
try {
double base = Double.parseDouble(baseTextField.getText());
double height = Double.parseDouble(heightTextField.getText());
double area = base * height;
areaTextField.setText(String.format("%.4f", area));
} catch (NumberFormatException e) {
areaTextField.setText("NaN");
}
}
}
Note that you need to hit the enter key in one of the two fields to update the area field. That is what it takes to trigger the ActionListener for a JTextField.