Access JLabel from another class - java

So, I'm trying to access the (only) label "lblNewLabel" in class "TesteRotulo" from class "Controle".
public class TesteRotulo {
private JFrame frame;
private JLabel lblNewLabel;
// getter for the label to be accessed by class Controle
public JLabel getLblNewLabel() {
return lblNewLabel;
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TesteRotulo window = new TesteRotulo();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TesteRotulo() {
initialize();
// instantiate new object Controle having this instance of Testerotulo as parameter
Controle c = new Controle(TesteRotulo.this);
c.setRotulo();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblNewLabel = new JLabel();
frame.getContentPane().add(lblNewLabel, BorderLayout.CENTER);
frame.setVisible(true);
}
}
The class Controle that should access the label in TesteRotulo
public class Controle {
private TesteRotulo jM;
private JFrame janela;
private JLabel rotulo;
public Controle(TesteRotulo jM) {
this.jM = jM;
}
public void setRotulo() {
this.rotulo = jM.getLblNewLabel();
rotulo.setText("teste");
}
}
So I think having the reference for the (only) instance of TesteRotulo I should be able to access the label.
But to no avail. Always get a null pointer exception.
What is wrong?
Thanks in advance...

Your label in initialize is a local variable. JLabel lblNewLabel = new JLabel();
You should write this.lblNewLabel = new JLabel();

Related

Dispose JDialog from another class

I want to dispose a JDialog from another class, because i am trying to keep classes and methods clean, and not create buttons and handle the listeners in the same class. So here is the problem.
I tried creating a get method from the first class to get the dialog and then dispose it on the third but didnt work.
public class AddServiceListener extends JFrame implements ActionListener {
/**
* Creates listener for the File/New/Service button.
*/
public AddServiceListener() {
}
/**
* Performs action.
*/
public void actionPerformed(ActionEvent e) {
AddServiceWindow dialog = new AddServiceWindow();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
}
}
public class AddServiceWindow extends JDialog {
private JPanel contentPanel;
private JFrame frame;
private JPanel buttonPanel;
private JLabel nameLabel;
private JTextField nameField;
private JLabel destinationLabel;
private JTextField destinationField;
private JButton destinationButton;
private JButton okButton;
private JButton cancelButton;
/**
* Creates the dialog window.
*/
public AddServiceWindow() {
ManageMinder mainFrame = new ManageMinder();
frame = mainFrame.getFrame();
contentPanel = new JPanel();
contentPanel.setLayout(null);
setTitle("New Service File");
setSize(340, 220);
setLocationRelativeTo(frame);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
createLabels();
createTextFields();
createButtons();
addListeners();
}
/**
* Creates the labels.
*/
private void createLabels() {
nameLabel = new JLabel("Name:");
nameLabel.setHorizontalAlignment(SwingConstants.RIGHT);
nameLabel.setBounds(25, 25, 52, 16);
contentPanel.add(nameLabel);
destinationLabel = new JLabel("Path:");
destinationLabel.setHorizontalAlignment(SwingConstants.RIGHT);
destinationLabel.setBounds(7, 70, 70, 16);
contentPanel.add(destinationLabel);
}
/**
* Creates the text fields.
*/
private void createTextFields() {
nameField = new JTextField();
nameField.setBounds(87, 22, 220, 22);
contentPanel.add(nameField);
nameField.setColumns(10);
destinationField = new JTextField();
destinationField.setBounds(87, 68, 220, 20);
contentPanel.add(destinationField);
destinationField.setColumns(10);
}
/**
* Creates the buttons of the window.
*/
private void createButtons() {
destinationButton = new JButton("Select...");
destinationButton.setBounds(87, 99, 82, 23);
destinationButton.setFocusPainted(false);
contentPanel.add(destinationButton);
okButton = new JButton("OK");
okButton.setFocusPainted(false);
buttonPanel.add(okButton);
cancelButton = new JButton("Cancel");
cancelButton.setFocusPainted(false);
buttonPanel.add(cancelButton);
}
/**
* Adds listeners to buttons.
*/
private void addListeners() {
ActionListener destinationAction = new AddDestinationListener(destinationField);
destinationButton.addActionListener(destinationAction);
ActionListener okAction = new SaveNewServiceFileListener(nameField, destinationField);
okButton.addActionListener(okAction);
}
}
public class SaveNewServiceFileListener extends JFrame implements ActionListener {
private JTextField nameField;
private JTextField destinationField;
private String path;
private File newService;
/**
* Creates listener for the File/New/Add Service/OK button.
*/
public SaveNewServiceFileListener(JTextField nameField, JTextField destinationField) {
this.nameField = nameField;
this.destinationField = destinationField;
}
/**
* Performs action.
*/
public void actionPerformed(ActionEvent e) {
path = destinationField.getText() + "\\" + nameField.getText() + ".csv";
try {
newService = new File(path);
if(newService.createNewFile()) {
System.out.println("Done!");
// DISPOSE HERE
}
else {
System.out.println("Exists!");
}
} catch (IOException io) {
throw new RuntimeException(io);
}
}
}
What should i do, so the dialog disposes on the third one, when OK is clicked and file is created?
The way to change the state of another object is to 1) have a reference to that object, and 2) call a public method on it.
Here the other object is the JDialog, and the state that you wish to change is its visibility by calling either .close() or .dispose() on it. The problem that you're having is that the reference to the JDialog is not readily available since it is buried within the actionPerformed(...) method of your AddServiceListener class.
So don't do this -- don't bury the reference but rather put it into a field of the class that needs it.
If you absolutely need to have stand-alone ActionListener classes, then I think that the simplest thing to do is to take the dialog out of the listener class and into the view class, your main GUI, and then have the listener call methods on the view. For example
Assume that the dialog class is called SomeDialog and the main GUI is called MainGui. Then put the reference to the dialog in the MainGui class:
public class MainGui extends JFrame {
private SomeDialog someDialog = new SomeDialog(this);
And rather than have your listeners create the dialog, have them call a method in the main class that does this:
public class ShowDialogListener implements ActionListener {
private MainGui mainGui;
public ShowDialogListener(MainGui mainGui) {
// pass the main GUI reference into the listener
this.mainGui = mainGui;
}
#Override
public void actionPerformed(ActionEvent e) {
// tell the main GUI to display the dialog
mainGui.displaySomeDialog();
}
}
Then MainGUI can have:
public void displaySomeDialog() {
someDialog.setVisible(true);
}
An example MRE program could look like so:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.*;
import javax.swing.*;
public class FooGui002 {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MainGui mainGui = new MainGui();
mainGui.setVisible(true);
});
}
}
#SuppressWarnings("serial")
class MainGui extends JFrame {
private SomeDialog someDialog;
private JButton showSomeDialogButton = new JButton("Show Some Dialog");
private JButton closeSomeDialogButton = new JButton("Close Some Dialog");
public MainGui() {
super("Main GUI");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(500, 200));
someDialog = new SomeDialog(this);
showSomeDialogButton.addActionListener(new ShowDialogListener(this));
showSomeDialogButton.setMnemonic(KeyEvent.VK_S);
closeSomeDialogButton.addActionListener(new CloseSomeDialogListener(this));
closeSomeDialogButton.setMnemonic(KeyEvent.VK_C);
setLayout(new FlowLayout());
add(showSomeDialogButton);
add(closeSomeDialogButton);
pack();
setLocationByPlatform(true);
}
public void displaySomeDialog() {
someDialog.setVisible(true);
}
public void closeSomeDialog() {
someDialog.setVisible(false);
}
}
#SuppressWarnings("serial")
class SomeDialog extends JDialog {
public SomeDialog(Window window) {
super(window, "Some Dialog", ModalityType.MODELESS);
setPreferredSize(new Dimension(300, 200));
add(new JLabel("Some Dialog", SwingConstants.CENTER));
pack();
setLocationByPlatform(true);
}
}
class ShowDialogListener implements ActionListener {
private MainGui mainGui;
public ShowDialogListener(MainGui mainGui) {
this.mainGui = mainGui;
}
#Override
public void actionPerformed(ActionEvent e) {
mainGui.displaySomeDialog();
}
}
class CloseSomeDialogListener implements ActionListener {
private MainGui mainGui;
public CloseSomeDialogListener(MainGui mainGui) {
this.mainGui = mainGui;
}
#Override
public void actionPerformed(ActionEvent e) {
mainGui.closeSomeDialog();
}
}

