Another question for Java... I know it's basic, but I am not pro.
So I have Main.java
public class Main {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://my.emerchantpay.com/");
eMerchantPay emp = PageFactory.initElements(driver, eMerchantPay.class);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new MainFrame("Please enter your credentials");
frame.setSize(500, 400);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
emp.uid(username);
emp.pwd(password);
emp.LoginButton.click();
And the string is located in DetailsPanel.java
public class DetailsPanel extends JPanel{
private static final long serialVersionUID = 1234567891;
private EventListenerList listenerList = new EventListenerList();
public DetailsPanel() {
Dimension size = getPreferredSize();
size.width = 250;
setPreferredSize(size);
setBorder(BorderFactory.createTitledBorder("Personal Details"));
JLabel nameLabel = new JLabel("Name: ");
JLabel passwordLabel = new JLabel("Password: ");
final JTextField nameField = new JTextField(10);
final JPasswordField passwordField = new JPasswordField(10);
final JButton addBtn = new JButton("Submit");
addBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
String name = nameField.getText();
String password = passwordField.getText();
String text = name + ": " + password + "\n";
JFrame frame = (JFrame) SwingUtilities.getWindowAncestor(addBtn);
frame.dispose();
System.out.println (text);
}
});
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
/// First column ///
gc.anchor = GridBagConstraints.LINE_END;
gc.weightx = 0.5;
gc.weighty = 0.5;
gc.gridx = 0;
gc.gridy = 0;
add(nameLabel, gc);
gc.gridx = 0;
gc.gridy = 1;
add(passwordLabel, gc);
/// Second column ///
gc.anchor = GridBagConstraints.LINE_START;
gc.gridx = 1;
gc.gridy = 0;
add(nameField, gc);
gc.gridx = 1;
gc.gridy = 1;
add(passwordField, gc);
/// Final row ///
gc.weighty = 10;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
gc.gridx = 1;
gc.gridy = 2;
add(addBtn, gc);
}
public void fireDetailEvent(DetailEvent event) {
Object[] listeners = listenerList.getListenerList();
for (int i=0; i < listeners.length; i += 2) {
if (listeners[i] == DetailListener.class) {
((DetailListener)listeners[i+1]).detailEventOccured(event);
}
}
}
public void addDetailsListener(DetailListener listener) {
listenerList.add(DetailListener.class, listener);
}
public void removeDetailListener(DetailListener listener) {
listenerList.remove(DetailListener.class, listener);
}
So the strings are located here
String name = nameField.getText();
String password = passwordField.getText();
How do I access these from Main.java? I have to assign the name value to emp.uid(username);
Your fields are package protected, thus they are visible in the same package.
However, you need an instance of your DetailsPanel to access them.
So, where your Main class uses the DetailsPanel, you could use something like this:
DetailsPanel details = new DeatilsPanel();
...
String name = details.nameField.getText();
char[] password = details.passwordField.getPassword();
(For security reasons JPasswordField does have the getText() method to return the password in a String deprecated.)
You can create two data members in your DetailsPanel.java file and can can name them as name and password.
In your Main.java, you can create an object of DetailsPanel and using the object you can access the values of name and password
Main.java
DetailsPanel obj=new DetailsPanel();
emp.uid(obj.name);
emp.pwd(obj.password);
DetailsPanel.java
class DetailsPanel{
String name;
String password;
}
Hope it helps you to get the basics.
Related
I am currently working on GUI of simple food ordering system. I created a button that whenever user clicks it it will go to another frame, however I am facing problem when I want to close the first frame (setVisible(false)).
This is my first frame
public class MainFrame extends JFrame {
private Manager manager = new Manager();
private JPanel titlepane;
private JLabel title;
MainFrame(String name){
setTitle(name);
}
public void content() {
Font titlefont = new Font("Times New Roman", Font.PLAIN, 22);
setLayout(new BorderLayout());
titlepane = new JPanel();
title = new JLabel("Welcome to POS!");
title.setFont(titlefont);
titlepane.add(title);
manager.LoginGUI();
add(titlepane,BorderLayout.NORTH);
add(manager,BorderLayout.CENTER);
}
public void runGUI() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
content();
setSize(700,700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
}
});
}
This is another class where the button is
public class Manager extends JPanel implements ActionListener {
private ArrayList<AccountInfo> manager = new ArrayList<AccountInfo>();
private GridBagConstraints gbc = new GridBagConstraints();
private JLabel id;
private JLabel pw;
private JTextField idfill;
private JTextField pwfill;
private JButton login;
private int isManager = 0;
private String idinput, pwinput;
private int temp = -1;
Manager() {
this.manager.add(new AccountInfo("admin", "1234"));
}
public void addManager(AccountInfo newManager) {
this.manager.add(newManager);
}
public void LoginGUI() {
Font standard = new Font("Times New Roman", Font.PLAIN, 18);
setLayout(new GridBagLayout());
id = new JLabel("ID");
id.setFont(standard);
// Alignment
gbc.gridx = 0;
gbc.gridy = 0;
gbc.ipadx = 10;
gbc.ipady = 10;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(id, gbc);
idfill = new JTextField(10);
idfill.setFont(standard);
// Alignment
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(idfill, gbc);
pw = new JLabel("Password");
pw.setFont(standard);
// Alignment
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(pw, gbc);
pwfill = new JTextField(10);
pwfill.setFont(standard);
// Alignment
gbc.gridx = 1;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(pwfill, gbc);
login = new JButton("Login");
login.setFont(standard);
login.addActionListener(this);
// Alignment
gbc.gridx = 1;
gbc.gridy = 2;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(login, gbc);
}
public void actionPerformed(ActionEvent e) {
verify();
if(isManager == 1) {
MenuFrame menu = new MenuFrame("Menu");
menu.runGUI();
MainFrame.setVisible(false); // This is the problem
}
}
private void verify() {
idinput = idfill.getText().trim();
pwinput = pwfill.getText();
for (int i = 0; i < manager.size(); i++) {
if (idinput.equals(manager.get(i).id)) {
temp = i;
}
}
if(temp == -1) {
JOptionPane.showMessageDialog(null, "Id or password incorrect, try again");
} else if(pwinput.equals(manager.get(temp).password)) {
isManager = 1;
} else
JOptionPane.showMessageDialog(null, "Id or password incorrect, try again");
}
}
(The codes are a bit lengthy as I am not confident that the other part was correct. All I know this has nothing to do with MenuFrame)
I get this error:
Cannot make a static reference to the non-static method setVisible(boolean) from the type Window
It might be my fault where it is not obvious enough for me to know which part of Manager or MainFrame is static. I also came across other posts regarding the same issue but none relates with mine. (Other post was having obvious static method)
Also tried the create an MainFrame object in Manager but it made it worse, please help, thank you!
You indeed need to keep the MainFrame object somewhere accessible, keep a reference to it. For this MVC, Model-View-Controller, is a nice paradigm.
Use MVC
I personally have my main method for swing in a Controller class (so the controller is the application class). It creates the main frame (View) and the controller is passed.
public void actionPerformed(ActionEvent e) {
verify();
if(isManager == 1) {
MenuFrame menu = new MenuFrame("Menu");
menu.runGUI();
controller.setMainFrameVisible(false);
}
}
Controller:
private MainFrame mainFrame;
public setMainFrameVisible(boolean visible) {
MainFrame.setVisible(visible);
}
Pass the MainFrame instance.
However you may also pass the MainFrame:
private final MainFrame mainFrame;
Manager(MainFrame mainFrame) {
this.mainFrame = mainFrame;
}
public void actionPerformed(ActionEvent e) {
verify();
if(isManager == 1) {
MenuFrame menu = new MenuFrame("Menu");
menu.runGUI();
mainFrame.setVisible(false);
}
}
If the panel is inside the MainFrame
((JFrame) getTopLevelAncestor()).setVisible(false);
Tip:
Should the application exit (EXIT_ON_CLOSE), change the default close operation.
MainFrame(String name){
setTitle(name);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
I am not able to close my frame after I click the button. The tricky part is that I do not need to quit the whole application, just close the GUI (not with system exit).
Would you be able to assist me?
Thank you in advance!!!
Main.java
public class Main {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://my.emerchantpay.com/");
eMerchantPay emp = PageFactory.initElements(driver, eMerchantPay.class);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new MainFrame("Please enter your credentials");
frame.setSize(500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
MainFrame.java
public class MainFrame extends JFrame {
private DetailsPanel detailsPanel;
public MainFrame(String title) {
super(title);
// Set layout manager
setLayout(new BorderLayout());
// Create Swing components
final JTextArea textArea = new JTextArea();
detailsPanel = new DetailsPanel();
detailsPanel.addDetailsListener(new DetailListener() {
public void detailEventOccured(DetailEvent event) {
String text = event.getText();
textArea.append(text);
}
});
// Add Swing components to content pane
Container c = getContentPane();
//c.add(textArea, BorderLayout.CENTER);
c.add(detailsPanel, BorderLayout.CENTER);
}
DetailsPanel.java
public class DetailsPanel extends JPanel{
private static final long serialVersionUID = 1234567891;
private EventListenerList listenerList = new EventListenerList();
public DetailsPanel() {
Dimension size = getPreferredSize();
size.width = 250;
setPreferredSize(size);
setBorder(BorderFactory.createTitledBorder("Personal Details"));
JLabel nameLabel = new JLabel("Name: ");
JLabel passwordLabel = new JLabel("Password: ");
final JTextField nameField = new JTextField(10);
final JPasswordField passwordField = new JPasswordField(10);
JButton addBtn = new JButton("Submit");
addBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
String name = nameField.getText();
String password = passwordField.getText();
String text = name + ": " + password + "\n";
System.out.println (text);
}
});
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
/// First column ///
gc.anchor = GridBagConstraints.LINE_END;
gc.weightx = 0.5;
gc.weighty = 0.5;
gc.gridx = 0;
gc.gridy = 0;
add(nameLabel, gc);
gc.gridx = 0;
gc.gridy = 1;
add(passwordLabel, gc);
/// Second column ///
gc.anchor = GridBagConstraints.LINE_START;
gc.gridx = 1;
gc.gridy = 0;
add(nameField, gc);
gc.gridx = 1;
gc.gridy = 1;
add(passwordField, gc);
/// Final row ///
gc.weighty = 10;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
gc.gridx = 1;
gc.gridy = 2;
add(addBtn, gc);
}
public void fireDetailEvent(DetailEvent event) {
Object[] listeners = listenerList.getListenerList();
for (int i=0; i < listeners.length; i += 2) {
if (listeners[i] == DetailListener.class) {
((DetailListener)listeners[i+1]).detailEventOccured(event);
}
}
}
public void addDetailsListener(DetailListener listener) {
listenerList.add(DetailListener.class, listener);
}
public void removeDetailListener(DetailListener listener) {
listenerList.remove(DetailListener.class, listener);
}
I need to close the frame once I click the login button in this piece of code:
addBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
String name = nameField.getText();
String password = passwordField.getText();
String text = name + ": " + password + "\n";
System.out.println (text);
}
});
In actionPerformed, add these lines to obtain and close the parent frame :
JFrame frame = (JFrame) SwingUtilities.getWindowAncestor(addBtn);
frame.dispose();// or frame.setVisible(false), depending on your needs
Note that you will have to declare your button final in order to use it in the anonymous listener :
final JButton addBtn = new JButton("Submit");
I have ran into yet another issue. I am trying to set the text of a JTextField from another java class, and it does not seem to work.
I have tried the following:
calling the setter from inside the GUI class to .setText with a String. WORKS!
Setting the JTextField to some text so it isnt NULL -failed
Calling another method inside the GUI class, pass the string, then call the setter for the JTextField to set its text to the string. -failed (Just an idea i wanted to play with)
I did insure that the string is passed into the setter method by using a println. WORKED.
From googling around I believe that i have not set the reference to the main GUI?
Here is the GUI Class:
package book;
import book.BookIO;
import java.awt.BorderLayout;
import java.awt.*;
import javax.swing.*;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/**
*
*
*/
public class UserInterface implements ActionListener {
//Containers
JFrame frame = new JFrame("Ye old Book stoppe");
JPanel toppane = new JPanel(new GridBagLayout());
JPanel bottomPane = new JPanel(new GridBagLayout());
//Buttons
JButton processItem = new JButton("Process Item #1");
JButton confirmItem = new JButton("Confirm Item #1");
JButton viewOrder = new JButton("View Order");
JButton finishOrder = new JButton("Finish Order ");
JButton newOrder = new JButton("New Order");
JButton exit = new JButton("Exit");
//TextFields
JTextField amount = new JTextField();
JTextField id = new JTextField();
JTextField quantity = new JTextField();
JTextField info = new JTextField("");
JTextField total = new JTextField();
//Labels
JLabel num = new JLabel("Enter Number of Items in this Order:");
JLabel bookID = new JLabel("Enter Book ID for Item #1:");
JLabel quantityItem = new JLabel("Enter Quantity for Item #1:");
JLabel itemInfo = new JLabel("Item #1:");
JLabel subtotal = new JLabel("Order subtotal for 0 Items(s):");
public void startUI() {
UserInterface gui = new UserInterface();
gui.bookingUI();
}
public void bookingUI() {
//sets windows, and pane in the UI
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagConstraints c = new GridBagConstraints();
frame.setSize(800, 300);
//adding the labels to the panel
c.insets = new Insets(5, 0, 0, 0);
c.gridx = 2;
c.gridy = 1;
toppane.add(num, c);
c.gridx = 2;
c.gridy = 2;
toppane.add(bookID, c);
c.gridx = 2;
c.gridy = 3;
toppane.add(quantityItem, c);
c.gridx = 2;
c.gridy = 4;
toppane.add(itemInfo, c);
c.gridx = 2;
c.gridy = 5;
toppane.add(subtotal, c);
toppane.setBackground(Color.GREEN);
frame.add(toppane);
//add textfield to panel
c.ipadx = 400;
c.insets = new Insets(5, 10, 0, 0);
c.gridx = 3;
c.gridy = 1;
toppane.add(amount, c);
c.gridx = 3;
c.gridy = 2;
toppane.add(id, c);
c.gridx = 3;
c.gridy = 3;
toppane.add(quantity, c);
c.gridx = 3;
c.gridy = 4;
toppane.add(info, c);
c.gridx = 3;
c.gridy = 5;
toppane.add(total, c);
//----------------------------------------------------------BUTTOM PANE-------------------------
//adding the buttons to the pane.---------------------------------------------------------------
GridBagConstraints b = new GridBagConstraints();
b.insets = new Insets(5, 5, 5, 5);
b.ipadx = 10;
b.ipady = 10;
b.gridx = 1;
b.gridy = 0;
bottomPane.add(processItem, b);
processItem.addActionListener(this);
b.gridx = 2;
b.gridy = 0;
bottomPane.add(confirmItem, b);
confirmItem.setEnabled(false);
confirmItem.addActionListener(this);
b.gridx = 3;
b.gridy = 0;
bottomPane.add(viewOrder, b);
viewOrder.setEnabled(true);
viewOrder.addActionListener(this);
b.gridx = 4;
b.gridy = 0;
bottomPane.add(finishOrder, b);
finishOrder.setEnabled(true);
finishOrder.addActionListener(this);
b.gridx = 5;
b.gridy = 0;
bottomPane.add(newOrder, b);
newOrder.addActionListener(this);
b.gridx = 6;
b.gridy = 0;
bottomPane.add(exit, b);
exit.addActionListener(this);
bottomPane.setBackground(Color.BLUE);
frame.add(bottomPane, BorderLayout.SOUTH);
frame.setSize(810, 310);
frame.setVisible(true);
}
//action listener for the buttons
public void actionPerformed(ActionEvent e) {
if (e.getSource() == processItem) {
confirmItem.setEnabled(true);
processItem.setEnabled(false);
BookIO findInfo = new BookIO();
findInfo.readFile(id.getText());
} else if (e.getSource() == confirmItem) {
processItem.setEnabled(true);
confirmItem.setEnabled(false);
} else if (e.getSource() == viewOrder) {
} else if (e.getSource() == finishOrder) {
} else if (e.getSource() == newOrder) {
} else if (e.getSource() == exit) {
System.exit(0);
}
}
//Creating getters and setters to change the text for the buttons and labels, as well as getting text from the textfields.
public void setProcessItemBtn(int num) {
processItem.setText("Process Item #" + num);
processItem.validate();
processItem.repaint();
}
public void setConfirmItemBtn(int num) {
confirmItem.setText("Confirm Item #" + num);
confirmItem.validate();
confirmItem.repaint();
}
public void setViewOrderBtn(String title) {
viewOrder.validate();
viewOrder.repaint();
}
public void setInfo(String title) {
System.out.println(title);
info.setText(title);
info.validate();
info.repaint();
}
public String getAmount() {
String str = amount.getText();
return str;
}
}
Here is the class with the method call to the setter:
package book;
import book.UserInterface;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Objects;
import java.util.StringTokenizer;
/**
*
*
*/
public class BookIO {
public void readFile(String bookID) {
try {
FileReader read = new FileReader("inventory.txt");
BufferedReader buffer = new BufferedReader(read);
StringBuffer stringBuff = new StringBuffer();
String line, delim = "[,]";
for (int i = 0; i < 12; i++) {
line = buffer.readLine();
String[] tokens = line.split(delim);
if ((Objects.equals(tokens[0], bookID)) == true) {
UserInterface setInfo = new UserInterface();
setInfo.setInfo(tokens[1]);
}
}
} catch (IOException e) {
System.out.println("Error starting file!");
}
}
}
Your error is that you are instantiating a new UserInterface object which is wrong:
UserInterface setInfo = new UserInterface();
setInfo.setInfo(tokens[1]);
Your readFile() from BookIO should be like this:
public static void readFile(String bookID, UserInterface userInterface) {
try {
FileReader read = new FileReader("inventory.txt");
BufferedReader buffer = new BufferedReader(read);
StringBuffer stringBuff = new StringBuffer();
String line, delim = "[,]";
for (int i = 0; i < 12; i++) {
line = buffer.readLine();
String[] tokens = line.split(delim);
if ((Objects.equals(tokens[0], bookID)) == true) {
userInterface.setInfo(tokens[1]);
}
}
} catch (IOException e) {
System.out.println("Error starting file!");
}
}
In your UserInterface class, where you have this:
BookIO findInfo = new BookIO();
findInfo.readFile(id.getText());
Change the lines to this:
//pass the already created userInterface object.
BookIO.readFile(id.getText(), this);
Note: I have tested this and it worked. Tell me if it doesn't work for you.
You always make a new UserInterface instance
UserInterface setInfo = new UserInterface();
setInfo.setInfo(tokens[1]);
That sounds incorrect. Normally you would only have one such unstance (the visible one), and update that one.
Small side-note
if( Objects.equals(tokens[0], bookID)) == true )
can be simplified to
if( Objects.equals(tokens[0], bookID)) )
So I have a login class that basically opens a new window if the login credentials are correct. So I call another class if the credentials are right. Problem is, the window comes up but its empty. Here is the window that I am trying to open. Its pretty basic as you can see:
(Summary: its just adding some buttons and textfields via grid bag layout and those buttons open up another window)
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Library extends JFrame{
private static JFrame frame;
private GridBagConstraints padding;
private JButton addB;
private JTextField aB;
private JButton issueB;
private JTextField iB;
private JButton holdB;
private JTextField hB;
private JButton renewB;
private JTextField rB;
private JButton logout;
private ImageIcon logo;
private JMenuBar menubar;
private JMenu file;
private JMenuItem exit;
public Library(){
frame = new JFrame();
frame.setLayout(new GridBagLayout());
padding = new GridBagConstraints();
}
//deals with the adding of textfield and label of adding book
public void addBLabels()
{
addB = new JButton("Add Book: ");
padding.fill = GridBagConstraints.HORIZONTAL;
padding.gridx = 4;
padding.weightx = 1;
padding.gridy = 0;
padding.weighty = 1;
frame.add(addB, padding);
aB = new JTextField(30);
padding.fill = GridBagConstraints.HORIZONTAL;
padding.gridx = 5;
padding.weightx = 1;
padding.gridy = 0;
padding.weighty = 1;
frame.add(aB, padding);
event1 butt = new event1();
addB.addActionListener(butt);
}
public class event1 implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
AddBookWindow bookWin = new AddBookWindow(Library.this);
bookWin.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
bookWin.setTitle("Add Book");
bookWin.setSize(500,200);
bookWin.setLocation(300,300);
bookWin.setVisible(true);
bookWin.setResizable(false);
}
}
//deals with issue book labels and textfield
public void issueBLabels(){
issueB = new JButton("Issue Book: ");
padding.fill = GridBagConstraints.HORIZONTAL;
padding.gridx = 4;
padding.weightx= 1;
padding.gridy = 2;
padding.weighty = 1;
frame.add(issueB, padding);
iB = new JTextField(30);
padding.fill = GridBagConstraints.HORIZONTAL;
padding.gridx = 5;
padding.weightx = 1;
padding.gridy = 2;
padding.weighty = 1;
frame.add(iB, padding);
event2 iss = new event2();
issueB.addActionListener(iss);
}
public class event2 implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
AddBookWindow bookWin = new AddBookWindow(Library.this);
bookWin.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
bookWin.setTitle("Issue Book");
bookWin.setSize(500,200);
bookWin.setLocation(300,300);
bookWin.setVisible(true);
bookWin.setResizable(false);
}
}
//deals with holdbook labels and textfield
public void holdBookLabels(){
holdB = new JButton("Hold Book: ");
padding.fill = GridBagConstraints.HORIZONTAL;
padding.gridx = 4;
padding.weightx = 1;
padding.gridy = 4;
padding.weighty = 1;
frame.add(holdB, padding);
hB = new JTextField(30);
padding.fill = GridBagConstraints.HORIZONTAL;
padding.gridx = 5;
padding.weightx = 1;
padding.gridy = 4;
padding.weighty = 1;
frame.add(hB, padding);
event3 hold = new event3();
holdB.addActionListener(hold);
}
public class event3 implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
AddBookWindow bookWin = new AddBookWindow(Library.this);
bookWin.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
bookWin.setTitle("Hold Book");
bookWin.setSize(500,200);
bookWin.setLocation(300,300);
bookWin.setVisible(true);
bookWin.setResizable(false);
}
}
//deals with the renewbook labels and textfield
public void renewBookLabels(){
renewB = new JButton("Renew Book: ");
padding.fill = GridBagConstraints.HORIZONTAL;
padding.gridx = 4;
padding.weightx = 1;
padding.gridy = 6;
padding.weighty = 1;
frame.add(renewB, padding);
rB = new JTextField(30);
padding.fill = GridBagConstraints.HORIZONTAL;
padding.gridx = 5;
padding.weightx = 1;
padding.gridy = 6;
padding.weighty = 1;
frame.add(rB, padding);
event4 renew = new event4();
renewB.addActionListener(renew);
}
public class event4 implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
AddBookWindow bookWin = new AddBookWindow(Library.this);
bookWin.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
bookWin.setTitle("Renew Book");
bookWin.setSize(500,200);
bookWin.setLocation(300,300);
bookWin.setVisible(true);
bookWin.setResizable(false);
}
}
//deals with adding the logout button
public void logOutButton(){
logout = new JButton("Logout");
padding.gridx = 5;
padding.weightx = 1;
padding.gridy = 10;
padding.weighty = 1;
padding.gridwidth = 1;
frame.add(logout, padding);
}
//deals with adding the image
public void addImage() throws IOException{
InputStream imageStream = this.getClass().getResourceAsStream("0521-1005-0822-0024_brunette_girl_smiling_and_holding_a_stack_books.jpg");
BufferedImage image = ImageIO.read(imageStream);
JLabel picLabel = new JLabel(new ImageIcon(image));
padding.gridheight = 10;
padding.fill = GridBagConstraints.VERTICAL;
padding.gridx = 0;
padding.weightx = 1;
padding.gridy = 0;
padding.weighty = 1;
frame.add(picLabel, padding);
}
private void menuBar(){
menubar = new JMenuBar();
padding.fill = GridBagConstraints.HORIZONTAL;
padding.gridx = 0;
padding.weightx = 1;
padding.gridy = 0;
padding.weighty = 1;
frame.add(menubar, padding);
file = new JMenu("File");
menubar.add(file);
exit = new JMenuItem("exit");
file.add(exit);
}
public static void main(String args[]) throws IOException{
Library gui = new Library();
//not working right now gui.menuBar();
gui.addBLabels();
gui.issueBLabels();
gui.holdBookLabels();
gui.renewBookLabels();
gui.logOutButton();
gui.addImage();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("La Biblioteca");
frame.setSize(880,430);
frame.setVisible(true);
frame.setResizable(false);
}
}
Basically in my Login class, my if statement says:
if(login credentials are correct)
Library gui = new Library();
gui.setSize(880,430);
gui.setVisible(true);
gui.addBLabels();
gui.issueBLabels();
gui.holdBookLabels();
gui.renewBookLabels();
gui.logOutButton();
gui.addImage();
Start by look at The Use of Multiple JFrames, Good/Bad Practice?.
The problem is Library extends from JFrame, but you have ANOTHER JFrame as a (static) instance field...
public class Library extends JFrame{
private static JFrame frame;
When you construct the Library class, you are using the frame field, but when you set it's properties from are using the Library class, you have two different frames.
The solution, don't extend from JFrame or any other top level container, ever, you are not adding any meaningful functionality to it and are limiting the re-use of your components.
Instead, consider using a CardLayout, see How to Use CardLayout for more details...
Here is how I created the labels and JTextFields:
JPanel panel3 = new JPanel(new SpringLayout());
String[] labels = {"Non-animated image name:","Left animation image name:","Top animation image name:",
"Right animation image name:","Bottom animation image name:"};
for(int i=0; i<labels.length; i++){
JLabel l = new JLabel(labels[i],JLabel.TRAILING);
JTextField n = new JTextField(10);
panel3.add(l);
l.setLabelFor(n);
panel3.add(n);
}
SpringUtilities.makeCompactGrid(panel3,
5, 2,
6, 6,
6, 6);
Say for example, how would I access/get the value of the text in the JTextField with the label, "Top animation image name:"?
I know that usually, one can perform JTextField.getText(), but to me it looks like that wouldn't work here.
Thanks in advance!
This is just a specific example of the question:
how can I access an object created in a loop.
The answer is the same: put them in a collection or array. Note that the collection option has greater flexibility. For instance if you create a bunch of JLabel/JTextField associations, you could use a HashMap<String, JTextField> to associate the JTextField with a String.
For example:
Map<String, JTextField> fieldMap = new HashMap<String, JTextField>();
String[] labels = {"Non-animated image name:","Left animation image name:","Top animation image name:",
"Right animation image name:","Bottom animation image name:"};
for(int i=0; i<labels.length; i++){
JLabel l = new JLabel(labels[i],JLabel.TRAILING);
JTextField n = new JTextField(10);
panel3.add(l);
l.setLabelFor(n);
panel3.add(n);
fieldMap.put(labels[i], n);
}
// and then later you can get the text field associated with the String:
String text = fieldMap.get(labels[2]).getText();
Or for a full example:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class InputForm extends JPanel {
private static final int COLUMNS = 10;
private static final int GAP = 3;
private static final Insets LABEL_INSETS = new Insets(GAP, GAP, GAP, 15);
private static final Insets TEXTFIELD_INSETS = new Insets(GAP, GAP, GAP, GAP);
private String[] labelTexts;
private Map<String, JTextField> fieldMap = new HashMap<String, JTextField>();
public InputForm(String[] labelTexts) {
this.labelTexts = labelTexts;
setLayout(new GridBagLayout());
for (int i = 0; i < labelTexts.length; i++) {
String text = labelTexts[i];
JTextField field = new JTextField(COLUMNS);
fieldMap.put(text, field);
addLabel(text, i);
addTextField(field, i);
}
}
public String[] getLabelTexts() {
return labelTexts;
}
private void addTextField(JTextField field, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 1;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = TEXTFIELD_INSETS;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(field, gbc);
}
private void addLabel(String text, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 0;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = LABEL_INSETS;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(new JLabel(text), gbc);
}
public String getFieldText(String key) {
String text = "";
JTextField field = fieldMap.get(key);
if (field != null) {
text = field.getText();
}
return text;
}
private static void createAndShowGui() {
String[] labelTexts = new String[] { "One", "Two",
"Three", "Four" };
InputForm inputForm = new InputForm(labelTexts);
int result = JOptionPane.showConfirmDialog(null, inputForm, "Enter Stuff Here",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
for (String text : labelTexts) {
System.out.printf("%20s %s%n", text, inputForm.getFieldText(text));
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Each time you create a JLabel and a JTextField, store references to each of them inside a new instance of a container class.
For example:
private class LabelTextFieldContainer {
JLabel label;
JTextField textField;
//Constructor goes here...
}
for(int i=0; i<labels.length; i++){
JLabel l = new JLabel(labels[i],JLabel.TRAILING);
JTextField n = new JTextField(10);
panel3.add(l);
l.setLabelFor(n);
panel3.add(n);
containerList.add( new Container(l, n) ); //Instantiate List<LabelTextFieldContainer> containerList somewhere else
}