How to dynamically create JPanel with given parameters? - java

I have main JFrame in my project. And one main JPanel with Y-AXIS BoxLayout which is used to contain another panels in it. This is the way i use my JFrame to show this JPanel by default (I'm not quite convinced if this is the right way):
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
mainPanel = new MainScreenPanel();
MainFrame mainFrame = new MainFrame();
mainFrame.setContentPane(mainPanel);
mainFrame.invalidate();
mainFrame.validate();
mainFrame.setVisible(true);
}
});
}
Next I add two JPanels into mainPanel like this:
public class MainScreenPanel extends javax.swing.JPanel {
public MainScreenPanel() {
StatusPanel sPanel = new StatusPanel();
LogPanel lPanel = new LogPanel();
add(sPanel);
add(lPanel);
}
}
lPanel has different gui elements on it. One of them is a button which opens another panel (addConnectionPanel), and replaces mainPanel in the jFrame Here is the way i do it:
private void addCnctButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
topFrame.setContentPane(new AddConnectionPanel());
topFrame.invalidate();
topFrame.validate();
}
AddConectionPanel has some labels and input text boxes. It has two buttons ok and cancel. Here is the code of cancel button:
private void cancelCnctBtnActionPerformed(java.awt.event.ActionEvent evt) {
JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
topFrame.setContentPane(new MainScreenPanel());
topFrame.invalidate();
topFrame.validate();
}
sPanel is empty. It must be empty until input boxes on AddConnectionPanel are not filled and 'ok' button is not pressed. When these actions are performed, I want to dynamically create JLabels which take parameters from inputs on sPanel. Labels should be grouped, so when the actions performed second time new group must be created. Can some one give me advice on how to do this? And show me my mistakes? Keep in mind I'm using NetBeans.

This would be my approach:
public interface ConnectionPanelListener{
void onOkButtonClicked(String... options);
void onCancelButtonClicked();
}
public class AddConnectionPanel extends JPanel {
private static final long serialVersionUID = 1L;
private ConnectionPanelListener listener;
public AddConnectionPanel(){
final Map<ConnectionOptions, JTextField> components = new HashMap<>(ConnectionOptions.values().length);
for(ConnectionOptions option:ConnectionOptions.values()){
this.add(new JLabel(option.labelCaption));
JTextField textField = new JTextField();
//setup textField;
this.add(textField);
components.put(option, textField);
}
JButton button = new JButton("OK");
button.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(final MouseEvent pE) {
super.mouseClicked(pE);
//TODO validate TextFields
Collection<String> inputs = new Stack<>();
for(Entry<?,JTextField> e : components.entrySet()){
String text = e.getValue().getText();
if(text==null || text.trim().isEmpty()){
//TODO improve input validation
System.out.println("Input text is empty for: "+e.getKey());
} else {
inputs.add(e.getKey() + ": " + text);
}
}
listener.onOkButtonClicked(inputs.toArray(new String[inputs.size()]));
}
});
this.add(button);
button = new JButton("cancel");
button.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(final MouseEvent pE) {
super.mouseClicked(pE);
listener.onCancelButtonClicked();
}
});
this.add(button);
}
public void setConnectionPanelListener(final ConnectionPanelListener l){
listener = l;
}
private enum ConnectionOptions{
IP_ADDRESS("IP-Address:"), PORT("Port:"), WHATEVER_ATTRIBUTE_YOU_NEED("Extras:");
private String labelCaption;
private ConnectionOptions(final String caption) {
labelCaption = caption;
}
}
}
As you can see, AddConnectionPanel expects a Listener to register for the case, that "OK" or "CANCEL" are clicked. So your adjusted implementation could be like:
private void addCnctButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
AddConnectionPanel panel = new AddConnectionPanel();
panel.setConnectionPanelListener(new ConnectionPanelListener(){
#Override
void onOkButtonClicked(String... options){ TODO: fill sPanel using the given Strings }
#Override
void onCancelButtonClicked(){ TODO }
});
topFrame.setContentPane(panel);
topFrame.invalidate();
topFrame.validate();
}

Related

Pass a String to another class

