Load panel by pressing a button - java

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);
}

Related

NullPointerException returned by javax.swing.JPanel.getBorder()

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());
}
}
}

How can i use multiple panels with different layouts for my gui?

i have problems with nesting 2 different button panels into my main panel. It worked for me with only one 1 panel. Now with my actual nesting i see the last added panel over my main panel and my first button panel. Additionally the "editButton" i added, is not showing up. I got no errors while compiling. It seems to be that i just made a mistake in the arrangement.
Would be very nice if there are any suggestions. Here is my code snippet:
Thanks in advance!
private final String name;
private JLabel catLabel;
private JButton cat1Button;
private JButton cat2Button;
private JButton cat3Button;
private JButton cat4Button;
private JButton editButton;
private JButton deleteButton;
private JButton insertButton;
public JPanel panelMain;
public JPanel panel;
public JPanel panel1;
public ReadwriteQuiz readwrite;
public GUIEdit(String name){
this.name = name;
this.setTitle(name);
this.setLocationRelativeTo(null);
this.setLayout((null));
this.setSize(400,300);
this.setLocation(400,150);
this.setResizable(false);
panelMain = new JPanel();
panelMain.setLayout(new BoxLayout(panelMain, BoxLayout.Y_AXIS));
panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.setBackground(Color.lightGray);
panel1 = new JPanel();
panel1.setLayout(new BoxLayout(panel1, BoxLayout.X_AXIS));
panel1.setBackground(Color.ORANGE);
panelMain.add(panel);
panelMain.add(panel1);
catLabel= new JLabel("Willkommen zum Quizzeln ! \n Wählen Sie Ihre Kategorie");
catLabel.setBounds(90,10,260,40);
panel.add(catLabel);
cat1Button = new JButton("Kategorie 1");
cat1Button.setBounds(52,90,120,40);
panel.add(cat1Button);
cat1Button.addActionListener((e) -> {
try {
readwrite.readFile("kategorie1.txt");
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
}
});
cat2Button = new JButton("Kategorie 2");
cat2Button.setBounds(220,90,120,40);
panel.add(cat2Button);
cat3Button = new JButton("Kategorie 3");
cat3Button.setBounds(52,160,120,40);
panel.add(cat3Button);
cat4Button = new JButton("Kategorie 4");
cat4Button.setBounds(220,160,120,40);
panel.add(cat4Button);
editButton = new JButton("Frage editieren");
editButton.setBounds(52,400,120,40);
panel1.add(editButton);
this.add(panelMain);
this.add(panel);
this.add(panel1);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
}
You have one main panel and you have already added the other nested panels to the main panel
so you only add that main panel to the parent panel
but you're adding the main panel ( including the other 2 ) and again adding the 1st panel and again adding the 2nd panel
so
this.add(panelMain);
should be enough
Full class
public class app {
private JTextField textField1;
private JPanel panel;
private JLabel label;
private JLabel catLabel;
private JButton cat1Button;
private JButton cat2Button;
private JButton cat3Button;
private JButton cat4Button;
private JButton editButton;
private JButton deleteButton;
private JButton insertButton;
public JPanel panelMain;
public JPanel panel2;
public JPanel panel1;
public app(JFrame frame) {
panelMain = new JPanel();
panelMain.setLayout(new BoxLayout(panelMain, BoxLayout.Y_AXIS));
panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
panel2.setBackground(Color.lightGray);
panel1 = new JPanel();
panel1.setLayout(new BoxLayout(panel1, BoxLayout.X_AXIS));
panel1.setBackground(Color.ORANGE);
panelMain.add(panel2);
panelMain.add(panel1);
catLabel= new JLabel("Willkommen zum Quizzeln ! \n Wählen Sie Ihre Kategorie");
catLabel.setBounds(90,10,260,40);
panel2.add(catLabel);
cat1Button = new JButton("Kategorie 1");
cat1Button.setBounds(52,90,120,40);
panel2.add(cat1Button);
cat2Button = new JButton("Kategorie 2");
cat2Button.setBounds(220,90,120,40);
panel2.add(cat2Button);
cat3Button = new JButton("Kategorie 3");
cat3Button.setBounds(52,160,120,40);
panel2.add(cat3Button);
cat4Button = new JButton("Kategorie 4");
cat4Button.setBounds(220,160,120,40);
panel2.add(cat4Button);
editButton = new JButton("Frage editieren");
editButton.setBounds(52,400,120,40);
panel1.add(editButton);
frame.add(panelMain);
}
public static void main(String[] args) {
JFrame fram = new JFrame("app");
new app(fram);
fram.pack();
fram.setVisible(true);
}
}

Adding a panel to a JFrame

