GUI building and using different classes Java - java

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.

Related

JButton in Eclipse: "Button cannot be resolved or is not a field"

New to Java and this Page.
I am trying to perfom a certain action when a JButton is pressed. Following this tutorial (in German, sorry) http://www.java-tutorial.org/actionlistener.html, I used the JFrame Design feature and added content afterwards:
public class JFrame extends javax.swing.JFrame implements ActionListener
{
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrame frame = new JFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JFrame()
{
this.setTitle("BMS Anpassen");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnFlush = new JButton("Flush!");
btnFlush.setBounds(170, 209, 89, 23);
contentPane.add(btnFlush);
JSpinner spinner = new JSpinner();
spinner.setToolTipText("Gib die Spannung ein!");
spinner.setModel(new SpinnerNumberModel(new Float(3000), new Float(2700), new Float(4100), new Float(100)));
spinner.setBounds(56, 49, 52, 20);
contentPane.add(spinner);
JLabel lblMv = new JLabel("mV");
lblMv.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblMv.setBounds(113, 51, 24, 14);
contentPane.add(lblMv);
JButton btnSetParameters = new JButton("Set Parameters");
btnSetParameters.setBounds(152, 175, 130, 23);
contentPane.add(btnSetParameters);
//Buttons dem Listener zuordnen
btnFlush.addActionListener(this);
btnSetParameters.addActionListener(this);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == this.btnSetParameters){
// Parameter in Config schreiben/Write parameters in Config
FileWriter fw = new FileWriter("ConfigBMS.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write("25000");
bw.newLine();
bw.write("42000");
bw.newLine();
bw.write("27000");
bw.newLine();
bw.write("41000");
bw.close();
}
else
{
}
}
}
It now gives me the errormessage "btnSetParameters cannot be resolved or is not a field". Reading through other posts on JButtons here didn't help me or I didn't understand it. I feel like the this in if(ae.getSource() == this.btnSetParameters){ is the problem, but I can't find a way to fix it.
Any push in the right direction is greatly appreciated and thank you in advance,
Oli
you have an scope issue, btnSetParameters must be declared as a Frame member field
public class JFrame extends javax.swing.JFrame implements ActionListener {
private JButton btnSetParameters;
and no inside the constructor, use the constructor instead to initialize the button!
public JFrame() {
....
btnSetParameters = new JButton("Set Parameters");
}
You have to make the the JButton btnSetParameters a field of the class - currently it's just in the context of the constructor.

Trying to pass the table number between two classes

I am trying to pass the table number from the restaurant class into tableLabel which is in the Menu page class. When the code is running the tableLabel returns null. Any help would be appreciated to enable the code when running to return a number in the tableLabel.
Extract from Restaurant Class
public class Restaurant extends JFrame {
private JPanel contentPane;
private JTextField restaurant_Txt;
private JTextField num_Diners;
private JTextField num_Diners_Txt;
private JTextField table_Num_Txt;
private JTextField num_Table;
private JButton num_TableSub_Btn;
private JButton proceed_Menu_Btn;
private JButton MyDocumentListener;
MenuPage parent;
public static String tableNumber;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Restaurant frame = new Restaurant();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Restaurant() {
super("Restaurant");
parent = new MenuPage();
initGUI();
num_Table = new JTextField("NewUser", 10);
}
public void initGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 640, 310);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
table_Num_Txt = new JTextField();
table_Num_Txt.setEditable(false);
table_Num_Txt.setText("Table number ?");
table_Num_Txt.setBounds(145, 164, 112, 26);
contentPane.add(table_Num_Txt);
table_Num_Txt.setColumns(10);
num_Table = new JTextField("");
num_Table.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (e.getKeyCode() == 10) {
tableNumber = num_Table.getText();
}
}
});
num_Table.setBounds(334, 161, 83, 26);
contentPane.add(num_Table);
num_Table.setColumns(10);
}
}
Extract from Menu Page class
tableLabel = new JLabel(" : " + Restaurant.tableNumber);
tableLabel.setBounds(16, 6, 61, 16);
contentPane.add(tableLabel);
This may be a stupid question, but are you sure you are pressing enter when being inside the num_Table field inside your GUI since the variable is set when this happens. Also you should probably pass it via the constructor to MainPage, not as a static variable.