I'm writing an application where I need to get two String objects from the GUI to the nullObject class.
I'm relatively new to programming, and am trying my best to learn. If you have any tips on how to make this better, I'd be really thankful!
My GUI class:
package com.giuly.jsoncreate;
public class GUI {
private JFrame startFrame;
private JFrame chkFrame;
private JFrame osFrame;
private JFrame appVFrame;
private JPanel controlPanel;
private JButton nextPage;
private JButton cancel;
private JButton save;
public GUI() {
generateGUI();
}
public static void main(String[]args) {
GUI gui = new GUI();
}
public void generateGUI() {
//Creation of the First Frame
startFrame = new JFrame("JSCON Creator");
startFrame.setSize(1000, 700);
startFrame.setLayout(new FlowLayout());
startFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//Panel Creation
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
//Button Creation
cancel = new JButton("Cancel");
cancel.setSize(100, 100);
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
nextPage = new JButton("Next");
nextPage.setSize(100, 100);
nextPage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startFrame.setVisible(false);
showText();
}
});
startFrame.add(controlPanel);
startFrame.add(cancel);
startFrame.add(nextPage);
startFrame.setVisible(true);
startFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void showText() {
JFrame textFrame = new JFrame();
textFrame.setSize(1000, 700);
textFrame.setTitle("Text");
textFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel textPanel = new JPanel();
JLabel titleLabel = new JLabel("Title");
textPanel.add(titleLabel);
JLabel descrLabel = new JLabel("Description");
JTextField tfTitle = new JTextField("",15);
tfTitle.setForeground(Color.BLACK);
tfTitle.setBackground(Color.WHITE);
JTextField tfDescr = new JTextField("",30);
tfDescr.setForeground(Color.BLACK);
tfDescr.setBackground(Color.WHITE);
textPanel.add(tfTitle);
textPanel.add(descrLabel);
textPanel.add(tfDescr);
JButton buttonOK = new JButton("OK");
textPanel.add(buttonOK);
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String jsonTitle = tfTitle.getText();
String jsonDescr = tfDescr.getText();
System.exit(0);
}
});
textFrame.add(textPanel);
textFrame.setVisible(true);
}
I want to get the Strings jsonTitle and jsonDescr into another class, so I can store them. In the end I will have some Strings and I need to save them in a JSON file. I need a way to get those two Strings, what advice do you guys have?
Erick is correct with his answer. Just thought I should add additional info. If you declare jstonTitle and jsonDescr like your other fields using private you still will not be able to access these fields from another class. Coding up a getter for the fields along with declaring them at the top of GUI should solve your problem. Then just create an instance of GUI in your other class and call the method.
public String getJsonTitle(){
return this.jsonTitle;
}
You're declaring jstonTitle and jsonDescr inside the actionPerformed() method. That means that as soon as actionPerformed() exits you'll lose those variables. You need to declare them in an enclosing context. For example, you could make them fields on the GUI class. Still assign them in actionPerformed(), but declare them up at the top of GUI where you're declaring startFrame, chkFrame, etc.
That will give you the ability to access those values from anywhere within GUI.
Oh, BTW, get rid of System.exit(0);. (Have you actually tried to run your program?)

How to use CardLayout, with Menu as action listener?

I want to change the JPanel of a JFrame, using the CardLayout class.
I have already run this example and it works.
Now I want to use as action listener, the JMenuItem; so If I press that JMenuItem, I want to change it, with a specific panel. So this is the JFrame:
public class FantaFrame extends JFrame implements Observer {
private static final long serialVersionUID = 1L;
private JPanel cardPanel = new JPanel();
private CardLayout cardLayout = new CardLayout();
public FantaFrame(HashMap<String, JPanel> fantaPanels) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("FantaCalcio App");
setSize(500, 500);
cardPanel.setLayout(cardLayout);
setPanels(fantaPanels);
}
public void update(Observable o, Object arg) {
cardLayout.show(cardPanel, arg.toString());
}
private void setPanels(HashMap<String, JPanel> fantaPanels) {
for (String name : fantaPanels.keySet()) {
cardPanel.add(fantaPanels.get(name), name);
}
}
}
Those are the Menu, the Controller and the Main:
private void pressed(){
home.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
controller.changePanel(home.getText());
}
});
}
public class Controller extends Observable {
public void changePanel(String panel){
setChanged();
notifyObservers(panel);
}
}
public static void main(String[] args) {
fantaPanels.put("Login", new LoginPanel());
Controller controller = new Controller();
MenuBarApp menuApp = new MenuBarApp(controller);
FantaFrame frame = new FantaFrame(fantaPanels);
frame.setJMenuBar(menuApp);
controller.addObserver(frame);
frame.setVisible(true);
}
The problem is that the JPanel doesn't change. What do you think is the problem ?
I've already debugged it, and in the update() method, the correct String value arrives.
You never add the cardPanel JPanel, the one using the CardLayout and displaying the "cards" to anything. You need to add it to your JFrame's contentPane for it to display anything. i.e.,
public FantaFrame(HashMap<String, JPanel> fantaPanels) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("FantaCalcio App");
setSize(500, 500);
cardPanel.setLayout(cardLayout);
add(cardPanel, BorderLayout.CENTER); // ****** add this line ******
setPanels(fantaPanels);
}

