Comparing two JTextFields with an ActionListener - java

what I am trying to do is compare two inputs from TextFields within a JFrame using an ActionListener. If the two inputs are equal and the user hits the button, a MessageDialog will pop up and say "equal". If they are not equal, a MessageDialog will pop up and say "not equal". I have the frame and ActionListener running, I just do not know how to take the inputs from the TextFields and compare them.
For example, if the user enters something like this,
Equal TextFields, this will pop up, Equal Message
Here is my Main Class:
public class LabFiveOne
{
public static void main(String[] args)
{
JFrame frame = new JFrame("String Equality Program");
JTextField tf1 = new JTextField(10);
tf1.setActionCommand(tf1.toString());
tfListener tfListen = new tfListener(tf1);
JTextField tf2 = new JTextField(10);
tf2.setActionCommand(tf2.toString());
JButton chEq = new JButton("Check Equality");
chEq.addActionListener(tfListen);
JPanel nPanel = new JPanel();
nPanel.add(tf1);
nPanel.add(tf2);
frame.add(nPanel, BorderLayout.NORTH);
JPanel sPanel = new JPanel();
sPanel.add(chEq);
frame.add(sPanel, BorderLayout.SOUTH);
nPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
And here is my ActionListener Class:
class tfListener implements ActionListener
{
private final JTextField tf3;
public tfListener(JTextField nameTF)
{
tf3 = nameTF;
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("abc"))
{
JOptionPane.showMessageDialog(null, "equal");
}
else
{
JOptionPane.showMessageDialog(null, "not equal");
}
}
}

EDIT: ok than try to change the constructor in your ActionListener Class to
public tfListener(JTextField tf1, JTextField tf2){
{
Hi :) just don't overthink and you should be fine. The simple way would be to implement the ActionListener directly to your Main Class like this:
public class LabFiveOne
{
public static void main(String[] args)
{
JFrame frame = new JFrame("String Equality Program");
final JTextField tf1 = new JTextField(10);
tf1.setActionCommand(tf1.toString());
tfListener tfListen = new tfListener(tf1);
final JTextField tf2 = new JTextField(10);
tf2.setActionCommand(tf2.toString());
JButton chEq = new JButton("Check Equality");
chEq.addActionListener(tfListen);
JPanel nPanel = new JPanel();
nPanel.add(tf1);
nPanel.add(tf2);
frame.add(nPanel, BorderLayout.NORTH);
JPanel sPanel = new JPanel();
sPanel.add(chEq);
frame.add(sPanel, BorderLayout.SOUTH);
nPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
{
class tfListener implements ActionListener
{
private final String tf1text;
private final String tf2text;
public tfListener(JTextField tf1, JTextField tf2)
{
tf1text = new String(tf1.getText());
tf1text = new String(tf2.getText());
}
#Override
public void actionPerformed(ActionEvent e)
{
if(tf1text.equal(tf2text))
{
JOptionPane.showMessageDialog(null, "equal");
}
else
{
JOptionPane.showMessageDialog(null, "not equal");
}
}
}
}

tf1.toString();
Shows you some information from the JTextField.
use another methods to get your input from the field. I mean it's the method:
tfi.getText();
Better look in a JTextField javadoc

To be honest with you, I don't think you need two classes; one for implementing the GUI and one for handling the ActionListener when you can have everything in one class like the class below
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
public class LabFiveOne implements ActionListener
{
private JFrame frame;
private JPanel nPanel, sPanel;
private JTextField tf1, tf2;
private JButton chEq;
public static void main(String[] args)
{
new LabFiveOne();
}
public LabFiveOne(){
frame = new JFrame("String Equality Program");
tf1 = new JTextField(10);
tf2 = new JTextField(10);
chEq = new JButton("Check Equality");
chEq.addActionListener(this);
nPanel = new JPanel();
nPanel.add(tf1);
nPanel.add(tf2);
frame.add(nPanel, BorderLayout.NORTH);
sPanel = new JPanel();
sPanel.add(chEq);
frame.add(sPanel, BorderLayout.SOUTH);
nPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String action = e.getActionCommand();
if(action.equals("Check Equality")){
String number1 = tf1.getText();
String number2 = tf2.getText();
int num1 = Integer.valueOf(number1);
int num2 = Integer.valueOf(number2);
if(num1 == num2){
JOptionPane.showMessageDialog(null, "Equal");
}
else{
JOptionPane.showMessageDialog(null, "Not Equal");
}
}
}
}
I have everything declared globally so that the ActionPerformed method will have access the values in the Textfields.

Related

How can I transfer data between one jframe to another jframe?

I'm new to java and for some reason I don't know any other way to transfer the data from another frame after pressing submit. For example, it will show the output frame the label and textfield that the user wrote in the first frame like this "Name: "user's name". If you do know please post the code I should put, thank you!
package eventdriven;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventDriven extends JFrame {
JPanel items = new JPanel();
JLabel fName = new JLabel("First Name: ");
JLabel lName = new JLabel("Last Name: ");
JLabel mName = new JLabel("Middle Name: ");
JLabel mNum = new JLabel("Mobile Number: ");
JLabel eAdd = new JLabel("Email Address: ");
JTextField fname = new JTextField(15);
JTextField lname = new JTextField(15);
JTextField mname = new JTextField(15);
JTextField mnum = new JTextField(15);
JTextField eadd = new JTextField(15);
JButton submit = new JButton("Submit");
JButton clear = new JButton("Clear All");
JButton okay = new JButton("Okay");
JTextArea infos;
JFrame output;
public EventDriven()
{
this.setTitle("INPUT");
this.setResizable(false);
this.setSize(230, 300);
this.setLocation(300, 300);
this.setLayout(new FlowLayout(FlowLayout.CENTER));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(fName);
this.add(fname);
this.add(lName);
this.add(lname);
this.add(mName);
this.add(mname);
this.add(mNum);
this.add(mnum);
this.add(eAdd);
this.add(eadd);
submit.addActionListener(new btnSubmit());
this.add(submit);
clear.addActionListener(new btnClearAll());
this.add(clear);
okay.addActionListener(new btnOkay());
this.add(items);
this.setVisible(true);
}
class btnSubmit implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == submit)
{
submit.setEnabled(false);
output = new JFrame("OUTPUT");
output.show();
output.setSize(300,280);
output.setTitle("OUTPUT");
output.add(okay);
output.setLayout(new FlowLayout(FlowLayout.CENTER));
}
}
}
class btnClearAll implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == clear)
{
fname.setText(null);
lname.setText(null);
mname.setText(null);
mnum.setText(null);
eadd.setText(null);
submit.setEnabled(true);
output.dispose();
}
}
}
class btnOkay implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == okay)
{
fname.setText(null);
lname.setText(null);
mname.setText(null);
mnum.setText(null);
eadd.setText(null);
submit.setEnabled(true);
output.dispose();
}
}
}
public static void main(String[] args)
{
EventDriven window = new EventDriven();
}
}
It's not clear what problem you are having displaying a value from one field in another frame. But here's an example of doing that (with fields reduced to just one for demonstration):
public class EventDriven extends JFrame {
private final JTextField nameField = new JTextField(15);
private final JButton submit = new JButton("Submit");
private final JButton clear = new JButton("Clear All");
public EventDriven() {
setTitle("Input");
setLayout(new FlowLayout(FlowLayout.CENTER));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JLabel("Name: "));
add(nameField);
submit.addActionListener(this::showOutput);
add(submit);
clear.addActionListener(this::clearInput);
add(clear);
pack();
}
private void showOutput(ActionEvent ev) {
submit.setEnabled(false);
JDialog output = new JDialog(EventDriven.this, "Output", true);
output.add(new Label("Name: " + nameField.getText()), BorderLayout.CENTER);
JButton okButton = new JButton("OK");
output.add(okButton, BorderLayout.SOUTH);
okButton.addActionListener(bv -> output.setVisible(false));
output.pack();
output.setVisible(true);
}
private void clearInput(ActionEvent ev) {
nameField.setText(null);
submit.setEnabled(true);
}
public static void main(String[] args) {
EventDriven window = new EventDriven();
window.setVisible(true);
}
}
You will also see that I've simplified your action listeners to demonstrate an easier way to respond to user driven event.s

