Message to JList [duplicate] - java

This question already has an answer here:
Gui JList ActionListener
(1 answer)
Closed 9 years ago.
hey all goodevening i have a problem about my second button named "Submit" because i cant transfer all information i entered to my null JList in the frame here is my code so far my problem is if i clicked submit my all information will appear in my Message area in frame it needs to be list. thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class vin extends JFrame
{
JLabel lab = new JLabel("Enter Your Name :");
JLabel lab2 = new JLabel("Enter Your Birthday :");
JLabel lab3 = new JLabel("Enter Your Age:");
JLabel lab4 = new JLabel("Enter Your HomeTown:");
JLabel lab5 = new JLabel("Choose Your Department:");
JButton b1 = new JButton("Exit");
JTextField t1 = new JTextField(15);
JTextField t2 = new JTextField(15);
JTextField t3 = new JTextField(15);
JTextField t4 = new JTextField(15);
JButton b2 = new JButton("Submit");
JButton b3 = new JButton("Clear");
JLabel lab6 = new JLabel("Message :");
JList list = new JList();
JPanel panel = new JPanel();
JLabel brief;
public vin()
{
setLocation(500,280);
panel.setLayout(null);
lab.setBounds(10,10,150,20);
t1.setBounds(130,10,150,20);
lab5.setBounds(10,40,150,20);
lab2.setBounds(10,140,150,20);
t2.setBounds(130,140,150,20);
lab3.setBounds(10,170,150,20);
t3.setBounds(110,170,150,20);
lab4.setBounds(10,200,150,20);
t4.setBounds(150,200,150,20);
lab6.setBounds(10,240,150,20);
list.setBounds(50,270,150,20);
list.setSize(250,150);
b1.setBounds(250,470,150,20);
b2.setBounds(60,470,150,20);
b3.setBounds(160,470,150,20);
b1.setSize(60,30);
b2.setSize(75,30);
b3.setSize(65,30);
panel.add(lab);
panel.add(t1);
panel.add(lab5);
panel.add(lab2);
panel.add(t2);
panel.add(t3);
panel.add(t4);
panel.add(lab4);
panel.add(lab3);
panel.add(lab6);
panel.add(b1);
panel.add(b2);
panel.add(b3);
panel.add(list);
brief = new JLabel("Goodmorning "+t1+" Today is "+t2+" its your birthday You are now"+t3+" of age You are From"+t4);
getContentPane().add(panel);
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b1)
{
System.exit(0);
}
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b2)
{
list = new JList();
}
}
});
b3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b3)
{
t1.setText("");
t2.setText("");
t3.setText("");
t4.setText("");
}
}
});
}
public static void main(String args [])
{
vin w = new vin();
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setSize(400,600);
w.setVisible(true);
}
}

