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

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

Related

Braces preventing Compilation

Im currently creating a GUI from scratch and I am including multiple classes on one page. Unfortunately, something is preventing me from seeing a class and I think it has to do with opening and closing brackets. Can anyone possibly help with where I went wrong so I dont do this in the future? My program is throwing an exception at RentalPanel class. It does not see it for some reason.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MavGUI2 extends JFrame
{
private JDesktopPane theDesktop;
public MavGUI2()
{
super("Mav Rental System");
theDesktop = new JDesktopPane();
JMenuBar bar = new JMenuBar();
JMenu addMenu = new JMenu("Add");
JMenuItem addRental = new JMenuItem ("Add Rental");
JMenuItem addCustomer = new JMenuItem("Add Customer");
addMenu.add(addRental);
addMenu.add(addCustomer);
bar.add(addMenu);
add(theDesktop);
setJMenuBar(bar);
addCustomer.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JInternalFrame frame = new JInternalFrame("Add Customer", true, true, true, true);
CustomerPanel cp = new CustomerPanel();
frame.add(cp);
frame.pack();
theDesktop.add(frame);
frame.setVisible(true);
}
});
addRental.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JInternalFrame frame = new JInternalFrame("Add Rental", true, true, true, true);
RentalPanel rp = new RentalPanel();
frame.add(rp);
frame.pack();
theDesktop.add(frame);
frame.setVisible(true);
}
});
JMenu exitMenu = new JMenu("Exit");
JMenuItem calCharges = new JMenuItem("Calculate Charges");
JMenuItem close = new JMenuItem("Close");
close.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
calCharges.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println("Calculations");
}
});
exitMenu.add(calCharges);
exitMenu.add(close);
bar.add(exitMenu);
add(theDesktop);
setJMenuBar(bar);
}
public static void main(String args[])
{
MavGUI2 m = new MavGUI2();
m.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
m.setSize(500,500);
m.setVisible(true);
}
class CustomerPanel extends Panel
{
private JLabel nameLabel;
private JLabel streetLabel;
private JLabel cityLabel;
private JLabel stateLabel;
private JLabel creditLabel;
private JLabel zipLabel;
private JLabel submitLabel;
private JButton submitButton;
private JTextField nameField;
private JTextField streetField;
private JTextField cityField;
private JTextField stateField;
private JTextField creditField;
private JTextField zipField;
public CustomerPanel()
{
setLayout(new GridLayout(7,2));
nameLabel = new JLabel(" Enter name: ");
streetLabel = new JLabel(" Enter street: ");
cityLabel = new JLabel(" Enter city: ");
stateLabel = new JLabel (" Enter state: ");
zipLabel = new JLabel(" Enter zip: ");
creditLabel = new JLabel(" Enter credit card number: ");
submitLabel = new JLabel(" Click when done!");
nameField = new JTextField(20);
streetField = new JTextField(20);
cityField = new JTextField(20);
stateField = new JTextField(20);
zipField = new JTextField(20);
creditField = new JTextField(20);
submitButton = new JButton(" SUBMIT ");
MyListener handler = new MyListener();
submitButton.addActionListener(handler);
add(nameLabel);
add(nameField);
add(streetLabel);
add(streetField);
add(cityLabel);
add(cityField);
add(stateLabel);
add(stateField);
add(zipLabel);
add(zipField);
add(creditLabel);
add(creditField);
add(submitLabel);
add(submitButton);
}
class MyListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.printf(nameField.getText() +" " + streetField.getText() + " "+ cityField.getText());
nameField.setText("");
streetField.setText("");
cityField.setText("");
stateField.setText("");
zipField.setText("");
creditField.setText("");
nameField.requestFocus();
}
}
class RentalPanel extends Panel
{
private JLabel custNameLabel;
private JLabel numDaysLabel;
private JLabel perDayLabel;
private JButton submit2Button;
private JLabel submit2Label;
private JTextField custNameField;
private JTextField numDaysField;
private JTextField perDayField;
private JCheckBox furnBox;
private JCheckBox elecBox;
private JComboBox<String> furnType;
String types[] = {"BED", "COUCH", "CHAIR"};
private JComboBox<String> elecType;
String type2[] = {"COMPUTER","TV"};
public RentalPanel()
{
setLayout(new GridLayout(6,2));
ButtonGroup group = new ButtonGroup();
furnBox = new JCheckBox(" Furniture ");
elecBox = new JCheckBox(" Electronic");
group.add(furnBox);
group.add(elecBox);
custNameLabel = new JLabel(" Enter customer name");
numDaysLabel = new JLabel(" Enter number of days");
perDayLabel = new JLabel(" Enter price per day");
submit2Label = new JLabel(" Click when done");
submit2Button = new JButton(" SUBMIT");
custNameField = new JTextField(20);
numDaysField = new JTextField(20);
perDayField = new JTextField(20);
furnType = new JComboBox<String>(types);
elecType = new JComboBox<String>(type2);
add(custNameLabel);
add(custNameField);
add(furnBox);
add(elecBox);
add(numDaysLabel);
add(numDaysField);
add(perDayLabel);
add(perDayField);
add(furnType);
add(elecType);
add(submit2Label);
add(submit2Button);
}//closes Rental Panel constructor
}//close rental panel
}// closes customer panel
}//closes MAVGUI
Blockquote
The trouble is, the RentalPanel class is a non-static inner class inside CustomerPanel. So you cannot directly access it from MavGUI2 class. Making RentalPanel and CustomerPanel classes static inner classes, will solve the compilation error.
In fact, it would be advisable to move them to their separate files.

