Area Calculator not working and not sure why - java

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.

Related

calling a JPanel from another JPanel in a window

I have a login and a register panel and a window to hold all the panels. What I am trying to do is to go to the login panel when the register button is pressed. But it does not work. The method that I use would work if the login panel is inside the window but when it is in its own class it doesn't. Can someone please let me know how to do this?
Here is my code for the Window
package userInterface;
import java.awt.*;
import java.awt.EventQueue;
import java.sql.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import company.CompanySys;
import javax.swing.*;
import java.awt.CardLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
public class FrontEnd {
/**
* Variables
*/
// System
CompanySys sys = CompanySys.getSystem();
private static FrontEnd front = new FrontEnd();
private JFrame frame;
private final JLayeredPane layeredPane = new JLayeredPane();
public final RegisterPanel registerPan = new RegisterPanel();
public final LoginPanel loginPan = new LoginPanel();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrontEnd window = new FrontEnd();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
private FrontEnd() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
this.setFrame();
this.setLayout();
this.addPanels();
}
/**
* Setting up the main frame
*/
private void setFrame() {
frame = new JFrame();
frame.setBounds(100, 100, 900, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
layeredPane.setBounds(0, 0, 900, 700);
frame.getContentPane().add(layeredPane);
layeredPane.setLayout(new CardLayout(0, 0));
}
/**
* Setting Layout
*/
public void setLayout() {
// frame.getContentPane().add(layeredPane, "name_2578740971832500");
// layeredPane.setLayout(new CardLayout(0, 0));
}
public void SetSizeandLocation() {
this.registerPan.setBounds(10, 10, 900, 700);
layeredPane.setLayer(loginPan, 0);
this.loginPan.setBounds(10, 10, 900, 700);
}
/**
* Set visibility of the components
*/
private void setVisibility() {
// this.registerPan.setVisible(true);
// this.loginPan.setVisible(true);
}
/**
* Adding panels to the window
*/
private void addPanels() {
layeredPane.add(registerPan);
layeredPane.add(loginPan);
}
public static FrontEnd getFront() {
return front;
}
/**
* Switching Panels
* #param panel
*/
public void switchPanels(JPanel panel) {
layeredPane.removeAll();
layeredPane.add(panel);
layeredPane.repaint();
layeredPane.revalidate();
}
public LoginPanel getLoginPan() {
return this.loginPan;
}
}
Here is the code for Register Panel
package userInterface;
import company.*;
import javax.swing.*;
import java.awt.event.*;
public class RegisterPanel extends JPanel implements ActionListener{
/**
* Variables
*/
// System
CompanySys sys = CompanySys.getSystem();
FrontEnd front = FrontEnd.getFront();
// Input fields
private JTextField usernameTextField = new JTextField();
private JPasswordField passwordField1 = new JPasswordField();
private JPasswordField passwordField2 = new JPasswordField();
// Labels
private JLabel usernameLabel = new JLabel("Username");
private JLabel password1Label = new JLabel("Password");
private JLabel password2Label = new JLabel("Password");
// Buttons
private JButton registerButton = new JButton("REGISTER");
private JButton cancelButton = new JButton("CANCEL");
private JButton haveAccount = new JButton("Already have an account? Login");
private JButton clearButton = new JButton("CLEAR");
// Others
private JCheckBox showPasswordCheckBox = new JCheckBox("Show Password");
/**
* Create the panel.
*/
public RegisterPanel() {
setLayout(null);
this.addComponents();
this.setSizeandLocations();
this.addActionEvent();
}
/**
* Methods
*/
// Set size and location of the components
public void setSizeandLocations() {
// Labels
usernameLabel.setBounds(312, 106, 64, 14);
password1Label.setBounds(324, 175, 64, 14);
password2Label.setBounds(312, 237, 64, 14);
// Input Fields
usernameTextField.setBounds(493, 103, 96, 20);
passwordField1.setBounds(493, 173, 97, 17);
passwordField2.setBounds(494, 234, 96, 20);
passwordField1.setEchoChar('*');
passwordField2.setEchoChar('*');
//Buttons
registerButton.setBounds(337, 301, 89, 23);
cancelButton.setBounds(479, 301, 89, 23);
haveAccount.setBounds(366, 363, 196, 23);
clearButton.setBounds(606, 301, 89, 23);
// Others
showPasswordCheckBox.setBounds(493, 261, 141, 23);
}
// Add all components to the panel
public void addComponents() {
// Add Labels
add(usernameLabel);
add(password1Label);
add(password2Label);
// Add input fields
add(usernameTextField);
add(passwordField1);
add(passwordField2);
// Add Buttons
add(registerButton);
add(cancelButton);
add(haveAccount);
add(clearButton);
// Others
add(showPasswordCheckBox);
}
/**
* Adding Action listener
*/
public void addActionEvent() {
this.registerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
front.switchPanels(front.getLoginPan());
}
});
this.cancelButton.addActionListener(this);
this.haveAccount.addActionListener(this);
this.clearButton.addActionListener(this);
this.showPasswordCheckBox.addActionListener(this);
}
/**
* Main method of the panel
* #param args
*/
public static void main(String args[]) {
RegisterPanel frame = new RegisterPanel();
frame.setVisible(true);
frame.setBounds(10, 10, 900, 500);
}
/**
* Adding the functionality to the components
*/
#Override
public void actionPerformed(ActionEvent e) {
String usr = this.usernameTextField.getText();
String pass1 = String.valueOf(this.passwordField1.getPassword());
String pass2 = String.valueOf(this.passwordField2.getPassword());
// if (e.getSource() == this.registerButton) {
// if (sys.register(usr, pass1, pass2)) {
// // JOptionPane.showConfirmDialog(null, "Success", getName(), JOptionPane.DEFAULT_OPTION);
//
// front.switchPanels(front.getLoginPan());
// }
// else {
// JOptionPane.showConfirmDialog(null, "fail", getName(), JOptionPane.DEFAULT_OPTION);
// }
// }
if (e.getSource() == this.cancelButton) {
}
else if (e.getSource() == this.haveAccount) {
}
else if (e.getSource() == this.showPasswordCheckBox) {
if(this.showPasswordCheckBox.isSelected()) {
this.passwordField1.setEchoChar((char) 0);
this.passwordField2.setEchoChar((char) 0);
}
else {
this.passwordField1.setEchoChar('*');
this.passwordField2.setEchoChar('*');
}
}
else if (e.getSource() == this.clearButton) {
this.passwordField1.setText("");
this.passwordField2.setText("");
this.usernameTextField.setText("");
}
}
}
Here is code for login panel
package userInterface;
import company.CompanySys;
import javax.swing.*;
import java.awt.event.*;
public class LoginPanel extends JPanel implements ActionListener{
/**
* Variables
*/
// System
CompanySys sys = CompanySys.getSystem();
// Fields
private JTextField userNameTextField = new JTextField();;
private JPasswordField passwordField = new JPasswordField();;
// Labels
JLabel userNameLabel = new JLabel("Username");
JLabel passwordLabel = new JLabel("Password");
// Buttons
JButton cancelButton = new JButton("CANCEL");
JButton loginButton = new JButton("LOGIN");
JButton noAccountButton = new JButton("Don't have an acount? register");
JButton clearButton = new JButton("CLEAR");
// Others
JCheckBox showPassCheckBox = new JCheckBox("Show Password");
/**
* Constructor
*/
public LoginPanel() {
setLayout(null);
this.setSizeAndLocation();
this.addComponent();
this.addAction();
}
/**
* Setting size and location of the components
*/
public void setSizeAndLocation() {
// Labels
userNameLabel.setBounds(97, 52, 69, 14);
passwordLabel.setBounds(97, 88, 48, 14);
// TextFields
passwordField.setBounds(197, 85, 103, 20);
userNameTextField.setBounds(197, 49, 96, 20);
// Buttons
clearButton.setBounds(325, 146, 89, 23);
noAccountButton.setBounds(85, 196, 208, 23);
cancelButton.setBounds(209, 146, 89, 23);
loginButton.setBounds(85, 146, 89, 23);
// Others
showPassCheckBox.setBounds(197, 116, 130, 23);
}
/**
* Adding components to the Panel
*/
public void addComponent() {
// Labels
this.add(userNameLabel);
this.add(passwordLabel);
// TextFields
this.add(userNameTextField);
this.add(passwordField);
// Buttons
this.add(loginButton);
this.add(cancelButton);
this.add(noAccountButton);
this.add(clearButton);
// Others
this.add(showPassCheckBox);
}
/**
* Adding ActionListener to the interactive components
*/
public void addAction() {
// Buttons
this.clearButton.addActionListener(this);
this.cancelButton.addActionListener(this);
this.loginButton.addActionListener(this);
this.noAccountButton.addActionListener(this);
// Others
this.showPassCheckBox.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
}
public static void main(String args[]) {
LoginPanel frame = new LoginPanel();
frame.setVisible(true);
frame.setBounds(10, 10, 900, 700);
}
}
I have tried other ways too but it doesnt work!