I modified your code so that your list is backed by a Vector which you update when you press the Submit button.
public class Frame extends JFrame
{
JLabel lab = new JLabel("Enter Your Name :");
JLabel lab2 = new JLabel("Enter Your Birthday :");
JLabel lab3 = new JLabel("Enter Your Age:");
JLabel lab4 = new JLabel("Enter Your HomeTown:");
JLabel lab5 = new JLabel("Choose Your Department:");
JButton b1 = new JButton("Exit");
JTextField t1 = new JTextField(15);
JTextField t2 = new JTextField(15);
JTextField t3 = new JTextField(15);
JTextField t4 = new JTextField(15);
JButton b2 = new JButton("Submit");
JButton b3 = new JButton("Clear");
JLabel lab6 = new JLabel("Message :");
Vector vector = new Vector();
JList list = new JList(vector);
JPanel panel = new JPanel();
JLabel brief;
public Frame()
{
setLocation(500,280);
panel.setLayout(null);
lab.setBounds(10,10,150,20);
t1.setBounds(130,10,150,20);
lab5.setBounds(10,40,150,20);
lab2.setBounds(10,140,150,20);
t2.setBounds(130,140,150,20);
lab3.setBounds(10,170,150,20);
t3.setBounds(110,170,150,20);
lab4.setBounds(10,200,150,20);
t4.setBounds(150,200,150,20);
lab6.setBounds(10,240,150,20);
list.setBounds(50,270,150,20);
list.setSize(250,150);
b1.setBounds(250,470,150,20);
b2.setBounds(60,470,150,20);
b3.setBounds(160,470,150,20);
b1.setSize(60,30);
b2.setSize(75,30);
b3.setSize(65,30);
panel.add(lab);
panel.add(t1);
panel.add(lab5);
panel.add(lab2);
panel.add(t2);
panel.add(t3);
panel.add(t4);
panel.add(lab4);
panel.add(lab3);
panel.add(lab6);
panel.add(b1);
panel.add(b2);
panel.add(b3);
panel.add(list);
brief = new JLabel("Goodmorning "+t1+" Today is "+t2+" its your birthday You are now"+t3+" of age You are From"+t4);
getContentPane().add(panel);
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b1)
{
System.exit(0);
}
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b2)
{
vector.add(t1.getText() + "-" + t2.getText() + "-" + t3.getText() + "-" + t4.getText());
list.setListData(vector);
list.revalidate();
list.repaint();
}
}
});
b3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
if(source == b3)
{
t1.setText("");
t2.setText("");
t3.setText("");
t4.setText("");
}
}
});
}
public static void main(String args [])
{
Frame w = new Frame();
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setSize(400,600);
w.setVisible(true);
}
}

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

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

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.

How Do I get the buttons to work? Java Programming