There are no errors in the code but i cant seem to see the Jlabels in the window. Im not sure if the panel was added or if the jlabels were added to the panel .
public class JDemoResistance extends JFrame{
private final JButton button1;
private JPanel panel;
private final int WINDOW_WIDTH = 320;
private final int WINDOW_HEIGHT = 320;
public JDemoResistance() {
super("JDemoResistance");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JLabels Configs
JLabel label1 = new JLabel("Too expensive");
JLabel label2 = new JLabel("Bad reviews");
JLabel label3 = new JLabel("Bad quality");
JLabel label4 = new JLabel("Not worth it");
JLabel label5 = new JLabel("Dosent work");
//Button Configs
button1 = new JButton("Button");
button1.addActionListener(new ButtonListener());
//Panel Configs
panel = new JPanel();
panel.add(label1);
panel.add(label2);
panel.add(label3);
panel.add(label4);
panel.add(label5);
panel.add(button1);
setVisible(true);
}
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e){
}
}
public static void main(String[] args) {
JDemoResistance jdr = new JDemoResistance();
}
}
You haven't added the panel to the frame, that's why you can't see any of the components. Add it before setting the JFrame visible.
//Add the panel to the frame
this.add(panel)
setVisible(true);
You must add the panel to the JFrame as well.
panel.add(...);
add(panel); // <-- you forgot this
setVisible(true);

BorderLayout not working JFrame

For some reason I can't get the BorderLayout to set the way it's supposed to. Just would like to know where I'm going wrong.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ColorFactory extends JFrame
{
final int width = 500;
final int height = 300;
private JPanel buttonPanel;
private JPanel radioButtonPanel;
private JLabel msgChangeColor;
public ColorFactory()
{
setTitle("Color Factory");
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
createTopPanel();
add(buttonPanel, BorderLayout.NORTH);
createBottomPanel();
add(radioButtonPanel, BorderLayout.SOUTH);
msgChangeColor = new JLabel("Top buttons change the panel color and bottom radio buttons change the text color.");
add(msgChangeColor, BorderLayout.CENTER);
pack();
}
private void createTopPanel()
{
buttonPanel = new JPanel();
setLayout(new FlowLayout());
JButton redButton = new JButton("Red");
redButton.setBackground(Color.RED);
redButton.addActionListener(new ButtonListener());
redButton.setActionCommand("R");
JButton orangeButton = new JButton("Orange");
orangeButton.setBackground(Color.ORANGE);
orangeButton.addActionListener(new ButtonListener());
orangeButton.setActionCommand("O");
JButton yellowButton = new JButton("Yellow");
yellowButton.setBackground(Color.YELLOW);
yellowButton.addActionListener(new ButtonListener());
yellowButton.setActionCommand("Y");
buttonPanel.add(redButton);
buttonPanel.add(orangeButton);
buttonPanel.add(yellowButton);
}
private void createBottomPanel()
{
radioButtonPanel = new JPanel();
setLayout(new FlowLayout());
JRadioButton greenRadioButton = new JRadioButton("Green");
greenRadioButton.setBackground(Color.GREEN);
greenRadioButton.addActionListener(new RadioButtonListener());
greenRadioButton.setActionCommand("G");
JButton blueRadioButton = new JButton("Blue");
blueRadioButton.setBackground(Color.BLUE);
blueRadioButton.addActionListener(new RadioButtonListener());
blueRadioButton.setActionCommand("B");
JButton cyanRadioButton = new JButton("Cyan");
cyanRadioButton.setBackground(Color.CYAN);
cyanRadioButton.addActionListener(new RadioButtonListener());
cyanRadioButton.setActionCommand("C");
radioButtonPanel.add(greenRadioButton);
radioButtonPanel.add(blueRadioButton);
radioButtonPanel.add(cyanRadioButton);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String actionColor = e.getActionCommand();
if(actionColor.equals("R"))
{
buttonPanel.setBackground(Color.RED);
radioButtonPanel.setBackground(Color.RED);
}
if(actionColor.equals("O"))
{
buttonPanel.setBackground(Color.ORANGE);
radioButtonPanel.setBackground(Color.ORANGE);
}
if(actionColor.equals("Y"))
{
buttonPanel.setBackground(Color.YELLOW);
radioButtonPanel.setBackground(Color.YELLOW);
}
}
}
private class RadioButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String actionTextColor = e.getActionCommand();
if(actionTextColor.equals("G"))
{
msgChangeColor.setForeground(Color.GREEN);
}
if(actionTextColor.equals("B"))
{
msgChangeColor.setForeground(Color.BLUE);
}
if(actionTextColor.equals("C"))
{
msgChangeColor.setForeground(Color.CYAN);
}
}
}
public static void main(String[] args)
{
ColorFactory run = new ColorFactory();
run.setVisible(true);
}
}
The problem is you are changing the layout manager for the frame when you create your top and bottom panels...
private void createTopPanel() {
buttonPanel = new JPanel();
setLayout(new FlowLayout()); // <--- This is call setLayout on the frame
This is why it's dangerous to...
Extend from something like JFrame directly...
Dynamically build components
It's all to easy to lose context and start effecting components you didn't actually want to...
Another problem (besides the one posted by MadProgrammer) is that you add your components to the JFrame itself.
You should add content to the content pane of the frame which you can get by calling JFrame.getContentPane().
Example:
JFrame f = new JFrame("Test");
Container c = f.getContentPane();
c.add(new JButton("In Center"), BorderLayout.CENTER);
c.add(new JButton("At the Bottom"), BorderLayout.SOUTH);
c.add(new JButton("At the Top"), BorderLayout.NORTH);
c.add(new JButton("On the Left"), BorderLayout.WEST);
c.add(new JButton("On the Right"), BorderLayout.EAST);
You can set/change the content panel by calling JFrame.setContentPane(). The default content panel already has BorderLayout so you don't even need to change it nor to set a new panel.

CardLayout issue

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);
}
}

Categories

Resources