How do I make my JPasswordField use a specific password?

Hello Guys I need a password that I want to be writen in the JPasswordField
(JPasswordFieldAnon) and attach submit action to the two JButtons
(AnonButton and AnonButton1).
Here is the code:
package javafx;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class Anonymous {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Anonymous window = new Anonymous();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Anonymous() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setTitle("Anonymous Terminal. Enter Password");
frame.setResizable(false);
frame.setVisible(true);
frame.setSize(952, 785);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel JLabelAnon = new JLabel("We are Anonymous. We are Legion. We do not forgive. We do not forget. Expect Us.");
JLabelAnon.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
JLabelAnon.setBackground(Color.BLACK);
JLabelAnon.setFont(new Font("hooge 05_53", Font.PLAIN, 13));
JLabelAnon.setForeground(Color.GREEN);
JLabelAnon.setBounds(116, 566, 695, 14);
frame.getContentPane().add(JLabelAnon);
JPasswordField JPasswordFieldAnon = new JPasswordField("Enter Password: ", 1);
JPasswordFieldAnon.setBackground(new Color(0, 128, 0));
JPasswordFieldAnon.setToolTipText("Enter Password\r\n");
JPasswordFieldAnon.setText("");
JPasswordFieldAnon.setName("Anonymous Password");
JPasswordFieldAnon.setBounds(367, 535, 206, 22);
frame.getContentPane().add(JPasswordFieldAnon);
JButton AnonButton = new JButton("Expect Us!");
AnonButton.setBackground(new Color(34, 139, 34));
AnonButton.setName("Log In");
AnonButton.setBounds(579, 535, 115, 22);
frame.getContentPane().add(AnonButton);
JButton AnonButton1 = new JButton("Expect Us!");
AnonButton1.setName("Log In");
AnonButton1.setBackground(new Color(34, 139, 34));
AnonButton1.setBounds(246, 535, 115, 22);
frame.getContentPane().add(AnonButton1);
JTextPane textPane1 = new JTextPane();
textPane1.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
textPane1.setEditable(false);
textPane1.setBackground(Color.BLACK);
textPane1.setBounds(108, 563, 703, 20);
frame.getContentPane().add(textPane1);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setIcon(new ImageIcon("F:\\FBI-Terminal_1.png"));
lblNewLabel.setBounds(0, 0, 948, 759);
frame.getContentPane().add(lblNewLabel);
}
public void actionPerformed(ActionEvent e) {
}
}
My problem is that I tried around 5 days now just trying a lot methods...
Some notes about your code.
Your password field variable does not have scope enough to retrieve the typed password later because it's a local variable within initialize() method. I'd define it as a class variable.
You have to attach an ActionListener to the buttons to actually "submit" the password.
You have an actionPerformed() method but the implementation of ActionListener interface is missing in your class header. This is why we should use #Override annotation when we implement or override existing methods.
See these tutorials:
How to Use Buttons
How to Use Password Fields
Variables (about different variable scopes)
Off-topic
Swing is designed to work with Layout Managers. and the use of methods such as setLocation(...), setBounds(...) or setXxxSize(...) is highly discouraged.

