Please have a look at the following code
WizardPanel.java
package wizardGUI;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WizardPanel extends JDialog
{
private JPanel cardPanel, buttonPanel;
private JButton next,previous;
private CardLayout c1;
private FileSelector fileSelector;
private DelemeterSelector delemeterSelector;
private int count = 1;
public WizardPanel()
{
//Intializing instance variables
fileSelector = FileSelector.getInstance();
delemeterSelector = DelemeterSelector.getInstance();
cardPanel = new JPanel();
c1 = new CardLayout();
cardPanel.setLayout(c1);
cardPanel.add(fileSelector,"1");
cardPanel.add(delemeterSelector,"2");
c1.show(cardPanel, "1");;
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
next = new JButton("Next");
next.addActionListener(new NextButtonAction());
previous = new JButton("Previous");
buttonPanel.add(next);
buttonPanel.add(previous);
//Creating the GUI
this.setLayout(new BorderLayout());
this.add(cardPanel,"Center");
this.add(buttonPanel,"South");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setResizable(true);
this.pack();
this.setVisible(true);
}
private class NextButtonAction implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
c1.show(cardPanel, "2");
}
}
}
FileSelector.java
package wizardGUI;
/*This is the first panel is wazard GUI. Using this window user can select the correct file
which contains the data required to create the table
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FileSelector extends JPanel
{
private JLabel fileName, description;
private JTextField fileTxt;
private JButton browse;
private GridBagLayout gbl;
private GridBagConstraints gbc;
private static FileSelector instance = null;
private FileSelector()
{
//Intializing instance variables
fileName = new JLabel("File Name: ");
description = new JLabel("Specify the source of the data");
fileTxt = new JTextField(10);
browse = new JButton("Browse");
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
//Creating GUI
this.setLayout(gbl);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.fill = GridBagConstraints.BOTH;
this.add(description,gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(0,10,0,0);
this.add(locationPanel(),gbc);
this.setBorder(BorderFactory.createEmptyBorder());
}
private JPanel locationPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(fileName);
panel.add(fileTxt);
panel.add(browse);
return panel;
}
public static FileSelector getInstance()
{
if(instance==null)
{
instance = new FileSelector();
}
return instance;
}
}
DelemeterSelector.java
/*This is the second windows in wizard
This class is designed to let the user to select the delemeter to break information */
package wizardGUI;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class DelemeterSelector extends JPanel
{
private JLabel description;
private JRadioButton tabBtn, semicolanBtn, commaBtn, spaceBtn;
private JTextArea txtArea;
private JScrollPane scroll;
private ButtonGroup btnGroup;
private GridBagLayout gbl;
private GridBagConstraints gbc;
private static DelemeterSelector instance = null;
private DelemeterSelector()
{
//Initializing instance variables
description = new JLabel("What delemeter separates your fields? Select the appropreiate delemeter");
tabBtn = new JRadioButton("Tab");
semicolanBtn = new JRadioButton("Semicolan");
commaBtn = new JRadioButton("Comma");
spaceBtn = new JRadioButton("Space");
btnGroup = new ButtonGroup();
btnGroup.add(tabBtn);
btnGroup.add(semicolanBtn);
btnGroup.add(commaBtn);
btnGroup.add(spaceBtn);
txtArea = new JTextArea(20,70);
scroll = new JScrollPane(txtArea);
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
this.setLayout(gbl);
//Creating the GUI
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(20,0,0,0);
this.add(description,gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(20,0,0,0);
this.add(radioPanel(),gbc);
gbc.gridx = 1;
gbc.gridy = 3;
gbc.insets = new Insets(10,0,0,0);
gbc.fill = GridBagConstraints.BOTH;
this.add(scroll,gbc);
}
private JPanel radioPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(tabBtn);
panel.add(semicolanBtn);
panel.add(commaBtn);
panel.add(spaceBtn);
panel.setBorder(BorderFactory.createTitledBorder("Choose the Delimeter that seperates your fields"));
return panel;
}
public static DelemeterSelector getInstance()
{
if(instance == null)
{
instance = new DelemeterSelector();
}
return instance;
}
}
Main.java
package wizardGUI
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame
{
public Main()
{
new WizardPanel().setVisible(true);
}
public static void main(String[]args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new Main();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
In here, we have only two buttons "Next" and "Previous" and they are commong for all the JPanels because it appears in "South" of 'WizardPanel' while other JPanels are in center.
Now, lets take "FileSelector". Guess I selected a file using the browse button.
Now how can I send this information to the next panel? which means to "DelemeterSelector" ?. I have only 2 'COMMON' buttons "Next" and "previous" which are located in ANOTHER CLASS.
I don't think writing business logic (getting selected file from 'FileSelector' and sending it to 'DelemeterSelector') inside that "Next" or "Previous" button's actionListener is a good idea. Because, I have to access another class, get it data and send it to the next JPanel (next class). There will be more JPanels, so this will be really hard and failing for sure.
I thought of adding "Next" and "Previous" buttons to each and every JPanel rather than the common ones. But then the problem is moving from one panel to another, because the reference to CardLayout is missing.
Please help me to find a correct and efficient way pass data from one class to another class, in this wizard. Thanks.
PS:
I don't want to do condition checking in "Next" buttons action class and let it hold all the actions. For an example, see the following EXAMPLE CODE snippet
//NON TESTED, NON COMPILED EXAMPLE CODE.
private class NextButtonAction implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if(fileSelector.isVisible(true))
{
//Access FileSelector
// Get the Data
// send data into delemeter class
}
else if(delemeterSelector.isVisible(true))
{
//Access delemeterSelector
// Get the Data
// send data into other class
}
else if(SOME_OTHER_CLASS.isVisible(true))
{
//Access delemeterSelector
// Get the Data
// send data into other class
}
}
}
Lunch break is over, so all I have time for is to post sample code, but I'll try to come back to explain it before the end of the day:
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;
public class MainGui {
public MainGui() {
new WizardPanel().setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new MainGui();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class WizardPanel extends JDialog {
private JPanel cardPanel, buttonPanel;
private JButton next, previous;
private CardLayout c1;
private SimpleModel simpleModel = new SimpleModel();
private FileSelector fileSelector;
private DelemeterSelector delemeterSelector;
private int count = 1;
public WizardPanel() {
fileSelector = FileSelector.getInstance();
delemeterSelector = DelemeterSelector.getInstance();
fileSelector.setModel(simpleModel); //!!
delemeterSelector.setModel(simpleModel); //!!
cardPanel = new JPanel();
c1 = new CardLayout();
cardPanel.setLayout(c1);
cardPanel.add(fileSelector, "1");
cardPanel.add(delemeterSelector, "2");
c1.show(cardPanel, "1");
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
next = new JButton("Next");
next.addActionListener(new NextButtonAction());
previous = new JButton("Previous");
buttonPanel.add(next);
buttonPanel.add(previous);
// Creating the GUI
this.setLayout(new BorderLayout());
this.add(cardPanel, "Center");
this.add(buttonPanel, "South");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setResizable(true);
this.pack();
this.setVisible(true);
}
private class NextButtonAction implements ActionListener {
public void actionPerformed(ActionEvent ae) {
// c1.show(cardPanel, "2");
c1.next(cardPanel); //!!
}
}
}
class FileSelector extends JPanel {
private JLabel fileName, description;
private JTextField fileTxt;
private JButton browse;
private GridBagLayout gbl;
private GridBagConstraints gbc;
private SimpleModel simpleModel;
private static FileSelector instance = null;
private FileSelector() {
// Intializing instance variables
fileName = new JLabel("File Name: ");
description = new JLabel("Specify the source of the data");
fileTxt = new JTextField(10);
browse = new JButton("Browse");
browse.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (simpleModel != null) {
simpleModel.setFileText(fileTxt.getText());
}
}
});
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
// Creating GUI
this.setLayout(gbl);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.fill = GridBagConstraints.BOTH;
this.add(description, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(0, 10, 0, 0);
this.add(locationPanel(), gbc);
this.setBorder(BorderFactory.createEmptyBorder());
}
public void setModel(SimpleModel simpleModel) {
this.simpleModel = simpleModel;
}
private JPanel locationPanel() {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(fileName);
panel.add(fileTxt);
panel.add(browse);
return panel;
}
public static FileSelector getInstance() {
if (instance == null) {
instance = new FileSelector();
}
return instance;
}
}
class DelemeterSelector extends JPanel {
private JLabel description;
private JRadioButton tabBtn, semicolanBtn, commaBtn, spaceBtn;
private JTextArea txtArea;
private JScrollPane scroll;
private ButtonGroup btnGroup;
private GridBagLayout gbl;
private GridBagConstraints gbc;
private SimpleModel simpleModel;
private static DelemeterSelector instance = null;
private DelemeterSelector() {
description = new JLabel(
"What delemeter separates your fields? Select the appropreiate delemeter");
tabBtn = new JRadioButton("Tab");
semicolanBtn = new JRadioButton("Semicolan");
commaBtn = new JRadioButton("Comma");
spaceBtn = new JRadioButton("Space");
btnGroup = new ButtonGroup();
btnGroup.add(tabBtn);
btnGroup.add(semicolanBtn);
btnGroup.add(commaBtn);
btnGroup.add(spaceBtn);
txtArea = new JTextArea(20, 70);
scroll = new JScrollPane(txtArea);
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
this.setLayout(gbl);
// Creating the GUI
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(20, 0, 0, 0);
this.add(description, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(20, 0, 0, 0);
this.add(radioPanel(), gbc);
gbc.gridx = 1;
gbc.gridy = 3;
gbc.insets = new Insets(10, 0, 0, 0);
gbc.fill = GridBagConstraints.BOTH;
this.add(scroll, gbc);
}
private JPanel radioPanel() {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(tabBtn);
panel.add(semicolanBtn);
panel.add(commaBtn);
panel.add(spaceBtn);
panel.setBorder(BorderFactory
.createTitledBorder("Choose the Delimeter that seperates your fields"));
return panel;
}
//!!
public void setModel(final SimpleModel simpleModel) {
this.simpleModel = simpleModel;
simpleModel.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (SimpleModel.FILE_TEXT.equals(evt.getPropertyName())) {
txtArea.append("File Text: " + simpleModel.getFileText() + "\n");
}
}
});
}
public static DelemeterSelector getInstance() {
if (instance == null) {
instance = new DelemeterSelector();
}
return instance;
}
}
class SimpleModel {
public static final String FILE_TEXT = "file text";
private SwingPropertyChangeSupport pcSupport =
new SwingPropertyChangeSupport(this);
private String fileText;
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcSupport.removePropertyChangeListener(listener);
}
public void setFileText(String fileText) {
String oldValue = this.fileText;
String newValue = fileText;
this.fileText = fileText;
pcSupport.firePropertyChange(FILE_TEXT, oldValue , newValue);
}
public String getFileText() {
return fileText;
}
}
Edit explanation of code:
This is a gross simplification of the Model-View-Controller or MVC design pattern since it is nothing more than model and view. The model holds the data and logic that the GUI works with and is essentially the "brains" of the program while the GUI is little more than a dumb display of the information.
The model here is quite simple and only holds one String field called fileText. It has setters and getters for this field, and the most interesting thing about it is the setter is wired so that it will notify any listeners that want to know if this field is ever changed. This process of using PropertyChangeSupport and allowing for PropertyChangeListeners means the the fileText field is a "bound" property.
Both of your JPanels have fields to hold a reference to the same SimpleModel object, and this model is set via a setter method, setModel(...).
fileSelector.setModel(simpleModel); // !!
delemeterSelector.setModel(simpleModel); // !!
I let the FileSelector object set the fileText field if its JButton is pressed:
browse.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (simpleModel != null) {
simpleModel.setFileText(fileTxt.getText());
}
}
});
I have the DelemeterSelector class add a PropertyChangeListener to the model so that it is notified whenever the fileText field's value is changed, and can respond to it as it sees fit:
public void setModel(final SimpleModel simpleModel) {
this.simpleModel = simpleModel;
simpleModel.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (SimpleModel.FILE_TEXT.equals(evt.getPropertyName())) {
txtArea.append("File Text: " + simpleModel.getFileText() + "\n");
}
}
});
}
Note that the model class has no idea what the GUI does with the information it holds, and that's a good thing as it means that "coupling" is fairly loose.
Related
Can someone help with this one? it's a system where you log in and another frame pops up. In that frame you can put 2 words and the frame will tell if the works are the same or not. But the button does not work for some reason. I've been doing this for 4 days and I really need some help.
Code
public class Userinter implements ActionListener {
//first frame
private static JLabel userLabel;
private static JTextField userText;
private static JLabel passwordLabel;
private static JPasswordField passwordText;
private static JButton button;
private static JLabel success;
//second frame
private static JLabel label1;
private static JLabel label2;
private static JTextField WordNum1;
private static JTextField WordNum2;
private static JButton button2;
private static JLabel success2;
public static void main(String[] args) {
//frame
JPanel panel = new JPanel();
JFrame frame = new JFrame();
frame.setSize(500,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
panel.setLayout(null);
//username
userLabel = new JLabel("Username");
userLabel.setBounds(80,80,80,25);
panel.add(userLabel);
userText = new JTextField(20);
userText.setBounds(180,80,165,25);
panel.add(userText);
//password
passwordLabel = new JLabel("password");
passwordLabel.setBounds(80,150,80,25);
panel.add(passwordLabel);
passwordText = new JPasswordField();
passwordText.setBounds(180,150,165,25);
panel.add(passwordText);
//button
button = new JButton("Login");
button.setBounds(80,190,80,25);
button.addActionListener((ActionListener) new Userinter());
panel.add(button);
success = new JLabel("set");
success.setBounds(80,250,300,25);
panel.add(success);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
String user = userText.getText();
String password = passwordText.getText();
if (user.equals("Gal") && password.equals("Skr")){
// second frame
JPanel Panel2 = new JPanel();
JFrame frame2 = new JFrame();
frame2.setSize(400,300);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setVisible(true);
frame2.add(Panel2);
Panel2.setLayout(null);
label1 = new JLabel("Set word/number here:");
label1.setBounds(10,20,200,25);
Panel2.add(label1);
WordNum1 = new JTextField();
WordNum1.setBounds(100,50,165,25);
Panel2.add(WordNum1);
label2 = new JLabel("Set word/number here:");
label2.setBounds(10,90,200,25);
Panel2.add(label2);
WordNum2 = new JTextField();
WordNum2.setBounds(100,130,165,25);
Panel2.add(WordNum2);
JButton Button2 = new JButton("Check");
Button2.setBounds(100,200,80,25);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e1) {
String word = WordNum1.getText();
String word2 = WordNum2.getText();
if(word.equals(word2)){
success2.setText("yes");
}
}
});
Panel2.add(Button2);
success = new JLabel("set");
success.setBounds(80,250,300,25);
Panel2.add(success);
}else
success.setText("incorrect username or/and password.");
}
}
You really need to take a look at Laying Out Components Within a Container, it is going to save you a lot of time and head aches.
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.EventListener;
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.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MainPane extends JPanel {
private LoginPane loginPane;
private WordPane wordPane;
private CardLayout cardLayout;
public MainPane() {
cardLayout = new CardLayout();
setLayout(cardLayout);
loginPane = new LoginPane();
loginPane.addLoginListener(new LoginPane.LoginListener() {
#Override
public void didLoginSuccessfully() {
cardLayout.show(MainPane.this, "words");
}
#Override
public void didCancelLogin() {
SwingUtilities.windowForComponent(MainPane.this).dispose();
}
});
wordPane = new WordPane();
add(loginPane, "login");
add(wordPane, "words");
}
}
public class WordPane extends JPanel {
public WordPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = gbc.REMAINDER;
gbc.insets = new Insets(8, 8, 8, 8);
add(new JLabel("Set word/number here:"), gbc);
gbc.gridy++;
gbc.gridwidth = 1;
gbc.anchor = GridBagConstraints.LINE_END;
add(new JLabel("First word:"), gbc);
gbc.gridy++;
add(new JLabel("Second word:"), gbc);
gbc.gridx++;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.LINE_START;
JTextField firstWordField = new JTextField(10);
JTextField secondWordField = new JTextField(10);
add(firstWordField, gbc);
gbc.gridy++;
add(secondWordField, gbc);
JButton checkButton = new JButton("Check");
gbc.gridy++;
gbc.gridx = 0;
gbc.gridwidth = gbc.REMAINDER;
gbc.anchor = GridBagConstraints.CENTER;
add(checkButton, gbc);
checkButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (firstWordField.getText().equals(secondWordField.getText())) {
JOptionPane.showMessageDialog(WordPane.this, "Words match", "Match", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(WordPane.this, "Words do not match", "Does Not Match", JOptionPane.ERROR_MESSAGE);
}
}
});
}
}
public class LoginPane extends JPanel {
public interface LoginListener extends EventListener {
// Probably should pass in the User which was authenticiated,
// but I'll leave that to you to figure out
public void didLoginSuccessfully();
public void didCancelLogin();
}
private JTextField userNameField;
private JPasswordField passwordField;
private JButton loginButton;
private JButton cancelButton;
public LoginPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_END;
gbc.insets = new Insets(8, 8, 8, 8);
add(new JLabel("User name:"), gbc);
gbc.gridy++;
add(new JLabel("Password:"), gbc);
userNameField = new JTextField(10);
passwordField = new JPasswordField(10);
DocumentListener documentListener = new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
fieldsDidChange();
}
#Override
public void removeUpdate(DocumentEvent e) {
fieldsDidChange();
}
#Override
public void changedUpdate(DocumentEvent e) {
fieldsDidChange();
}
};
userNameField.getDocument().addDocumentListener(documentListener);
passwordField.getDocument().addDocumentListener(documentListener);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_START;
add(userNameField, gbc);
gbc.gridy++;
add(passwordField, gbc);
loginButton = new JButton("Login");
loginButton.setEnabled(false);
loginButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
performLogin();
}
});
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
performCancel();
}
});
JPanel buttonPane = new JPanel(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = gbc.HORIZONTAL;
buttonPane.add(loginButton, gbc);
gbc.gridx++;
buttonPane.add(cancelButton, gbc);
gbc = new GridBagConstraints();
gbc.gridy = 2;
gbc.gridx = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(buttonPane, gbc);
}
public void addLoginListener(LoginListener listener) {
listenerList.add(LoginListener.class, listener);
}
public void removeLoginListener(LoginListener listener) {
listenerList.remove(LoginListener.class, listener);
}
protected void fireDidLoginSuccessfully() {
LoginListener[] listeners = listenerList.getListeners(LoginListener.class);
System.out.println(listeners.length);
if (listeners.length == 0) {
return;
}
for (LoginListener listener : listeners) {
listener.didLoginSuccessfully();
}
}
protected void fireDidCancel() {
LoginListener[] listeners = listenerList.getListeners(LoginListener.class);
if (listeners.length == 0) {
return;
}
for (LoginListener listener : listeners) {
listener.didCancelLogin();
}
}
protected void fieldsDidChange() {
if (userNameField.getText().length() > 0 && passwordField.getPassword().length > 0) {
loginButton.setEnabled(true);
} else {
loginButton.setEnabled(false);
}
}
protected void performLogin() {
// Peform the authentication
// In a production system, it would be fesible to have this
// done via a different class passed into this class
fireDidLoginSuccessfully();
}
protected void performCancel() {
fireDidCancel();
}
}
}
As to you "question"
This...
button.addActionListener((ActionListener) new Userinter());
is going to generate a disconnection between what is displayed on the UI and what you code is going to executing against, as you have two instance of Userinter
I am currently working on GUI of simple food ordering system. I created a button that whenever user clicks it it will go to another frame, however I am facing problem when I want to close the first frame (setVisible(false)).
This is my first frame
public class MainFrame extends JFrame {
private Manager manager = new Manager();
private JPanel titlepane;
private JLabel title;
MainFrame(String name){
setTitle(name);
}
public void content() {
Font titlefont = new Font("Times New Roman", Font.PLAIN, 22);
setLayout(new BorderLayout());
titlepane = new JPanel();
title = new JLabel("Welcome to POS!");
title.setFont(titlefont);
titlepane.add(title);
manager.LoginGUI();
add(titlepane,BorderLayout.NORTH);
add(manager,BorderLayout.CENTER);
}
public void runGUI() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
content();
setSize(700,700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
}
});
}
This is another class where the button is
public class Manager extends JPanel implements ActionListener {
private ArrayList<AccountInfo> manager = new ArrayList<AccountInfo>();
private GridBagConstraints gbc = new GridBagConstraints();
private JLabel id;
private JLabel pw;
private JTextField idfill;
private JTextField pwfill;
private JButton login;
private int isManager = 0;
private String idinput, pwinput;
private int temp = -1;
Manager() {
this.manager.add(new AccountInfo("admin", "1234"));
}
public void addManager(AccountInfo newManager) {
this.manager.add(newManager);
}
public void LoginGUI() {
Font standard = new Font("Times New Roman", Font.PLAIN, 18);
setLayout(new GridBagLayout());
id = new JLabel("ID");
id.setFont(standard);
// Alignment
gbc.gridx = 0;
gbc.gridy = 0;
gbc.ipadx = 10;
gbc.ipady = 10;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(id, gbc);
idfill = new JTextField(10);
idfill.setFont(standard);
// Alignment
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(idfill, gbc);
pw = new JLabel("Password");
pw.setFont(standard);
// Alignment
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(pw, gbc);
pwfill = new JTextField(10);
pwfill.setFont(standard);
// Alignment
gbc.gridx = 1;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(pwfill, gbc);
login = new JButton("Login");
login.setFont(standard);
login.addActionListener(this);
// Alignment
gbc.gridx = 1;
gbc.gridy = 2;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(login, gbc);
}
public void actionPerformed(ActionEvent e) {
verify();
if(isManager == 1) {
MenuFrame menu = new MenuFrame("Menu");
menu.runGUI();
MainFrame.setVisible(false); // This is the problem
}
}
private void verify() {
idinput = idfill.getText().trim();
pwinput = pwfill.getText();
for (int i = 0; i < manager.size(); i++) {
if (idinput.equals(manager.get(i).id)) {
temp = i;
}
}
if(temp == -1) {
JOptionPane.showMessageDialog(null, "Id or password incorrect, try again");
} else if(pwinput.equals(manager.get(temp).password)) {
isManager = 1;
} else
JOptionPane.showMessageDialog(null, "Id or password incorrect, try again");
}
}
(The codes are a bit lengthy as I am not confident that the other part was correct. All I know this has nothing to do with MenuFrame)
I get this error:
Cannot make a static reference to the non-static method setVisible(boolean) from the type Window
It might be my fault where it is not obvious enough for me to know which part of Manager or MainFrame is static. I also came across other posts regarding the same issue but none relates with mine. (Other post was having obvious static method)
Also tried the create an MainFrame object in Manager but it made it worse, please help, thank you!
You indeed need to keep the MainFrame object somewhere accessible, keep a reference to it. For this MVC, Model-View-Controller, is a nice paradigm.
Use MVC
I personally have my main method for swing in a Controller class (so the controller is the application class). It creates the main frame (View) and the controller is passed.
public void actionPerformed(ActionEvent e) {
verify();
if(isManager == 1) {
MenuFrame menu = new MenuFrame("Menu");
menu.runGUI();
controller.setMainFrameVisible(false);
}
}
Controller:
private MainFrame mainFrame;
public setMainFrameVisible(boolean visible) {
MainFrame.setVisible(visible);
}
Pass the MainFrame instance.
However you may also pass the MainFrame:
private final MainFrame mainFrame;
Manager(MainFrame mainFrame) {
this.mainFrame = mainFrame;
}
public void actionPerformed(ActionEvent e) {
verify();
if(isManager == 1) {
MenuFrame menu = new MenuFrame("Menu");
menu.runGUI();
mainFrame.setVisible(false);
}
}
If the panel is inside the MainFrame
((JFrame) getTopLevelAncestor()).setVisible(false);
Tip:
Should the application exit (EXIT_ON_CLOSE), change the default close operation.
MainFrame(String name){
setTitle(name);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
I need to make the JTextField in my ChatPanel class respond to JButton clicks in my Toolbar class. Is there any way to do this that will scale well if my program gets large? I tried doing this with an Action object, but i'm not sure what I need to do with the object. Here is my code:
public class Toolbar extends JPanel {
private JButton helloButton;
public Toolbar() {
setLayout(new FlowLayout());
helloButton = new JButton(new HelloAction("Hello", null));
add(helloButton);
}
class HelloAction extends AbstractAction {
public HelloAction(String text, ImageIcon icon) {
super(text, icon);
}
#Override
public void actionPerformed(ActionEvent e) {
//want to print "hello\n" in the JTextArea in ChatPanel
}
}
}
public class ChatPanel extends JPanel {
private JLabel nameLabel;
private JTextField chatField;
private JTextArea chatArea;
private GridBagConstraints gc;
private static final String NEWLINE = "\n";
public ChatPanel() {
super(new GridBagLayout());
//chatArea
chatArea = new JTextArea(8, 30);
chatArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(chatArea);
gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
add(scrollPane, gc);
//nameLabel
nameLabel = new JLabel("Name: ");
gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 2;
gc.anchor = GridBagConstraints.LINE_START;
gc.weightx = 0.0;
add(nameLabel, gc);
//chatField
chatField = new JTextField(25);
chatField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String message = chatField.getText() + NEWLINE;
chatArea.append(message);
chatField.setText("");
}
});
gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 2;
gc.anchor = GridBagConstraints.LINE_END;
gc.weightx = 0.0;
add(chatField, gc);
}
}
public class MainFrame {
private static int width = 800;
private static int height = (int) (width * (9.0 / 16));
private JFrame mainFrame = new JFrame("Main Frame");
public MainFrame() {
mainFrame.setPreferredSize(new Dimension(width, height));
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLayout(new GridBagLayout());
mainFrame.pack();
mainFrame.setResizable(false);
//Toolbar
Toolbar toolbar = new Toolbar();
GridBagConstraints gcToolbar = new GridBagConstraints();
gcToolbar.gridx = 0;
gcToolbar.gridy = 0;
mainFrame.add(toolbar);
//ChatPanel
ChatPanel chatPanel = new ChatPanel();
GridBagConstraints gcChatPanel = new GridBagConstraints();
gcChatPanel.gridx = 0;
gcChatPanel.gridy = 2;
gcChatPanel.gridwidth = 2;
gcChatPanel.weighty = 1.0;
gcChatPanel.weightx = 1.0;
gcChatPanel.anchor = GridBagConstraints.LAST_LINE_START;
mainFrame.add(chatPanel, gcChatPanel);
mainFrame.setVisible(true);
}
}
Also, any feedback on what I can improve / what i'm doing wrong is appreciated.
Your problem is actually a little larger, but with some clever ideas, ease to overcome...
Essentially, you need some way to communicate with the ChatPanel from the Toolbar. There are a number of ways you might achieve this, but if you want flexibility then you should to breaking the requirements down and focusing on the functionality of each section...
The tool bar holds "actions"
Some of these "actions" add text to something
From here, we need something that can bridge the actions and what ever wants to be updated.
Lets start with a simple contract
public interface Outlet {
public void say(String text);
}
All this says is, a implementation of this interface can accept some text.
Next, we need some way to set the text when an action occurs, assuming you're going to want several different actions, something like...
public class OutletAction extends AbstractAction {
private Outlet outlet;
private String text;
public OutletAction(Outlet outlet, String text) {
this.outlet = outlet;
this.text = text;
}
public Outlet getOutlet() {
return outlet;
}
public String getText() {
return text;
}
#Override
public void actionPerformed(ActionEvent e) {
getOutlet().say(getText());
}
}
Will make life easier. Basically, this allows you to specify the Outlet to which the text should be sent and the text to be sent
Now, to make life easier you could set a series of common "word" actions, for example...
public class HelloAction extends OutletAction {
public HelloAction(Outlet outlet) {
super(outlet, "Hello");
putValue(Action.NAME, "Hello");
//putValue(Action.SMALL_ICON, icon);
}
}
Now, you need someway to apply these actions to the Toolbar...
public class Toolbar extends JPanel {
public void addAction(Action action) {
add(new JButton(action));
}
}
Simply adding a addAction method which takes care of creating the JButton and apply the action to it seems like a simple solution.
Finally, we need to update the ChatPanel to implement the Outlet interface
public class ChatPanel extends JPanel implements Outlet {
//...
#Override
public void say(String text) {
chatArea.append(text + NEWLINE);
}
}
Now, you just need to bind them all together...
ChatPanel chatPane = new ChatPanel();
HelloAction action = new HelloAction(chatPane);
Toolbar toolBar = new Toolbar();
toolBar.addAction(action);
//... Add what ever other actions you might like...
This demonstrates a principle commonly known as "code to interface (not implementation)", it decouples the code a way that allows you to change the underlying implementation without it effecting the rest of the code. It also guards you code against unwanted interaction, as the actions can only call the say method of the Outlet interface ;)
And finally, a runnable example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
ChatPanel chatPane = new ChatPanel();
HelloAction action = new HelloAction(chatPane);
Toolbar toolBar = new Toolbar();
toolBar.addAction(action);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(toolBar, BorderLayout.NORTH);
frame.add(chatPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Toolbar extends JPanel {
public void addAction(Action action) {
add(new JButton(action));
}
}
public class OutletAction extends AbstractAction {
private Outlet outlet;
private String text;
public OutletAction(Outlet outlet, String text) {
this.outlet = outlet;
this.text = text;
}
public Outlet getOutlet() {
return outlet;
}
public String getText() {
return text;
}
#Override
public void actionPerformed(ActionEvent e) {
getOutlet().say(getText());
}
}
public class HelloAction extends OutletAction {
public HelloAction(Outlet outlet) {
super(outlet, "Hello");
putValue(Action.NAME, "Hello");
//putValue(Action.SMALL_ICON, icon);
}
}
public interface Outlet {
public void say(String text);
}
public class ChatPanel extends JPanel implements Outlet {
private JLabel nameLabel;
private JTextField chatField;
private JTextArea chatArea;
private GridBagConstraints gc;
private static final String NEWLINE = "\n";
public ChatPanel() {
super(new GridBagLayout());
//chatArea
chatArea = new JTextArea(8, 30);
chatArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(chatArea);
gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
add(scrollPane, gc);
//nameLabel
nameLabel = new JLabel("Name: ");
gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 2;
gc.anchor = GridBagConstraints.LINE_START;
gc.weightx = 0.0;
add(nameLabel, gc);
//chatField
chatField = new JTextField(25);
chatField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String message = chatField.getText() + NEWLINE;
chatArea.append(message);
chatField.setText("");
}
});
gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 2;
gc.anchor = GridBagConstraints.LINE_END;
gc.weightx = 0.0;
add(chatField, gc);
}
#Override
public void say(String text) {
chatArea.append(text + NEWLINE);
}
}
}
In my FlashCardPanel class, I have a subpanel,LabelPanel, with a Grid Bag Layout. It consists of a constructor with an edit button, a button to "flip" the card, and the label to display the term/definition. My problem is that every time I click my "Flip" Button to display the definition of my term, the flip button will change size, usually matching the length of the definition.
Images of the problem
http://postimg.org/gallery/ymww3axq/
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
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 javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class FlashCardPanel extends JPanel{
private String term;
private String definition;
// shows the current text whether it is a term or definition
private JLabel currentLabel;
private static String NO_CARDS = "This set is empty";
//current card being displayed
private FlashCard currentCard;
//new card that is added to the deck
private FlashCard newCard;
// true = term is showing; false = definition is showing
private boolean termShowing = true;
private AddNewCard frame;
private CardSet cardSet;
private int cardIndex = 0;
private ButtonPanel bPanel;
private LabelPanel lPanel;
private static JButton flipButton;
private static JButton nextButton;
private static JButton prevButton;
private static JButton addCard;
private static JButton deleteCard;
private static JButton editButton;
public FlashCardPanel(CardSet cardSet) {
this.cardSet = cardSet;
this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
term = cardSet.get(0).getTerm();
definition = cardSet.get(0).getDefintion();
currentCard = cardSet.get(0);
createButtons();
lPanel = new LabelPanel();
bPanel = new ButtonPanel();
add(lPanel);
add(bPanel);
}
public FlashCardPanel() {
this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
add(lPanel);
add(bPanel);
}
private class LabelPanel extends JPanel {
public LabelPanel() {
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(15,15,15,15);
currentLabel = new JLabel(term);
currentLabel.setText(cardSet.get(0).getTerm());
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0;
c.gridx = 0;
c.gridy = 0;
add(editButton,c);
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0;
c.gridwidth = 0;
c.weightx = 0;
c.gridx = 2;
c.gridy = 0;
add(flipButton,c);
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40;
c.weightx = 0;
c.gridwidth = 3;
c.gridx = 1;
c.gridy = 3;
add(currentLabel,c);
}
}
private class ButtonPanel extends JPanel {
public ButtonPanel() {
this.setLayout(new GridLayout(2,2));
add(prevButton);
add(nextButton);
add(addCard);
add(deleteCard);
}
}
/*
* creates buttons for the panel. Should be called before
* any subpanel is created.
*/
private void createButtons()
{
flipButton = new JButton(" Flip Card ");
flipButton.addActionListener(new ButtonListener());
flipButton.setActionCommand("1");
nextButton = new JButton(" Next Card ");
nextButton.addActionListener(new ButtonListener());
nextButton.setActionCommand("2");
prevButton = new JButton(" Previous Card ");
prevButton.addActionListener(new ButtonListener());
prevButton.setActionCommand("3");
addCard = new JButton(" Add Card ");
addCard.addActionListener(new ButtonListener());
addCard.setActionCommand("4");
deleteCard = new JButton(" Delete Card ");
deleteCard.addActionListener(new ButtonListener());
deleteCard.setActionCommand("5");
editButton = new JButton("Edit");
editButton.addActionListener(new ButtonListener());
editButton.setActionCommand("6");
}
private class ButtonListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e) {
int action = Integer.parseInt(e.getActionCommand());
switch(action){
case 1:
flipCard();
break;
case 2:
nextCard();
break;
case 3:
previousCard();
break;
case 4:
createFrame();
break;
case 5:
deleteCard();
case 6:
createFrame(term,definition);
}
}
}
private void flipCard()
{
if (!cardSet.isEmpty()) {
if (termShowing) {
termShowing = false;
currentLabel.setText(definition);
}
else {
termShowing = true;
currentLabel.setText(term);
}
}
else {
currentLabel.setText(NO_CARDS);
term = "";
definition = "";
JOptionPane.showMessageDialog(this, "This set is empty");
}
}
private void nextCard()
{
if (!cardSet.isEmpty()) {
if (cardIndex == cardSet.size()-1)
cardIndex = 0;
else
cardIndex++;
term = cardSet.get(cardIndex).getTerm();
definition = cardSet.get(cardIndex).getDefintion();
if(termShowing)
currentLabel.setText(term);
else
currentLabel.setText(definition);
currentCard = cardSet.get(cardIndex);
}
else JOptionPane.showMessageDialog(this, "This set is empty");
}
private void previousCard()
{
if (!cardSet.isEmpty()) {
if (cardIndex == 0)
cardIndex = cardSet.size()-1;
else
cardIndex--;
term = cardSet.get(cardIndex).getTerm();
definition = cardSet.get(cardIndex).getDefintion();
if(termShowing)
currentLabel.setText(term);
else
currentLabel.setText(definition);
currentCard = cardSet.get(cardIndex);
}
else JOptionPane.showMessageDialog(this, "This set is empty");
}
/*
* adding a card
*/
private void createFrame() {
frame = new AddNewCard(100,100,this);
}
/*
* editing an existing card
*/
private void createFrame(String t, String d)
{
frame = new AddNewCard(100,100,this,t,d);
}
public void addNewCard(String t, String d) {
newCard = new FlashCard(t,d);
cardSet.add(newCard);
if (cardSet.isEmpty()) currentLabel.setText(newCard.getTerm());
}
public void editCard(String t, String d) {
currentCard.setTerm(t);
currentCard.setDefinition(d);
if (termShowing) currentLabel.setText(t);
else currentLabel.setText(d);
}
/*
* Deletes current card on display
*/
private void deleteCard()
{
if (!cardSet.isEmpty()) {
// if on the last card of the set
if (cardIndex == cardSet.size()-1) cardIndex--;
cardSet.remove(currentCard);
if (!cardSet.isEmpty()) {
currentCard = cardSet.get(cardIndex);
currentLabel.setText(cardSet.get(cardIndex).getTerm());
}
else currentLabel.setText(NO_CARDS);
}
else JOptionPane.showMessageDialog(this, "This set is empty");
}
}
You have several options including:
using a nested JPanels each with its own layout. For instance the buttons could be placed into a GridLayout JPanel, and this placed into a BorderLayout JPanel with the label BorderLayout.CENTER
I suggest that the long definition text be displayed within a JTextArea, not a JLabel. If you make it non-editable and remove borders, it could look like a JLabel.
If you go this route, you will want to turn on word wrap on the JTextArea.
You could swap JTextArea with JLabel (for the term) using a CardLayout.
Note, for future questions, please pare down your problem. For instance, if this were my question, I'd create something like the code below, small, self contained, runnable and demonstrates the problem:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class FlashCardPanel2 extends JPanel {
private static final long serialVersionUID = 1L;
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
private JLabel currentLabel;
private String term = "Term";
private String definition = "Definition: This will be a very long String to "
+ "illustrate the problem that you are having, and to try to help you get "
+ "a solution";
private JButton editButton = new JButton("Edit");
private JButton flipButton = new JButton(new FlipAction("Flip"));
public FlashCardPanel2() {
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(15, 15, 15, 15);
currentLabel = new JLabel(term);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0;
c.gridx = 0;
c.gridy = 0;
add(editButton, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0;
c.gridwidth = 0;
c.weightx = 0;
c.gridx = 2;
c.gridy = 0;
add(flipButton, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40;
c.weightx = 0;
c.gridwidth = 3;
c.gridx = 1;
c.gridy = 3;
add(currentLabel, c);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class FlipAction extends AbstractAction {
public FlipAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
String text = currentLabel.getText();
text = (text.equals(term)) ? definition : term;
currentLabel.setText(text);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("FlashCardPanel2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new FlashCardPanel2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
And here's a potential solution with CardLayout and GridLayout and BorderLayout:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
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 javax.swing.*;
public class FlashCardPanel3 extends JPanel {
private static final long serialVersionUID = 1L;
private static final String CURRENT_LABEL = "current label";
private static final String DEFINITION = "definition";
private JLabel currentLabel;
private JTextArea currentDefinitionArea = new JTextArea(6, 20);
private CardLayout cardLayout = new CardLayout();
private JPanel cardHolder = new JPanel(cardLayout);
private String term = "Term";
private String definition = "Definition: This will be a very long String to "
+ "illustrate the problem that you are having, and to try to help you get "
+ "a solution";
private JButton editButton = new JButton("Edit");
private JButton flipButton = new JButton(new FlipAction("Flip"));
public FlashCardPanel3() {
currentDefinitionArea.setOpaque(false);
currentDefinitionArea.setText(definition);
currentDefinitionArea.setWrapStyleWord(true);
currentDefinitionArea.setLineWrap(true);
currentDefinitionArea.setEditable(false);
currentDefinitionArea.setFocusable(false);
currentLabel = new JLabel(term, SwingConstants.CENTER);
cardHolder.add(currentLabel, CURRENT_LABEL);
cardHolder.add(new JScrollPane(currentDefinitionArea), DEFINITION);
JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 5, 0));
buttonPanel.add(editButton);
buttonPanel.add(flipButton);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout(5, 5));
add(buttonPanel, BorderLayout.PAGE_START);
add(cardHolder);
}
private class FlipAction extends AbstractAction {
public FlipAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// String text = currentLabel.getText();
// text = (text.equals(term)) ? definition : term;
// currentLabel.setText(text);
cardLayout.next(cardHolder);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("FlashCardPanel2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new FlashCardPanel3());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
This question already has answers here:
Button for closing a JDialog
(5 answers)
Closed 9 years ago.
I've created Dialog using awt and swing. In this form I hafe JTextField and okButton which is JButton. How to make the Dialog window hide on clicking okButton?
Here is my class's code:
public class QueueDialog extends JFrame implements ActionListener {
private static final long SerialVersionUID = 1L;
private static JTextField field = new JTextField(15);
private Sender sender;
private String incommingMessagesFolderUrl = "/etc/dlp/templates";
public QueueDialog() throws Exception {
sender = new Sender();
// field.setSize(60, 15);
JButton okButton = new JButton("ok");
final JLabel label = new JLabel("Enter the name of queue:");
GridBagLayout gbag = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gbag);
gbc.insets = new Insets(2, 0, 2, 0);
gbc.gridy = 0;
gbc.gridx = 0;
gbag.setConstraints(label, gbc);
gbc.gridy = 1;
gbc.gridx = 0;
gbag.setConstraints(field, gbc);
gbc.gridy = 2;
gbc.gridx = 0;
gbag.setConstraints(okButton, gbc);
add(okButton);
add(field);
add(label);
setTitle("Queue name");
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
setVisible(true);
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("ok")) {
// label.setText(field.getText());
send(field.getText());
}
}
});
}
}
As I mentioned in my comment (i.e, the very first comment) setVisible(false) is working absolutely fine on click of Ok button
Please Check this code again Where I have addd the statement in action listener. Just now did it to prove the solution is correct> I was not following this post hoping you must have got your answer in the comment itself
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class QueueDialog extends JFrame implements ActionListener {
private static final long SerialVersionUID = 1L;
private static JTextField field = new JTextField(15);
//private Sender sender;
private String incommingMessagesFolderUrl = "/etc/dlp/templates";
public QueueDialog() throws Exception {
// sender = new Sender();
// field.setSize(60, 15);
JButton okButton = new JButton("ok");
final JLabel label = new JLabel("Enter the name of queue:");
GridBagLayout gbag = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gbag);
// gbc.insets = new Insets(2, 0, 2, 0);
gbc.gridy = 0;
gbc.gridx = 0;
gbag.setConstraints(label, gbc);
gbc.gridy = 1;
gbc.gridx = 0;
gbag.setConstraints(field, gbc);
gbc.gridy = 2;
gbc.gridx = 0;
gbag.setConstraints(okButton, gbc);
add(okButton);
add(field);
add(label);
setTitle("Queue name");
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
setVisible(true);
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("ok")) {
System.out.println("Hello");
setVisible(false);
// label.setText(field.getText());
// send(field.getText());
}
}
});
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
public static void main(String[] args) throws Exception {
QueueDialog diag = new QueueDialog();
}
}