I created an Address Book GUI, I just don't understand How to make the save and delete buttons to work, so when the user fills the text fields they can click save and it saves to the JList I have created and then they can also delete from it. How Do I Do this?
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class AddressBook {
private JLabel lblFirstname,lblSurname, lblMiddlename, lblPhone,
lblEmail,lblAddressOne, lblAddressTwo, lblCity, lblPostCode, picture;
private JTextField txtFirstName, txtSurname, txtAddressOne, txtPhone,
txtMiddlename, txtAddressTwo, txtEmail, txtCity, txtPostCode;
private JButton btSave, btExit, btDelete;
private JList contacts;
private JPanel panel;
public static void main(String[] args) {
new AddressBook();
}
public AddressBook(){
JFrame frame = new JFrame("My Address Book");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,400);
frame.setVisible(true);
panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.cyan);
lblFirstname = new JLabel("First name");
lblFirstname.setBounds(135, 50, 150, 20);
Font styleOne = new Font("Arial", Font.BOLD, 13);
lblFirstname.setFont(styleOne);
panel.add(lblFirstname);
txtFirstName = new JTextField();
txtFirstName.setBounds(210, 50, 150, 20);
panel.add(txtFirstName);
lblSurname = new JLabel ("Surname");
lblSurname.setBounds(385,50,150,20);
Font styleTwo = new Font ("Arial",Font.BOLD,13);
lblSurname.setFont(styleTwo);
panel.add(lblSurname);
txtSurname = new JTextField();
txtSurname.setBounds(450,50,150,20);
panel.add(txtSurname);
lblMiddlename = new JLabel ("Middle Name");
lblMiddlename.setBounds(620,50,150,20);
Font styleThree = new Font ("Arial", Font.BOLD,13);
lblMiddlename.setFont(styleThree);
panel.add(lblMiddlename);
txtMiddlename = new JTextField();
txtMiddlename.setBounds(710,50,150,20);
panel.add(txtMiddlename);
lblPhone = new JLabel("Phone");
lblPhone.setBounds(160,100,100,20);
Font styleFour = new Font ("Arial", Font.BOLD,13);
lblPhone.setFont(styleFour);
panel.add(lblPhone);
txtPhone = new JTextField();
txtPhone.setBounds(210,100,150,20);
panel.add(txtPhone);
lblEmail = new JLabel("Email");
lblEmail.setBounds(410,100,100,20);
Font styleFive = new Font ("Arial", Font.BOLD,13);
lblEmail.setFont(styleFive);
panel.add(lblEmail);
txtEmail = new JTextField();
txtEmail.setBounds(450,100,150,20);
panel.add(txtEmail);
lblAddressOne = new JLabel("Address 1");
lblAddressOne.setBounds(145,150,100,20);
Font styleSix = new Font ("Arial", Font.BOLD,13);
lblAddressOne.setFont(styleSix);
panel.add(lblAddressOne);
txtAddressOne = new JTextField();
txtAddressOne.setBounds(210,150,150,20);
panel.add(txtAddressOne);
lblAddressTwo = new JLabel("Address 2");
lblAddressTwo.setBounds(145,200,100,20);
Font styleSeven = new Font ("Arial", Font.BOLD,13);
lblAddressTwo.setFont(styleSeven);
panel.add(lblAddressTwo);
txtAddressTwo = new JTextField();
txtAddressTwo.setBounds(210,200,150,20);
panel.add(txtAddressTwo);
lblCity = new JLabel("City");
lblCity.setBounds(180,250,100,20);
Font styleEight = new Font ("Arial", Font.BOLD,13);
lblCity.setFont(styleEight);
panel.add(lblCity);
txtCity = new JTextField();
txtCity.setBounds(210,250,150,20);
panel.add(txtCity);
lblPostCode = new JLabel("Post Code");
lblPostCode.setBounds(380,250,100,20);
Font styleNine = new Font ("Arial", Font.BOLD,13);
lblPostCode.setFont(styleNine);
panel.add(lblPostCode);
txtPostCode = new JTextField();
txtPostCode.setBounds(450,250,150,20);
panel.add(txtPostCode);
//image
ImageIcon image = new ImageIcon("C:\\Users\\Hassan\\Desktop\\icon.png");
picture = new JLabel(image);
picture.setBounds(600,90, 330, 270);
panel.add(picture);
//buttons
btSave = new JButton ("Save");
btSave.setBounds(380,325,100,20);
panel.add(btSave);
btDelete = new JButton ("Delete");
btDelete.setBounds(260,325,100,20);
panel.add(btDelete);
btExit = new JButton ("Exit");
btExit.setBounds(500,325,100,20);
panel.add(btExit);
btExit.addActionListener(new Action());
//list
contacts=new JList();
contacts.setBounds(0,10,125,350);
panel.add(contacts);
frame.add(panel);
frame.setVisible(true);
}
//button actions
static class Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFrame option = new JFrame();
int n = JOptionPane.showConfirmDialog(option,
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
}
Buttons need Event Handlers to work. You have not added any Event Handlers to the Save and Delete buttons. You need to call the addActionListener on those buttons too.
I recommend anonymous inner classes:
mybutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//do whatever should happen when the button is clicked...
}
});
You need to addActionListener to the buttons btSave and btDelete.
You could create a anonymous class like this and perform your work there.
btSave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Do you work for the button here
}
}
btDelete.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Do you work for the button here
}
}
Edit:
I have an example to which you can refer to and accordingly make changes by understanding it. I got it from a professor at our institute.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TooltipTextOfList{
private JScrollPane scrollpane = null;
JList list;
JTextField txtItem;
DefaultListModel model;
public static void main(String[] args){
TooltipTextOfList tt = new TooltipTextOfList();
}
public TooltipTextOfList(){
JFrame frame = new JFrame("Tooltip Text for List Item");
String[] str_list = {"One", "Two", "Three", "Four"};
model = new DefaultListModel();
for(int i = 0; i < str_list.length; i++)
model.addElement(str_list[i]);
list = new JList(model){
public String getToolTipText(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (-1 < index) {
String item = (String)getModel().getElementAt(index);
return item;
} else {
return null;
}
}
};
txtItem = new JTextField(10);
JButton button = new JButton("Add");
button.addActionListener(new MyAction());
JPanel panel = new JPanel();
panel.add(txtItem);
panel.add(button);
panel.add(list);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction extends MouseAdapter implements ActionListener{
public void actionPerformed(ActionEvent ae){
String data = txtItem.getText();
if (data.equals(""))
JOptionPane.showMessageDialog(null,"Please enter text in the Text Box.");
else{
model.addElement(data);
JOptionPane.showMessageDialog(null,"Item added successfully.");
txtItem.setText("");
}
}
}
}

Categories

Resources