How to use a text area?

I m creating a GUI in java and would like to use a JTextArea, however I am having a lot of trouble adding it to the frame. How would I go about creating a text Area and then using it to read text or display text?
Here is my GUI code so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class addMemoUI extends JFrame {
JFrame frame = new JFrame();
/**
* Create the application.
*/
public addMemoUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame.getContentPane().setBackground(new Color(255, 255, 255));
frame.getContentPane().setLayout(null);
JButton button = new JButton("Create");
button.setBackground(new Color(100, 149, 237));
button.setBounds(135, 350, 130, 50);
frame.getContentPane().add(button);
JLabel lblMemos = new JLabel("MEMOS");
lblMemos.setForeground(new Color(100, 149, 237));
lblMemos.setFont(new Font("Moire", Font.BOLD, 30));
lblMemos.setBounds(22, 21, 234, 37);
frame.getContentPane().add(lblMemos);
JButton button_1 = new JButton("Cancel");
button_1.setBackground(new Color(100, 149, 237));
button_1.setBounds(5, 350, 130, 50);
frame.getContentPane().add(button_1);
frame.setBounds(100, 100, 270, 400);
frame.setUndecorated(true); //REMOVES MENU BAR
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnExit = new JButton("");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MemoUI window = new MemoUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Thanks very much :)
Here is example for how to use JTextArea. You can set, get or append text. You can find the others by google.
public class Example {
private JTextArea jtextbox;
private void initialize() {
JFrame frm = new JFrame();
:
JScrollPane scroll = new JScrollPane();
jtextbox= new JTextArea();
scroll.setViewportView(jtextbox); // add scroll panel
jtextbox.setTabSize(4);
jtextbox.setLineWrap(true);
jtextbox.setBackground(SystemColor.window);
}
private void setText(String text) {
jtextbox.append(text); // or setText(text)
}
private String getText() {
return jtextbox.getText();
}
}

