I have a card layout, first card is a menu.
I Select the second card, and carry out some action. We'll say add a JTextField by clicking a button. If I return to the menu card, and then go back to the second card, that JTextField I added the first time will still be there.
I want the second card to be as I originally constructed it each time I access it, with the buttons, but without the Textfield.
Make sure the panel you're trying to reset has code that takes it back to its "as it was originally constructed" state. Then, when you process the whatever event that causes you to change cards, call that code to restore the original state before showing the card.
Here is the final sorted out version, to remove the card, after doing changes to it, have a look, use the revalidate() and repaint() thingy as usual :-)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ApplicationBase extends JFrame
{
private JPanel centerPanel;
private int topPanelCount = 0;
private String[] cardNames = {
"Login Window",
"TextField Creation"
};
private TextFieldCreation tfc;
private LoginWindow lw;
private JButton nextButton;
private JButton removeButton;
private ActionListener actionListener = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == nextButton)
{
CardLayout cardLayout = (CardLayout) centerPanel.getLayout();
cardLayout.next(centerPanel);
}
else if (ae.getSource() == removeButton)
{
centerPanel.remove(tfc);
centerPanel.revalidate();
centerPanel.repaint();
tfc = new TextFieldCreation();
tfc.createAndDisplayGUI();
centerPanel.add(tfc, cardNames[1]);
}
}
};
private void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
centerPanel = new JPanel();
centerPanel.setLayout(new CardLayout());
lw = new LoginWindow();
lw.createAndDisplayGUI();
centerPanel.add(lw, cardNames[0]);
tfc = new TextFieldCreation();
tfc.createAndDisplayGUI();
centerPanel.add(tfc, cardNames[1]);
JPanel bottomPanel = new JPanel();
removeButton = new JButton("REMOVE");
nextButton = new JButton("NEXT");
removeButton.addActionListener(actionListener);
nextButton.addActionListener(actionListener);
bottomPanel.add(removeButton);
bottomPanel.add(nextButton);
add(centerPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
pack();
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ApplicationBase().createAndDisplayGUI();
}
});
}
}
class TextFieldCreation extends JPanel
{
private JButton createButton;
private int count = 0;
public void createAndDisplayGUI()
{
final JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(0, 2));
createButton = new JButton("CREATE TEXTFIELD");
createButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JTextField tfield = new JTextField();
tfield.setActionCommand("JTextField" + count);
topPanel.add(tfield);
topPanel.revalidate();
topPanel.repaint();
}
});
setLayout(new BorderLayout(5, 5));
add(topPanel, BorderLayout.CENTER);
add(createButton, BorderLayout.PAGE_END);
}
}
class LoginWindow extends JPanel
{
private JPanel topPanel;
private JPanel middlePanel;
private JPanel bottomPanel;
public void createAndDisplayGUI()
{
topPanel = new JPanel();
JLabel userLabel = new JLabel("USERNAME : ", JLabel.CENTER);
JTextField userField = new JTextField(20);
topPanel.add(userLabel);
topPanel.add(userField);
middlePanel = new JPanel();
JLabel passLabel = new JLabel("PASSWORD : ", JLabel.CENTER);
JTextField passField = new JTextField(20);
middlePanel.add(passLabel);
middlePanel.add(passField);
bottomPanel = new JPanel();
JButton loginButton = new JButton("LGOIN");
bottomPanel.add(loginButton);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(topPanel);
add(middlePanel);
add(bottomPanel);
}
}
If you just wanted to remove the Latest Edit made to the card, try this code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ApplicationBase extends JFrame
{
private JPanel centerPanel;
private int topPanelCount = 0;
private String[] cardNames = {
"Login Window",
"TextField Creation"
};
private TextFieldCreation tfc;
private LoginWindow lw;
private JButton nextButton;
private JButton removeButton;
private ActionListener actionListener = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == nextButton)
{
CardLayout cardLayout = (CardLayout) centerPanel.getLayout();
cardLayout.next(centerPanel);
}
else if (ae.getSource() == removeButton)
{
TextFieldCreation.topPanel.remove(TextFieldCreation.tfield);
TextFieldCreation.topPanel.revalidate();
TextFieldCreation.topPanel.repaint();
}
}
};
private void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
centerPanel = new JPanel();
centerPanel.setLayout(new CardLayout());
lw = new LoginWindow();
lw.createAndDisplayGUI();
centerPanel.add(lw, cardNames[0]);
tfc = new TextFieldCreation();
tfc.createAndDisplayGUI();
centerPanel.add(tfc, cardNames[1]);
JPanel bottomPanel = new JPanel();
removeButton = new JButton("REMOVE");
nextButton = new JButton("NEXT");
removeButton.addActionListener(actionListener);
nextButton.addActionListener(actionListener);
bottomPanel.add(removeButton);
bottomPanel.add(nextButton);
add(centerPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
pack();
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ApplicationBase().createAndDisplayGUI();
}
});
}
}
class TextFieldCreation extends JPanel
{
private JButton createButton;
private int count = 0;
public static JTextField tfield;
public static JPanel topPanel;
public void createAndDisplayGUI()
{
topPanel = new JPanel();
topPanel.setLayout(new GridLayout(0, 2));
createButton = new JButton("CREATE TEXTFIELD");
createButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
tfield = new JTextField();
tfield.setActionCommand("JTextField" + count);
topPanel.add(tfield);
topPanel.revalidate();
topPanel.repaint();
}
});
setLayout(new BorderLayout(5, 5));
add(topPanel, BorderLayout.CENTER);
add(createButton, BorderLayout.PAGE_END);
}
}
class LoginWindow extends JPanel
{
private JPanel topPanel;
private JPanel middlePanel;
private JPanel bottomPanel;
public void createAndDisplayGUI()
{
topPanel = new JPanel();
JLabel userLabel = new JLabel("USERNAME : ", JLabel.CENTER);
JTextField userField = new JTextField(20);
topPanel.add(userLabel);
topPanel.add(userField);
middlePanel = new JPanel();
JLabel passLabel = new JLabel("PASSWORD : ", JLabel.CENTER);
JTextField passField = new JTextField(20);
middlePanel.add(passLabel);
middlePanel.add(passField);
bottomPanel = new JPanel();
JButton loginButton = new JButton("LGOIN");
bottomPanel.add(loginButton);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(topPanel);
add(middlePanel);
add(bottomPanel);
}
}
Related
This is my code:
class MyFrame extends JFrame {
public MyFrame() {
setTitle("Carrera de coets");
setBounds(15, 15, 310, 230);
setResizable(false);
MyPanel panel1 = new MyPanel();
MyPanel panel2 = new MyPanel();
Border loweredEtchedBorder = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
TitledBorder titledBorder1 = BorderFactory.createTitledBorder(loweredEtchedBorder, "32WESSDS");
TitledBorder titledBorder2 = BorderFactory.createTitledBorder(loweredEtchedBorder, "LDSFJA32");
panel1.setBorder(titledBorder1);
panel2.setBorder(titledBorder2);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.SOUTH);
}
}
class MyPanel extends JPanel {
public MyPanel() {
setLayout(new GridLayout(2, 1));
JPanel panel1, panel2;
panel1 = new JPanel();
panel2 = new JPanel();
JLabel label1, label2;
JTextField textField1, textField2;
JButton button1, button2;
label1 = new JLabel("Velocitat:");
label2 = new JLabel("Increment:");
textField1 = new JTextField(10);
textField2 = new JTextField(10);
button1 = new JButton("Modificar");
button2 = new JButton("Modificar");
MyListener listener1, listener2;
listener1 = new MyListener(this, textField1);
listener2 = new MyListener(this, textField2);
button1.addActionListener(listener1);
button2.addActionListener(listener2);
panel1.add(label1);
panel1.add(textField1);
panel1.add(button1);
panel2.add(label2);
panel2.add(textField2);
panel2.add(button2);
add(panel1);
add(panel2);
}
private class MyListener implements ActionListener {
private String identifier;
private JTextField textField;
public MyListener(JPanel panel, JTextField textField) {
identifier = ((TitledBorder) panel.getBorder()).getTitle();
this.textField = textField;
}
#Override
public void actionPerformed(ActionEvent event) {
Do something with identifier and textField.
}
}
}
And this is how it looks:
What I want to do is add functionality to these buttons, but this line: identifier = ((TitledBorder) panel.getBorder()).getTitle(); is returning a NullPointerException and I can't figure out why because those JPanel instances do have Borders with titles.
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "javax.swing.border.TitledBorder.getTitle()" because the return value of "javax.swing.JPanel.getBorder()" is null
Okay, as others already stated, you do not hand in the actual instance of your TitledBorder. This means, you don't have a border inside your panel. I refactored your code a little, now it works.
I commented the lines I worked on
class MyFrame extends JFrame {
public MyFrame() {
setTitle("Carrera de coets");
setBounds(15, 15, 310, 230);
setResizable(false);
// instantiate your Borders before you instantiate your Panels
Border loweredEtchedBorder = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
TitledBorder titledBorder1 = BorderFactory.createTitledBorder(loweredEtchedBorder, "32WESSDS");
TitledBorder titledBorder2 = BorderFactory.createTitledBorder(loweredEtchedBorder, "LDSFJA32");
// instantiate your Panels and hand in the borders
MyPanel panel1 = new MyPanel(titledBorder1);
MyPanel panel2 = new MyPanel(titledBorder1);
// WRONG HERE. REMOVE IT.
// panel1.setBorder(titledBorder1);
// panel2.setBorder(titledBorder2);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.SOUTH);
}
}
class MyPanel extends JPanel {
// take the border as argument for the constructor
public MyPanel(TitledBorder border) {
setLayout(new GridLayout(2, 1));
// SET THE BORDER
setBorder(border);
JPanel panel1, panel2;
panel1 = new JPanel();
panel2 = new JPanel();
JLabel label1, label2;
JTextField textField1, textField2;
JButton button1, button2;
label1 = new JLabel("Velocitat:");
label2 = new JLabel("Increment:");
textField1 = new JTextField(10);
textField2 = new JTextField(10);
button1 = new JButton("Modificar");
button2 = new JButton("Modificar");
MyListener listener1, listener2;
listener1 = new MyListener(this, textField1);
listener2 = new MyListener(this, textField2);
button1.addActionListener(listener1);
button2.addActionListener(listener2);
panel1.add(label1);
panel1.add(textField1);
panel1.add(button1);
panel2.add(label2);
panel2.add(textField2);
panel2.add(button2);
add(panel1);
add(panel2);
}
private class MyListener implements ActionListener {
private String identifier;
private JTextField textField;
public MyListener(JPanel panel, JTextField textField) {
identifier = ((TitledBorder) panel.getBorder()).getTitle();
this.textField = textField;
}
#Override
public void actionPerformed(ActionEvent event) {
System.out.println("And the winner is: " + identifier);
}
}
}
I fixed it by doing this:
class MyFrame extends JFrame {
public MyFrame() {
setTitle("Carrera de coets");
setBounds(15, 15, 310, 230);
setResizable(false);
MyPanel panel1 = new MyPanel();
MyPanel panel2 = new MyPanel();
Border loweredEtchedBorder = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
TitledBorder titledBorder1 = BorderFactory.createTitledBorder(loweredEtchedBorder, "32WESSDS");
TitledBorder titledBorder2 = BorderFactory.createTitledBorder(loweredEtchedBorder, "LDSFJA32");
panel1.setBorder(titledBorder1);
panel2.setBorder(titledBorder2);
panel1.listen(); // New
panel2.listen();
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.SOUTH);
}
}
class MyPanel extends JPanel {
private JTextField textField1, textField2;
private JButton button1, button2;
private MyListener listener1, listener2;
public MyPanel() {
setLayout(new GridLayout(2, 1));
JPanel panel1, panel2;
panel1 = new JPanel();
panel2 = new JPanel();
JLabel label1, label2;
label1 = new JLabel("Velocitat:");
label2 = new JLabel("Increment:");
textField1 = new JTextField(10);
textField2 = new JTextField(10);
button1 = new JButton("Modificar");
button2 = new JButton("Modificar");
panel1.add(label1);
panel1.add(textField1);
panel1.add(button1);
panel2.add(label2);
panel2.add(textField2);
panel2.add(button2);
add(panel1);
add(panel2);
}
// New
public void listen() {
listener1 = new MyListener(this, textField1);
listener2 = new MyListener(this, textField2);
button1.addActionListener(listener1);
button2.addActionListener(listener2);
}
private class MyListener implements ActionListener {
private String identifier;
private JTextField textField;
public MyListener(JPanel panel, JTextField textField) {
identifier = ((TitledBorder) panel.getBorder()).getTitle();
this.textField = textField;
}
#Override
public void actionPerformed(ActionEvent event) {
System.out.println(identifier + " " + textField.getText());
}
}
}
I have two-panel class, PannelloM and PannelloM2.
Initially, I add to the JFrame an instance of PannelloM2.
I would like that when I press, "new .." is loaded on the JFrame PannelloM instead of the PannelloM2. How can I achieve this
The problem is that I have the button listeners inside the panel class, so I cannot add the panel itself to the frame.
Thank you
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.rmi.*;
import java.util.*;
class ProvaMail{
public static void main(String[] args){
EmailMonitor em = new EmailMonitor();
em.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
em.setVisible(true);
}
}
class EmailMonitor extends JFrame{
private PannelloM pannelloM;
private PannelloM2 pannelloM2;
public EmailMonitor(){
ini();
pannelloM= new PannelloM();
pannelloM2= new PannelloM2();
add(pannelloM2);
}
private void ini(){
// prende la dimensione dello schermo
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
//centra il frame nello schermo
setSize(screenWidth / 4, screenHeight / 2);
setLocation(screenWidth / 4, screenHeight / 4);
//imposta il titolo e il dimensionamento non automatico
setTitle("Email Monitor");
setResizable(false);
}
}
class PannelloM2 extends JPanel implements ActionListener{
private JPanel panel1;
private JPanel panel4;
JButton nuovo;
JButton leggi;
JButton elimina;
public PannelloM2(){
iniP();
}
private void iniP(){
setLayout(new BorderLayout());
panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
JLabel label0 = new JLabel("Posta in arrivo:");
panel1.add(label0, BorderLayout.NORTH);
add(panel1, BorderLayout.NORTH);
panel4 = new JPanel();
panel4.setLayout(new BorderLayout());
nuovo = new JButton("Nuovo..");
leggi = new JButton("Leggi..");
elimina = new JButton("Elimina..");
panel4.add(nuovo,BorderLayout.NORTH);
panel4.add(leggi,BorderLayout.CENTER);
panel4.add(elimina,BorderLayout.SOUTH);
add(panel4, BorderLayout.SOUTH);
//registro i componenti al listener
nuovo.addActionListener(this);
leggi.addActionListener(this);
elimina.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if(command.equals("Nuovo..")) { }
else if(command.equals("Leggi..")) {
}
else if(command.equals("Elimina..")) {
}
}
}
class PannelloM extends JPanel {
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
private JPanel panel4;
private JPanel panel5;
JButton arrivo;
JButton rispondi;
JButton rispondiTutti;
JButton inoltra;
JButton after;
JTextArea text1;
JTextField text2;
JTextField text3;
public PannelloM(){
iniP();
}
private void iniP(){
setLayout(new BorderLayout());
panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
JLabel label0 = new JLabel("Destinatari:");
panel1.add(label0, BorderLayout.NORTH);
text2 = new JTextField("",10);
panel1.add(text2, BorderLayout.CENTER);
panel2 = new JPanel();
panel2.setLayout(new BorderLayout());
JLabel label1 = new JLabel("Oggetto:");
panel2.add(label1, BorderLayout.NORTH);
text3 = new JTextField("",20);
panel2.add(text3, BorderLayout.CENTER);
panel1.add(panel2, BorderLayout.SOUTH);
add(panel1, BorderLayout.NORTH);
//imposto terzo pannello
panel3 = new JPanel();
panel3.setLayout(new BorderLayout());
JLabel label3 = new JLabel("Testo:");
panel3.add(label3, BorderLayout.NORTH);
text1 = new JTextArea(5,20);
panel3.add(text1, BorderLayout.CENTER);
add(panel3, BorderLayout.CENTER);
//imposto quarto pannello
panel4 = new JPanel();
panel4.setLayout(new BorderLayout());
arrivo = new JButton("Posta in arrivo..");
rispondi = new JButton("Rispondi..");
rispondiTutti = new JButton("Rispondi a tutti..");
inoltra = new JButton("Inoltra..");
panel4.add(arrivo,BorderLayout.NORTH);
panel4.add(rispondi,BorderLayout.CENTER);
//imposto quinto pannello dentro il panel 4
panel5 = new JPanel();
panel5.setLayout(new BorderLayout());
panel5.add(rispondiTutti,BorderLayout.NORTH);
panel5.add(inoltra,BorderLayout.SOUTH);
panel4.add(panel5,BorderLayout.SOUTH);
add(panel4,BorderLayout.SOUTH);
//registro i componenti al listener
arrivo.addActionListener(this);
rispondi.addActionListener(this);
rispondiTutti.addActionListener(this);
inoltra.addActionListener(this);
}
}
Remove ActionListener from your Panels PannelloM and PannelloM2 and add the ActionListener inside EmailMonitor
public class EmailMonitor extends JFrame implements ActionListener {
Then implementing the abstract method actionPerformed
I would deal with changing the panel from pannello2 to panneloM
#Override
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("Nuovo..")) {
this.setContentPane(pannelloM);
this.invalidate();
this.validate();
} else if (command.equals("Leggi..")) {
} else if (command.equals("Elimina..")) {
}
}
Connecting the button listeners to EmailMonitor
I would create a reference to EmailMonitor on PannelloM2 and PannelloM constructor
private EmailMonitor em;
public PannelloM2(EmailMonitor em) {
this.em = em;
iniP();
}
And
private EmailMonitor em;
public PannelloM(EmailMonitor em) {
this.em = em;
iniP();
}
Then you change your addActionListeners buttons inside your JPanels to reference EmailMonitor
//registro i componenti al listener
nuovo.addActionListener(em);
leggi.addActionListener(em);
elimina.addActionListener(em);
and
//registro i componenti al listener
arrivo.addActionListener(em);
rispondi.addActionListener(em);
rispondiTutti.addActionListener(em);
EmailMonitor initialize your Panels like this
public EmailMonitor() {
ini();
pannelloM = new PannelloM(this);
pannelloM2 = new PannelloM2(this);
add(pannelloM2);
}
I just started learning Swing with a simple code to create login form.
package swingbeginner;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class LoginForm {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel inputLabel;
private JPanel inputPanel;
private JPanel controlPanel;
private JLabel statusLabel;
public LoginForm() {
prepareGUI();
}
public static void main(String[] args) {
LoginForm loginForm = new LoginForm();
loginForm.loginProcess();
}
private void prepareGUI() {
mainFrame = new JFrame("Login");
mainFrame.setSize(600, 600);
mainFrame.setLayout(new FlowLayout());
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
}
});
inputLabel = new JLabel();
inputLabel.setLayout(null);
inputPanel = new JPanel();
inputPanel.setLayout(null);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(inputLabel);
mainFrame.add(inputPanel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void loginProcess() {
headerLabel.setText("Please Login to Continue!");
JLabel usernameLabel = new JLabel("Username");
usernameLabel.setBounds(10,20,80,25);
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 20, 80, 25);
JTextField usernameTextbox = new JTextField();
usernameTextbox.setBounds(100,20,165,25);
JPasswordField passwordTextbox = new JPasswordField();
passwordTextbox.setBounds(100,20,165,25);
JButton loginButton = new JButton("Login");
JButton cancelButton = new JButton("Cancel");
loginButton.setActionCommand("Login");
cancelButton.setActionCommand("Cancel");
loginButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
inputLabel.add(usernameLabel);
inputPanel.add(usernameTextbox);
inputLabel.add(passwordLabel);
inputPanel.add(passwordTextbox);
controlPanel.add(loginButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
if(command.equals("Login")) {
statusLabel.setText("Logging In");
}
else if(command.equals("Cancel")) {
statusLabel.setText("Login Cancelled");
}
}
}
}
My code displays header along with Login and Cancel button. But the Labels/Text field (Username and Password) are not been displayed in the panel.
Where am I going wrong?
since everyone is missing the fact of the null layout ill create an answer myself.
inputPanel.setLayout(null);
if you add components to this, you will have to specify the position or you simply use a layoutmanager like BorderLayout or FlowLayout.
inputPanel.setLayout(new FlowLayout());
if you use this you will be able to simply add the components to the JPanel. Also as stated in the other answers, don't add JLabels to other JLables, because the most top one will override the others. With that being said a solution code which should work would looks like this:
public class LoginForm {
private JFrame mainFrame;
private JLabel headerLabel;
private JPanel inputPanel;
private JPanel controlPanel;
private JLabel statusLabel;
public LoginForm() {
prepareGUI();
}
public static void main(String[] args) {
LoginForm loginForm = new LoginForm();
loginForm.loginProcess();
}
private void prepareGUI() {
mainFrame = new JFrame("Login");
mainFrame.setSize(600, 600);
mainFrame.setLayout(new FlowLayout());
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
}
});
//changes here
inputPanel = new JPanel();
inputPanel.setLayout(new FlowLayout());
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(inputLabel);
mainFrame.add(inputPanel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void loginProcess() {
headerLabel.setText("Please Login to Continue!");
JLabel usernameLabel = new JLabel("Username");
usernameLabel.setBounds(10,20,80,25);
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 20, 80, 25);
JTextField usernameTextbox = new JTextField();
usernameTextbox.setBounds(100,20,165,25);
JPasswordField passwordTextbox = new JPasswordField();
passwordTextbox.setBounds(100,20,165,25);
JButton loginButton = new JButton("Login");
JButton cancelButton = new JButton("Cancel");
loginButton.setActionCommand("Login");
cancelButton.setActionCommand("Cancel");
loginButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
inputPanel.add(usernameLabel); //changes here
inputPanel.add(usernameTextbox);
inputPanel.add(passwordLabel); //changes here
inputPanel.add(passwordTextbox);
controlPanel.add(loginButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
if(command.equals("Login")) {
statusLabel.setText("Logging In");
}
else if(command.equals("Cancel")) {
statusLabel.setText("Login Cancelled");
}
}
}
}
Here is your solution:
package swingbeginner;
public class LoginForm {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel inputLabel;
private JPanel inputPanel;
private JPanel controlPanel;
private JLabel statusLabel;
public LoginForm() {
prepareGUI();
}
public static void main(String[] args) {
LoginForm loginForm = new LoginForm();
loginForm.loginProcess();
}
private void prepareGUI() {
mainFrame = new JFrame("Login");
mainFrame.setSize(600, 600);
mainFrame.setLayout(new BorderLayout());
headerLabel = new JLabel("header", JLabel.CENTER);
statusLabel = new JLabel("status", JLabel.CENTER);
statusLabel.setSize(350, 100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 100, 100));
mainFrame.add(headerLabel, BorderLayout.NORTH);
mainFrame.add(controlPanel, BorderLayout.CENTER);
mainFrame.add(statusLabel, BorderLayout.SOUTH);
mainFrame.setVisible(true);
}
private void loginProcess() {
headerLabel.setText("Please Login to Continue!");
JLabel usernameLabel = new JLabel("Username");
usernameLabel.setBounds(10, 20, 80, 25);
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 20, 80, 25);
JTextField usernameTextbox = new JTextField(20);
usernameTextbox.setBounds(100, 20, 165, 25);
JPasswordField passwordTextbox = new JPasswordField(20);
passwordTextbox.setBounds(100, 20, 165, 25);
JButton loginButton = new JButton("Login");
JButton cancelButton = new JButton("Cancel");
loginButton.setActionCommand("Login");
cancelButton.setActionCommand("Cancel");
loginButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
controlPanel.add(usernameLabel);
controlPanel.add(usernameTextbox);
controlPanel.add(passwordLabel);
controlPanel.add(passwordTextbox);
controlPanel.add(loginButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
if (command.equals("Login")) {
statusLabel.setText("Logging In");
}
else if (command.equals("Cancel")) {
statusLabel.setText("Login Cancelled");
}
}
}
}
You are adding usernameLabel and passwordLabel onto another label inputLabel. [When stacking labels, the topmost label will overwrite and those labels will disappear.] (JLabel on top of another JLabel)! Why don't you add all the labels and fields directly to the mainFrame i.e. the JFrame object?
You are adding Labels/Textfield(Username and Password) to inputLabel which is an instance of JLabel which is not of type of a container.
Change
inputLabel.add(usernameLabel);
inputPanel.add(usernameTextbox);
inputLabel.add(passwordLabel);
inputPanel.add(passwordTextbox);
to
controlPanel.add(usernameLabel);
controlPanel.add(usernameTextbox);
controlPanel.add(passwordLabel);
controlPanel.add(passwordTextbox);
Also give JTextField a default size, so change
JTextField usernameTextbox = new JTextField();
JPasswordField passwordTextbox = new JPasswordField();
to
JTextField usernameTextbox = new JTextField(20);
JPasswordField passwordTextbox = new JPasswordField(20);
Or you can change the type of inputLabel variable to JPanel and set it a layout like FlowLayout.
In this case no need to use setBounds method on components.
Note: that you use the same bounds for multiple components which will make them one on top of another.
I have a class BasicInfoWindow that gets the user information such as name, address, etc. I then have another class ReviewandSubmit where it show the the texts the user entered from BasicInfoWindow in the JTextArea. I am using card layout to switch between each panel. I am not sure how to send the info from BasicInfoWindow and receive it from ReviewandSubmit. Here is my code so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main extends JPanel
{
private static void createAndShowGUI()
{
final Main test = new Main();
JPanel buttonPanel = new JPanel(new BorderLayout());
JPanel southPanel = new JPanel();
buttonPanel.add(southPanel, BorderLayout.SOUTH);
final JButton btnNext = new JButton("NEXT");
final JButton btnPrev = new JButton("PREVIOUS");
buttonPanel.add(btnNext, BorderLayout.EAST);
buttonPanel.add(btnPrev, BorderLayout.WEST);
btnNext.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
test.nextCard();
}
});
btnPrev.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
test.prevCard();
}
});
JFrame frame = new JFrame("Employment Application");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(test);
frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
//frame.setSize(750,500);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
public static void main(String [] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private CardLayout cardLayout = new CardLayout();
private JPanel cardShowingPanel = new JPanel(cardLayout);
public Main()
{
BasicInfoWindow window1 = new BasicInfoWindow();
cardShowingPanel.add(window1, "1");
EmploymentHistoryWindow window2 = new EmploymentHistoryWindow();
cardShowingPanel.add(window2, "2");
EducationAndAvailbleWindow window3 = new EducationAndAvailbleWindow();
cardShowingPanel.add(window3, "3");
ReviewAndSubmitWindow window4 = new ReviewAndSubmitWindow();
cardShowingPanel.add(window4, "4");
setLayout(new BorderLayout());
add(cardShowingPanel, BorderLayout.CENTER);
}
public void nextCard()
{
cardLayout.next(cardShowingPanel);
}
public void prevCard()
{
cardLayout.previous(cardShowingPanel);
}
public void showCard(String key)
{
cardLayout.show(cardShowingPanel, key);
}
}
BasicInfo Class
ommitted some methods
public class BasicInfoWindow extends JPanel
{
private JTextField txtName, txtAddress, txtCity, txtState, txtZipCode, txtPhoneNumber, txtEmail;
private JComboBox cbDate, cbYear, cbMonth;
private JLabel labelName, labelAddress, labelCity, labelState, labelZipCode, labelPhoneNumber, labelEmail, labelDOB;
private JButton btnClear;
public BasicInfoWindow()
{
createView();
}
private void createView()
{
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
add(panel);
northPanel(panel);
centerPanel(panel);
southPanel(panel);
}
public ArrayList<HiringPersonInfo> sendInfo()
{
String name = txtName.getText();
String address = txtAddress.getText();
String city = txtCity.getText();
String state = txtState.getText();
String zip = txtZipCode.getText();
String phone = txtPhoneNumber.getText();
String email = txtEmail.getText();
String DOB = cbMonth.getSelectedItem() + " " + cbDate.getSelectedItem() + " " + cbYear.getSelectedItem();
HiringPersonInfo addNewInfo = new HiringPersonInfo(name, address, city, state, zip, phone, email, DOB);
ArrayList<HiringPersonInfo> personInfo = new ArrayList();
personInfo.add(addNewInfo);
return personInfo;
}
ReviewAndSubmit class
public class ReviewAndSubmitWindow extends JPanel
{
private JButton btnSubmit;
public ReviewAndSubmitWindow()
{
createView();
}
private void createView()
{
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
add(panel);
northPanel(panel);
centerPanel(panel);
southPanel(panel);
}
private void northPanel(JPanel panel)
{
JPanel northPanel = new JPanel();
panel.add(northPanel, BorderLayout.NORTH);
JLabel labelMessage = new JLabel("Review and Submit");
labelMessage.setFont(new Font("Serif", Font.BOLD, 25));
northPanel.add(labelMessage, BorderLayout.CENTER);
}
private void centerPanel(JPanel panel)
{
JPanel centerPanel = new JPanel();
JTextArea showReview = new JTextArea();
showReview.setLineWrap(true);
showReview.setWrapStyleWord(true);
showReview.setEditable(false);
JScrollPane scrollPane = new JScrollPane(showReview);
scrollPane.setPreferredSize(new Dimension(600, 385));
centerPanel.add(scrollPane, BorderLayout.CENTER);
BasicInfoWindow getInfo = new BasicInfoWindow();
showReview.append(getInfo.sendInfo().toString());
panel.add(centerPanel);
}
private void southPanel(JPanel panel)
{
JPanel southPanel = new JPanel();
panel.add(southPanel, BorderLayout.SOUTH);
btnSubmit = new JButton("SUBMIT");
// creates a new file
southPanel.add(btnSubmit);
}
}
You could use a Singleton Pattern in the HiringPersonInfo class to instantiate one instance of the class and then during the submit you could add that instance of that class to an ArrayList.
Singleton Patterns can be used to create one instance of the object that can be shared by all the classes in that package. You can think of it like a "global" variable in a way for OOP.
I am completely new to programming: I have two classes in my Java Swing application, and when I press the button a new window opens, but only the frame is visible and not the content of the frame.
I appreciate any help.
The first class:
public class Learning {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public Learning(){
prepareGUI();
}
public static void main(String[] args) {
Learning swingControlDemo = new Learning();
swingControlDemo.showEventDemo();
}
private void prepareGUI() {
mainFrame = new JFrame("software component architecture quizess");
mainFrame.setSize(600,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showEventDemo() {
headerLabel.setText("Learning invironment for CBSC and SOA");
JButton okButton = new JButton("Drag and Drop");
JButton submitButton = new JButton("multiple choice quizess");
JButton cancelButton = new JButton("true false quizzes");
JButton newButton = new JButton("Component Description Language");
okButton.setActionCommand("Drag and Drop");
submitButton.setActionCommand("multiple choice quizess");
cancelButton.setActionCommand("true false quizzes");
newButton.setActionCommand("true false quizzes");
controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);
controlPanel.add(newButton);
mainFrame.setVisible(true);
newButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
mainFrame.dispose();
new DLC1();
}
});
}
}
And the second class:
public class DLC1 {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private JLabel msglabel;
public DLC1(){
prepareGUI();
}
public static void main(String[] args){
DLC1 swingLayoutDemo = new DLC1();
swingLayoutDemo.showBorderLayoutDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("component description language");
mainFrame.setSize(600,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showBorderLayoutDemo(){
headerLabel.setText("Layout in action: BorderLayout");
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
panel.setSize(300,300);
BorderLayout layout = new BorderLayout();
layout.setHgap(10);
layout.setVgap(10);
panel.setLayout(layout);
panel.add(new JButton("dlgggggggggc"),BorderLayout.CENTER);
panel.add(new JButton("Line Start"),BorderLayout.LINE_START);
panel.add(new JButton("Line End"),BorderLayout.LINE_END);
panel.add(new JButton("East"),BorderLayout.EAST);
panel.add(new JButton("West"),BorderLayout.WEST);
panel.add(new JButton("North"),BorderLayout.NORTH);
panel.add(new JButton("South"),BorderLayout.SOUTH);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
}