Gui not loading because the program is stuck in an infinite loop [duplicate]

Im fairly new to Java and im just looking for a little help Im trying to create a program which allows the user to enter as a gui the name and> >location of a department store. It allows this but the program does not wait for the >details to be entered it just initializes the Gui class and simply continues on with the >processing Which is to add the details entered into the Gui into an array list. But the >details have not yet been entered yet so it is creating a null value because it has jumped >ahead.
So how can I make it stop and wait till the values have been entered and then submitted?
Here is the Gui component of the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class guiDepartment extends JFrame
{
private String depName;
private String depLocation;
private static Department newDepartment;
private JTextField departmentDetails1;
private JTextField departmentDetails2;
private JTextField departmentDetails3;
private Employee worksInInTheDepartment;
public guiDepartment()
{
System.out.println("bob the builder ");
JButton submit;
JButton b1;
JFrame frame = new JFrame();
departmentDetails1 = new JTextField(10);
departmentDetails2 = new JTextField(10);
departmentDetails3 = new JTextField(10);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(320, 75));
frame.setTitle("Department Details");
frame.setLayout(new FlowLayout());
frame.add(new JLabel("Please enter department Name: "));
frame.add(departmentDetails1);
ButtonListenerDepName dListener = new ButtonListenerDepName();
System.out.println(depName);
frame.add(new JLabel("Please enter department location: "));
frame.add(departmentDetails2);
ButtonListenerDepName1 dListener1 = new ButtonListenerDepName1();
b1 = new JButton ("Submit");
ButtonListener listener = new ButtonListener();
b1.addActionListener(listener);
b1.addActionListener(dListener);
b1.addActionListener(dListener1);
frame.add(b1);
frame.pack();
frame.setSize(300,300);
frame.setVisible(true);
}
public class ButtonListenerDepName implements ActionListener
{
public void actionPerformed (ActionEvent e )
{
depName = departmentDetails1.getText();
System.out.println("and This is the departments name :"+ depName);
}
}
public class ButtonListenerDepName1 implements ActionListener
{
public void actionPerformed (ActionEvent e )
{
depLocation = departmentDetails2.getText();
System.out.println("and This is the departments location :"+ depLocation);
}
}
public class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent e )
{
//create a new department and then adds it to thee system
newDepartment = new Department(depName, depLocation);
}
}
public static Department getDepartment()
{
return newDepartment;
}
}
>>and this is the Main class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class MainWelcomeGui1
{
JFrame frame = new JFrame();
JButton b1 ;
JButton b2 ;
JButton b3 ;
JButton b4 ;
JButton b5 ;
JButton b6 ;
JButton b7 ;
JButton b8 ;
JButton b9 ;
JButton b10 ;
JButton b11 ;
JButton b12 ;
private String fName;
private String sName;
private String gender;
private String pLevel;
private String empIDnumber;
private int dPayLevel;
private static ArrayList<Employee> allEmployees = new ArrayList<Employee>();
private static ArrayList<Department> allDepartments = new ArrayList<Department>();
public MainWelcomeGui1()
{
frame.setTitle("Human Resources allocation screen");
JLabel hdr = new JLabel ("Welcome to the Human Resources employee control system");
b1 = new JButton ("Add a new department");
ButtonListener listener = new ButtonListener();
b1.addActionListener(listener);
// addDepartmentToSystem();
b2 = new JButton ("Add a new employee to the system");
ButtonListener listener1 = new ButtonListener();
b2.addActionListener(listener1);
b3 = new JButton ("Alter a employees details");
ButtonListener listener2 = new ButtonListener();
b3.addActionListener(listener2);
b4 = new JButton ("Add a employee to a department of my choice");
ButtonListener listener3 = new ButtonListener();
b4.addActionListener(listener3);
b5 = new JButton ("Assign a employee to a department");
b6 = new JButton ("Designate a employee as department head");
b7 = new JButton ("Delete a department");
b8 = new JButton ("To delete an employee from the system");
b9 = new JButton ("To see a list of all employees assigned to a particular department");
b10 = new JButton ("To see the amounts needed to be paid fortnightly");
b11 = new JButton ("To chane an employees pay level");
b12 = new JButton ("To change an employees name");
frame.setLayout (new GridLayout (6, 6));
frame.setBackground (Color.green);
frame.add(hdr,BorderLayout.NORTH);
frame.add (b1);
frame.add (b2);
frame.add (b3);
frame.add (b4);
frame.add (b5);
frame.add (b6);
frame.add (b7);
frame.add (b8);
frame.add (b9);
frame.add (b10);
frame.add (b11);
frame.add (b12);
frame.setSize(400, 100);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
new MainWelcomeGui1();
}
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent e )
{
if (e.getSource() == b1)
{
guiDepartment guiDepartment = new guiDepartment();
System.out.println("i should really come after bob the builder");
addDepartmentToSystem();
}
else if (e.getSource() == b2)
{
guiEmployee1 theGuiEmployee = new guiEmployee1();
}
else if (e.getSource() == b3)
{
System.out.println("hello1 button 2");
}
else if (e.getSource() == b4)
{
System.out.println("hello button 3");
}
else if (e.getSource() == b5)
{
guiEmployee1 theGuiEmployee = new guiEmployee1();
}
else if (e.getSource() == b6)
{
System.out.println("hello1 button 2");
}
else if (e.getSource() == b7)
{
System.out.println("hello button 3");
}
}
}
public void addDepartmentToSystem()
{
Department departmentToAdd = new Department("berel","sam") ;
System.out.println("to two");
System.out.println(departmentToAdd);
departmentToAdd = guiDepartment.getDepartment();
System.out.println("got to three");
allDepartments.add(departmentToAdd);
System.out.println("to four+");
System.out.println(allDepartments);
}
}
You shouldn't have a JFrame launching other JFrames, especially if you want the child windows to behave as a modal dialogs -- a dialog that halts the code in the launching window until it has been fully dealt with. When this is the case, make the dialog windows dialogs by using modal JDialogs in place of JFrames for the dialog windows.
For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainWelcomeGui2 {
public static void main(String[] args) {
final JFrame frame = new JFrame("Main GUI");
JButton addDeptButtonLaunchJFrame = new JButton(
"Add a New Department, Launch JFrame");
JButton addDeptButtonLaunchJDialog = new JButton(
"Add a New Department, Launch JDialog");
addDeptButtonLaunchJDialog.addActionListener(new LaunchJDialogListener(
frame));
addDeptButtonLaunchJFrame.addActionListener(new LaunchJFrameListener());
JPanel panel = new JPanel();
panel.add(addDeptButtonLaunchJDialog);
panel.add(addDeptButtonLaunchJFrame);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class LaunchJDialogListener implements ActionListener {
JDialog dialog;
public LaunchJDialogListener(JFrame parentFrame) {
JButton doneButton = new JButton(new AbstractAction("Done") {
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(100, 100));
panel.add(doneButton);
dialog = new JDialog(parentFrame, "Dialog", true);
dialog.add(panel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("called before setting dialog visible");
dialog.setVisible(true);
System.out
.println("called after setting dialog visible. Note that this line doesn't show until the dialog disappears");
}
}
class LaunchJFrameListener implements ActionListener {
JFrame frame;
public LaunchJFrameListener() {
JButton doneButton = new JButton(new AbstractAction("Done") {
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(100, 100));
panel.add(doneButton);
frame = new JFrame("JFrame");
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("called before setting frame visible");
frame.setVisible(true);
System.out
.println("called after setting frame visible. Note that this line shows up immediately.");
}
}

Comparing two JTextFields with an ActionListener

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.

how to edit awt textfield via code

I can't find out how to change text in my AWT textboxes. I already tried this:
textBox1.setText("text");
textBox1.validate();
or
textBox1.setText("text");
textBox1.repaint();
None of them works. What could be this issue?
Look this example how I am setting text to text field
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showTextFieldDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showTextFieldDemo(){
headerLabel.setText("Control in action: TextField");
Label namelabel= new Label("User ID: ", Label.CENTER);
final TextField userText = new TextField(16);
userText.setText("name");
Button displayButton = new Button("Display");
displayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Username: " + userText.getText();
statusLabel.setText(data);
}
});
controlPanel.add(namelabel);
controlPanel.add(userText);
controlPanel.add(displayButton);
mainFrame.setVisible(true);
}
}

How to position JButton in a JFrame window?

My program is about a supermarket. I want to position the JButton 'b1' just below JLabel 'l1' and also below JTextField 'jt1'. I want the JButton 'b1' to also be in the centre but below 'l1' and 'jt1'. Below is the delivery() method of my program:
public static void delivery()
{
final JFrame f1 = new JFrame("Name");
f1.setVisible(true);
f1.setSize(600,200);
f1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f1.setLocation(700,450);
JPanel p1 = new JPanel();
final JLabel l1 = new JLabel("Enter your name: ");
final JTextField jt1 = new JTextField(20);
JButton b1 = new JButton("Ok");
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
input1 = jt1.getText();
f1.setVisible(false);
}
});
p1.add(b1);
p1.add(l1);
p1.add(jt1);
f1.add(p1);
final JFrame f2 = new JFrame("Address");
f2.setVisible(true);
f2.setSize(600,200);
f2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f2.setLocation(700,450);
JPanel p2 = new JPanel();
final JLabel l2 = new JLabel("Enter your address: ");
final JTextField jt2 = new JTextField(20);
JButton b2 = new JButton("Ok");
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
input2 = jt2.getText();
f2.setVisible(false);
}
});
p2.add(b2);
p2.add(l2);
p2.add(jt2);
f2.add(p2);
}
}
You can use multiple JPanels to get close to what you want:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyGui {
public static void delivery()
{
JFrame f1 = new JFrame("Name");
f1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f1.setBounds(200, 100, 500, 300);
Container cpane = f1.getContentPane();
JPanel p1 = new JPanel();
p1.setLayout(new BoxLayout(p1, BoxLayout.LINE_AXIS)); //Horizontal
JLabel l1 = new JLabel("Enter your name: ");
JTextField jt1 = new JTextField(20);
jt1.setMaximumSize( jt1.getPreferredSize() );
p1.add(l1);
p1.add(jt1);
JPanel p2 = new JPanel();
p2.setLayout(new BoxLayout(p2, BoxLayout.PAGE_AXIS)); //Vertical
p2.add(p1);
JButton b1 = new JButton("Ok");
p2.add(b1);
cpane.add(p2);
f1.setVisible(true);
}
}
public class SwingProg {
private static void createAndShowGUI() {
MyGui.delivery();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Use the GridBagLayout Class. It's for custom designing using Constraints.

Categories

Resources