Java Swing: Can't show several instances of my JPanel - java

I'm making a GUI and having trouble with a JPanel.
First of all here is my JPanel:
public class ExperimentPanel extends JPanel{
private static File file1,file2=null;
private static DefaultListModel model = new DefaultListModel();
private static JList list = new JList(model);
private static JPanel mainpanel = new JPanel();
private static JPanel leftpanel = new JPanel();
private static JPanel rightpanel = new JPanel();
private static JPanel twoFiles = new SelectTwoFiles();
private static JPanel folderOrFile = new SelectFolderOrFile();
private static JPanel foldersOrFiles = new SelectTwoFoldersOrFiles();
public ExperimentPanel(int selectID){
this.setBorder(new EmptyBorder(10, 10, 10, 10));
if(selectID==Constants.SelectTwoFiles){
this.add(twoFiles, BorderLayout.NORTH);
}
else if(selectID==Constants.SelectFolderOrFile){
this.add(folderOrFile, BorderLayout.NORTH);
}
else if(selectID==Constants.SelectTwoFoldersOrFiles){
this.add(foldersOrFiles,BorderLayout.NORTH);
}
JButton remove =new JButton("Remove Method");
JButton add = new JButton("Add Method");
JButton save = new JButton("Save list");
JButton load = new JButton("Load list");
leftpanel.add(new JScrollPane(list));
Box listOptions = Box.createVerticalBox();
listOptions.add(add);
listOptions.add(remove);
listOptions.add(save);
listOptions.add(load);
rightpanel.add(listOptions);
Box mainBox = Box.createHorizontalBox();
mainBox.add(leftpanel);
mainBox.add(rightpanel);
//mainBox.add(leftleft);
this.add(mainBox, BorderLayout.CENTER);
//start jobs
JButton start = new JButton("Launch experiment");
this.add(start,BorderLayout.PAGE_END);
start.addActionListener(launch);
add.addActionListener(adding);
remove.addActionListener(delete);
}
public static ActionListener launch = new ActionListener(){
public void actionPerformed(ActionEvent event){
//check the files
if((file1==null)||(file2==null)){
JOptionPane.showMessageDialog(null,
"A graph file is missing",
"Wrong files",
JOptionPane.ERROR_MESSAGE);
}
//checks the list
}
};
public static ActionListener delete = new ActionListener() {
public void actionPerformed(ActionEvent event) {
ListSelectionModel selmodel = list.getSelectionModel();
int index = selmodel.getMinSelectionIndex();
if (index >= 0)
model.remove(index);
}
};
public static ActionListener adding = new ActionListener(){
public void actionPerformed(ActionEvent event){
JComboBox combo = new JComboBox();
final JPanel cards = new JPanel(new CardLayout());
JPanel form = new JPanel();
JPanel methode1 = new JPanel();
methode1.add(new JLabel("meth1"));
methode1.setBackground(Color.BLUE);
methode1.setName("meth1");
JPanel methode2 = new JPanel();
methode2.add(new JLabel("meth2"));
methode2.setBackground(Color.GREEN);
methode1.setName("meth2");
combo.addItem("meth1");
combo.addItem("meth2");
cards.add(methode1,"meth1");
cards.add(methode2,"meth2");
JPanel control = new JPanel();
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox jcb = (JComboBox) e.getSource();
CardLayout cl = (CardLayout) cards.getLayout();
cl.show(cards, jcb.getSelectedItem().toString());
}
});
control.add(combo);
form.add(cards, BorderLayout.CENTER);
form.add(control, BorderLayout.SOUTH);
JOptionPane.showMessageDialog(null,form,"Select a method",JOptionPane.PLAIN_MESSAGE);
}
};
}
The problem is that if i create several instances of that panel they won't show like intended.
I tried creating 2 simple JFrames in my main with a new ExperimentPanel for each so the problem is not from the caller.
It works well with one JFrame calling one experiementPanel.
here is the display for one and 2 calls:
http://imgur.com/a/4DHJn
And how i call them:
JFrame test = new JFrame();
test.add(new ExperimentPanel(3));
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
test.setLocation(dim.width/3 - test.getWidth()/3, dim.height/3 - test.getHeight()/3);
test.setSize(550,300);
test.setVisible(true);
JFrame test2 = new JFrame();
test2.add(new ExperimentPanel(3));
test2.setLocation(dim.width/3 - test.getWidth()/3, dim.height/3 - test.getHeight()/3);
test2.setSize(550,300);
test2.setVisible(true);

