I have a simple form setup and I was following how the book, Core Java Vol I, sets up their forms, where they have a top level class that extends JFrame create objects of the different components, and lays them out in the frame. If this isn't the way you are "typically" supposed to do it, please let me know.
I got confused when I wrote my inner classes to perform actions when buttons were pressed. I could put my inner class in my AddressBookForm class since that's where I put my buttons and it would have access to the private variables of the JTextFields. The problem I have (assuming so far the other parts are 'ok'), is I don't know how to get the addressList.size() so I can update my statusBar label with the total number of people when the Insert button is pressed. Any thoughts? Thanks.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.List;
import java.util.ArrayList;
public class AddressBook
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
AddressBookFrame frame = new AddressBookFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem saveAsItem = new JMenuItem("Save As");
JMenuItem printItem = new JMenuItem("Print");
JMenuItem exitItem = new JMenuItem("Exit");
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(saveAsItem);
fileMenu.add(printItem);
fileMenu.add(exitItem);
menuBar.add(fileMenu);
JMenu editMenu = new JMenu("Edit");
JMenuItem newItem = new JMenuItem("New");
JMenuItem editItem = new JMenuItem("Edit");
JMenuItem deleteItem = new JMenuItem("Delete");
JMenuItem findItem = new JMenuItem("Find");
JMenuItem firstItem = new JMenuItem("First");
JMenuItem previousItem = new JMenuItem("Previous");
JMenuItem nextItem = new JMenuItem("Next");
JMenuItem lastItem = new JMenuItem("Last");
editMenu.add(newItem);
editMenu.add(editItem);
editMenu.add(deleteItem);
editMenu.add(findItem);
editMenu.add(firstItem);
editMenu.add(previousItem);
editMenu.add(nextItem);
editMenu.add(lastItem);
menuBar.add(editMenu);
JMenu helpMenu = new JMenu("Help");
JMenuItem documentationItem = new JMenuItem("Documentation");
JMenuItem aboutItem = new JMenuItem("About");
helpMenu.add(documentationItem);
helpMenu.add(aboutItem);
menuBar.add(helpMenu);
frame.setVisible(true);
}
});
}
}
class AddressBookFrame extends JFrame
{
public AddressBookFrame()
{
setLayout(new BorderLayout());
setTitle("Address Book");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
AddressBookToolBar toolBar = new AddressBookToolBar();
add(toolBar, BorderLayout.NORTH);
AddressBookStatusBar aStatusBar = new AddressBookStatusBar();
add(aStatusBar, BorderLayout.SOUTH);
AddressBookForm form = new AddressBookForm();
add(form, BorderLayout.CENTER);
}
public static final int DEFAULT_WIDTH = 500;
public static final int DEFAULT_HEIGHT = 500;
}
/* Create toolbar buttons and add buttons to toolbar */
class AddressBookToolBar extends JPanel
{
public AddressBookToolBar()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
JToolBar bar = new JToolBar();
JButton newButton = new JButton("New");
JButton editButton = new JButton("Edit");
JButton deleteButton = new JButton("Delete");
JButton findButton = new JButton("Find");
JButton firstButton = new JButton("First");
JButton previousButton = new JButton("Previous");
JButton nextButton = new JButton("Next");
JButton lastButton = new JButton("Last");
bar.add(newButton);
bar.add(editButton);
bar.add(deleteButton);
bar.add(findButton);
bar.add(firstButton);
bar.add(previousButton);
bar.add(nextButton);
bar.add(lastButton);
add(bar);
}
}
/* Creates the status bar string */
class AddressBookStatusBar extends JPanel
{
public AddressBookStatusBar()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
this.statusBarString = new JLabel("Total: " + totalContacts);
add(this.statusBarString);
}
public void updateLabel(int n)
{
contactsLabel.setText((new Integer(n)).toString());
}
private JLabel statusBarString;
private JLabel contactsLabel;
}
class AddressBookForm extends JPanel
{
public AddressBookForm()
{
// create form panel
this.setLayout(new GridLayout(2, 1));
JPanel formPanel = new JPanel();
formPanel.setLayout(new GridLayout(4, 2));
firstName = new JTextField(20);
lastName = new JTextField(20);
telephone = new JTextField(20);
email = new JTextField(20);
JLabel firstNameLabel = new JLabel("First Name: ", JLabel.LEFT);
formPanel.add(firstNameLabel);
formPanel.add(firstName);
JLabel lastNameLabel = new JLabel("Last Name: ", JLabel.LEFT);
formPanel.add(lastNameLabel);
formPanel.add(lastName);
JLabel telephoneLabel = new JLabel("Telephone: ", JLabel.LEFT);
formPanel.add(telephoneLabel);
formPanel.add(telephone);
JLabel emailLabel = new JLabel("Email: ", JLabel.LEFT);
formPanel.add(emailLabel);
formPanel.add(email);
add(formPanel);
// create button panel
JPanel buttonPanel = new JPanel();
JButton insertButton = new JButton("Insert");
JButton displayButton = new JButton("Display");
ActionListener insertAction = new AddressBookListener();
ActionListener displayAction = new AddressBookListener();
insertButton.addActionListener(insertAction);
displayButton.addActionListener(displayAction);
buttonPanel.add(insertButton);
buttonPanel.add(displayButton);
add(buttonPanel);
}
public int getTotalContacts()
{
return addressList.size();
}
private JTextField firstName;
private JTextField lastName;
private JTextField telephone;
private JTextField email;
private JLabel contacts;
private List<Person> addressList = new ArrayList<Person>();
private class AddressBookListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String buttonPressed = e.getActionCommand();
System.out.println(buttonPressed);
if (buttonPressed == "Insert") {
Person aPerson = new Person(firstName.getText(), lastName.getText(), telephone.getText(), email.getText());
addressList.add(aPerson);
}
else {
for (Person p : addressList) {
System.out.println(p);
}
}
}
}
}
Don't store a list of persons in a component, that's tight coupling.
Have a service class or interface that provides the list of Persons, something like this
public interface AddressBookService {
List<Person> getContacts();
void addContact(Person contact);
void deleteContact(Person person);
}
Now give each of your components access to this service, either by injecting it or by using it as a singleton or any other lookup method.
I vote for seanizer's solution, but if you insist on using your code, you can make use of accessing outer class's addressList variable (AddressBookFrame) in its inner classes this way:
class AddressBookFrame extends JFrame {
private List<Person> addressList = new ArrayList<Person>();
public AddressBookFrame() {
setLayout(new BorderLayout());
setTitle("Address Book");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
AddressBookToolBar toolBar = new AddressBookToolBar();
add(toolBar, BorderLayout.NORTH);
AddressBookStatusBar aStatusBar = new AddressBookStatusBar();
add(aStatusBar, BorderLayout.SOUTH);
AddressBookForm form = new AddressBookForm();
add(form, BorderLayout.CENTER);
}
public static final int DEFAULT_WIDTH = 500;
public static final int DEFAULT_HEIGHT = 500;
/* Creates the status bar string */
class AddressBookStatusBar extends JPanel {
public AddressBookStatusBar() {
setLayout(new FlowLayout(FlowLayout.LEFT));
this.statusBarString = new JLabel("Total: " + addressList.size());
add(this.statusBarString);
}
public void updateLabel(int n) {
contactsLabel.setText((new Integer(n)).toString());
}
private JLabel statusBarString;
private JLabel contactsLabel;
}
/* Create toolbar buttons and add buttons to toolbar */
class AddressBookToolBar extends JPanel {
public AddressBookToolBar() {
setLayout(new FlowLayout(FlowLayout.LEFT));
JToolBar bar = new JToolBar();
JButton newButton = new JButton("New");
JButton editButton = new JButton("Edit");
JButton deleteButton = new JButton("Delete");
JButton findButton = new JButton("Find");
JButton firstButton = new JButton("First");
JButton previousButton = new JButton("Previous");
JButton nextButton = new JButton("Next");
JButton lastButton = new JButton("Last");
bar.add(newButton);
bar.add(editButton);
bar.add(deleteButton);
bar.add(findButton);
bar.add(firstButton);
bar.add(previousButton);
bar.add(nextButton);
bar.add(lastButton);
add(bar);
}
}
class AddressBookForm extends JPanel {
public AddressBookForm() {
// create form panel
this.setLayout(new GridLayout(2, 1));
JPanel formPanel = new JPanel();
formPanel.setLayout(new GridLayout(4, 2));
firstName = new JTextField(20);
lastName = new JTextField(20);
telephone = new JTextField(20);
email = new JTextField(20);
JLabel firstNameLabel = new JLabel("First Name: ", JLabel.LEFT);
formPanel.add(firstNameLabel);
formPanel.add(firstName);
JLabel lastNameLabel = new JLabel("Last Name: ", JLabel.LEFT);
formPanel.add(lastNameLabel);
formPanel.add(lastName);
JLabel telephoneLabel = new JLabel("Telephone: ", JLabel.LEFT);
formPanel.add(telephoneLabel);
formPanel.add(telephone);
JLabel emailLabel = new JLabel("Email: ", JLabel.LEFT);
formPanel.add(emailLabel);
formPanel.add(email);
add(formPanel);
// create button panel
JPanel buttonPanel = new JPanel();
JButton insertButton = new JButton("Insert");
JButton displayButton = new JButton("Display");
ActionListener insertAction = new AddressBookListener();
ActionListener displayAction = new AddressBookListener();
insertButton.addActionListener(insertAction);
displayButton.addActionListener(displayAction);
buttonPanel.add(insertButton);
buttonPanel.add(displayButton);
add(buttonPanel);
}
public int getTotalContacts() {
return addressList.size();
}
private JTextField firstName;
private JTextField lastName;
private JTextField telephone;
private JTextField email;
private JLabel contacts;
private class AddressBookListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String buttonPressed = e.getActionCommand();
System.out.println(buttonPressed);
if (buttonPressed == "Insert") {
Person aPerson = new Person(firstName.getText(), lastName
.getText(), telephone.getText(), email.getText());
addressList.add(aPerson);
} else {
for (Person p : addressList) {
System.out.println(p);
}
}
}
}
}
}
Related
how do you get the User input inside JTextFeild and SET/ADD the input to the table in another frame? Student objects are stored in an ArrayList. The array list is added to table view and displayed in another frame. StudentCntl, StudentListUI, StudentUI are shown below. StudentListUI(left) StudentUI(right)
public class StudentCntl {
private static final int STARTING_INDEX_OF_DISPLAY = 0;
StudentCntl studentCntl;
StudentList studentList;
StudentUI studentUI;
StudentListUI studentListUI;
StudentTableModel theStudentTable;
public StudentCntl() {
studentList = new StudentList();
theStudentTable = new StudentTableModel(studentList.getStudentList());
studentUI = new StudentUI(this, STARTING_INDEX_OF_DISPLAY);
studentUI.setVisible(true);
studentListUI = new StudentListUI(this, studentUI);
studentListUI.setVisible(true);
}
public StudentTableModel getStudentTableModel() {
return theStudentTable;
}
Student getStudent(int index) {
Student student = studentList.getStudentList().get(index);
return student;
}
public class StudentUI extends JFrame {
private int indexOfElementToDisplay;
private final JTextField firstNameDisplayValue = new JTextField(15);
private final JTextField lastNameDisplayValue = new JTextField(15);
private final JTextField gpaDisplayValue = new JTextField(15);
private JPanel studentPanel;
private JPanel buttonPanel;
String[] info = {firstNameDisplayValue.getText(),lastNameDisplayValue.getText(),gpaDisplayValue.getText()};
private final StudentCntl studentCntl;
public StudentUI(StudentCntl studentCntl, int startingIndexOfDisplay) {
this.studentCntl = studentCntl;
indexOfElementToDisplay = startingIndexOfDisplay;
initComponents();
setFieldView();
}
private void initComponents() {
setTitle("Student Viewer");
setSize(500, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
studentPanel = new JPanel(new GridLayout(5, 1));
studentPanel.add(new JLabel("First Name"));
studentPanel.add(firstNameDisplayValue);
studentPanel.add(new JLabel("Last Name"));
studentPanel.add(lastNameDisplayValue);
studentPanel.add(new JLabel("GPA"));
studentPanel.add(gpaDisplayValue);
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton nextButton = new JButton("Next");
JButton previousButton = new JButton("Previous");
JButton deleteButton = new JButton("Delete");
JButton newButton = new JButton("New Entry");
JButton saveButton = new JButton("Save");
nextButton.addActionListener(e -> showNext(indexOfElementToDisplay));
buttonPanel.add(nextButton);
previousButton.addActionListener(e -> showPrevious(indexOfElementToDisplay));
buttonPanel.add(previousButton);
deleteButton.addActionListener(e -> showDelete(indexOfElementToDisplay));
buttonPanel.add(deleteButton);
saveButton.addActionListener(e -> addToList(info));
buttonPanel.add(saveButton);
newButton.addActionListener(e -> showNew());
buttonPanel.add(newButton);
setContentPane(new JPanel(new BorderLayout()));
getContentPane().add(studentPanel, BorderLayout.CENTER);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}
private void setFieldView() {
firstNameDisplayValue.setText(studentCntl.getStudent(indexOfElementToDisplay).getFirstName());
lastNameDisplayValue.setText(studentCntl.getStudent(indexOfElementToDisplay).getLastName());
gpaDisplayValue.setText(Double.toString(studentCntl.getStudent(indexOfElementToDisplay).getGpa()));
}
private void NewEntryView() {
firstNameDisplayValue.setText(" ");
lastNameDisplayValue.setText(" ");
gpaDisplayValue.setText(" ");
}
private void addToList(String[] info){
studentCntl.studentList.getStudentList().add(new Student(info));
}
private void showNew() {
NewEntryView();
}
void refreshDisplayWithNewValues(int index) {
setFieldView();
this.repaint();
}
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.
I've tried different methods to fix this, but apparently nothing works. Because I am new to java I actually don't know if there's something wrong with my code.
I've tried setting the size of the text area that is supposed to go into the SOUTH part of the border layout, but the size is still to small to see.
Anyone know of a solution?
package package1;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SimpleDatabasePanel extends JFrame implements ActionListener {
private JMenuBar menuBar;
private JMenu file;
private JMenuItem save, load, quit;
private JButton add, undo, find, delete, display;
private JScrollPane pane;
private JTable table;
private JPanel panel;
private JTextArea tName, tGNum, tGPA, results;
private JLabel name, gNum, gpa;
private LinkedList list;
public SimpleDatabasePanel(){
setLayout(new BorderLayout());
setTitle("Simple Database");
//setSize(1000,1000);
menuBar = new JMenuBar();
setJMenuBar(menuBar);
file = new JMenu("File");
quit = new JMenuItem("Quit");
save = new JMenuItem("Save");
load = new JMenuItem("Load");
add = new JButton("Add");
undo = new JButton("Undo");
find = new JButton("Find");
delete = new JButton("Delete");
display = new JButton("Display");
tName = new JTextArea();
tGNum = new JTextArea();
tGPA = new JTextArea();
results = new JTextArea(10,20);
name = new JLabel("Name");
gNum = new JLabel("G Number");
gpa = new JLabel("GPA");
list = new LinkedList();
panel = new JPanel();
panel.setLayout(new GridLayout(3, 4, 4, 4));
//frame = new JFrame();
pane = new JScrollPane();
pane.setSize(300, 60);
table = new JTable();
menuBar = new JMenuBar();
menuBar.add(file);
file.add(save);
file.add(load);
file.add(quit);
panel.add(name);
panel.add(tName);
panel.add(undo);
panel.add(add);
panel.add(gNum);
panel.add(tGNum);
panel.add(find);
panel.add(delete);
panel.add(gpa);
panel.add(tGPA);
panel.add(display);
pane.add(results);
add(menuBar, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
add(pane, BorderLayout.SOUTH);
this.pack();
ButtonListener listener = new ButtonListener();
file.addActionListener(file.getAction());
find.addActionListener(listener);
undo.addActionListener(listener);
save.addActionListener(this);
quit.addActionListener(this);
add.addActionListener(listener);
load.addActionListener(this);
delete.addActionListener(listener);
display.addActionListener(listener);
}
public void actionPerformed(ActionEvent e) {
JMenuItem file = (JMenuItem) e.getSource();
if(file == quit){
System.exit(0);
}
if(file == load){
String filename = JOptionPane.showInputDialog("Enter File Name: ");
(list).load(filename);
}
if(file == save){
String filename = JOptionPane.showInputDialog("Enter File Name: ");
(list).save(filename);
}
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if(event.getSource() == add){
}
if(event.getSource() == delete){
}
if(event.getSource() == display){
}
if(event.getSource() == find){
}
if(event.getSource() == undo){
}
}
}
public static void main(String[] args){
SimpleDatabasePanel s =new SimpleDatabasePanel();
s.setVisible(true);
s.setResizable(false);
}
}
change this
pane.add(results);
to this
pane.setViewportView(results);
or this
pane.getViewport().add(results, null);
use setViewportView or getViewport().add to set component to jscrollpane.also you can pass component (jtextarea ) to constructor of jscrollpane.read more about jscrollpane here
output
I am working on a project for my Java class and cannot get my clear button to work. More specifically, I am having an issue implementing Action and ItemListeners. My understanding is that I need to use ActionListener for my clear button, but I need to use ItemListener for my ComboBoxes. I am very new to Java and this is an intro class. I haven't even begun to code the submit button and ComboBoxes and am a little overwhelmed. For now, I could use help figuring out why my clear function will not work. Any help is greatly appreciated. Thanks in advance.
Here is my updated code after suggestions:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class cousinsTree extends JApplet
{
Container Panel;
JButton submitButton;
JButton clearButton;
JTextField firstName;
JTextField lastName;
JTextField Address;
JTextField City;
JMenuBar menuBar;
JTextField Total;
JComboBox Service;
JComboBox howOften;
JComboBox numTrees;
LayoutManager setLayout;
String[] TreeList;
String[] numList;
String[] oftenList;
#Override
public void init()
{
Panel = getContentPane();
this.setLayout(new FlowLayout());
TreeList= new String[3];
TreeList [0] = "Trim";
TreeList [1] = "Chemical Spray";
TreeList [2] = "Injection";
numList = new String[3];
numList [0] = "0-5";
numList [1] = "6-10";
numList [2] = "11 >";
oftenList = new String[3];
oftenList [0] = "Monthly";
oftenList [1] = "Quarterly";
oftenList [2] = "Annually";
Panel.setBackground (Color.green);
submitButton = new JButton("Submit");
submitButton.setPreferredSize(new Dimension(100,30));
clearButton.addActionListener(new clrButton());
clearButton = new JButton("Clear");
clearButton.setPreferredSize(new Dimension(100,30));
firstName = new JTextField("", 10);
JLabel lblFirstName = new JLabel("First Name");
lastName = new JTextField("", 10);
JLabel lblLastName = new JLabel("Last Name");
Address = new JTextField("", 15);
JLabel lblAddress = new JLabel("Address");
City = new JTextField("Columbus", 10);
JLabel lblCity = new JLabel("City");
Total = new JTextField("", 10);
JLabel lblTotal = new JLabel("Total");
//Service = new TextField("Service (Trim, Chemical Spray, or Injection).", 20);
JLabel lblService = new JLabel("Service");
Service=new JComboBox(TreeList);
JLabel lblhowOften = new JLabel("How often?");
howOften = new JComboBox(oftenList);
JLabel lblnumTrees = new JLabel("Number of Trees");
numTrees = new JComboBox(numList);
/* Configuration */
//add items to panel
Panel.add(lblFirstName);
Panel.add(firstName);
Panel.add(lblLastName);
Panel.add(lastName);
Panel.add(lblAddress);
Panel.add(Address);
Panel.add(lblCity);
Panel.add(City);
Panel.add(lblnumTrees);
Panel.add(numTrees);
Panel.add(lblService);
Panel.add(Service);
Panel.add(lblhowOften);
Panel.add(howOften);
Panel.add(submitButton);
Panel.add(clearButton);
Panel.add(lblTotal);
Panel.add(Total);
this.setSize(new Dimension(375, 275));
this.setLocation(0,0);
Service.setSelectedIndex (1);
howOften.setSelectedIndex (1);
numTrees.setSelectedIndex (1);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menuFile = new JMenu("File", true);
menuFile.setMnemonic(KeyEvent.VK_F);
menuFile.setDisplayedMnemonicIndex(0);
menuBar.add(menuFile);
JMenu menuSave = new JMenu("Save", true);
menuSave.setMnemonic(KeyEvent.VK_S);
menuSave.setDisplayedMnemonicIndex(0);
menuBar.add(menuSave);
JMenu menuExit = new JMenu("Exit", true);
menuExit.setMnemonic(KeyEvent.VK_X);
menuExit.setDisplayedMnemonicIndex(0);
menuBar.add(menuExit);
}
class clrButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
// clearButton.addActionListener(this);
firstName.setText("");
lastName.setText("");
Address.setText("");
City.setText("");
}
}
class subButton implements ItemListener {
public void itemStateChanged(ItemEvent e) {
submitButton.addItemListener(this);
Service.addItemListener(this);
numTrees.addItemListener(this);
howOften.addItemListener(this);
}
}
}
I was able to get it to work...Thank you all for your help. I removed the class and it worked.
Here is the working code:
[Code]
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class cousinsTree extends JApplet implements ActionListener
{
Container Panel;
JButton submitButton;
JButton clearButton;
JTextField firstName;
JTextField lastName;
JTextField Address;
JTextField City;
JMenuBar menuBar;
JTextField Total;
JComboBox Service;
JComboBox howOften;
JComboBox numTrees;
LayoutManager setLayout;
String[] TreeList;
String[] numList;
String[] oftenList;
public void init()
{
Panel = getContentPane();
this.setLayout(new FlowLayout());
TreeList= new String[3];
TreeList [0] = "Trim";
TreeList [1] = "Chemical Spray";
TreeList [2] = "Injection";
numList = new String[3];
numList [0] = "0-5";
numList [1] = "6-10";
numList [2] = "11 >";
oftenList = new String[3];
oftenList [0] = "Monthly";
oftenList [1] = "Quarterly";
oftenList [2] = "Annually";
Panel.setBackground (Color.green);
submitButton = new JButton("Submit");
submitButton.setPreferredSize(new Dimension(100,30));
clearButton = new JButton("Clear");
clearButton.addActionListener(this);
clearButton.setPreferredSize(new Dimension(100,30));
firstName = new JTextField("", 10);
JLabel lblFirstName = new JLabel("First Name");
lastName = new JTextField("", 10);
JLabel lblLastName = new JLabel("Last Name");
Address = new JTextField("", 15);
JLabel lblAddress = new JLabel("Address");
City = new JTextField("Columbus", 10);
JLabel lblCity = new JLabel("City");
Total = new JTextField("", 10);
JLabel lblTotal = new JLabel("Total");
//Service = new TextField("Service (Trim, Chemical Spray, or Injection).", 20);
JLabel lblService = new JLabel("Service");
Service=new JComboBox(TreeList);
JLabel lblhowOften = new JLabel("How often?");
howOften = new JComboBox(oftenList);
JLabel lblnumTrees = new JLabel("Number of Trees");
numTrees = new JComboBox(numList);
/* Configuration */
//add items to panel
Panel.add(lblFirstName);
Panel.add(firstName);
Panel.add(lblLastName);
Panel.add(lastName);
Panel.add(lblAddress);
Panel.add(Address);
Panel.add(lblCity);
Panel.add(City);
Panel.add(lblnumTrees);
Panel.add(numTrees);
Panel.add(lblService);
Panel.add(Service);
Panel.add(lblhowOften);
Panel.add(howOften);
Panel.add(submitButton);
Panel.add(clearButton);
Panel.add(lblTotal);
Panel.add(Total);
this.setSize(new Dimension(375, 275));
this.setLocation(0,0);
Service.setSelectedIndex (1);
howOften.setSelectedIndex (1);
numTrees.setSelectedIndex (1);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menuFile = new JMenu("File", true);
menuFile.setMnemonic(KeyEvent.VK_F);
menuFile.setDisplayedMnemonicIndex(0);
menuBar.add(menuFile);
JMenu menuSave = new JMenu("Save", true);
menuSave.setMnemonic(KeyEvent.VK_S);
menuSave.setDisplayedMnemonicIndex(0);
menuBar.add(menuSave);
JMenu menuExit = new JMenu("Exit", true);
menuExit.setMnemonic(KeyEvent.VK_X);
menuExit.setDisplayedMnemonicIndex(0);
menuBar.add(menuExit);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == clearButton) {
firstName.setText("");
lastName.setText("");
Address.setText("");
City.setText("");
}
}
}
[/Code]
Add following line
clearButton.addActionListener(new clrButton());
class clrButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
// clearButton.addActionListener(this); Comment it
// if(e.getSource() == clearButton){-> this line don't need.
firstName.setText("");
lastName.setText("");
Address.setText("");
City.setText("");
}
}
You are doing good. But just place the following code
clearButton.addActionListener(new clrButton());
Before and outside of class clrButton
Also try placing these statements outside of class subButton
submitButton.addItemListener(new subButton());
Service.addItemListener(new anotherClass());
numTrees.addItemListener(new anotherClass());
howOften.addItemListener(new anotherClass());
You need to add actionlistener to your buttons. so, the action events will be propogated to the listener where you do your logic of the action. so, you have to addActionListener to your button
clearButton.addActionListener(new clrButton());
i.e in your init() method
clearButton = new JButton("Clear");
clearButton.setPreferredSize(new Dimension(100,30));
//add this below line to add action listener to the button
clearButton.addActionListener(new clrButton());
Onemore line to be removed is clearButton.addActionListener(this); from your action performed method
I have a problem with a JList. When I select an item, it resizes itself. How can I set the JList to a fixed size?
Here is a screenshot before I selected anything
and this is after
Here is my code:
public class AgendaView extends JFrame {
private JLabel firstNameLabel, lastNameLabel, adressLabel, phoneNumberLabel, extraInfoLabel;
private Button editButton, addButton, deleteButton, showButton;
private JPanel labels, gui, buttons;
private DefaultListModel model;
private JList list;
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem newItem, saveItem, saveAsItem, exitItem, openItem;
private Agenda agenda;
private JScrollPane scrollPane;
public AgendaView() {
super("***Agenda View***");
menuBar = new JMenuBar();
menu = new JMenu("Menu");
menu.add(new JSeparator());
newItem = new JMenuItem("New");
saveItem = new JMenuItem("Save");
saveItem.setEnabled(false);
saveAsItem = new JMenuItem("Save as..");
saveAsItem.setEnabled(false);
exitItem = new JMenuItem("Exit");
openItem = new JMenuItem("Open");
saveItem.add(new JSeparator());
exitItem.add(new JSeparator());
menu.add(newItem);
menu.add(openItem);
menu.add(saveItem);
menu.add(saveAsItem);
menu.add(exitItem);
gui = new JPanel(new BorderLayout(2, 2));
gui.setBorder(new TitledBorder("Owner"));
labels = new JPanel(new GridLayout(0, 1, 1, 1));
labels.setBorder(new TitledBorder("Contact "));
buttons = new JPanel(new GridLayout(1, 0, 1, 1));
editButton = new Button("Edit");
addButton = new Button("Add");
deleteButton = new Button("Delete");
showButton = new Button("Show");
editButton.setEnabled(false);
addButton.setEnabled(false);
deleteButton.setEnabled(false);
showButton.setEnabled(false);
buttons.add(showButton);
buttons.add(editButton);
buttons.add(addButton);
buttons.add(deleteButton);
firstNameLabel = new JLabel("First name: ");
lastNameLabel = new JLabel("Last name: ");
adressLabel = new JLabel("Adress: ");
phoneNumberLabel = new JLabel("Phone number: ");
extraInfoLabel = new JLabel("Extra info: ");
labels.add(firstNameLabel);
labels.add(lastNameLabel);
labels.add(adressLabel);
labels.add(phoneNumberLabel);
labels.add(extraInfoLabel);
model = new DefaultListModel();
list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setVisibleRowCount(-1);
list.addListSelectionListener(
new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent lse) {
String name = list.getSelectedValue().toString();
String[] split = name.split(" ");
Contact contact = agenda.searchContactbyName(split[0], split[1]);
firstNameLabel.setText("First name: " + contact.getFirstName());
lastNameLabel.setText("Last name: " + contact.getLastName());
adressLabel.setText("Adress: " + contact.getAdress());
phoneNumberLabel.setText("Phone number: " + contact.getPhoneNumber());
if (contact.getType().compareTo("Acquaintance") == 0) {
extraInfoLabel.setText("Occupation: " + contact.getExtraInfo());
} else if (contact.getType().compareTo("Colleague") == 0) {
extraInfoLabel.setText("Email: " + contact.getExtraInfo());
} else if (contact.getType().compareTo("Friend") == 0) {
extraInfoLabel.setText("Birthdate: " + contact.getExtraInfo());
} else {
extraInfoLabel.setVisible(false);
}
}
});
scrollPane = new JScrollPane(list);
gui.add(labels, BorderLayout.CENTER);
gui.add(scrollPane, BorderLayout.WEST);
gui.add(buttons, BorderLayout.SOUTH);
add(gui);
menuBar.add(menu);
setJMenuBar(menuBar);
Here is where I display the GUI:
public class JavaLab3_pb1Java {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
Agenda agenda = new Agenda();
AgendaView agendaView = new AgendaView();
agendaView.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
agendaView.setSize(500, 300);
agendaView.pack();
agendaView.setVisible(true);
}
}
You need to call pack() on your JFrame after adding all components and before calling setVisible(true) on it. This will tell the GUI's layout managers to manage their layouts, and will resize the GUI to the preferred size as specified by the components and the layouts.
Edit
Never call setSize(...) on anything. Better to override getPreferredSize(). For example, my sscce:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
public class AgendaView extends JFrame {
private static final int PREF_W = 500;
private static final int PREF_H = 300;
private JLabel firstNameLabel, lastNameLabel, adressLabel, phoneNumberLabel,
extraInfoLabel;
private JButton editButton, addButton, deleteButton, showButton;
private JPanel labels, gui, buttons;
private DefaultListModel<String> model;
private JList<String> list;
private JScrollPane scrollPane;
public AgendaView() {
super("***Agenda View***");
gui = new JPanel(new BorderLayout(2, 2));
gui.setBorder(new TitledBorder("Owner"));
labels = new JPanel(new GridLayout(0, 1, 1, 1));
labels.setBorder(new TitledBorder("Contact "));
buttons = new JPanel(new GridLayout(1, 0, 1, 1));
editButton = new JButton("Edit");
addButton = new JButton("Add");
deleteButton = new JButton("Delete");
showButton = new JButton("Show");
editButton.setEnabled(false);
addButton.setEnabled(false);
deleteButton.setEnabled(false);
showButton.setEnabled(false);
buttons.add(showButton);
buttons.add(editButton);
buttons.add(addButton);
buttons.add(deleteButton);
firstNameLabel = new JLabel("First name: ");
lastNameLabel = new JLabel("Last name: ");
adressLabel = new JLabel("Adress: ");
phoneNumberLabel = new JLabel("Phone number: ");
extraInfoLabel = new JLabel("Extra info: ");
labels.add(firstNameLabel);
labels.add(lastNameLabel);
labels.add(adressLabel);
labels.add(phoneNumberLabel);
labels.add(extraInfoLabel);
model = new DefaultListModel<String>();
list = new JList<String>(model);
String[] eles = { "Ciprian Aftode", "Andrei Batinas", "Bogdan Fichitiu",
"Valentin Pascau" };
for (String ele : eles) {
model.addElement(ele);
}
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// list.setVisibleRowCount(-1);
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent lse) {
firstNameLabel.setText("First name: first name");
lastNameLabel.setText("Last name: last name");
adressLabel.setText("Address: Address");
phoneNumberLabel.setText("Phone number: PhoneNumber");
extraInfoLabel.setText("Occupation: ExtraInfo");
}
});
int ebGap = 8;
list.setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
scrollPane = new JScrollPane(list);
gui.add(labels, BorderLayout.CENTER);
gui.add(scrollPane, BorderLayout.WEST);
gui.add(buttons, BorderLayout.SOUTH);
add(gui);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
AgendaView frame = new AgendaView();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}