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);
Related
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!
I'm trying to filter data in my array list according to my comboBox selected item wise. I still can't solve this problem.
public class FoodItem {
private String name;
private String type;
public FoodItem(String n,String t){
name=n;
type=t;
}
public String getType(){
return type;
}
public String getName(){
return name;
}
}
sample.java
<code>
public class A2Demo extends JFrame {
private JPanel contentPane;
private JTextField txtName;
List listFoodItem = new List();
JComboBox comboType = new JComboBox();
FoodItem[] foodItems;
private final JTextField txtBudget = new JTextField();
private final JButton btnBudget = new JButton("Search Budget");
private final JTextField textField = new JTextField();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
A2Demo frame = new A2Demo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public A2Demo() {
textField.setBounds(93, 247, 134, 28);
textField.setColumns(10);
txtBudget.setBounds(183, 11, 86, 20);
txtBudget.setColumns(10);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 334);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
foodItems=new FoodItem[2];
foodItems[0]=new FoodItem("Chicken Cutlet","Main");
foodItems[1]=new FoodItem("Chendol","Dessert");
comboType.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
comboType.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
JOptionPane.showMessageDialog(null,comboType.getSelectedItem());
}
});
comboType.setBounds(32, 11, 93, 20);
contentPane.add(comboType);
for(int i=0; i<foodItems.length; i++)
comboType.addItem(foodItems[i].getType());
listFoodItem.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
txtName.setText(listFoodItem.getSelectedItem());
}
});
listFoodItem.setBounds(37, 63, 330, 125);
contentPane.add(listFoodItem);
JLabel lblName = new JLabel("Name");
lblName.setBounds(37, 217, 46, 14);
contentPane.add(lblName);
txtName = new JTextField();
txtName.setBounds(93, 214, 134, 20);
contentPane.add(txtName);
txtName.setColumns(10);
contentPane.add(txtBudget);
btnBudget.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, comboType.getSelectedItem()+ " "+txtBudget.getText());
}
});
btnBudget.setBounds(280, 10, 127, 23);
contentPane.add(btnBudget);
contentPane.add(textField);
}
}
i want to display food name in the list. but combobox changeing to different type my list need to change according l
public class Sort_BenchMark extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnBubbleSort;
private JLabel label_1;
private JButton btnGenerate;
private JButton btnSelectionSort;
private JLabel lblSs;
private JLabel lblStatus;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
Sort_BenchMark frame = new Sort_BenchMark();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Sort_BenchMark()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField("Enter ");
textField.setForeground(Color.GRAY);
textField.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
}
#Override
public void focusGained(FocusEvent e) {
textField.setText("");
textField.setForeground(Color.BLACK);
}
});
textField.setBounds(29, 30, 139, 20);
contentPane.add(textField);
textField.setColumns(10);
label_1 = new JLabel("");
label_1.setBounds(334, 20, 120, 30);
contentPane.add(label_1);
btnBubbleSort = new JButton("Bubble Sort");
btnBubbleSort.setBounds(204, 20, 120, 30);
contentPane.add(btnBubbleSort);
btnSelectionSort = new JButton("Selection Sort");
btnSelectionSort.setBounds(204, 70, 120, 30);
contentPane.add(btnSelectionSort);
lblSs = new JLabel("");
lblSs.setBounds(334, 70, 120, 30);
contentPane.add(lblSs);
lblStatus = new JLabel("");
lblStatus.setBounds(75, 87, 93, 23);
contentPane.add(lblStatus);
final JRadioButton rdbtnAvgCase = new JRadioButton("Avg Case");
rdbtnAvgCase.setBounds(29, 150, 109, 23);
contentPane.add(rdbtnAvgCase);
ButtonGroup b = new ButtonGroup();
b.add(rdbtnAvgCase);
btnGenerate = new JButton("Generate");
btnGenerate.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
btnBubbleSort.setEnabled(true);
btnSelectionSort.setEnabled(true);
final String s = textField.getText();
if(s.contentEquals(""))
{
lblStatus.setText("Enter length");
}
else
{
lblStatus.setText("Ready");
if(rdbtnAvgCase.isSelected())
{
btnBubbleSort.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Thread t1 = new Thread(new Runnable()
{
#Override
public void run()
{
btnBubbleSort.setEnabled(false);
label_1.setText("done");
btnBubbleSort.setEnabled(true);
}
});
t1.start();
}
});
btnSelectionSort.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Thread t3 = new Thread(new Runnable()
{
#Override
public void run()
{
btnSelectionSort.setEnabled(false);
lblSs.setText("done");
btnSelectionSort.setEnabled(true);
}
});
t3.start();
}
});
}
}
}
});
btnGenerate.setBounds(64, 62, 88, 25);
contentPane.add(btnGenerate);
}
}
The above code is about Swing.
The actual code how i designed is:-(In the frame)
Select the Average Case (RadioButton)
Enter any number in textfield (Enter)
click on generate
click on any sort button(Bubble Sort and Selection Sort)
Now, whats the problem is, If I click on BubbleSort the text field gets cleared. But it should not happen as per I designed. Can anyone suggest me the solution so that text field wont get clear after entered anything in it?
These lines here:
#Override
public void focusGained(FocusEvent e) {
textField.setText(""); //HERE
textField.setForeground(Color.BLACK);
}
in the focus listener code says that when you click in the textfield then set its text to a empty string.
Firstly, horrible nested ActionPerformed you've got there.
That aside, Vincent Ramdhanie is right as to where the problem is originating. The reason why it only happens when you click a certain button, is because when you disable a button, then it cannot have focus, which forces the focus to be on something else, which in the disable-btnBubbleSort's case, appears to be your textfield.
Instead of btnSelectionSort.setEnabled(false) and btnSelectionSort.setEnabled(true), try using setVisible(false) and setVisible(true).
If that doesn't work, drop the onfocus-part, and do something with a mouse-click event instead.
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();
}
}
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.