formatting JTextfields using another class

this is the code of the Gui Design class and below is the Class that provides functionality to the program. Im trying to get user input from the textfields so i can remove the text using the clearAll method and also save user input using the saveit method.I tried using nameEntry.setText(""); in the clearAll method but it wont work can someone help me please!
//Import Statements
import javax.swing.*;
import java.awt.*;
import javax.swing.JOptionPane;
import java.awt.event.*;
//Class Name
public class Customer extends JFrame {
Function fun = new Function();
public static void main(String[]args){
Customer.setLookAndFeel();
Customer cust = new Customer();
}
public Customer(){
super("Resident Details");
setSize(500,500);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
FlowLayout two = new FlowLayout(FlowLayout.LEFT);
setLayout(two);
JPanel row1 = new JPanel();
JLabel name = new JLabel("First Name",JLabel.LEFT);
JTextField nameEntry = new JTextField("",20);
row1.add(name);
row1.add(nameEntry);
add(row1);
JPanel row2 = new JPanel();
JLabel surname = new JLabel("Surname ",JLabel.LEFT);
JTextField surnameEntry = new JTextField("",20);
row2.add(surname);
row2.add(surnameEntry);
add(row2);
JPanel row3 = new JPanel();
JLabel contact1 = new JLabel("Contact Details : Email ",JLabel.LEFT);
JTextField contact1Entry = new JTextField("",10);
FlowLayout newflow = new FlowLayout(FlowLayout.LEFT,10,30);
setLayout(newflow);
row3.add(contact1);
row3.add(contact1Entry);
add(row3);
JPanel row4 = new JPanel();
JLabel contact2 = new JLabel("Contact Details : Phone Number",JLabel.LEFT);
JTextField contact2Entry = new JTextField("",10);
row4.add(contact2);
row4.add(contact2Entry);
add(row4);
JPanel row5 = new JPanel();
JLabel time = new JLabel("Duration Of Stay ",JLabel.LEFT);
JTextField timeEntry = new JTextField("",10);
row5.add(time);
row5.add(timeEntry);
add(row5);
JPanel row6 = new JPanel();
JComboBox<String> type = new JComboBox<String>();
type.addItem("Type Of Room");
type.addItem("Single Room");
type.addItem("Double Room");
type.addItem("VIP Room");
row6.add(type);
add(row6);
JPanel row7 = new JPanel();
FlowLayout amt = new FlowLayout(FlowLayout.LEFT,100,10);
setLayout(amt);
JLabel amount = new JLabel("Amount Per Day ");
JTextField AmountField = new JTextField("\u20ac ",10);
row7.add(amount);
row7.add(AmountField);
add(row7);
JPanel row8 = new JPanel();
FlowLayout prc = new FlowLayout(FlowLayout.LEFT,100,10);
setLayout(prc);
JLabel price = new JLabel("Total Price ");
JTextField priceField = new JTextField("\u20ac ",10);
row8.add(price);
row8.add(priceField);
add(row8);
JPanel row9 = new JPanel();
JButton clear = new JButton("Clear");
row9.add(clear);
add(row9);
JPanel row10 = new JPanel();
JButton save = new JButton("Save");
save.addActionListener(fun);
row10.add(save);
add(row10);
//Adding ActionListners
nameEntry.addActionListener(fun);
clear.addActionListener(fun);
save.addActionListener(fun);
setVisible(true);
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore error
}
}
}
//Import Statements
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import javax.swing.JOptionPane;
import java.awt.event.*;
//Class Name
public class Function implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("Add Customer")) {
Login();
}
else if(command.equals("Register")){
Registration();
}
else if(command.equals("Exit")){
System.exit(0);
}
else if(command.equals("Clear")){
ClearAllFields();
}
else if(command.equals("Save")){
SaveIt();
}
}
public static void Login(){
Customer cust = new Customer();
}
public static void Registration(){
//Do Nothing
}
//This clears all the text from the JTextFields
public static void ClearAllFields(){
}
//This will save Info on to another Class
public static void SaveIt(){
}
}
Alternatively, you can make nameEntry known to the Function class by defining it before calling the constructor for Function and then passing it into the constructor, like:
JTextField nameEntry = new JTextField("",20);
Function fun = new Function(nameEntry);
Then, in Function, add nameEntry as a member variable of Function and make a constructor for Function which accepts nameEntry, (right after the "public class Function..." line), like:
JTextField nameEntry;
public Function(JTextField nameEntry) {
this.nameEntry = nameEntry;
}
Now, the following will compile:
public void ClearAllFields(){
nameEntry.setText("");
}
And, the Clear button will clear the name field.
Again as per comments, one simple way to solve this is to give the gui public methods that the controller (the listener) can call, and then pass the current displayed instance of the GUI into the listener, allowing it to call any public methods that the GUI might have. The code below is simpler than yours, having just one JTextField, but it serves to illustrate the point:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class GUI extends JPanel {
private JTextField textField = new JTextField(10);
private JButton clearButton = new JButton("Clear");
public GUI() {
// pass **this** into the listener class
MyListener myListener = new MyListener(this);
clearButton.addActionListener(myListener);
clearButton.setMnemonic(KeyEvent.VK_C);
add(textField);
add(clearButton);
}
// public method in GUI that will do the dirty work
public void clearAll() {
textField.setText("");
}
// other public methods here to get text from the JTextFields
// to set text, and do whatever else needs to be done
private static void createAndShowGui() {
GUI mainPanel = new GUI();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class MyListener implements ActionListener {
private GUI gui;
// use constructor parameter to set a field
public MyListener(GUI gui) {
this.gui = gui;
}
#Override
public void actionPerformed(ActionEvent e) {
gui.clearAll(); // call public method in field
}
}
A better and more robust solution is to structure your program in a Model-View-Controller fashion (look this up), but this would probably be overkill for this simple academic exercise that you're doing.

For some reason my window that im creating wont launch

My code is messy so you might not be able to follow it, but I am trying to make a YouTube to MP3 converter.
It opens up a JPanel for the user to type in the YouTube URL. When I try to get the text from the JTextField, I had to make my method return a value so i can use the value in my other class, and I think that is causing my code not to work.
If someone could help me out, that would be great. I am really new to Java coding and I'm not sure why I chose such a complicated program, but I almost have it done. This is the last part then the cosmetics and cleaning up the code starts :)
My code:
public class Bank_Statement extends JFrame {
// width & height of window
private static final int WIDTH = 500;
private static final int HEIGHT = 500;
public static final Keys text = null;
final ActionListener convertButtonHandler = null;
static Scanner console = new Scanner(System.in);
static String M1;
public static String Bank_Statement1() {
//create/set labels
JButton skinny = new JButton("Convert");
skinny.addActionListener(new ButtonListener());
JPanel buttonPane = new JPanel();
buttonPane.add(skinny);
JButton skinny2 = new JButton("Paste");
JPanel buttonPane2 = new JPanel();
buttonPane2.add(skinny2);
JTextField text;
text = new JTextField(" ");
JPanel textPane = new JPanel();
textPane.add(text);
JTextField text2 = new JTextField("----------------------------------------WAIT LIST----------------------------------------");
JPanel textPane2 = new JPanel();
textPane2.add(text2);
JFrame frame = new JFrame("Youtube Converter");
frame.setSize(WIDTH, HEIGHT);
frame.add(textPane, BorderLayout.WEST);
frame.add(buttonPane2, BorderLayout.CENTER);
frame.add(buttonPane, BorderLayout.EAST);
frame.add(textPane2, BorderLayout.PAGE_END);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
return text.getText();
}
public static void main(String[] args) {
Bank_Statement recObject = new Bank_Statement();
}
}
class ButtonListener implements ActionListener {
ButtonListener() {}
public void actionPerformed(ActionEvent e) {
WebDriver driver = new HtmlUnitDriver();
driver.get("http://www.youtubeinmp3.com/");
String J = Bank_Statement.Bank_Statement1();
driver.findElement(By.id("video")).sendKeys(J + Keys.ENTER);
driver.findElement(By.id("download")).click();
String L= driver.getCurrentUrl();
System.out.println(L);
try {
Runtime.getRuntime().exec(new String[] {"cmd", "/c","start chrome " + L});
} catch (IOException e1) {
e1.printStackTrace();
}
driver.quit();
}
}
return text.getText();
Will be executed right after the Windows appears. It does not wait until the user enters some text.
Try the following:
public class Bank_Statement extends JFrame {
private JTextField text;
public static Bank_Statement bank_statement;
public Bank_Statement() {
//create/set labels
JButton skinny = new JButton("Convert");
skinny.addActionListener(new ButtonListener());
text = new JTextField(" ");
JPanel textPane = new JPanel();
textPane.add(text);
...
frame.setVisible(true);
}
public String getText(){
return text.getText();
}
public static void main(String[] args) {
bank_statement = new Bank_Statement();
}
}
class ButtonListener implements ActionListener {
ButtonListener() {}
public void actionPerformed(ActionEvent e) {
String J = Bank_Statement.bank_statement.getText();
System.out.println(J);
}
}
I removed a few lines in the middle to keep it compact. I hope it is clear, ask otherwise. The design is quite bad, but I didn't want to change to mutch of your code.
Well, first of all, I assume this is your constructor for the Bank_Statement class
public static String Bank_Statement1() {
//create/set labels
JButton skinny = new JButton("Convert");
skinny.addActionListener(new ButtonListener());
JPanel buttonPane = new JPanel();
buttonPane.add(skinny);
JButton skinny2 = new JButton("Paste");
JPanel buttonPane2 = new JPanel();
buttonPane2.add(skinny2);
JTextField text;
text = new JTextField(" ");
JPanel textPane = new JPanel();
textPane.add(text);
JTextField text2 = new JTextField("----------------------------------------WAIT LIST----------------------------------------");
JPanel textPane2 = new JPanel();
textPane2.add(text2);
JFrame frame = new JFrame("Youtube Converter");
frame.setSize(WIDTH, HEIGHT);
frame.add(textPane, BorderLayout.WEST);
frame.add(buttonPane2, BorderLayout.CENTER);
frame.add(buttonPane, BorderLayout.EAST);
frame.add(textPane2, BorderLayout.PAGE_END);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
return text.getText();
}
This is an incorrect use of a constructor.
In this case, your constructor should be declared as:
public static Bank_Statement(){
//constructor code goes here
}
then you can declare a getter method for your JTextField value like so:
public String getText(){
return text.getText();
}
then you should be able to call that method (getText) in any method once the object is instantiated. Like this:
public static void main(String[] args){
//just an example...you wouldn't really want to do this
Bank_Statement recObject = new Bank_Statement();
recObject.getText();
}
But overall this solution is not a "good" fix because there are many other ways to do it that are considered better. This will simply fix your error you are having. I would look into understanding classes and objects better before you continue. :)

JTextArea - How to set text at a specified offset?

I want to set some text at a specified offset in my JTextArea. Let's say I have already in my edit "aaa bbb" and I want to overwrite "bbb" with "house", how can I do that in Java?
You could use replaceRange()
public void replaceRange(String str,
int start,
int end)
Replaces text from the indicated start to end position with the new text specified. Does nothing if the model is null. Simply does a delete if the new string is null or empty.
This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.
You need to take a look at three methods setSelectionStart(...), setSelectionEnd(...) and replaceSelection(...).
Here is a small sample program to help your cause :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextAreaSelection
{
private JTextField replaceTextField;
private JTextField startIndexField;
private JTextField endIndexField;
private void createAndDisplayGUI()
{
final JFrame frame = new JFrame("JTextArea Selection");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setOpaque(true);
final JTextArea tarea = new JTextArea(10, 10);
tarea.setText("aaa bbb");
final JButton updateButton = new JButton("UPDATE TEXT");
updateButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//tarea.setSelectionStart(4);
//tarea.setSelectionEnd(7);
//tarea.replaceSelection("house");
int selection = JOptionPane.showConfirmDialog(null, getPanel());
if (selection == JOptionPane.OK_OPTION)
{
if (replaceTextField.getDocument().getLength() > 0
&& startIndexField.getDocument().getLength() > 0
&& endIndexField.getDocument().getLength() > 0)
{
String text = replaceTextField.getText().trim();
int start = Integer.parseInt(startIndexField.getText().trim());
int end = Integer.parseInt(endIndexField.getText().trim());
tarea.replaceRange(text, start, end);
}
}
}
});
contentPane.add(tarea, BorderLayout.CENTER);
contentPane.add(updateButton, BorderLayout.PAGE_END);
frame.getContentPane().add(contentPane);
frame.pack();
frame.setVisible(true);
}
private JPanel getPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 2, 2, 2));
JLabel replaceLabel = new JLabel("Enter new String : "
, JLabel.CENTER);
replaceTextField = new JTextField(10);
JLabel startIndexLabel = new JLabel("Enter Start Index : "
, JLabel.CENTER);
startIndexField = new JTextField(10);
JLabel endIndexLabel = new JLabel("Enter End Index : ");
endIndexField = new JTextField(10);
panel.add(replaceLabel);
panel.add(replaceTextField);
panel.add(startIndexLabel);
panel.add(startIndexField);
panel.add(endIndexLabel);
panel.add(endIndexField);
return panel;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextAreaSelection().createAndDisplayGUI();
}
});
}
}

