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.
Related
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);
}
}
It runs okay, but my lists doesn't print at all. Also, where should I add the convert to lowercase method for my lists? And I also need to trim the white spaces before or after the lists, which method is best for that?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
public class ShoppingList extends JFrame {
private JPanel groceryPanel;
private JPanel selectedGroceryPanel;
private JPanel buttonPanel;
private JList groceryList;
private JList selectedGroceryList;
private JLabel label;
private JTextField selectedGroceryItem;
private JButton button1;
private JButton button2;
private JButton button3;
private JButton button4;
private String[] lists = { "Burger Patty", "Honey Ham", "Milk",
"Egg", "Orange Juice", "Ketchup", "Lettuce",
"Hamburger Buns", "Tomatoes", "Cheese"
};
//ctor
public ShoppingList() {
setTitle("Shopping List");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
buildGroceryPanel();
buildSelectedGroceryPanel();
buildButtonPanel();
add(groceryPanel, BorderLayout.NORTH);
add(selectedGroceryPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
}//end ctor
private void buildGroceryPanel() {
groceryPanel = new JPanel();
groceryList = new JList(lists);
groceryList.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}//end buildGroceryPanel
private void buildSelectedGroceryPanel() {
selectedGroceryPanel = new JPanel();
label = new JLabel("You selected: ");
selectedGroceryList = new JList();
selectedGroceryItem = new JTextField(10);
selectedGroceryItem.setEditable(false);
selectedGroceryPanel.add(label);
selectedGroceryPanel.add(selectedGroceryItem);
}//end buildSelectedGroceryPanel
private void buildButtonPanel() {
buttonPanel = new JPanel();
button1 = new JButton("ADD");
button2 = new JButton("REMOVE");
button3 = new JButton("SAVE");
button4 = new JButton("LOAD");
button1.addActionListener(new ButtonListener());
button2.addActionListener(new ButtonListener());
button3.addActionListener(new ButtonListener());
button4.addActionListener(new ButtonListener());
buttonPanel.add(button1);
buttonPanel.add(button2);
buttonPanel.add(button3);
buttonPanel.add(button4);
}//end buildButtonPanel
private class ButtonListener
implements ActionListener {
public void actionPerformed(ActionEvent e) {
Object[] selections =
groceryList.getSelectedValues();
selectedGroceryList.setListData(selections);
}
}
public static void main(String[] args) {
new ShoppingList();
}//end main
}
You need to add your groceryList to your groceryPanel. Adding groceryPanel.add(groceryList); in buildGroceryPanel() will help.
Not sure if this is what you're asking for, but there already exists two methods for what you're speaking of in the String class. Example:
String str = " SamPle TeXt ";
str = str.toLowerCase().trim();
System.out.println(str);
Will print out "sample text"
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();
...
How can I set a button to link to a completely different grid pane? If I click the JButton "More options" for example, I want it to link me to a new page with more JButton options. Right now, everything is static.
The program right now just calculates the area of a rectangle given an length and width when you press "Calculate." The grid layout is 4 x 2, denoted by JLabel, JTextField, and JButton listed below.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class RectangleProgram extends JFrame
{
private static final int WIDTH = 400;
private static final int HEIGHT = 300;
private JLabel lengthL, widthL, areaL;
private JTextField lengthTF, widthTF, areaTF;
private JButton calculateB, exitB;
//Button handlers:
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
public RectangleProgram()
{
lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
areaL = new JLabel("Area: ", SwingConstants.RIGHT);
lengthTF = new JTextField(10);
widthTF = new JTextField(10);
areaTF = new JTextField(10);
//SPecify handlers for each button and add (register) ActionListeners to each button.
calculateB = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
setTitle("Sample Title: Area of a Rectangle");
Container pane = getContentPane();
pane.setLayout(new GridLayout(4, 2));
//Add things to the pane in the order you want them to appear (left to right, top to bottom)
pane.add(lengthL);
pane.add(lengthTF);
pane.add(widthL);
pane.add(widthTF);
pane.add(areaL);
pane.add(areaTF);
pane.add(calculateB);
pane.add(exitB);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double width, length, area;
length = Double.parseDouble(lengthTF.getText()); //We use the getText & setText methods to manipulate the data entered into those fields.
width = Double.parseDouble(widthTF.getText());
area = length * width;
areaTF.setText("" + area);
}
}
public class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)
{
RectangleProgram rectObj = new RectangleProgram();
}
}
You can use CardLayout. It allows the two or more components share the same display space.
Here is a simple example
public class RectangleProgram {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Area of a Rectangle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField lengthField = new JTextField(10);
JTextField widthField = new JTextField(10);
JTextField areaField = new JTextField(10);
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
final JPanel content = new JPanel(new CardLayout());
JButton optionsButton = new JButton("More Options");
optionsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) content.getLayout();
cardLayout.next(content);
}
});
JPanel panel = new JPanel(new GridLayout(0, 2)) {
#Override
public Dimension getPreferredSize() {
return new Dimension(250, 100);
}
};
panel.add(new JLabel("Enter the length: ", JLabel.RIGHT));
panel.add(lengthField);
panel.add(new JLabel("Enter the width: ", JLabel.RIGHT));
panel.add(widthField);
panel.add(new JLabel("Area: ", JLabel.RIGHT));
panel.add(areaField);
panel.add(calculateButton);
panel.add(exitButton);
JPanel optionsPanel = new JPanel();
optionsPanel.add(new JLabel("Options", JLabel.CENTER));
content.add(panel, "Card1");
content.add(optionsPanel, "Card2");
frame.add(content);
frame.add(optionsButton, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
});
}
}
Read How to Use CardLayout
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);
}
}