passing values from JPanel class to JFrame class

I have a JFrame which uses JPanel initialized from the JPanel.
This is the JFrame class : LoginPage
public class LoginPage extends JFrame
{
private JPanel contentPane;
static int cnf;
static String data;
private static LoginPage frame;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
frame = new LoginPage();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
//cnf = chk;
if( cnf == 1)
{
frame.dispose();
JFrame m = new MainPage();
m.setVisible(true);
}
}
/**
* Create the frame.
*/
public LoginPage()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel m = new MainLogin();
m.setBounds(0, 0, 448, 271);
contentPane.add(m);
}
}
And, this is the JPanel class : MainLogin
public class MainLogin extends JPanel
{
private JTextField uname;
private JPasswordField pass;
public static int chk;
public MainLogin()
{
setLayout(null);
uname = new JTextField();
uname.setBounds(236, 22, 167, 25);
add(uname);
uname.setColumns(10);
pass = new JPasswordField();
pass.setBounds(236, 53, 167, 25);
add(pass);
JButton login = new JButton("Login");
login.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String u = uname.getText();
char[] tp = pass.getPassword();
String p = new String(tp);
chk = authentication.verify(u, p);
System.out.println(chk);
}
});
login.setBounds(235, 90, 117, 25);
add(login);
}
}
As in the MainLogin Panel, there is a class authentication who has a method verify(), which returns an integer, and this integer is stored in chk.
Since, this chk resides in MainLogin JPanel class, I want to pass it to the LoginPage JFrame class.
Is there any way to do this other than using a File?
Open the main page from LoginPage instance not from the main method.
Add a login() method to the LoginPage
public class LoginPage extends JFrame {
//other parts
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
frame = new LoginPage();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
public LoginPage() {
//...
JPanel m = new MainLogin(this);
//...
}
public void login(int chk) {
JFrame m = new MainPage();
m.setVisible(true);
this.dispose();
}
}
And pass login frame to the panel as a parameter
public class MainLogin extends JPanel
{
private int chk;//no need to be static
public MainLogin(final LoginFrame loginFrame)
{
setLayout(null);//null layout is bad
//...
login.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//...
chk = authentication.verify(u, p);
loginFrame.login(chk);
}
});
//...
}
}
Not only does this question get asked quite a bit, it also has a number of possible solutions, including using a modal dialog or Observer Pattern depending on your needs
See How to Make Dialogs for more details
You might also like to take a look at
Open JFrame, only after successfull login verification with database. Using Eclipse?
Java and GUI - Where do ActionListeners belong according to MVC pattern?
for more discussion on the subject
The basic answer here is, you want to separate the areas of responsibility.
You need to:
Gather the user credentials
Validate those credentials
Take a appropriate action based on the success of that check
These are three distinct actions, all which should be separated, it's not the responsibility of the login panel to validate the credentials, that's someone else's responsibility, equally, it's not the validators responsibility to decide what should be done when the validation fails or succeeds, that's someone else's responsibility

