In my GUI, after importing an Excel file, I need to create a variable amount of panels/tabs. The amount depends on the number of rows imported from the Excel file. I need to show the information contained in row in a different panel, with a couple of buttons to move between all the tabs. For example, if the Excel file contains 6 rows:
Field1: user1
Field2: user1Age
< [1/6] >
So, I can move through the different panels, by clicking on the arrows:
Field1: user2
Field2: user2Age
< [2/6] >
One more consideration: Excel file import is not the only way to get information, it must be possible to manually add information. Therefore, after starting the GUI there must be at least one panel, and if the user decides to import an Excel file, then multiple panels must be created.
I need just a hint to start coding. And of course I am open to other possibilities.
Here is a sample code that should get you started (you will need to reorganize a bit the code). Although there are 1000 dummy users, it only uses a single panel to display the information:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestMultiplePanels {
private final UserList userList;
private User currentUser;
private JTextField name;
private JTextField age;
private JTextField index;
private JButton prev;
private JButton next;
public TestMultiplePanels(UserList userList) {
this.userList = userList;
}
protected void initUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel userPanel = new JPanel(new BorderLayout());
JPanel userInfoPanel = new JPanel(new GridBagLayout());
JPanel buttonPanel = new JPanel(new FlowLayout());
JLabel nameLabel = new JLabel("Name");
JLabel ageLabel = new JLabel("Age");
name = new JTextField(30);
age = new JTextField(5);
index = new JTextField(5);
index.setEditable(false);
prev = new JButton("<");
prev.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setCurrentUser(userList.previous(currentUser));
}
});
next = new JButton(">");
next.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setCurrentUser(userList.next(currentUser));
}
});
GridBagConstraints gbcLabel = new GridBagConstraints();
gbcLabel.anchor = GridBagConstraints.EAST;
GridBagConstraints gbcField = new GridBagConstraints();
gbcField.anchor = GridBagConstraints.WEST;
gbcField.gridwidth = GridBagConstraints.REMAINDER;
userInfoPanel.add(nameLabel, gbcLabel);
userInfoPanel.add(name, gbcField);
userInfoPanel.add(ageLabel, gbcLabel);
userInfoPanel.add(age, gbcField);
buttonPanel.add(prev);
buttonPanel.add(index);
buttonPanel.add(next);
userPanel.add(userInfoPanel);
userPanel.add(buttonPanel, BorderLayout.SOUTH);
setCurrentUser(userList.getUsers().get(0));
frame.add(userPanel);
frame.pack();
frame.setMinimumSize(frame.getPreferredSize());
frame.setVisible(true);
}
private void setCurrentUser(User user) {
currentUser = user;
name.setText(user.getUserName());
age.setText(String.valueOf(user.getAge()));
index.setText(user.getIndex() + "/" + userList.getCount());
next.setEnabled(userList.hasNext(user));
prev.setEnabled(userList.hasPrevious(user));
}
public static class UserList {
private List<User> users;
private List<User> unmodifiableUsers;
public UserList() {
super();
this.users = load();
unmodifiableUsers = Collections.unmodifiableList(users);
}
public int getCount() {
return users.size();
}
public List<User> getUsers() {
return unmodifiableUsers;
}
private List<User> load() {
List<User> users = new ArrayList<TestMultiplePanels.User>();
for (int i = 0; i < 1000; i++) {
User user = new User();
user.setUserName("User " + (i + 1));
user.setAge((int) (Math.random() * 80));
user.setIndex(i + 1);
users.add(user);
}
return users;
}
public boolean hasNext(User user) {
return user.getIndex() - 1 < users.size();
}
public boolean hasPrevious(User user) {
return user.getIndex() > 1;
}
public User next(User user) {
if (hasNext(user)) {
return users.get(user.getIndex());
} else {
return null;
}
}
public User previous(User user) {
if (hasPrevious(user)) {
return users.get(user.getIndex() - 2);
} else {
return null;
}
}
}
public static class User {
private String userName;
private int age;
private int index;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
public static void main(String[] args) {
final UserList userList = new UserList();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestMultiplePanels testMultiplePanels = new TestMultiplePanels(userList);
testMultiplePanels.initUI();
}
});
}
}
You can create the panels dynamically using an ArrayList, which I think is flexible enough for that and easily manageable. To handle panels display, you can use a CardLayout. Hope it helps
ArrayList<JPanel> panelGroup = new ArrayList<JPanel>();
for (int i=0;i<numberOfPanelsToCreate;i++){
panelGroup.add(new JPanel());
}
Related
Here is the code that I have so far. I have created the whole login screen and login button. Right now I have it so that the button disappears when it's pressed but I want to be able to check the JSON file to confirm the username and password and then move to the next screen.
Login Screen:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
public class LoginPage extends JPanel implements ActionListener {
private static final long serialVersionUID = -337449186297669567L;
private JLabel user_label = new JLabel("Username: ");
private JLabel password_label = new JLabel("Password: ");
private JLabel screenName = new JLabel("Login",SwingConstants.CENTER);
private JTextField username = new JTextField(10);
private JTextField password = new JTextField(10);
private JButton login, cancel;
private JPanel panel = new JPanel();
private String hidden = "login";
public LoginPage() {
System.out.println("Creating the label panel");
setBorder(BorderFactory.createEtchedBorder());
setLayout(new GridLayout(0, 1));
add(screenName);
add(user_label);
add(username);
add(password_label);
add(password);
login = new JButton("LOGIN");
setVisible(true);
addToggleListener();
initialize();
//setVisible(true);
}
public void initialize(){
JPanel buttonPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
add(buttonPanel);
c.weightx = 0.6;
c.weighty = 0.6;
c.gridx = 1;
c.gridy = 1;
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(10, 50, 10, 20);
login.setPreferredSize(new Dimension(100,50));
c.anchor = GridBagConstraints.SOUTHEAST;
buttonPanel.add(login,c);
}
public void setText(String s) {
screenName.setText(s);
}
public boolean isLabelVisible() {
return screenName.isVisible();
}
public void setLabelVisibility(boolean value) {
screenName.setVisible(value);
}
public void addToggleListener(ActionListener al){
login.addActionListener(al);
}
public void addToggleListener() {
login.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
if(hidden.equals("login")){
login.setVisible(false);
} else {
login.setVisible(true);
}
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
Main which contains the code for the json file:
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.enterprise.util.TypeLiteral;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
public class Main {
public static void main(String[] args) {
AppFrame frame = new AppFrame();
LoginPage lp = new LoginPage();
ToggleListener tl = new ToggleListener(lp);
lp.addToggleListener(tl);
frame.setLayout(new BorderLayout());
frame.add(lp, BorderLayout.CENTER);
frame.setVisible(true);
List<Student> studentList = new ArrayList<>();
addAnisa(studentList);
Jsonb jsonb = JsonbBuilder.create();
String jsonStudent = jsonb.toJson(studentList);
java.lang.reflect.Type t = new TypeLiteral<List<Student>>(){}.getType();
List<Student> l2 = jsonb.fromJson(jsonStudent, t);
String homeDirectory = System.getProperty("user.home");
Path p = Paths.get(homeDirectory + "/NetBeansProjects");
if(!Files.exists(p)){
File f = new File(homeDirectory + "/NetBeansProjects");
if(!f.mkdir()){
System.out.println("Nope");
}
}
String s = homeDirectory + "/NetBeansProjects/studentInfo.json";
p = Paths.get(s);
File f2 = new File(s);
try{
System.out.println("writing out file");
System.out.println(f2.getAbsoluteFile());
FileWriter fw = new FileWriter(f2.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(jsonStudent);
bw.close();
}
catch(IOException e){
e.printStackTrace();
System.exit(-1);
}
}
private static void addAnisa(List<Student> list){
Student s = new Student();
s.setFirstName("Anisa");
s.setLastName("Callis");
List<LoginInfo> loginInfo = new ArrayList<>();
LoginInfo LI = new LoginInfo();
LI.setUsername("amc123");
LI.setPassword("demo2021");
loginInfo.add(LI);
s.setLoginInfo(loginInfo);
list.add(s);
}
}
The frame:
import javax.swing.*;
public class AppFrame extends JFrame {
private static final long serialVersionUID = -337449186297669567L;
public AppFrame(){
setTitle("Plan & Earn");
setSize(400, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Student LoginInfo:
public class LoginInfo {
String username;
String password;
public LoginInfo(){
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Student info for the json file:
import java.util.ArrayList;
import java.util.List;
public class Student {
String firstName;
String lastName;
private List<LoginInfo> loginInfo;
public Student(){
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<LoginInfo> getLoginInfo() {
return loginInfo;
}
public void setLoginInfo(List<LoginInfo> loginInfo) {
this.loginInfo = loginInfo;
}
#Override
public String toString(){
return "Student{" + "firstName=" + firstName + ", lastName=" + lastName + ", Login Info=" + loginInfo + '}';
}
}
Okay, you're kind of heading in the right direction. Some things you're going to want to consider are:
Providing a self contained manager/service for managing the students. This would be responsible for loading, updating and generally manager the students, preferably in some way which decoupled the physical "how" away from the rest of the app (no one cares that it's backed by a JSON file, they only care about "doing stuff")
Providing some kind of authentication workflow which is independent of the UI. The LoginPages responsibility is about collecting information from the user. It's not responsible for the underlying workflow of "how" a user is authenticated
Providing some kind of callback from the LoginPage to inform interested parties that a student has logged in
The main goal is to reduce the coupling of the system (the amount that any one part of the system relies on another part). When designing a solution, you want to be always thinking about how hard it would be to modify any one part of the solution and how much impact that might have on other parts of the system.
For example, if you decided to move the student management to a SQL database or a web service, what impact would that have on other parts your solution. If you find yourself having to make major modifications to other parts of the solution, then it's tightly coupled, which isn't a good thing.
There are number of ways you can approach these issues, but the following are some basic design principles you should keep in mind:
Delegation Pattern
Dependency Injection
Observer
There's also discussions over how much information any part of the system really needs, for example, the LoginPage doesn't really need access to the student database, that's not it's responsibility, so we should "hide" the details from it and only provide it with the details it really needs to do its job.
This is where you will find the concept of "code to interface" powerful
Smarter Java development
OOP Good Practices: Coding to the interface
And many more, just Google around 😉
Okay, but how does that help? Well a lot actually.
Let's start back at the LoginPage. It wants to ...
Get the user's login credentials from the user
Validate the credentials against the system
Notify some interested party when the authentication is success
To start with, we need some way to authenticate the user which is decoupled from the physical implementation (ie "delegate")...
public interface Authenticator {
public Student authenticate(String userName, char[] password);
}
I know, you're underwhelmed, but this is really very powerful. This provides the LoginPage with the ability to pass the credentials into some system and have it either return a Student or null based on it's own internal needs. LoginPage doesn't care. So we could implement a bunch of different workflows and LoginPage won't ever change, win 🎉
Next, we need someway for LoginPage to notify interested parties when the authentication is success (ie an "observer)...
public class LoginPage extends JPanel {
public static interface LoginListener {
public void loginWasSucessful(LoginPage source, Student student);
}
Now, I've defined this as a inner interface to LoginPage, this is mostly done this way because LoginListener will only ever be used within a context of LoginPage, but you can declare it as seperate interface in it's own file if you want, doesn't matter. The point is, this defines a contract to which interested parties can be notified of "successful logins"
Now, we need to start putting it together.
First, I updated your LoginPage. I've modified the constructor to accept an instance of Authenticator and LoginListener...
public class LoginPage extends JPanel {
public static interface LoginListener {
public void loginWasSucessful(LoginPage source, Student student);
}
private static final long serialVersionUID = -337449186297669567L;
private JLabel user_label = new JLabel("Username: ");
private JLabel password_label = new JLabel("Password: ");
private JLabel screenName = new JLabel("Login", SwingConstants.CENTER);
private JTextField username = new JTextField(10);
private JPasswordField password = new JPasswordField(10);
private JButton login, cancel;
private JPanel panel = new JPanel();
private String hidden = "login";
private Authenticator authenticator;
private LoginListener loginListener;
public LoginPage(Authenticator authenticator, LoginListener loginListener) {
this.authenticator = authenticator;
this.loginListener = loginListener;
setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(16, 16, 16, 16), BorderFactory.createEtchedBorder()));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(screenName, gbc);
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.LINE_END;
add(user_label, gbc);
gbc.gridy++;
add(password_label, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.LINE_START;
add(username, gbc);
gbc.gridy++;
add(password, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
login = new JButton("LOGIN");
add(login, gbc);
login.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
login.setEnabled(false);
Student student = authenticator.authenticate(username.getText(), password.getPassword());
if (student != null) {
loginListener.loginWasSucessful(LoginPage.this, student);
} else {
JOptionPane.showMessageDialog(LoginPage.this, "Authentication failed", "Error", JOptionPane.ERROR_MESSAGE);
}
login.setEnabled(true);
}
});
}
}
The interesting part is here at the end, where we handle the ActionEvent for login
Next, we need someway to actually authenticate the user, for this, I wrote a super simple "authenticator"
public class DefaultAuthenticator implements Authenticator {
private List<Student> students;
public DefaultAuthenticator(List<Student> students) {
this.students = students;
}
#Override
public Student authenticate(String userName, char[] password) {
for (Student student : students) {
for (LoginInfo loginInfo : student.loginInfo) {
if (userName.equals(loginInfo.getUsername()) && Arrays.equals(loginInfo.getPassword().toCharArray(), password)) {
return student;
}
}
}
return null;
}
}
This is for test purposes. When you build your "student manager", I'd be the tempted to either implement Authenticator directly or pass it (inject it) to the above implementation, what ever seems most appropriate to you at the time.
The next part is to test it! For this, I built a simple Student and LoginInfo which was passed into the DefaultAuthenticator. This then got passed to my main panel, which was responsible for setting up the primary UI...
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
// Load student information, maybe through some kind
// of student service
LoginInfo loginInfo = new LoginInfo("test", "1234");
List<LoginInfo> loginList = new ArrayList<>();
loginList.add(loginInfo);
Student student = new Student();
student.setLoginInfo(loginList);
List<Student> students = new ArrayList<>();
students.add(student);
Authenticator authenticator = new DefaultAuthenticator(students);
JFrame frame = new JFrame();
frame.add(new TestPane(authenticator));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private CardLayout cardLayout;
public TestPane(Authenticator authenticator) {
cardLayout = new CardLayout();
setLayout(cardLayout);
LoginPage login = new LoginPage(authenticator, new LoginPage.LoginListener() {
#Override
public void loginWasSucessful(LoginPage source, Student student) {
cardLayout.show(TestPane.this, "welcome");
}
});
add(login, "login");
add(new JLabel("Welcome", JLabel.CENTER), "welcome");
}
}
The interesting part here is the handling of the successful login. While all I'm doing here flip the UI over to show the "welcome" label, you can see that it's all decoupled and divorced from each other.
I don't care how the authentication works or how/when I get notified of the successful login, only that it can happen
Runnable example
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.CompoundBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
// Load student information, maybe through some kind
// of student service
LoginInfo loginInfo = new LoginInfo("test", "1234");
List<LoginInfo> loginList = new ArrayList<>();
loginList.add(loginInfo);
Student student = new Student();
student.setLoginInfo(loginList);
List<Student> students = new ArrayList<>();
students.add(student);
Authenticator authenticator = new DefaultAuthenticator(students);
JFrame frame = new JFrame();
frame.add(new TestPane(authenticator));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private CardLayout cardLayout;
public TestPane(Authenticator authenticator) {
cardLayout = new CardLayout();
setLayout(cardLayout);
LoginPage login = new LoginPage(authenticator, new LoginPage.LoginListener() {
#Override
public void loginWasSucessful(LoginPage source, Student student) {
cardLayout.show(TestPane.this, "welcome");
}
});
add(login, "login");
add(new JLabel("Welcome", JLabel.CENTER), "welcome");
}
}
public interface Authenticator {
public Student authenticate(String userName, char[] password);
}
public class DefaultAuthenticator implements Authenticator {
private List<Student> students;
public DefaultAuthenticator(List<Student> students) {
this.students = students;
}
#Override
public Student authenticate(String userName, char[] password) {
for (Student student : students) {
for (LoginInfo loginInfo : student.loginInfo) {
if (userName.equals(loginInfo.getUsername()) && Arrays.equals(loginInfo.getPassword().toCharArray(), password)) {
return student;
}
}
}
return null;
}
}
public class LoginPage extends JPanel {
public static interface LoginListener {
public void loginWasSucessful(LoginPage source, Student student);
}
private static final long serialVersionUID = -337449186297669567L;
private JLabel user_label = new JLabel("Username: ");
private JLabel password_label = new JLabel("Password: ");
private JLabel screenName = new JLabel("Login", SwingConstants.CENTER);
private JTextField username = new JTextField(10);
private JPasswordField password = new JPasswordField(10);
private JButton login, cancel;
private JPanel panel = new JPanel();
private String hidden = "login";
private Authenticator authenticator;
private LoginListener loginListener;
public LoginPage(Authenticator authenticator, LoginListener loginListener) {
this.authenticator = authenticator;
this.loginListener = loginListener;
setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(16, 16, 16, 16), BorderFactory.createEtchedBorder()));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(screenName, gbc);
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.LINE_END;
add(user_label, gbc);
gbc.gridy++;
add(password_label, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.LINE_START;
add(username, gbc);
gbc.gridy++;
add(password, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
login = new JButton("LOGIN");
add(login, gbc);
login.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
login.setEnabled(false);
Student student = authenticator.authenticate(username.getText(), password.getPassword());
if (student != null) {
loginListener.loginWasSucessful(LoginPage.this, student);
} else {
JOptionPane.showMessageDialog(LoginPage.this, "Authentication failed", "Error", JOptionPane.ERROR_MESSAGE);
}
login.setEnabled(true);
}
});
}
}
public class LoginInfo {
String username;
String password;
public LoginInfo(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public class Student {
String firstName;
String lastName;
private List<LoginInfo> loginInfo;
public Student() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<LoginInfo> getLoginInfo() {
return loginInfo;
}
public void setLoginInfo(List<LoginInfo> loginInfo) {
this.loginInfo = loginInfo;
}
#Override
public String toString() {
return "Student{" + "firstName=" + firstName + ", lastName=" + lastName + ", Login Info=" + loginInfo + '}';
}
}
}
Caveat
I have NOT, deliberately, merged your "student management" workflow with my example. All I've done here is present a means by which you can build a workflow, connecting the authentication work (delegation) to the "what happens next" (observer) workflows.
You will need to build your solution in and around these concepts.
But why (did you do that)?! ðŸ˜
Because, giving you a "copy and paste" solution doesn't help you. You need to be able to see your problem and design a solution around it using these design principles (there's a reason why they are bases of software engineering).
You have a runnable example which demonstrates the basic idea(s), now, you need to build your solution to around them and try and learn and understand them.
I am trying to create a student registration program in which the user inputs data in a JFrame in a JTextField and that data is stored into a variable in another class.
package acgregistration;
import java.util.*;
/**
*
* #author Frank
*/
public class AcgRegistration {
public static void main(String[] args) {
memberDialogBox memberDialogBox = new memberDialogBox();
}
}
package acgregistration;
/**
*
* #author Frank
*/
class acgMember {
private String name;
private int num;
private String email;
public acgMember(String name, int number, String email) {
this.name = name;
this.num = number;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package acgregistration;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* #author Frank
*/
public class memberDialogBox {
String options[] = {"Student","Faculty/Staff"};
JComboBox choices = new JComboBox(options);
JButton b = new JButton("Confirm");
JLabel l = new JLabel("Select your ACG Status");
public memberDialogBox(){
frame();
}
public void frame(){
JFrame f = new JFrame();
f.setVisible(true);
f.setSize(210,150);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel p = new JPanel();
p.add(choices);
p.add(b);
p.add(l);
f.add(p);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = choices.getSelectedItem().toString();
if ("Student".equals(choices.getSelectedItem())){
studentDialogBox student = new studentDialogBox();
//This code gives me an error code saying I should call
//acgMemberModel
}
else{
facultyDialogBox faculty= new facultyDialogBox();
}
f.dispose();
}
});
}
}
package acgregistration;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class studentDialogBox {
private JTextField nameField = new JTextField("", 20);
private JTextField emailField = new JTextField("", 20);
private JTextField numberField = new JTextField("", 20);
private JButton confirmButton = new JButton("Confirm");
private acgMemberModel model;
public studentDialogBox(acgMemberModel model) {
this.model = model;
frame();
}
public void frame() {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(nameField);
panel.add(emailField);
panel.add(numberField);
panel.add(confirmButton);
frame.add(panel);
confirmButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String number = numberField.getText();
String email = emailField.getText();
acgMember member = new acgMember(name,
Integer.valueOf(number), email);
model.addNew(member);
}
});
}
}
class acgMemberModel {
private List<acgMember> members = new ArrayList<>();
public void addNew(acgMember member) {
members.add(member);
}
public List<acgMember> getMembers() {
return Collections.unmodifiableList(members);
}
}
I'm basically trying to do this for all the text fields and then save it into an ArrayList or a Hashmap ( basically the end result). My only question is, how would i store text field inputs from one class to another?
Any help would be highly appreciated! Thank you!
Just create new instance of Member every time when you populate fields and push button in result of this action listener will invoked and you will grab all data from text field and pass it to new instance constructor. Every time you create new Member pass it to MemberModel separate class.
P.S. you need to read something about naming convention of java language especially about variables, you made mistake in way to set action listener to a TextField instead of Button because your variable names completely meaningless. I refactor code in way to change all variable names to human readable form and fix mistake in my solution because all that conventions has not been used.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
MemberModel model = new MemberModel();
StudentsToOutputListener outputListener
= new StudentsToOutputListener(model, new FileOutput(new File("path to your default file")));
Window studentDialog = new StudentDialogBox(model);
Window facilityDialog = new FacultyDialogBox();
Window memberDialog = new MemberDialogBox(studentDialog, facilityDialog);
memberDialog.show();
}
}
class Member {
private String name;
private int number;
private String email;
public Member(String name, int number, String email) {
this.name = name;
this.number = number;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Member{" +
"name='" + name + '\'' +
", number=" + number +
", email='" + email + '\'' +
'}';
}
}
interface Window {
void show();
}
interface Output {
void output(List<Member> members);
}
interface Listener {
void update();
}
class MemberDialogBox implements Window {
private JFrame frame = new JFrame();
private JComboBox<Window> choiceComboBox = new JComboBox<>();
private JButton confirmButton = new JButton("Confirm");
private JLabel selectLabel = new JLabel("Select your ACG Status");
public MemberDialogBox(Window... windows) {
for (Window window : windows) {
choiceComboBox.addItem(window);
}
frame();
}
public void show() {
frame.setVisible(true);
}
public void frame() {
frame = new JFrame();
frame.setSize(210, 150);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(choiceComboBox);
panel.add(confirmButton);
panel.add(selectLabel);
frame.add(panel);
confirmButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Window window = (Window) choiceComboBox.getSelectedItem();
window.show();
frame.dispose();
}
});
}
}
class StudentDialogBox implements Window, Listener, Output {
private JTextField nameField = new JTextField("", 20);
private JTextField emailField = new JTextField("", 20);
private JTextField numberField = new JTextField("", 20);
private JButton confirmButton = new JButton("Confirm");
private JButton saveButton = new JButton("Save students to file");
private JFrame frame;
private JList<Member> list = new JList<>();
private MemberModel model;
public StudentDialogBox(MemberModel model) {
this.model = model;
model.addListener(this);
frame();
}
public void show() {
frame.setVisible(true);
}
public void output(List<Member> members) {
list.setListData(members.toArray(new Member[]{}));
}
public void update() {
model.outputStudentsTo(this);
}
public void frame() {
frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(nameField);
panel.add(emailField);
panel.add(numberField);
panel.add(confirmButton);
panel.add(list);
panel.add(saveButton);
frame.add(panel);
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.showSaveDialog(frame);
File selectedFile = fileChooser.getSelectedFile();
Output output = new FileOutput(selectedFile);
model.outputStudentsTo(output);
}
});
confirmButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String number = numberField.getText();
String email = emailField.getText();
Member member = new Member(name, Integer.valueOf(number), email);
model.addNewStudent(member);
}
});
}
public String toString() {
return "Student";
}
}
class FacultyDialogBox implements Window {
public void show() {
System.out.println("you need to implement FacultyDialogBox " +
"in similar way than StudentDialog box");
}
public String toString() {
return "Faculty/Stuff";
}
}
class MemberModel {
private List<Member> students = new ArrayList<>();
private List<Member> stuff = new ArrayList<>();
private List<Listener> listeners = new ArrayList<>();
public void addListener(Listener listener) {
listeners.add(listener);
}
private void notifyListeners() {
for (Listener listener : listeners) {
listener.update();
}
}
public void addNewStudent(Member member) {
students.add(member);
notifyListeners();
}
public void addNewStuff(Member member) {
stuff.add(member);
notifyListeners();
}
public void outputStudentsTo(Output output) {
output.output(Collections.unmodifiableList(students));
}
public void outputStuffTo(Output output) {
output.output(Collections.unmodifiableList(stuff));
}
}
class FileOutput implements Output {
private final File destination;
public FileOutput(File destination) {
this.destination = destination;
}
public void output(List<Member> members) {
try (BufferedWriter file = new BufferedWriter(new FileWriter(destination))) {
for (Member member : members) {
file.write(member.toString());
file.write("\n");
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
class StudentsToOutputListener implements Listener {
private final MemberModel model;
private final Output output;
public StudentsToOutputListener(MemberModel model, Output output) {
this.model = model;
this.output = output;
model.addListener(this);
}
public void update() {
model.outputStudentsTo(output);
}
}
I update answer to you question clarification, i understand what do you want to implement and fix your program, also i refactor this code and make it more in oop style and more readable, but you need to implement by yourself second dialog Facility in similar way than Student dialog box. Also you need to place every class in this source to different *.java file.
You're talking about data binding. I recently posted a demo that shows how to do what you need as an answer to this question: Switching JPanels moves content diagonally
Essentially, the GUI passes information to the model and vice-versa by events, typically Property Change Events but there are lots of options you could choose. The process would look like this:
User enters a value in a field
The field fires a property change event for the property "value" when it looses focus
The GUI (or controller class) listens for the property change event and fires another event, such as a Vetoable Change Event.
The Model (or controller) listens for the Vetoable change and validates the value, saving the "state" in the correct place. If the validation fails, it fires an exception.
The GUI checks for the veto exception and reverts the field if required.
A similar approach can allow the model to send property change requests to the GUI to update the value of fields.
The benefit of using these events is that it keeps the GUI simple, separates the model from the representation and makes it easier to replace/duplicate the GUI with another technology rather easily.
Have you tried making the variables you want to share between classes public static?
I currently have multiples of a JPanel (ItemPanel) within a JPanel (FlipPanel) within my JFrame. An ItemPanel is added to FlipPanel when a JButton in a separate panel (FlipFormPanel) is pressed. I have a JButton on ItemPanel labelled "Cancel" and I would like to remove the specific ItemPanel whose Cancel JButton was pressed. What I currently have only removes the ItemPanel whose button was selected, but after that no other buttons will remove any more ItemPanels.
How can I fix my code to do what I'm trying to accomplish?
My code for each class is below. I tried to remove as much of the extraneous material as possible to avoid cluttering the task at hand. I believe the issue is located in FlipPanel under the methods addItemPanel(, setItemListener(, and in the ItemPanelListener and ItemPanelEvent classes. Thanks for any help provided.
FlipPanel:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import net.miginfocom.swing.MigLayout;
public class FlipPanel extends JPanel {
private JPanel mainPanel;
private JScrollPane scrollPane;
private ItemPanel itemPanel;
private JPanel titlePanel;
private JLabel titleLabel;
private List<ItemPanel> itmPnls = new ArrayList<ItemPanel>();
private int count;
public FlipPanel() {
setLayout(new BorderLayout());
mainPanel = new JPanel();
scrollPane = new JScrollPane(mainPanel);
add(scrollPane, BorderLayout.CENTER);
mainPanel.setLayout(new MigLayout("align center, fillx", "fill", ""));
titlePanel = new JPanel();
mainPanel.add(titlePanel, "wrap, gapbottom 13, gaptop 7");
titlePanel.setLayout(new GridBagLayout());
titleLabel = new JLabel("CURRENT FLIPS");
Font labelFont = titleLabel.getFont();
titleLabel.setFont(new Font(labelFont.getName(), Font.BOLD, 25));
titlePanel.setBorder(BorderFactory.createMatteBorder(0, 0, 3, 0, Color.BLACK));
titlePanel.add(titleLabel);
count = 0;
}
public void addItemPanel(String item, String buyPrice, String sellPrice,
String quantity, String pcBuyPrice, String pcSellPrice) {
this.itemPanel = new ItemPanel(count, item, buyPrice, sellPrice, quantity,
pcBuyPrice, pcSellPrice);
mainPanel.add(itemPanel, "wrap");
itmPnls.add(itemPanel);
count++;
setItemListener(this.itemPanel);
}
public void setItemListener(ItemPanel iP) {
iP.setItemPanelListener(new ItemPanelListener() {
public void itemPanelEventOccurred(ItemPanelEvent e) {;
System.out.println("Remove");
System.out.println("Current Position: " + e.getPosition());
mainPanel.remove(itmPnls.get(e.getPosition()));
System.out.println("Positions:");
for (int i = 0; i < count; i++) {
System.out.println(itmPnls.get(i).getPosition());
}
if(e.getPosition() < count - 1) {
for (int i = e.getPosition() + 1; i < count; i++) {
itmPnls.get(i).setPosition(i);
}
}
count--;
revalidate();
repaint();
System.out.println("Positions:");
for (int i = 0; i < count; i++) {
System.out.println(itmPnls.get(i).getPosition());
}
setItemListener(itmPnls.get(0));
}
});
}
ItemPanel:
import javax.swing.JPanel;
public class ItemPanel extends JPanel {
private int position;
private String item;
private String buyPrice;
private String sellPrice;
private String quantity;
private String pcBuyPrice;
private String pcSellPrice;
private JButton logBtn;
private JButton editBtn;
private JButton cancelBtn;
private ItemPanelListener itemPanelListener;
public ItemPanel(int position, String item, String buyPrice, String sellPrice,
String quantity, String pcBuyPrice, String pcSellPrice) {
this.position = position;
this.item = item;
this.buyPrice = buyPrice;
this.sellPrice = sellPrice;
this.quantity = quantity;
this.pcBuyPrice = pcBuyPrice;
this.pcSellPrice = pcSellPrice;
Dimension dim = getPreferredSize();
dim.height = 100;
setPreferredSize(dim);
setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
logBtn = new JButton("Log Item");
editBtn = new JButton("Edit Item");
cancelBtn = new JButton("Cancel Item");
setupLabels();
setupCancelItemButton();
layoutComponents();
}
public int getPosition() {
return position;
}
public void setPosition(int pos) {
position = pos;
}
public void setupCancelItemButton() {
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ItemPanelEvent ev = new ItemPanelEvent(this);
if (itemPanelListener != null) {
itemPanelListener.itemPanelEventOccurred(ev);
}
}
});
}
public void setItemPanelListener(ItemPanelListener listener) {
this.itemPanelListener = listener;
}
ItemPanelListener:
import java.util.EventListener;
public interface ItemPanelListener extends EventListener {
public void itemPanelEventOccurred(ItemPanelEvent e);
}
ItemPanelEvent:
import java.util.EventObject;
public class ItemPanelEvent extends EventObject {
private int position;
public ItemPanelEvent(Object source) {
super(source);
}
public ItemPanelEvent(Object source, int position) {
super(source);
this.position = position;
}
public int getPosition() {
return position;
}
}
I am trying to sort a JList when pressing the sort button but I can't figure it out how.
This is my code:
Song class:
package song;
public class Song implements Comparable<Song>{
private String name;
private String artist;
public Song(String name, String artist){
this.name = name;
this.artist = artist;
}
public String getName(){
return name;
}
public String getArtist(){
return artist;
}
public void setArtist(String artist){
this.artist = artist;
}
public void setName(String name){
this.name = name;
}
public int compareTo(Song s){
return this.name.compareTo(s.getName());
}
public String toString(){
return name + " " + artist;
}
}
List Model:
package song;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.AbstractListModel;
public class ListModel extends AbstractListModel{
ArrayList<Song> songs;
public ListModel(ArrayList<Song> array){
songs = array;
}
public int getSize(){
return songs.size();
}
public Object getElementAt(int index){
return (Song)songs.get(index);
}
public ArrayList<Song> getSongList(){
return songs;
}
public void setList(ArrayList<Song> array){
this.songs = array;
}
public void getSortedList(ArrayList<Song> array){
Collections.sort(array);
songs = array;
}
}
App class:
package song;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
public class App extends JFrame{
JFrame frame;
JList<Song> list;
ArrayList<Song> songList;
ListModel songModelList;
private static final String FILE = "songs.txt";
JPanel loadPanel, addBtnPanel;
JButton btnLoad, btnSort, btnAdd, btnSave;
JTextField txtArtist, txtName;
public static void main(String[] args){
App a = new App();
}
public App(){
frame = new JFrame("Playlist");
loadPanel = createLoadPanel();
loadPanel.setBackground(Color.BLUE);
JPanel btnPanel = createButtonPanel();
btnPanel.setBackground(Color.ORANGE);
frame.getContentPane().add(btnPanel,BorderLayout.EAST);
frame.getContentPane().add(loadPanel,BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
// frame.pack();s
frame.setVisible(true);
}
public JPanel createButtonPanel(){
JPanel panel = new JPanel();
btnLoad = new JButton("Load List");
btnSort = new JButton("Sort list");
btnAdd = new JButton("Add");
btnSort.addActionListener(new ActionListener() { //here is the action listener for the button used for sorting
#Override
public void actionPerformed(ActionEvent e) {
// Collections.sort(songList);
// songModelList.setList(songList);
songModelList.getSortedList(songList);
list.updateUI();
}
});
btnLoad.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
loadPanel.setVisible(true);
}
});
btnAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
addBtnPanel = createAddPanel();
}
});
panel.add(btnLoad);
panel.add(btnSort);
panel.add(btnAdd);
return panel;
}
public JPanel createAddPanel(){
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(3,2));
JLabel lblName = new JLabel("Name");
JLabel lblArtist = new JLabel("Artist");
txtName = new JTextField(15);
txtArtist = new JTextField(15);
panel.add(lblName);
panel.add(txtName);
panel.add(lblArtist);
panel.add(txtArtist);
btnSave = new JButton("Save");
panel.add(btnSave);
btnSave.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String name = txtName.getText();
String artist = txtArtist.getText();
Song s = new Song(name, artist);
songModelList.getSongList().add(s);
list.updateUI();
}
});
frame.getContentPane().add(BorderLayout.CENTER,panel);
frame.setVisible(true);
frame.setSize(new Dimension(300,100));
return panel;
}
public JPanel createLoadPanel(){
JPanel LoadPanel = new JPanel();
list = new JList<Song>();
songList = loadFromFile();
songModelList = new ListModel(songList);
songList = new ArrayList<Song>();
list.setModel(songModelList);
list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
LoadPanel.add(list);
LoadPanel.setVisible(false);
return LoadPanel;
}
public ArrayList<Song> loadFromFile(){
ArrayList<Song> array = new ArrayList<Song>();
try{
BufferedReader reader = new BufferedReader(new FileReader(FILE));
String line = null;
while((line = reader.readLine()) != null){
String[] parts = line.split(" - ");
if(parts.length == 2){
String name = parts[0];
String artist = parts[1];
Song s = new Song(name, artist);
array.add(s);
}
else{
System.out.println("Invalid line!");
}
}
reader.close();
}catch(IOException e){
System.out.println("File not found");
e.printStackTrace();
}
return array;
}
}
So, the JList desplays the elements in the order they are added. But if the user wants to sort them I made a sort button and when the button is pressed the JList shows the elements in sorted order. How do I manage to do that? I tried over and over again but it doesn't work.
Just add method sort() to ListModel:
public void sort(){
Collections.sort(songs);
fireContentsChanged(this, 0, songs.size());
}
And fix btnSort action:
btnSort.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
songModelList.sort();
}
});
In your model, try using a TreeSet<Song> and then create a Comparator<Song> and pass it into the constructor of your TreeSet<Song>. It will automatically sort all the elements as elements are added.
You need to call the appropriate fire* method of the list model when you have modified the contents. Call fireContentsChanged(this, 0, songs.size() - 1) in getSortedList(). (Which, by the way, is confusingly named).
Maybe you can help me out here :)
I want to "simulate" like say 10 machine-stations. In my JFrame/Container (I tried both) I put these 10 maschines ( = 10 JPanels containing x buttons, textfields, whatever of my desired design), and I want to have different informations on each one and change them for my needs.
I tried to change the value of a JTextField with an JButton (like setting the priority of the machine + 1. But I cannot distinguish between the 10 "priority up" buttons :(
How you do that? My idea was to speak somehow to the JPanel it came from but I can´t.
Container wizardFrame = new JFrame();
wizardFrame.setLayout(new GridLayout(2,5));
String Name;
for(int i = 1; i < 11; i++){
Name = "Maschine " + i;
fillWizardFrame(wizardFrame, Name, i);
}
wizardFrame.setVisible(true);
}
public void fillWizardFrame(Container wizardFrame, String Name, int i) {
JPanel MaschineId = new JPanel();
MaschineId.setLayout(new BorderLayout());
JTextField maschineName = new JTextField(Name ,10);
MaschineId.add(maschineName, BorderLayout.WEST);
maschinePrioritaet = new JTextField("20",10);
MaschineId.add(maschinePrioritaet,BorderLayout.CENTER);
JButton Higher = new JButton("Higher " + i); Higher.addActionListener(this);
MaschineId.add(Higher, BorderLayout.NORTH);
wizardFrame.add(MaschineId);
}
#Override
public void actionPerformed(ActionEvent event) {
if(event.getActionCommand().contains("Higher")){
System.out.println("Higher pressed " + event.getActionCommand());
}
// i tried .getID , .getSource etc... :/
}
I want to change the value of maschinePrioritaet with my "higher" button, but I can´t... This thing took me hours of searching and trying but wasn´t able to find something.
Thank you so much for your help!
Best, Andrea
You have to work more with objects and especially Views (like in MVC). A View represents an object, in this case it looks like some machine (which is a name, an id and a priority). So you need to create a machine panel that is attached to that model.
Here is something closer to that (but there are still many improvements to do):
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Wizard {
public Wizard() {
JFrame wizardFrame = new JFrame();
wizardFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
wizardFrame.setLayout(new GridLayout(2, 5));
String name;
for (int i = 1; i < 11; i++) {
name = "Maschine " + i;
MashinePanel mashinePanel = new MashinePanel(name, i);
wizardFrame.add(mashinePanel.getPanel());
}
wizardFrame.pack();
wizardFrame.setVisible(true);
}
public static class MashinePanel implements ActionListener {
private final String name;
private final int id;
private JTextField maschineNameTF;
private JFormattedTextField maschinePrioritaetTF;
private JButton higher;
private JPanel machinePanel;
public MashinePanel(String name, int i) {
super();
this.name = name;
this.id = i;
machinePanel = new JPanel();
machinePanel.setLayout(new BorderLayout());
maschineNameTF = new JTextField(name, 10);
machinePanel.add(maschineNameTF, BorderLayout.WEST);
maschinePrioritaetTF = new JFormattedTextField(20);
maschinePrioritaetTF.setColumns(10);
machinePanel.add(maschinePrioritaetTF, BorderLayout.CENTER);
higher = new JButton("Higher " + i);
higher.addActionListener(this);
machinePanel.add(higher, BorderLayout.NORTH);
}
public JPanel getPanel() {
return machinePanel;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
#Override
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().contains("Higher")) {
Object value = maschinePrioritaetTF.getValue();
int priority = 20;
if (value instanceof Integer) {
priority = (Integer) value;
}
maschinePrioritaetTF.setValue(priority + 1);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Wizard();
}
});
}
}