You create a Panel class ExperimentPanel which itself consists of several components which are stored in class fields of ExperimentPanel.
Since you declare these class fields as static there is only one instance of them. When you instantiate several ExperimentPanel objects they all want to share these fields, which leads to the effects you have seen.
Therefore remove the static modifier from these fields:
public class ExperimentPanel extends JPanel{
private File file1,file2=null;
private DefaultListModel model = new DefaultListModel();
private JList list = new JList(model);
private JPanel mainpanel = new JPanel();
private JPanel leftpanel = new JPanel();
...

Related

Java Swing Event Handling between classes

I have a main frame class, and 2 panel classes.
One of the panels has input fields
The second panel has buttons
I am trying to figure out how to set up event handling such that when a button in the second panel is clicked, I am able to perform an operation which requires accessing components (text field) from the first panel.
The problem is I am unable to access the components from a different class
Code:
public class MainFrame extends JFrame {
private InputPanel input_panel;
private ButtonPanel button_panel;
public MainFrame() {
setTitle("Shop");
setSize(650,350);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
input_panel = new InputPanel();
button_panel = new ButtonPanel();
add(input_panel, BorderLayout.CENTER);
add(button_panel, BorderLayout.SOUTH);
setVisible(true);
}
}
public class InputPanel extends JPanel {
private static JLabel item_num;
private static JLabel book_id;
private static JLabel quantity;
private static JLabel item_info;
private static JLabel subtotal;
private static JTextField t_item_num;
private static JTextField t_book_id;
private static JTextField t_quantity;
private static JTextField t_item_info;
private static JTextField t_subtotal;
public InputPanel() {
//Layout Manager
FlowLayout flow_input_layout = new FlowLayout(FlowLayout.TRAILING, 75, 10);
//Panel
setLayout(flow_input_layout);
setBackground(Color.yellow);
//Text Fields and Labels
item_num = new JLabel("Enter number of items in this order:");
add(item_num);
t_item_num = new JTextField(20);
add(t_item_num);
book_id = new JLabel("Enter Book ID for Item # 1:");
add(book_id);
t_book_id = new JTextField(20);
add(t_book_id);
quantity = new JLabel("Enter quantity for Item # 1:");
add(quantity);
t_quantity = new JTextField(20);
add(t_quantity);
item_info = new JLabel("Item # 1 Info:");
add(item_info);
t_item_info = new JTextField(20);
add(t_item_info);
subtotal = new JLabel("Order subtotal for X Items:");
add(subtotal);
t_subtotal = new JTextField(20);
add(t_subtotal);
}
}
public class ButtonPanel extends JPanel implements ActionListener {
private static JButton process_btn;
private static JButton confirm_btn;
private static JButton view_btn;
private static JButton finish_btn;
private static JButton new_btn;
private static JButton exit_btn;
public ButtonPanel() {
//Layout Manager
FlowLayout flow_input_layout = new FlowLayout();
//Button Panel
setLayout(flow_input_layout);
setBackground(Color.blue);
//Buttons
process_btn = new JButton("Process Item #1");
process_btn.addActionListener(this);
add(process_btn);
confirm_btn = new JButton("Confirm Item #1");
confirm_btn.addActionListener(this);
add(confirm_btn);
view_btn = new JButton("View Order");
view_btn.addActionListener(this);
add(view_btn);
finish_btn = new JButton("Finish Order");
finish_btn.addActionListener(this);
add(finish_btn);
new_btn = new JButton("New Order");
new_btn.addActionListener(this);
add(new_btn);
exit_btn = new JButton("Exit");
exit_btn.addActionListener(this);
add(exit_btn);
}
#Override
public void actionPerformed(ActionEvent event) {
;
}
}
Problem is I cannot access components from my other panel class. Not sure what to do
The easiest thing would be to add the InputPanel to the constructor of the ButtonPanel and then store it in a variable.
input_panel = new InputPanel();
button_panel = new ButtonPanel(input_panel);
And in the ButtonPanel:
public class ButtonPanel extends JPanel implements ActionListener {
...
private final InputPanel inputPanel;
public ButtonPanel(final InputPanel inputPanel) {
this.inputPanel = inputPanel;
...
}
#Override
public void actionPerformed(ActionEvent event) {
this.inputPanel.getItemNum().doSomething() // you will need to also create accessor methods in the inputPanel
}
And btw you should be using camelCase in Java.

More than 1 object in a single JFrame

I'm hoping someone can push me in the right direction with this. I have 3 separate classes, Calculator, Calculator2, and a Calculator3. In principal they are all the same, except for a few changes to some of the buttons, so I'll just paste the code for Calculator. I was wondering how can I get them so all appear in a single JFrame next to each other in a main? I attached my most recent attempt of the main as well.
Here is Calculator:
public class Calculator implements ActionListener {
private JFrame frame;
private JTextField xfield, yfield;
private JLabel result;
private JButton subtractButton;
private JButton divideButton;
private JButton addButton;
private JButton timesButton;
private JPanel xpanel;
public Calculator() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
xpanel = new JPanel();
xpanel.setLayout(new GridLayout(3,2));
xpanel.add(new JLabel("x:", SwingConstants.RIGHT));
xfield = new JTextField("0", 5);
xpanel.add(xfield);
xpanel.add(new JLabel("y:", SwingConstants.RIGHT));
yfield = new JTextField("0", 5);
xpanel.add(yfield);
xpanel.add(new JLabel("Result:"));
result = new JLabel("0");
xpanel.add(result);
frame.add(xpanel, BorderLayout.NORTH);
/***********************************************************************
***********************************************************************
**********************************************************************/
JPanel southPanel = new JPanel(); //New panel for the artimatic buttons
southPanel.setBorder(BorderFactory.createEtchedBorder());
timesButton = new JButton("Multiplication");
southPanel.add(timesButton);
timesButton.addActionListener(this);
subtractButton = new JButton("Subtract");
southPanel.add(subtractButton);
subtractButton.addActionListener(this);
divideButton = new JButton("Division");
southPanel.add(divideButton);
divideButton.addActionListener(this);
addButton = new JButton("Addition");
southPanel.add(addButton);
addButton.addActionListener(this);
frame.add(southPanel , BorderLayout.SOUTH);
Font thisFont = result.getFont(); //Get current font
result.setFont(thisFont.deriveFont(thisFont.getStyle() ^ Font.BOLD)); //Make the result bold
result.setForeground(Color.red); //Male the result answer red in color
result.setBackground(Color.yellow); //Make result background yellow
result.setOpaque(true);
frame.pack();
frame.setVisible(true);
}
/**
* clear()
* Resets the x and y field to 0 after invalid integers were input
*/
public void clear() {
xfield.setText("0");
yfield.setText("0");
}
#Override
public void actionPerformed(ActionEvent event) {
String xText = xfield.getText(); //Get the JLabel fiels and set them to strings
String yText = yfield.getText();
int xVal;
int yVal;
try {
xVal = Integer.parseInt(xText); //Set global var xVal to incoming string
yVal = Integer.parseInt(yText); //Set global var yVal to incoming string
}
catch (NumberFormatException e) { //xVal or yVal werent valid integers, print message and don't continue
result.setText("ERROR");
clear();
return ;
}
if(event.getSource().equals(timesButton)) { //Button pressed was multiply
result.setText(Integer.toString(xVal*yVal));
}
else if(event.getSource().equals(divideButton)) { //Button pressed was division
if(yVal == 0) { //Is the yVal (bottom number) 0?
result.setForeground(Color.red); //Yes it is, print message
result.setText("CAN'T DIVIDE BY ZERO!");
clear();
}
else
result.setText(Integer.toString(xVal/yVal)); //No it's not, do the math
}
else if(event.getSource().equals(subtractButton)) { //Button pressed was subtraction
result.setText(Integer.toString(xVal-yVal));
}
else if(event.getSource().equals(addButton)) { //Button pressed was addition
result.setText(Integer.toString(xVal+yVal));
}
}
}
And here is my current main:
public class DemoCalculator {
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Calculators");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Calculator calc = new Calculator();
Calculator2 calc2 = new Calculator2();
JPanel calcPanel = new JPanel(new BorderLayout());
JPanel calcPanel2 = new JPanel(new BorderLayout());
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
//calcPanel.add(calc, BorderLayout.CENTER);
//calcPanel2.add(calc2, BorderLayout.CENTER);
mainPanel.add(calcPanel);
mainPanel.add(calcPanel2);
calcPanel.add(mainPanel);
mainFrame.getContentPane().add(calcPanel);
mainFrame.getContentPane().add(calcPanel2);
mainFrame.pack();
mainFrame.setVisible(true);
}
}
You should just create a single JFrame and put your Calculator classes each into a single JPanel.Don't create a new JFrame for each class.
public class Calculator{
JPanel panel;
public Calculator(){
panel = new JPanel();
/*
* Add labels and buttons etc.
*/
panel.add(buttons);
panel.add(labels);
}
//Method to return the JPanel
public JPanel getPanel(){
return panel;
}
}
Then add the panels to your JFrame in your testers class using whatever layout best suits your needs.
public class DemoCalculator {
public static void main(String[] args) {
JPanel cal1,cal2;
JFrame frame = new JFrame("Calculators");
frame.add(cal1 = new Calculator().getPanel(),new BorderLayout().EAST);
frame.add(cal2 = new Calculator2().getPanel(),new BorderLayout().WEST);
frame.setSize(1000,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.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.

NullPointerException error and cardlayout [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
The NullPointerException only comes about when I click the 'next' button.
I'm trying to get the frame to transition to another panel using cardlayout, but I have failed to do so.
Second question: How do I get my current panel to transition to the next panel (LoginPanel) in another class? I've already created an instance of it
public class InsuranceMain extends JFrame {
private CardLayout cardPanel;
private JPanel buttonPanel;
private JButton next;
private JLabel label;
public InsuranceMain() {
buttonPanel = new JPanel();
JPanel card1 = new JPanel();
JPanel cards = new JPanel(cardPanel);
LoginPanel loginPanelA = new LoginPanel(this);
CardLayout cardLayout = new CardLayout();
cards.setLayout(cardLayout);
next = new JButton("Next"); // Button
label = new JLabel("Test");
// Main frame settings
setTitle("Travel Insurance Application");
setSize(300, 300);
setLayout(new FlowLayout());
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonPanel.add(next);
add(buttonPanel);
card1.add(label);
cards.add(card1, "card1");
cards.add(loginPanelA, "loginPanelA");
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == next) {
cardLayout.show(cards, "loginPanelA");
}}
});
}
public static void main(String[] args) {
InsuranceMain test = new InsuranceMain();
}
}
Here's my LoginPanel code. I apologize if it's very disorganized
public class LoginPanel extends JPanel {
private JButton loginB, registerB, clearB;
private JTextField nricTextField, passwordTextField;
private JLabel nric, password, loginTitle;
private JPanel centerPanel, southPanel;
private InsuranceMain main;
public LoginPanel(InsuranceMain main){
this.main = main;
// JLabels
loginTitle = new JLabel("Insurance Login", JLabel.CENTER);
nric = new JLabel("NRIC: ");
password = new JLabel("Password: ");
// JTextField
nricTextField = new JTextField("");
passwordTextField = new JTextField("");
// JButton
loginB = new JButton("Login");
loginB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == loginB) {
//cardLayout.show(cards, "card1");
}}
});
registerB = new JButton("Register");
clearB = new JButton("Clear");
// North Panel
setLayout(new BorderLayout()); // main panel's layout
add(loginTitle, BorderLayout.NORTH);
// Center Panel
centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(2,2));
centerPanel.add(nric);
centerPanel.add(nricTextField);
centerPanel.add(password);
centerPanel.add(passwordTextField);
add(centerPanel, BorderLayout.CENTER);
// South Panel
southPanel = new JPanel();
southPanel.setLayout(new FlowLayout());
southPanel.add(loginB);
southPanel.add(registerB);
southPanel.add(clearB);
add(southPanel, BorderLayout.SOUTH);
}
}
A NPE in the actionPerformed method can only be caused by cardLayout being null. So instead of
CardLayout cardLayout = (CardLayout) cards.getLayout(); // yields null
You should create the layout you need.
CardLayout cardLayout = new CardLayout();
See also
Cannot refer to a non-final variable inside an inner class defined in a different method
See also Erwin's comment.
//change to
final CardLayout cardLayout = new CardLayout();
final JPanel cards = new JPanel(cardPanel);
cards.setLayout(cardLayout);
You have to declare the variables final so you can refer to them from an anonymus inner class
new ActionListener() {}
Also use the naming convention of java for naming classes => start with capital letter i.e InsuranceMain, LoginPanel

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