How I can get output from 1st frame textfield input text to 2nd frame textArea

Here is my 1st frame - I want went I input text in textfield example name then click button report will display output to 2nd frame using textArea... please help me
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class Order extends JFrame implements ActionListener
{
private JPanel pInfo,pN, pIC, pDate,Blank,pBlank, button, pTotal;
private JLabel nameL,icL,DateL;
private JTextField nameTF, icTF;
private JFormattedTextField DateTF;
private JButton calB,clearB,exitB,reportB;
public Order()
{
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.setBackground(Color.gray);
pInfo = new JPanel();
pN = new JPanel();
pIC = new JPanel();
pDate = new JPanel();
nameTF = new JTextField(30);
icTF = new JTextField(30);
DateTF = new JFormattedTextField(
java.util.Calendar.getInstance().getTime());
DateTF.setEditable (false);
DateTF.addActionListener(this);
nameL = new JLabel(" NAME : ",SwingConstants.RIGHT);
icL = new JLabel(" IC : ",SwingConstants.RIGHT);
DateL = new JLabel(" DATE :",SwingConstants.RIGHT);
pInfo.setLayout(new GridLayout(10,2,5,5));
pInfo.setBorder(BorderFactory.createTitledBorder
(BorderFactory.createEtchedBorder(),"ORDER"));
pN.add(nameL);
pN.add(nameTF);
pIC.add(icL);
pIC.add(icTF);
pDate.add(DateL);
pDate.add(DateTF);
pInfo.add(pN);
pInfo.add(pIC);
pInfo.add(pDate);
pInfo.setBackground(Color.GRAY);
pN.setBackground(Color.gray);
pIC.setBackground(Color.gray);
pDate.setBackground(Color.gray);
nameL.setForeground(Color.black);
icL.setForeground(Color.black);
DateL.setForeground(Color.black);
nameTF.setBackground(Color.pink);
icTF.setBackground(Color.pink);
DateTF.setBackground(Color.pink);
contentPane.add(pInfo,BorderLayout.CENTER);
Blank = new JPanel();
pBlank = new JPanel();
button = new JPanel();
calB = new JButton("CALCULATE");
calB.setToolTipText("Click to calculate");
clearB = new JButton("RESET");
clearB.setToolTipText("Click to clear");
reportB = new JButton ("REPORT");
reportB.setToolTipText ("Click to print");
exitB = new JButton("EXIT");
exitB.setToolTipText("Click to exit");
Blank.setLayout(new GridLayout(2,2));
Blank.setBorder(BorderFactory.createTitledBorder
(BorderFactory.createEtchedBorder(),""));
button.setLayout(new GridLayout(1,4));
button.add(calB,BorderLayout.WEST);
button.add(clearB,BorderLayout.CENTER);
button.add(reportB,BorderLayout.CENTER);
button.add(exitB,BorderLayout.EAST);
Blank.add(pBlank);
Blank.add(button);
contentPane.add(Blank,BorderLayout.SOUTH);
Blank.setBackground(Color.gray);
pBlank.setBackground(Color.gray);
calB.setForeground(Color.black);
clearB.setForeground(Color.black);
reportB.setForeground(Color.black);
exitB.setForeground(Color.black);
calB.setBackground(Color.pink);
clearB.setBackground(Color.pink);
reportB.setBackground(Color.pink);
exitB.setBackground(Color.pink);
calB.addActionListener(this);
clearB.addActionListener(this);
reportB.addActionListener(this);
exitB.addActionListener(this);
}
public void actionPerformed(ActionEvent p)
{
if (p.getSource() == calB)
{
}
else if (p.getSource() == clearB)
{
}
else if (p.getSource () == reportB)
{
}
else if (p.getSource() == exitB)
{
}
}
public static void main (String [] args)
{
Order frame = new Order();
frame.setTitle("Order");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);//center the frame
}
}
If you only have one String to pass, add it to the constructor of your second JFrame:
public class SecondFrame extends JFrame {
public SecondFrame(String someValueFromFirstFrame) {
someTextField.setText(someValueFromFirstFrame);
}
}
and pass it when creating the second JFrame:
SecondFrame secondFrame = new SecondFrame(firstTextField.getText());
If there is more than one attribute to pass, consider putting them together in another class and pass the instance of this class. This saves you from changing the constructor every time you need to pass an additional variable.
Simply add some reference to the first frame in the second or pass the value you're interested in to the second frame before you display it.
As for the code example you requested:
public class SecondFrame extends JFrame {
private JFrame firstFrame;
public SecondFrame(JFrame firstFrame) {
this.firstFrame = firstFrame;
}
}
Now you can obtain everything there is to obtained from the firstFrame through the internal reference to it.

Categories

Resources