This is the class where I store the data:
package entities;
import java.util.ArrayList;
public class EshopData {
private static ArrayList<User> users = new ArrayList<User>();
public ArrayList<User> getUsers() {
return users;
}
public static void setUsers( ArrayList<User> users) {
EshopData.users = users;
}
}
This is my main Frame:
package ui;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
import entities.User;
public class Frame extends JFrame{
public static void main(String[] args) {
//FRAME
JFrame frame = new JFrame("My first Eshop");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
//frame.setVisible(true);
frame.setLayout(null);
//LABELS
JLabel l1 = new JLabel("Username:");
JLabel l2 = new JLabel("Password:");
l1.setBounds(35, 60, 80, 20);
l2.setBounds(35, 110, 80, 20);
//TEXTFIELDS
JTextField tf1 = new JTextField();
JTextField tf2 = new JTextField();
tf1.setBounds(150, 60, 90, 20);
tf2.setBounds(150, 110, 90, 20);
//BUTTONS
JButton b1 = new JButton("Register");
JButton b2 = new JButton("Login");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
RegisterFrame rframe = new RegisterFrame();
rframe.setVisible(true);
rframe.setSize(600, 600);
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
}
});
b1.setBounds(35, 150, 100, 20);
b2.setBounds(160, 150, 80, 20);
//ADDING TO FRAME
frame.add(l1);
frame.add(l2);
frame.add(tf1);
frame.add(tf2);
frame.add(b1);
frame.add(b2);
frame.setVisible(true);
}
}
In my main Frame I have a button "Login" (its the 'b2' button) and I want to create an actionListener that will iterate through the array list from above and search for the User.username, if the username exists it will search for the User.password afterwards.
I am not sure whether I am explaining it correctly or not but any kind of help will be appreciated.
If you need any other part of the code I am here to provide it for you. Thnak's in advance!
You can create a custom wrapper class for ActionListener. This custom class, let's call it EshopDataBasedActionListener will contain a field for EshopData object. When you create this Listener, you will pass in the actual Object of EshopData that has already been created and that contains the user list. Now you are able to access this object inside your listener.
The next part of your problem of binding the Listener to your Login button will now be easier to achieve. You can now provide the implementation of the actionPerformed method that will contain your logic. You can pass in the username and password in the same fashion.
Related
I've made the initialize method public, didn't help and I've set visible to true both here and the external class as seen below, any help would be appreciated. I created the gui using the window builder tool from eclipse
GeneralWindow frame = new GeneralWindow();
frame.setVisible(true);
package gui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import java.awt.Font;
public class GeneralWindow extends JFrame{
private JFrame frame;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GeneralWindow window = new GeneralWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GeneralWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Order");
btnNewButton.setBounds(309, 12, 115, 23);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("Search");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_1.setBounds(309, 46, 115, 23);
frame.getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Stock");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnNewButton_2.setBounds(309, 80, 115, 23);
frame.getContentPane().add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("Emplyoees");
btnNewButton_3.setBounds(309, 114, 115, 23);
frame.getContentPane().add(btnNewButton_3);
JButton btnNewButton_4 = new JButton("Price Amend");
btnNewButton_4.setBounds(309, 148, 115, 23);
frame.getContentPane().add(btnNewButton_4);
JButton btnNewButton_5 = new JButton("Total");
btnNewButton_5.setBounds(309, 182, 115, 23);
frame.getContentPane().add(btnNewButton_5);
textField = new JTextField();
textField.setBounds(10, 228, 178, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblProductcodeBar = new JLabel("Productcode Bar");
lblProductcodeBar.setFont(new Font("Tahoma", Font.BOLD, 11));
lblProductcodeBar.setBounds(10, 209, 125, 14);
frame.getContentPane().add(lblProductcodeBar);
JButton btnEnter = new JButton("Enter");
btnEnter.setBounds(198, 227, 89, 23);
frame.getContentPane().add(btnEnter);
JTextArea textArea = new JTextArea();
textArea.setBounds(10, 11, 277, 196);
frame.getContentPane().add(textArea);
}
}
You're making the frame frame, of type GeneralWindow, visible. But you never add any component to that frame. Instead, your initialize method creates yet another frame, and adds many components to that frame. Don't create another frame, and add the components to this, instead.
In Your initialize() just change the frame to this keyword
e.g
//Remove this line
frame = new JFrame();
//change frame to this keyword
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
That its u r done...
Whilst the two answers provide here give a correct solution, they both reinforce the view that you should extend JFrame. This is not good advice in general, as you should favour composition over inheritance. Indeed the way you were writing the code to include a JFrame as a private member was the correct instinct.
I've included a stripped down version of your code that doesn't extend JFrame Instead it creates an instance of the JFrame when you call the createAndDisplayFrame() method.
public class GeneralWindow {
private JFrame frame;
private JButton orderButton;
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
GeneralWindow window = new GeneralWindow();
window.crateAndDisplayFrame();
}
});
}
public void crateAndDisplayFrame() {
initialize();
frame.setVisible(true);
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
orderButton = new JButton("Order");
orderButton.setBounds(309, 12, 115, 23);
frame.getContentPane().add(orderButton);
}
}
I'm trying to build a program and I am having trouble getting my ArrayList from another class to show up in a JComboBox. My program will look something like this but before where "Melissa" is written, I want to have a JComboBox that has a list of users and be able to select from it to get the results:
UPDATE Here is my error:
----jGRASP exec: javac -g UserHistory.java
UserHistory.java:20: error: cannot find symbol
String[] userListItems = users.toArray(new String[0]);
^
symbol: variable users
location: class UserHistory
Note: UserHistory.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Here is my incomplete code which gives me an error because it cannot locate my arrayList:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.ArrayList;
public class UserHistory extends JPanel {
private JLabel jcomp1;
private JComboBox userList;
private JLabel jcomp3;
private JTextField selectedUser;
private JLabel jcomp5;
private JTextField pointsEarned;
private JLabel jcomp7;
private JList choresCompleted;
public UserHistory() {
//construct preComponents
String[] userListItems = users.toArray(new String[0]);
String[] choresCompletedItems = {"Item 1", "Item 2", "Item 3"};
//construct components
jcomp1 = new JLabel ("User History");
userList = new JComboBox(userListItems);
jcomp3 = new JLabel ("Below are the results of : ");
selectedUser = new JTextField (5);
jcomp5 = new JLabel ("Total points earned: ");
pointsEarned = new JTextField (5);
jcomp7 = new JLabel ("List of chores completed: ");
choresCompleted = new JList (choresCompletedItems);
//set components properties
userList.setToolTipText ("Select a user");
//adjust size and set layout
setPreferredSize (new Dimension (465, 343));
setLayout (null);
//add components
add (jcomp1);
add (userList);
add (jcomp3);
add (selectedUser);
add (jcomp5);
add (pointsEarned);
add (jcomp7);
add (choresCompleted);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (120, 20, 70, 25);
userList.setBounds (210, 20, 100, 25);
jcomp3.setBounds (95, 70, 155, 25);
selectedUser.setBounds (245, 70, 100, 25);
jcomp5.setBounds (125, 105, 140, 25);
pointsEarned.setBounds (245, 105, 100, 25);
jcomp7.setBounds (95, 140, 160, 25);
choresCompleted.setBounds (245, 145, 100, 75);
}
public static void main (String[] args) {
JFrame frame = new JFrame ("UserHistory");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new UserHistory());
frame.pack();
frame.setVisible (true);
}
}
Here's my code for another panel that contains the ArrayList:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.JCheckBox;
public class ManageUsersGUI extends JPanel {
public ArrayList<User> users = new ArrayList<>();
private JLabel addNewUserLabel;
private JTextField addNewUserTextField;
private JLabel deleteUsersLabel;
private JButton addButton;
private JButton deleteButton;
private JPanel namePanel;
public ManageUsersGUI() {
//construct components
addNewUserLabel = new JLabel ("Add new User here:");
addNewUserTextField = new JTextField (0);
deleteUsersLabel = new JLabel ("Select which User(s) you would like to delete:");
addButton = new JButton ("Add");
deleteButton = new JButton ("Delete");
namePanel = new JPanel();
namePanel.setLayout(new BoxLayout(namePanel, BoxLayout.Y_AXIS));
//set components properties
addNewUserTextField.setToolTipText ("Enter name and click on Add button.");
addButton.setToolTipText ("Click here to Add new user.");
deleteButton.setToolTipText ("Click here to delete User(s) selected.");
//adjust size and set layout
setPreferredSize (new Dimension (580, 485));
setLayout (null);
//add components
add (addNewUserLabel);
add (addNewUserTextField);
add (deleteUsersLabel);
add (namePanel);
add (addButton);
add (deleteButton);
//set component bounds (only needed by Absolute Positioning)
addNewUserLabel.setBounds (85, 130, 120, 25);
addNewUserTextField.setBounds (235, 130, 125, 25);
deleteUsersLabel.setBounds (135, 225, 281, 25);
addButton.setBounds (385, 130, 100, 25);
namePanel.setBounds(225, 270, 140, 0);
deleteButton.setBounds (230, 335, 100, 25);
addButton.addActionListener(new AddButtonListener());
deleteButton.addActionListener(new DeleteButtonListener());
}
public ArrayList<User> getUser() {
return users;
}
private class AddButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = addNewUserTextField.getText();
users.add(new User(text));
// Display the changes.
JOptionPane.showMessageDialog(null, text + " has been added.");
JCheckBox nameCheckBox = new JCheckBox();
nameCheckBox.setText(addNewUserTextField.getText());
namePanel.add(nameCheckBox);
namePanel.setBounds(225, 270, 140, namePanel.getHeight() + 25);
deleteButton.setBounds(230, deleteButton.getY() + 25, 100, 25);
JFrame frame = (JFrame) getRootPane().getParent();
frame.setSize(frame.getWidth(), frame.getHeight() + 25);
frame.pack();
}
}
private class DeleteButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
for(Component component : namePanel.getComponents()) {
if(component instanceof JCheckBox) {
if(((JCheckBox)component).isSelected())
namePanel.remove(component);
}
}
namePanel.revalidate();
namePanel.repaint();
}
}
public static void main (String[] args) {
JFrame frame = new JFrame ("AddUsersPanel1");
frame.setTitle("Manage Users");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new ManageUsersGUI());
frame.pack();
frame.setVisible (true);
}
}
Here's my User class that was used to make the ArrayList:
public class User {
private String userName;
private int points = 0;
public User(String userName) {
this.userName = userName;
}
public User() {
userName = "";
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void addPoints(int chorePoints) {
points += chorePoints;
}
// public String toString() {
// return userName + "\n";
// }
}
First of all you would better call user manager module from history main like
JFrame frame = new JFrame ("UserHistory");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new UserHistory());
frame.pack();
frame.setVisible (true);
manageUsers();
Which will start both JPanels so you can manage users and watch history at the same time.
Additionally,
// in ManageUsersGUI
public static void manageUsers() {
JFrame frame = new JFrame ("AddUsersPanel1");
frame.setTitle("Manage Users");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new ManageUsersGUI());
frame.pack();
frame.setVisible (true);
}
And one more thing, as soon as you initialize userlist you need to attach a listener like below:
userList = new JComboBox(userListItems);
userList.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
userList.removeAllItems();
for (User user: users) {
userList.addItem(user.getUserName());
}
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
});
These two corrections would you make be able to list user names on the combo box and the dynamic change of user list would be reflected to the listing in the box.
Cheers.
Let me upload the whole source code here
User.java -- Source code just follows (I don't know why they came out of box.)
package userchorelist;
public class User {
private String userName;
private int points = 0;
public User(String userName) {
this.userName = userName;
}
public User() {
userName = "";
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void addPoints(int chorePoints) {
points += chorePoints;
}
}
ManageUsersGUI.java -- Source code just follows (I don't know why they came out of box, again.)
package userchorelist;
import javax.swing.;
import java.awt.;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.JCheckBox;
public class ManageUsersGUI extends JPanel {
public static ArrayList users = new ArrayList<>();
private JLabel addNewUserLabel;
private JTextField addNewUserTextField;
private JLabel deleteUsersLabel;
private JButton addButton;
private JButton deleteButton;
private JPanel namePanel;
public ManageUsersGUI() {
//construct components
addNewUserLabel = new JLabel ("Add new User here:");
addNewUserTextField = new JTextField (0);
deleteUsersLabel = new JLabel ("Select which User(s) you would like to delete:");
addButton = new JButton ("Add");
deleteButton = new JButton ("Delete");
namePanel = new JPanel();
namePanel.setLayout(new BoxLayout(namePanel, BoxLayout.Y_AXIS));
//set components properties
addNewUserTextField.setToolTipText ("Enter name and click on Add button.");
addButton.setToolTipText ("Click here to Add new user.");
deleteButton.setToolTipText ("Click here to delete User(s) selected.");
//adjust size and set layout
setPreferredSize (new Dimension (580, 485));
setLayout (null);
//add components
add (addNewUserLabel);
add (addNewUserTextField);
add (deleteUsersLabel);
add (namePanel);
add (addButton);
add (deleteButton);
//set component bounds (only needed by Absolute Positioning)
addNewUserLabel.setBounds (85, 130, 120, 25);
addNewUserTextField.setBounds (235, 130, 125, 25);
deleteUsersLabel.setBounds (135, 225, 281, 25);
addButton.setBounds (385, 130, 100, 25);
namePanel.setBounds(225, 270, 140, 0);
deleteButton.setBounds (230, 335, 100, 25);
addButton.addActionListener(new AddButtonListener());
deleteButton.addActionListener(new DeleteButtonListener());
}
public ArrayList<User> getUser() {
return users;
}
private class AddButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = addNewUserTextField.getText();
users.add(new User(text));
// Display the changes.
JOptionPane.showMessageDialog(null, text + " has been added.");
JCheckBox nameCheckBox = new JCheckBox();
nameCheckBox.setText(addNewUserTextField.getText());
namePanel.add(nameCheckBox);
namePanel.setBounds(225, 270, 140, namePanel.getHeight() + 25);
deleteButton.setBounds(230, deleteButton.getY() + 25, 100, 25);
JFrame frame = (JFrame) getRootPane().getParent();
frame.setSize(frame.getWidth(), frame.getHeight() + 25);
frame.pack();
}
}
private class DeleteButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
for(Component component : namePanel.getComponents()) {
if(component instanceof JCheckBox) {
if(((JCheckBox)component).isSelected())
namePanel.remove(component);
}
}
namePanel.revalidate();
namePanel.repaint();
}
}
public static void main (String[] args) {
JFrame frame = new JFrame ("AddUsersPanel1");
frame.setTitle("Manage Users");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new ManageUsersGUI());
frame.pack();
frame.setVisible (true);
}
// in ManageUsersGUI
public static void manageUsers() {
JFrame frame = new JFrame ("AddUsersPanel1");
frame.setTitle("Manage Users");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new ManageUsersGUI());
frame.pack();
frame.setVisible (true);
}
}
UserHistory.java -- Source code just follows (I don't know why they came out of box, third and final time.)
import java.awt.;
import javax.swing.;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import userchorelist.ManageUsersGUI;
import static userchorelist.ManageUsersGUI.manageUsers;
import static userchorelist.ManageUsersGUI.users;
import userchorelist.User;
public class UserHistory extends JPanel {
private JLabel jcomp1;
private JComboBox userList;
private JLabel jcomp3;
private JTextField selectedUser;
private JLabel jcomp5;
private JTextField pointsEarned;
private JLabel jcomp7;
private JList choresCompleted;
public UserHistory() {
//construct preComponents
String[] userListItems = new String[users.size()];
String[] choresCompletedItems = {"Item 1", "Item 2", "Item 3"};
//construct components
jcomp1 = new JLabel ("User History");
userList = new JComboBox(userListItems);
userList.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
userList.removeAllItems();
for (User user: users) {
userList.addItem(user.getUserName());
}
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
});
jcomp3 = new JLabel ("Below are the results of : ");
selectedUser = new JTextField (5);
jcomp5 = new JLabel ("Total points earned: ");
pointsEarned = new JTextField (5);
jcomp7 = new JLabel ("List of chores completed: ");
choresCompleted = new JList (choresCompletedItems);
//set components properties
userList.setToolTipText ("Select a user");
//adjust size and set layout
setPreferredSize (new Dimension (465, 343));
setLayout (null);
//add components
add (jcomp1);
add (userList);
add (jcomp3);
add (selectedUser);
add (jcomp5);
add (pointsEarned);
add (jcomp7);
add (choresCompleted);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (120, 20, 70, 25);
userList.setBounds (210, 20, 100, 25);
jcomp3.setBounds (95, 70, 155, 25);
selectedUser.setBounds (245, 70, 100, 25);
jcomp5.setBounds (125, 105, 140, 25);
pointsEarned.setBounds (245, 105, 100, 25);
jcomp7.setBounds (95, 140, 160, 25);
choresCompleted.setBounds (245, 145, 100, 75);
}
public static void main (String[] args) {
JFrame frame = new JFrame ("UserHistory");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new UserHistory());
frame.pack();
frame.setVisible (true);
manageUsers();
}
}
I suggest you add receive the list of users as an explicit parameter in both classes UserHistory and ManageUsersGUI:
class UserHistory
{
private final List<User> users;
public UserHistory(List<User> users)
{
super();
this.users=users;
...
}
}
class ManageUsersGUI
{
private final List<User> users;
public UserHistory(List<User> users)
{
super();
this.users=users;
...
}
}
Then, you can create a unique list of users as an external class, let's say UserManagement, and make it a singleton:
public class UserManagement
{
private static final UserManagement INSTANCE=new UserManagement();
private final List<User> list=new ArrayList<User>();
public static UserManagement getInstance()
{
return INSTANCE;
}
private UserManagement()
{
}
public List<User> getUsers()
{
return users;
}
}
Then, you must provide the list of users when instatiating both classes in the main methods (and further, future instatiations you may have):
public static void main (String[] args) {
...
UserManagement.getInstance().getUsers().add("winkum");
UserManagement.getInstance().getUsers().add("blinkum");
UserManagement.getInstance().getUsers().add("nod");
frame.getContentPane().add (new UserHistory(UserManagement.getInstance().getUsers()));
...
}
I almost have this code working. I can launch the GUI, however, when I press any of the buttons, I get the following error message:
The type TextFieldDemo must implement the inherited abstract method ActionListener
I have looked around online and can't see any issues with the code. Can someone help me please?
Thanks :)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TextFieldDemo implements ActionListener{
private JLabel lblName, lblAddress, lblPhone;
private JTextField txtName, txtAddress, txtPhone;
private JButton btnUpper, btnLower, btnExit;
private JPanel panel;
private JFrame frame;
public static void main(String[] args){
new TextFieldDemo();
}
public TextFieldDemo(){
createForm();
addFields();
addButtons();
frame.add(panel);
frame.setVisible(true);
}
public void createForm(){
frame = new JFrame();
frame.setTitle("Student Form");
frame.setSize(400,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(null);
}
public void addFields(){
txtName = new JTextField("Fred Bloggs");
txtName.setBounds(110, 50, 150, 20);
panel.add(txtName);
lblAddress = new JLabel ("Address");
lblAddress.setBounds(10, 70, 100, 20);
panel.add (lblAddress);
txtAddress = new JTextField ("Ashley Road");
txtAddress.setBounds(110, 70, 150, 20);
panel.add (txtAddress);
lblPhone = new JLabel ("Phone Number");
lblPhone.setBounds(10, 90, 100, 20);
panel.add (lblPhone);
txtPhone= new JTextField("01202 191 3333");
txtPhone.setBounds(110, 90, 150, 20);
panel.add (txtPhone);
lblName = new JLabel("Student Name");
lblName.setBounds(10, 50, 100, 20);
panel.add(lblName);
}
public void addButtons(){
btnUpper = new JButton ("UpperCase");
btnUpper.setBounds(50, 200, 100, 20);
btnUpper.addActionListener(this);
panel.add (btnUpper);
btnLower = new JButton ("LowerCase");
btnLower.setBounds(150, 200, 100, 20);
btnLower.addActionListener(this);
panel.add (btnLower);
btnExit = new JButton ("Exit");
btnExit.setBounds(250, 200, 100, 20);
btnExit.addActionListener(this);
panel.add (btnExit);
}
class UpperCaseHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
txtName.setText(txtName.getText().toUpperCase());
txtAddress.setText(txtAddress.getText().toUpperCase());
}
class LowerCaseHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
txtName.setText(txtName.getText().toLowerCase());
txtAddress.setText(txtAddress.getText().toLowerCase());
}
class ExitHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showConfirmDialog(frame,
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
}
}
}
You say TextFieldDemo implements ActionListener, but it doesn't have an actionPerformed() method, so it's not actually implementing the interface.
Either implement the method or don't claim it implements the interface.
I didn't think it would compile like you have it, but there you go!
The error should make you check the documentation of ActionListener to find out what method(s) is missing. Sometimes eclipse will prompt you to add stubs for the missing methods.
The documentation shows the interface ActionListener has one method to be implemented, actionPerformed();
http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html
Strange, the compiler should throw an error on this.
So I'm starting a new project and I was wondering how can I setup multiple classes for my different JPanels. It looks very messy in one class. Let me show you the example. I would like the JPanel for a menu screen in it's own class.
import java.awt.EventQueue;
public class TakeAwayLogin {
private JFrame frmTakeAwaySystem;
private JTextField textFieldId;
private JPasswordField passwordField;
/**
* Launch the application.
* #return
*/
public void login() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TakeAwayLogin window = new TakeAwayLogin();
window.frmTakeAwaySystem.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TakeAwayLogin() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmTakeAwaySystem = new JFrame();
frmTakeAwaySystem.setTitle("Take Away System Alpha");
frmTakeAwaySystem.setBounds(100, 100, 450, 300);
frmTakeAwaySystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTakeAwaySystem.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel panelLogin = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelLogin, "name_254735117500687");
panelLogin.setLayout(null);
panelLogin.setVisible(true);
final JLabel lblIncorrect = new JLabel("Incorrect login, try again");
lblIncorrect.setHorizontalAlignment(SwingConstants.CENTER);
lblIncorrect.setFont(new Font("Tahoma", Font.PLAIN, 9));
lblIncorrect.setForeground(Color.RED);
lblIncorrect.setBounds(148, 74, 139, 14);
panelLogin.add(lblIncorrect);
lblIncorrect.setVisible(false);
final JPanel panelPassword = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelPassword, "name_254738265432897");
panelPassword.setLayout(null);
passwordField = new JPasswordField();
passwordField.setBounds(112, 157, 205, 41);
panelLogin.add(passwordField);
passwordField.setHorizontalAlignment(JPasswordField.CENTER);
JButton btnNewButton = new JButton("Lock Application");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panelPassword.setVisible(false);
panelLogin.setVisible(true);
passwordField.setText("");
textFieldId.disable();
}
});
btnNewButton.setBounds(135, 155, 172, 50);
panelPassword.add(btnNewButton);
panelPassword.setVisible(false);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String login = textFieldId.getText();
char[] pass = passwordField.getPassword();
String p = new String(pass);
String password = "pass";
if (login.equalsIgnoreCase("milan") && p.equals(password)) {
panelPassword.setVisible(true);
panelLogin.setVisible(false);
}else {
lblIncorrect.setVisible(true);
}
}
});
btnLogin.setBounds(160, 209, 97, 41);
panelLogin.add(btnLogin);
textFieldId = new JTextField();
textFieldId.setBounds(112, 88, 205, 43);
panelLogin.add(textFieldId);
textFieldId.setColumns(10);
textFieldId.setHorizontalAlignment(JTextField.CENTER);
JLabel lblId = new JLabel("Enter the business login:");
lblId.setHorizontalAlignment(SwingConstants.CENTER);
lblId.setBounds(112, 63, 205, 14);
panelLogin.add(lblId);
JLabel lblEnterYourPassword = new JLabel("Enter your password");
lblEnterYourPassword.setHorizontalAlignment(SwingConstants.CENTER);
lblEnterYourPassword.setBounds(148, 142, 139, 14);
panelLogin.add(lblEnterYourPassword);
JPanel panelPizza = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelPizza, "name_254741096954780");
}
}
So help would be great.
Thanks very much.
I don't know why creating a second class would be necessary. If you just want the code to look less messy, then add comment separators between Panels or something to that effect. I think that splitting up the Panels into their own classes would be just cause you to have to write more calls to be able to create the same functionality. But if you must, then make a class within your initiate class and work from there.
Simplifying, you want something like:
public class MyMainJFrame extends JFrame{
private JPanel panel1 = new MyFooPanel();
private JPanel panel2 = new MyBarPanel();
public MyMainPanel(){
initialize();
}
void initialize(){
//init the JFrame
this.setTitle("Take Away System Alpha");
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new CardLayout(0, 0));
//and add the panels
this.add(panel1);
this.add(panel2);
}
}
// a file for each one
public class MyFooPanel extends JPanel{
private JButton button;
//... add components and logic
}
public class MyBarPanel extends JPanel{
private JTextField field;
//... add components and logic
}
If you want to use specific methods for each custom panel, then change the type of variable for the same name of the custom class.
I have two JFrame Forms-SelectContactsfrm.java and Taskfrm.java. There is JTable in SelectContactsfrm file to show the contacts.When user select a contact from JTable and when he/she press OK button,selected values should be copied into Taskfrm.java's JTextField.
Taskfrm.java's JTextField's name is-txtContacts and access modifier is-public
Below is the code which I wrote on SelectContactsfrm's OK button's actionPerformed.Button name-btnOK
private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {
// Code to get the selected rows value and paste Contact's full name in Taskfrm's txtContacts JTextField:
selrow=ctable.getSelectedRow();
selcol=ctable.getSelectedColumn();
Object value=ctable.getModel().getValueAt(selrow,1);
new Taskfrm().txtContacts.setText(value.toString());
//Just to check whether I get the correct values or not.
System.out.println("selrow=="+selrow);
System.out.println("selcol=="+selcol);
System.out.println("txtContacts=="+value);
}
I can see the correct selected values in output but didnt get why this value has not been set in Taskfrm's JTextField.In Taskfrm's constructor only initComponents() is there.Is there any way to attach class files here instead of pasting?
It depends on how Taskfrm is set up and what is in it's constructor.
I tried something like this and it works
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class ClassA extends JFrame {
JTextField text;
public ClassA() {
JLabel l = new JLabel("Name: ");
text = new JTextField(20);
JButton b = new JButton("Send");
setLayout(null);
l.setBounds(10, 10, 100, 20);
text.setBounds(120, 10, 150, 20);
b.setBounds(120, 40, 80, 20);
add(l);
add(text);
add(b);
setVisible(true);
setSize(300, 100);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new ClassB().text.setText(ClassA.this.text.getText());
}
});
}
public static void main(String a[]) {
new ClassA();
}
}
class ClassB extends JFrame {
JTextField text;
public ClassB() {
JLabel l = new JLabel("Name: ");
text = new JTextField(20);
setLayout(null);
l.setBounds(10, 10, 100, 20);
text.setBounds(120, 10, 150, 20);
add(l);
add(text);
setVisible(true);
setSize(300, 100);
}
}
set its visibility and made changes in Taskfrm's constructor.Now its working.
new Taskfrm(value);
new Taskfrm(value).setVisible(true);