How to get ArrayList from another class to show up inside a JComboBox?

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

Java:Background Image add on JFrame

I'm making a gui program everything going right but add background image in frame so i take jpanel private variable.Also i add image in src which is
but how to use this jpanel variable to add background image in frame.
Code:
public class App extends JFrame{
private JPanel panel;
private JTextField field1;
private JTextField print;
private JLabel label;
private JLabel label2;
private JButton button;
public App(){
super();
getContentPane().setLayout(null);
label = new JLabel("Value");
label.setForeground(Color.RED);
label.setFont(new Font("SansSerif", Font.PLAIN, 18));
label.setBounds(178, 46, 51, 26);
getContentPane().add(label);
label2 = new JLabel("Print");
label2.setForeground(Color.RED);
label2.setFont(new Font("SansSerif", Font.PLAIN, 18));
label2.setBounds(178, 143, 42, 26);
getContentPane().add(label2);
field1 = new JTextField();
field1.setBounds(178, 72, 76, 26);
getContentPane().add(field1);
print = new JTextField();
print.setBounds(178, 181, 77, 26);
getContentPane().add(print);
button = new JButton("Click");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String w= field1.getText();
print.setText(w);
}
});
button.setBounds(178, 219, 77, 26);
getContentPane().add(button);
}
}
Main Method:
public class Main {
public static void main(String[] args) {
App object = new App();
object.setSize(450, 400);
object.setDefaultCloseOperation(object.EXIT_ON_CLOSE);
object.setLocationRelativeTo(null);
object.setVisible(true);
}
}
You have set Layout to null which is making a problem. Whenever we make layout null we have to set bounds for it.
Folow this method:
first of all copy your background image and paste in src of code
than set layout to borderlayout like this:
setLayout(new BorderLayout());
now add this code:
setContentPane(new JLabel new ImageIcon(getClass().getResource("image.jpg"))));
Note: add your image name here "image.jpg"

Changing a JButton on click event

I'm trying to do something very simple, change the text in a button when it has been clicked.
I can't seem to get it to work, can someone show me the correct place to add an ActionListener?
Main Class
public class ATM implements ActionListener{
public static void main(String[] args) {
atmGUI gui = new atmGUI();
gui.login();
}
}
atmGUI Class
public class atmGUI implements ActionListener {
public JTextField usernameField;
public JTextField pinField;
public String userName;
public int pin;
/**
* #wbp.parser.entryPoint
*/
public void login() {
JFrame frame = new JFrame();
frame.getContentPane().setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setTitle("Virtual Bank Account");
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(16, 88, 82, 16);
frame.getContentPane().add(lblUsername);
usernameField = new JTextField();
usernameField.setBounds(13, 107, 124, 28);
frame.getContentPane().add(usernameField);
usernameField.setColumns(10);
JLabel lblPin = new JLabel("PIN");
lblPin.setBounds(16, 140, 61, 16);
frame.getContentPane().add(lblPin);
pinField = new JTextField();
pinField.setBounds(13, 157, 124, 28);
frame.getContentPane().add(pinField);
pinField.setColumns(10);
JButton btnLogin = new JButton("Login");
btnLogin.setBounds(355, 232, 117, 29);
btnLogin.addActionListener(new ActionListener(){
btnLogin.setText("Clicked");
});
frame.getContentPane().add(btnLogin);
frame.setResizable(false);
frame.setAlwaysOnTop(true);
frame.setVisible(true);
}
}
EDIT :
Here is the error that is produced
The type new ActionListener(){} must implement the inherited abstract method ActionListener.actionPerformed(ActionEvent)
add function anonymous
btnLogin.addActionListener(new ActionListener(){
//do something
//lblUsername.setText("blah blah");
});
Detail:
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//do something
//lblUsername.setText("blah blah");
}
});
You should implement the actionperformed() method inside your atmGUI class to handle the clicked action.
You will need to add the onActionPerformed(ActionEvent) method to your atmgui class, do it like:
public void onActionPerformed(ActionEvent avt)
{
//code to handle the button click
}
OR
You can also use it while initializing the JButton:
JButton b=new JButton("Click Me!" );
b.addActionListener(new ActionListener() {
//handle the button click here
}

Categories

Resources