Java File Copy and Opening New jFrame

I am creating a program where the contents of a directory is being copied to another directory. Before the copy process commences I am trying to open a second Jframe to tell the user that the copying is in progress. The issue is that the second JFrame does not load completely until the copy progress is completed. Does anyone know of a way to load the second frame completely before starting the copying?
First Frame Code
public class First {
private JFrame frmFirstFrame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
First window = new First();
window.frmFirstFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public First() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmFirstFrame = new JFrame();
frmFirstFrame.setTitle("First Frame");
frmFirstFrame.setBounds(100, 100, 450, 300);
frmFirstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmFirstFrame.getContentPane().setLayout(null);
JButton btnCopy = new JButton("Copy");
btnCopy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String source = "D:\\";
String destination = "D:\\test\\";
Second second = new Second();
second.setVisible(true);
File s = new File (source);
File d = new File (destination);
try {
FileUtils.copyDirectory(s, d);
//second.setVisible(false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnCopy.setBounds(184, 111, 89, 23);
frmFirstFrame.getContentPane().add(btnCopy);
}}
Second Frame Code
public class Second extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Second frame = new Second();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Second() {
setTitle("Second Frame");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblCopyCompleted = new JLabel("Copy in Progress...");
lblCopyCompleted.setBounds(76, 70, 217, 37);
contentPane.add(lblCopyCompleted);
}
}
This is what I am getting during the copy progress.
It should look like this during copying.
The second JFrame should be a JDialog, since your application should have only one JFrame (main window). For more on this, please see: The Use of Multiple JFrames, Good/Bad Practice?
Your problem is that your code does not respect Swing threading rules, and by doing long-running tasks on the Swing event thread, you tie up the thread, preventing it from doing its necessary jobs, including drawing to windows and interacting with the user.
A good solution is to use a background thread, specifically one obtained from a SwingWorker. Tutorial: Lesson: Concurrency in Swing
import java.awt.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
#SuppressWarnings("serial")
public class First2 extends JPanel {
private static final int COLS = 15;
private JTextField sourceField = new JTextField(COLS);
private JTextField destField = new JTextField(COLS);
private JDialog dialog;
private DialogPanel dialogPanel = new DialogPanel();
public First2() {
setLayout(new GridBagLayout());
add(new JLabel("Source:"), createGbc(0, 0));
add(sourceField, createGbc(1, 0));
add(new JLabel("Destination:"), createGbc(0, 1));
add(destField, createGbc(1, 1));
add(new JButton(new CopyAction("Copy")), createGbc(1, 2));
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(4, 4, 4, 4);
return gbc;
}
private class CopyAction extends AbstractAction {
public CopyAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
String src = sourceField.getText();
String dest = destField.getText();
MyWorker myWorker = new MyWorker(src, dest);
myWorker.addPropertyChangeListener(new WorkerListener());
myWorker.execute();
Window window = SwingUtilities.getWindowAncestor(First2.this);
dialog = new JDialog(window, "File Copy", ModalityType.APPLICATION_MODAL);
dialog.add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
}
private class MyWorker extends SwingWorker<Void, Void> {
private String src;
private String dest;
public MyWorker(String src, String dest) {
this.src = src;
this.dest = dest;
}
#Override
protected Void doInBackground() throws Exception {
FileUtils.copyDirectory(src, dest);
return null;
}
}
private class WorkerListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
if (dialog != null && dialog.isVisible()) {
dialog.dispose();
}
try {
((MyWorker) evt.getSource()).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
}
private static void createAndShowGui() {
First2 mainPanel = new First2();
JFrame frame = new JFrame("First2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class DialogPanel extends JPanel {
private static final int PREF_W = 300;
private static final int PREF_H = 250;
public DialogPanel() {
setLayout(new GridBagLayout());
add(new JLabel("Copy in Progress..."));
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
}

GUI and application logic of WindowBuilder interaction java?

i have a MainWindow class which has main method,its constructor and initialize() method. The initialize() method has frame, Jbutton and a final Jtextarea. The actionPerformed() is in the another class Data which handles ActionListener. I want to display some text after the button is pressed in the Jtextfield which is inside only private variable frame of the MainWindow class.I haven't mentioned the Application logic, help me interact with it and GUI.. thank you !!!!!
The MainWindow class:
public class MainWindow {
private JFrame frame;
public Data data;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainWindow() {
this.data = new Data();
initialize();
}
private void initialize(){
frame = new JFrame();
frame.setBounds(100, 100, 396, 469);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
final JTextArea textarea = new JTextArea();
textarea.setFont(new Font("Dialog", Font.PLAIN, 75));
textarea.setTabSize(15);
textarea.setBounds(12, 28, 370, 85);
frame.getContentPane().add(textarea);
JButton button7 = new JButton("7");
button7.addActionListener(this.data); // Data data class has the actionperformed() method
button7.setActionCommand("7");
button7.setBounds(12, 125, 65, 73);
frame.getContentPane().add(button7);
}
}
Then the class Data is:
public class Data implements ActionListener {
public String s;
public Data(){
//constructor
}
public void actionPerformed(ActionEvent e) {
// this will set string s with some string
// that has to be returned to be displayed
// in the Jtextarea of the frame in MainWindow
}
public string returnString(){
return s;
}
i just want to set the JtextArea of the frame variable in MainWindow class..please help
If I understand correctly, you can simply pass the reference of the TextArea to your ActionListener via getter or constructor. Here I just used getter
public class Data implements ActionListener {
public JTextArea textArea;
public Data() {
//constructor
}
// here I used setter
public void setTextArea( JTextArea textArea ) {
this.textArea = textArea;
}
public void actionPerformed(ActionEvent e) {
// this will work, if you click the button 7
textArea.setText("Any modification you want");
}
}
And add this code in your initialize() method after textarea initialization
this.data.setTextArea(textarea);
Hope it helps.
UPDATE
public class MainWindow {
private JFrame frame;
public Data data;
final JTextArea textarea;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public class Data implements ActionListener {
public String s;
public MainWindow mainWindow;
public Data( MainWindow mainWindow ) {
this.mainWindow = mainWindow;
//constructor
}
public void actionPerformed(ActionEvent e) {
s = "test";
// this will set string s with some string
// that has to be returned to be displayed
// in the Jtextarea of the frame in MainWindow
mainWindow.updateTextArea(s);
}
public String returnString() {
return s;
}
}
That is just a simple implementation.

How to change card layout panels from another panel?

I Googled for a lot, and no solutions found. I think there shall be java masters to help me out ...
This is my initialize method:
private void initialize() {
this.setSize(750, 480);
this.setContentPane(getJContentPane());
this.setTitle("Registration");
JPanel topPane = new TopPane();
this.getContentPane().add(topPane,BorderLayout.PAGE_START);
cards=new JPanel(new CardLayout());
cards.add(step0(),"step0");
cards.add(step1(),"step1");
cards.add(step2(),"step2");
this.getContentPane().add(cards,BorderLayout.CENTER);
}
public JPanel step2(){
EnumMap<DPFPFingerIndex,DPFPTemplate> template = new EnumMap<DPFPFingerIndex, DPFPTemplate>(DPFPFingerIndex.class);
JPanel enrol = new Enrollment(template,2);
return enrol;
}
public JPanel step0(){
JPanel userAgree = new UserAgreement();
return userAgree;
}
public JPanel step1(){
JPanel userInfo = new UserInformation();
return userInfo;
}
public JPanel getCards(){
return cards;
}
This, is the method at another step0 JPanel:
jButtonAgree.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
Registration reg = new Registration();
LayoutManager cards = reg.getCards().getLayout();
((CardLayout) cards).show(reg.getCards(),"step1");
}
});
No reation at all, i tried revalidate, repaint and other staff... doesn't work ... any one got any soution here!
It's all about exposing the right methods and constant Strings to the outside world to allow the class to swap views itself. For example, give your first class a private CardLayout field called cardlayout and a private JPanel field called cards (the card holder JPanel), and some public String constants that are used to add your card JPanels to the cards container. Also give it a public method, say called public void swapView(String key) that allows outside classes to swap cards... something like so:
// code corrected
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Registration extends JPanel {
// use these same constants as button texts later
private static final Dimension PREF_SIZE = new Dimension(450, 300);
public static final String USER_AGREEMENT = "User Agreement";
public static final String USER_INFO = "User Information";
public static final String ENROLLMENT = "Enrollment";
// we'll extract them from this array
public static final String[] KEY_TEXTS = {USER_AGREEMENT, USER_INFO, ENROLLMENT};
private CardLayout cardlayout = new CardLayout();
private JPanel cards = new JPanel(cardlayout);
public Registration() {
cards.add(createUserAgreePanel(), USER_AGREEMENT);
cards.add(createUserInfoPanel(), USER_INFO);
cards.add(createEnrollmentPanel(), ENROLLMENT);
setLayout(new BorderLayout());
add(cards, BorderLayout.CENTER);
}
#Override
public Dimension getPreferredSize() {
return PREF_SIZE;
}
private JPanel createEnrollmentPanel() {
JPanel enrol = new JPanel();
enrol.add(new JLabel("Enrollment"));
return enrol;
}
private JPanel createUserAgreePanel() {
JPanel userAgree = new JPanel();
userAgree.add(new JLabel("User Agreement"));
return userAgree;
}
private JPanel createUserInfoPanel() {
JPanel userInfo = new JPanel();
userInfo.add(new JLabel("User Information"));
return userInfo;
}
public void swapView(String key) {
cardlayout.show(cards, key);
}
}
Then an outside class can swap views simply by calling the swapView on the visualized instance of this class, passing in the appropriate key String such as in this case CardTest.USER_INFO to show the user info JPanel.
Now you have a problem with this bit of code where I indicate by comment:
jButtonAgree.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
Registration reg = new Registration(); // **** HERE *****
LayoutManager cards = reg.getCards().getLayout();
((CardLayout) cards).show(reg.getCards(),"step1");
}
});
On that line you're creating a new Registration object, probably one that is completely unrelated to the one that is visualized on the GUI, and so calling methods on this new object will have absolutely no effect on the currently viewed gui. YOu need instead to get a reference to the viewed Registration object, perhaps by giving this class a getRegistration method, and then call its methods, like so:
class OutsideClass {
private Registration registration;
private JButton jButtonAgree = new JButton("Agree");
public OutsideClass() {
jButtonAgree.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// make sure registration reference has been obtained first!
if (registration != null) {
registration.swapView(Registration.USER_AGREEMENT);
}
}
});
}
// here I allow the calling class to pass a reference to the visualized
// Registration instance.
public void setRegistration(Registration registration) {
this.registration = registration;
}
}
For example:
#SuppressWarnings("serial")
class ButtonPanel extends JPanel {
private Registration registration;
public ButtonPanel() {
setLayout(new GridLayout(1, 0, 10, 0));
// go through String array making buttons
for (final String keyText : Registration.KEY_TEXTS) {
JButton btn = new JButton(keyText);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (registration != null) {
registration.swapView(keyText);
}
}
});
add(btn);
}
}
public void setRegistration(Registration registration) {
this.registration = registration;
}
}
and the MainClass that drives this all
class MainClass extends JPanel {
public MainClass() {
Registration registration = new Registration();
ButtonPanel buttonPanel = new ButtonPanel();
buttonPanel.setRegistration(registration);
buttonPanel.setBorder(BorderFactory.createTitledBorder("Button Panel"));
registration.setBorder(BorderFactory.createTitledBorder("Registration Panel"));
setLayout(new BorderLayout());
add(registration, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Registration");
frame.getContentPane().add(new MainClass());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}

Categories