opening only one window on actionPerformed

I've looked through topics on how to open only one window when a button is clicked but none of the solutions there helped, perhaps because my code was structured a bit differently.
So I have a main window class extending JFrame and one of the buttons is supposed to open a new window when clicked. I have defined the widgets/panels etc for the new window in a separate class. At the moment, every time I click on the button a new window is opened. I want to make it so that if a window is already opened then it would switch to that window once the button is clicked again.
Here is a bit of my code:
public class MainWindow extends JFrame{
/*
* create widgets and panels
*/
Button.addActionListener(new ActionListener() { // the button that opens
//a new window
#Override
public void actionPerformed(ActionEvent e) {
Window2 ww = new Window2(); //creating the new window here
}
});
}
NB. The Window2 class is also extending JFrame, if that's of any help.
Thanks
pull out ojbect creation from actionPerformed method beacuse each time you click button it's create new object. below can help you :-
Make a Window2 class singalton for more detail about singalton click here.
2 . add null check as below :-
....
Window2 ww = null; // static or instence variable
......
#Override
public void actionPerformed(ActionEvent e) {
if(ww==null)
{
ww = new Window2();
ww.someMethod();
}
else
{
ww.someMethod();
}
}
});
Here is a full working example:
Window2.java
public class Window2 extends JFrame {
private static final long serialVersionUID = 7843480295403205677L;
}
MainWindow.java
public class MainWindow extends JFrame {
private static final long serialVersionUID = -9170930657273608379L;
public static void main(String[] args) {
MainWindow mw = new MainWindow();
mw.go();
}
private void go() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
private void createAndShowGUI() {
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
private Window2 ww = null;
#Override
public void actionPerformed(ActionEvent e) {
if (ww==null) {
ww = new Window2(); //creating the new window here
ww.setDefaultCloseOperation(HIDE_ON_CLOSE);
ww.setTitle("Window2 created on " + new Date());
ww.setSize(500, 200);
}
pack();
ww.setVisible(true);
}
});
setLayout(new BorderLayout());
add(button);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
pack();
setVisible(true);
}
}
What you can try is make two windows and put the actionPeformed method in the main class so that when the button is pressed it displays the second window

Passing values between classes