create your own swing component

A software component is required which allows to find a given word in a given passage, whenever the component find the desired word in the passage the components will invoke all the listener that are attached to it that it has find the desired word.
This component must be used from a Swing UI based application showing user a text field to take a word and a text area for passage. There must be a label which will update its value showing count that how many times the given word has been found within the given passage.
this is my code it's displya gui but count field is not changed or set.
import java.awt.EventQueue;
public class compomentex implements ActionListener{
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
compomentex window = new compomentex();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public interface wordsearcherinterface
{
public void wordsearch();
}
public class wordsearcher implements wordsearcherinterface
{
public String word;
public String paragraph;
public void addwordsearch(wordsearcherinterface obj)
{
obj.wordsearch();
}
public void wordsearch()
{
//if(event.getSource()==Check)
String word;
String Words;
String [] Words2;
int disp=0;
word=textField.getText();
Words=textArea.getText();
Words2=Words.split(" ");
for(int i=0;i<Words2.length;i++)
{
if(Words2[i].equals(word))
{
disp++;
}
}
String show;
show=disp+"";
textField_1.setText(show);
if(disp==0)
{
JOptionPane.showMessageDialog(null, "The Word is not present int Passage");
}
}
}
* Create the application.
public compomentex() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblWord = new JLabel("WORD");
lblWord.setBounds(29, 81, 46, 14);
frame.getContentPane().add(lblWord);
textField = new JTextField();
textField.setBounds(121, 78, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblPassage = new JLabel("PASSAGE");
lblPassage.setBounds(29, 143, 46, 14);
frame.getContentPane().add(lblPassage);
JTextArea textArea = new JTextArea();
textArea.setBounds(97, 161, 196, 90);
frame.getContentPane().add(textArea);
JButton btnCheck = new JButton("CHECK");
btnCheck.setBounds(326, 213, 98, 23);
frame.getContentPane().add(btnCheck);
JLabel lblSeeker = new JLabel("SEEKER");
lblSeeker.setBounds(161, 11, 46, 14);
frame.getContentPane().add(lblSeeker);
JLabel lblCount = new JLabel("COUNT");
lblCount.setBounds(349, 81, 46, 14);
frame.getContentPane().add(lblCount);
textField_1 = new JTextField();
textField_1.setBounds(325, 106, 86, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
Thanks in advance
There are lots of issues in your code. I have mentioned corrected code below. Please correct.
First - actionPerformed method is empty.
#Override
public void actionPerformed(ActionEvent arg0) {
new wordsearcher().wordsearch();
}
Second - instance variable textArea is not initialized.
textArea = new JTextArea();
Third - ActionListener is not added on button btnCheck
btnCheck.addActionListener(this);

Appending text to a JTextArea on button press?

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);
}
});

Categories