I have a JPanel form which contains a JList and some JButton.
The JPanel looks like this
When I click the Add List button, a separate JFrame form is displayed.
The JFrame form will look like this
When the add button on the JFrame is clicked, I need to add the value of the JTextfield (named List Name) to the JList on the previous JPanel. I wonder how to pass the value from the JFrame to the JPanel? Any suggestion would be appreciated.
Here is a code of the JPanel form (using Designer GUI)
package multimediaproject;
public class musicPlayerPanel extends javax.swing.JPanel {
public musicPlayerPanel() {
initComponents();
}
private void initComponents() {
//...here is the generated code by using designer GUI
}
// Variables declaration - do not modify
//..generated code
// End of variables declaration
}
Here is the code of JFrame form (using Designer GUI)
package multimediaproject;
public class addListFrame extends javax.swing.JFrame {
public addListFrame() {
initComponents();
this.setLocation(515, 0);
setVisible(true);
}
private void initComponents() {
//..here is the generated code by using Designer GUI
}
private void addBtnActionPerformed(java.awt.event.ActionEvent evt){
//some validation
if(...)
{
//validation
}
else
{
//IF VALUE IS CORRECT, ADD the List Name JTextfield value to the JList on the previous JPanel
errorMessage.setText("");
}
}
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new addListFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
//....generated code
// End of variables declaration
}
UPDATE with your code.
You can take advantage of PropertyChangeListener and PropertyChangeSupport (This classes implements Observer Pattern).
I give you an example you for guidance:
public class MusicPlayerPanel extends JPanel {
private JList list;
private JButton addButton;
private PropertyChangeListener listener = new MyPropertyChangeListener();
//..in some place
addButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
JFrame form = new FrameForm();
form.addPropertyChangeListener(FrameForm.BUTTON_CLICKED,listener);
form.setVisible(true);
}
});
//in another place
private class MyPropertyChangeListener implements PropertyChangeListener{
#Override
public void propertyChange(PropertyChangeEvent evt){
if(evt == null)
return;
if(evt.getPropertyName().equals(FrameForm.BUTTON_CLICKED)){
String value = (String) evt.getNewValue();
((DefaultListModel)list.getModel()).addElement(value);
}
}
}
}
And the frame form like this:
public class AddListFrame extends JFrame{
private JTextField textfield;
private JButton submitButton;
public static final String BUTTON_CLICKED ="buttonClicked";
// in some place
submitButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
firePropertyChange(BUTTON_CLICKED,null,textfield.getText());
}
});
}
Note: In java by convention, classes start with uppercase and follow a camel style. This is very important for readability.
OK.This is easy if i understand your problem.
Step 1:Create setter and getter for your JList object reference.
Step 2:On button click , when you open new JFrame pass your panel reference in constructor of class which inherits JFrame.
Step 3:By doing this you are able to call getter method on panel reference.
Step 4:Now you have reference of JList,do what you want.
I hope this is best solution of your problem
"when I click the add button, a separate jFrame form is displayed. The jFrame contain a jTextfield and a submit button."
Did you seriously create an entirely new JFrame for a JTextField and a JButton?!
Have you not heard of JOptionPane? That's exactly what you are trying to replicate. The only code you need is this:
String s = JOptionPane.showInputDialog(component, message);
model.addElement(s);
The first line will cover all your code for your custom JFrame.
Take a look at this example
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JOPDemo extends JPanel {
JList list;
JButton button = new JButton("Add Name");
String name;
DefaultListModel model;
public JOPDemo() {
model = new DefaultListModel();
list = new JList(model);
setLayout(new BorderLayout());
add(list, BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
name = JOptionPane.showInputDialog(this, "Enter a name");
model.addElement(name);
}
});
}
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
private static void createAndShowGui() {
JFrame frame = new JFrame();
frame.add(new JOPDemo());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Edit
What you can do is have an inner class which is your JFrame. Personally, I'd go with a JDialog though.
From comment: Have your frame as an inner class of your main class. That way it can access all the variables from your main class. You can have a String listName also in the GUI class. From the other frame when you hit add, it sets the listName in GUI class, then adds to the list.
public class GUI {
String listName;
JList list;
InnerFrame inner = new InnerFrame();
private class InnerFrame extends JFrame {
JButton addButton;
}
}

Accessing JFrame created in main from actionlistener

I've created a frame (mainframe) for my program in the main class which I want to add and remove panels from in order switch between different screens of my program. The first screen of my program is the login panel which has a start button. When I press the start button I want to switch to the menu frame.
The removeAll method seems to work fine since the login panel disappears, but nothing appears in its place when I use the add, validate and repaint methods. I have tried to refer explicitly to the mainframe in the actionlistener (i.e. mainframe.add(menu)) but it does not recognise the object.
Thanks in advance!
public class Main {
public static JFrame mainframe = new JFrame();
public static void main(String[] args) {
// Create mainframe to add and remove panels from
LoginPanel lp = new LoginPanel();
System.out.println("mainframe created!");
// Set size of mainframe
mainframe.setBounds(0, 0, 500, 500);
mainframe.add(lp);
// Get the size of the screen
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
// Determine the new location of the mainframe
int w = mainframe.getSize().width;
int h = mainframe.getSize().height;
int x = (dim.width-w)/2;
int y = (dim.height-h)/2;
// Move the mainframe
mainframe.setLocation(x, y);
mainframe.setVisible(true);
}
}
This is my login panel class:
public class LoginPanel extends JPanel {
private JTextField usernameField;
private JPasswordField passwordField;
private final Action action = new SwingAction();
/**
* Create the panel.
*/
public LoginPanel() {
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = new String (passwordField.getPassword());
Login login = new Login();
boolean Correct = login.isCorrect(username, password);
**if (Correct == true){
removeAll();
Menu menu = new Menu();
add(menu);
validate();
repaint();
setBounds(0, 0, 500, 500);
System.out.println("Attempted to start menu!");
}**
}
});
btnLogin.setAction(action);
btnLogin.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
}});
}
I want to add and remove panels from in order switch between different screens of my program
Sounds like you should be using a Card Layout.
Define mainframe as a class field:
private JFrame mainframe;

Categories