How to tidy up code into class files and methods - java

I am still learning Java and I am currently creating a program in Swing. I have been confused regarding when and when I should use methods and class files. I have created an application that has two cards, card 1: homeJPanel and card 2: guestFixturesJPanel and I want these to switch between each other on button click - which i have done to an extent. However, my code looks extremely messy and is hard to look at as all JPanels are in one method. I was wondering if there was any way I could put guestFixturesJPanel into a separate method or class file and still be able to call the card on button click. Is this possible? Also, does anyone know of any good tutorials that explain methods and class files well as I have been confused and this may be the solution to my problem.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
public class Main
{
protected static final Component c1 = null;
private JButton viewFixturesButton, loginButton, guestBackButton;
private JLabel testTextJLabel, testTextJLabel2;
JPanel container = new JPanel();
CardLayout cardLayout = new CardLayout();
public Main()
{
final JFrame window = new JFrame ("Main Game");
final CardLayout c1 = new CardLayout();
final JPanel container = new JPanel(c1);
JPanel homeJPanel = new JPanel(new BorderLayout());
container.add(homeJPanel);
JPanel centerJPanel = new JPanel(new BorderLayout());
testTextJLabel = new JLabel("TEST");
centerJPanel.add(testTextJLabel);
JPanel southPanel = new JPanel(new FlowLayout());
viewFixturesButton = new JButton("View Fixtures");
loginButton = new JButton("Login");
southPanel.add(viewFixturesButton);
southPanel.add(loginButton);
homeJPanel.add(centerJPanel, BorderLayout.CENTER);
homeJPanel.add(southPanel, BorderLayout.SOUTH);
centerJPanel.setBackground(Color.BLUE);
southPanel.setBackground(Color.GREEN);
JPanel guestFixturesJPanel = new JPanel(new BorderLayout());
container.add(guestFixturesJPanel);
JPanel guestCenterJPanel = new JPanel(new BorderLayout());
JPanel guestSouthPanel = new JPanel(new FlowLayout());
guestBackButton = new JButton("Back");
guestSouthPanel.add(guestBackButton);
guestFixturesJPanel.add(guestCenterJPanel, BorderLayout.CENTER);
guestFixturesJPanel.add(guestSouthPanel, BorderLayout.SOUTH);
guestCenterJPanel.setBackground(Color.BLUE);
guestSouthPanel.setBackground(Color.GREEN);
viewFixturesButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
c1.show(container, "2");
}
});
container.add(homeJPanel, "1");
container.add(guestFixturesJPanel, "2");
c1.show(container, "1");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(container);
window.setSize(600, 500);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setResizable(false);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new Main();
}
});
}
}

You could extract the guestFixturesPanel to a class of its own like this:
public class GuestFixturesPanel extends JPanel {
public GuestFixturesPanel() {
this.setLayout(new BorderLayout());
JPanel guestCenterJPanel = new JPanel(new BorderLayout());
JPanel guestSouthPanel = new JPanel(new FlowLayout());
JButton guestBackButton = new JButton("Back");
guestSouthPanel.add(guestBackButton);
add(guestCenterJPanel, BorderLayout.CENTER);
add(guestSouthPanel, BorderLayout.SOUTH);
guestCenterJPanel.setBackground(Color.BLUE);
guestSouthPanel.setBackground(Color.GREEN);
}
}
Then in your Main class you could instantiate a GuestFixturesPanel and add it to your container. This would preserve the functionality you have now, and extract the code out of your Main class.
GuestFixturesPanel guestFixturesPanel = new GuestFixturesPanel();
container.add(guestFixturesPanel, "2");
Not sure if that addresses the question you had, but I hope this helps.

Related

How to pass JTextfield info from a JDialog into a JFrame (separate classes)

I have been trying to pass the info of my JTextField that is in a JDialog into my JFrame. Both the JDialog and JFrame are in separate classes. I have tried to store the JTextField into a JLable using the .setText and .getText and then passing the JLable into the JFrame but with no luck.
I know there are many similar questions but I have tried many different approaches but still no luck. I am relatively new to Java and do not know all the in's and out's. Any help is very appreciated!
My code for the JFrame:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JPanel;
public class StockApp extends JFrame implements PropertyChangeListener {
private JPanel main = new JPanel();
private JPanel north = new JPanel();
private JPanel center = new JPanel();
private JPanel south = new JPanel();
private JButton buyStock = new JButton("Buy Stock");
private JButton sellStock = new JButton("Sell Stock");
public TestTest variables = new TestTest();
private JLabel stockNameNorth = new JLabel("Stock Name");
private JLabel stockPriceNorth = new JLabel("Stock Price");
String stockName = variables.getStockName();
String stockPrice = variables.getStockPrice();
public StockApp() {
setTitle("StockApp");
getContentPane().setBackground(Color.white);
setSize(400,400);
setLocation(500,200);
setVisible(true);
main.setLayout(new BorderLayout());
north.setLayout(new FlowLayout());
center.setLayout(new FlowLayout());
south.setLayout(new FlowLayout());
stockNameNorth.setText(stockName);
stockPriceNorth.setText(stockPrice);
add(main);
north.add(stockNameNorth);
north.add(stockPriceNorth);
south.add(buyStock);
south.add(sellStock);
main.add(north, BorderLayout.NORTH);
main.add(center, BorderLayout.CENTER);
main.add(south, BorderLayout.SOUTH);
}
}
And Dialog:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestTest extends JDialog implements ActionListener {
private JPanel main = new JPanel();
private JPanel north = new JPanel();
private JPanel center = new JPanel();
private JPanel south = new JPanel();
private JLabel stockNameLabel = new JLabel("Stock name: ");
private JLabel stockPriceLabel = new JLabel("Stock price(£): ");
private JTextField stockNameIn = new JTextField(5);
private JTextField stockPriceIn = new JTextField(5);
private JButton buttonOK = new JButton("OK");
public JLabel stockPrice = new JLabel();
public JLabel stockName = new JLabel();
public TestTest() {
getContentPane().setBackground(Color.white);
setSize(400,400);
setLocation(500,200);
setModal(false);
setVisible(true);
getRootPane().setDefaultButton(buttonOK);
main.setLayout(new BorderLayout());
north.setLayout(new FlowLayout());
center.setLayout(new FlowLayout());
south.setLayout(new FlowLayout());
add(main);
north.add(stockNameLabel);
north.add(stockNameIn);
center.add(stockPriceLabel);
center.add(stockPriceIn);
south.add(buttonOK);
main.add(north, BorderLayout.NORTH);
main.add(center, BorderLayout.CENTER);
main.add(south, BorderLayout.SOUTH);
buttonOK.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonOK){
stockName.setText(stockNameIn.getText());
stockPrice.setText(stockPriceIn.getText());
dispose();
new StockApp();
}
}
public String getStockName() {
return stockNameIn.getText();
}
public String getStockPrice() {
return stockPriceIn.getText();
}
}
I am trying to pass the stockName and stockPrice variables from the JDialog into the JFrame. I then want the name and price to display at the top of the JFrame.
For demonstration, what the problem is, we need less Fields and Buttons.
So far, no component of StockApp needs to be accessed from different methods, so there is no need to make them visible outside of the ctor.
More explanations in the code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
public class StockApp extends JFrame {
public StockApp() {
// move those unreferenced panels here, so we don't have to reason about them:
JPanel main = new JPanel();
JPanel north = new JPanel();
JPanel center = new JPanel();
JPanel south = new JPanel();
// add price later, when name works
JButton buyStock = new JButton("Buy Stock");
JLabel stockNameNorth = new JLabel("Stock Name");
// critical change: Make the label, which you like to update,
// accessible by whom it should be updated:
TestTest variables = new TestTest (stockNameNorth);
setTitle ("StockApp");
getContentPane().setBackground(Color.white);
setSize (600,400);
setLocation (500,200);
setVisible (true);
// make the close-frame action terminate the program:
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
main.setLayout (new BorderLayout());
north.setLayout (new FlowLayout());
center.setLayout (new FlowLayout());
south.setLayout (new FlowLayout());
add (main);
north.add (stockNameNorth);
south.add (buyStock);
main.add (north, BorderLayout.NORTH);
main.add (center, BorderLayout.CENTER);
main.add (south, BorderLayout.SOUTH);
}
// Main method to start the damn thing
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new StockApp ();
}
});
}
}
// no need to make this class public in a short test:
class TestTest extends JDialog implements ActionListener {
// this are elements, visible outside the construction phase,
// we need to have access to from more than one method.
// Make this important distinction visible to the reader:
JLabel name;
JTextField stockNameIn = new JTextField (5);
JButton buttonOK = new JButton ("OK");
// add the JLabel to update to the ctor, so that it can't be forgotten
// to be set
public TestTest (JLabel pname) {
// we copy the reference to the label, to have access to it in
// the actionPerformed method.
name = pname;
JPanel main = new JPanel();
JPanel north = new JPanel();
JPanel center = new JPanel();
JPanel south = new JPanel();
JLabel stockNameLabel = new JLabel ("Stock name: ");
getContentPane().setBackground(Color.white);
// different size/location than frame, so that they don't hide
// each other completly
setSize (400,600);
setLocation (700,300);
setModal (false);
setVisible (true);
getRootPane().setDefaultButton(buttonOK);
main.setLayout (new BorderLayout());
north.setLayout (new FlowLayout());
center.setLayout (new FlowLayout());
south.setLayout (new FlowLayout());
add (main);
north.add (stockNameLabel);
north.add (stockNameIn);
south.add (buttonOK);
main.add (north, BorderLayout.NORTH);
main.add (center, BorderLayout.CENTER);
main.add (south, BorderLayout.SOUTH);
buttonOK.addActionListener(this);
}
// here we need access to the button - was it the OK-Button, clicked?
// and the textfield stockNameIn, to read the text
// and the name field from the frame, to set the text
public void actionPerformed(ActionEvent e) {
if (e.getSource () == buttonOK) {
name.setText (stockNameIn.getText());
dispose();
}
}
}

Why is my JFrame empty?

I can't seem to figure out why my JFrame is empty. Where am I going wrong?
import javax.swing.*;
import java.awt.FlowLayout;
public class GUIExample extends JFrame {
JCheckBox box1 = new JCheckBox("Satellite Radio");
JCheckBox box2 = new JCheckBox("Air Conditioning");
JCheckBox box3 = new JCheckBox("Manual Tranmission");
JCheckBox box4 = new JCheckBox("Leather Seats");
JRadioButton radio1 = new JRadioButton("Car");
JRadioButton radio2 = new JRadioButton("Pickup Truck");
JRadioButton radio3 = new JRadioButton("Minivan");
JTextField text = new JTextField();
ButtonGroup group = new ButtonGroup();
public void newGUI() {
setLayout(new FlowLayout());
JPanel panel = new JPanel();
JPanel textPanel = new JPanel();
add(textPanel);
add(panel);
panel.add(box1);
panel.add(box2);
panel.add(box3);
panel.add(radio1);
panel.add(radio2);
panel.add(radio3);
group.add(radio1);
group.add(radio2);
group.add(radio3);
}
public static void main(String[] args) {
JFrame frame = new JFrame("GUI Example");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
You forgot to add the contentPane in your jFrame, something like this
frame.setContentPane(panel);
I notice you're using inheritance to build your jFrame, so in this case you need to instantiate your own class. I've refactored your code with the minimun to run an jFrame.
public class GUIExample extends JFrame {
JCheckBox box1 = new JCheckBox("Satellite Radio");
public static void main(String[] args) {
JFrame frame = new GUIExample("GUI Example");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(box1);
frame.setContentPane(panel);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
Basically you create an JFrame, create an JPanel, add your components to this panel and set the panel to your frame with setContentPane(panel).
I'm sorry I can't test this right now, so if someone could and fix if needed, would really appreciate, but is something like this.
First of all this is quite a good try to what you are trying to do. However there seem to be some basic misunderstandings as to how you are coding the GUI.
There are two ways of making a GUI in java. Either you create frames and panel objects then add your components to them, or you can create and extend your own classes by extends JFrame. But in this case you have tried to do both. You have extended JFrame and you have created the Objects.
I actually quite like how you've tried to extended the JFrame, so I've continued this and made code that add stuff to your screen!
See below - GUIExample.java:
import javax.swing.*;
import java.awt.FlowLayout;
public class GUIExample extends JFrame {
JCheckBox box1 = new JCheckBox("Satellite Radio");
JCheckBox box2 = new JCheckBox("Air Conditioning");
JCheckBox box3 = new JCheckBox("Manual Tranmission");
JCheckBox box4 = new JCheckBox("Leather Seats");
JRadioButton radio1 = new JRadioButton("Car");
JRadioButton radio2 = new JRadioButton("Pickup Truck");
JRadioButton radio3 = new JRadioButton("Minivan");
JTextField text = new JTextField();
ButtonGroup group = new ButtonGroup();
GUIExample() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
newGUI();
}
public void newGUI() {
setLayout(new FlowLayout());
JPanel panel = new JPanel();
JPanel textPanel = new JPanel();
add(textPanel);
add(panel);
panel.add(box1);
panel.add(box2);
panel.add(box3);
panel.add(radio1);
panel.add(radio2);
panel.add(radio3);
group.add(radio1);
group.add(radio2);
group.add(radio3);
}
}
test.java:
public class test {
public static void main(String[] args) {
GUIExample e = new GUIExample();
}
}
To get this working. Compile both of the files and then run your program through test.java.
Moreover your original solution, nowhere did you add a newGUI() call so all that code becomes redundant. However as the main method is static, you wouldn't be able to call it anyways.
I hope this helps!

Java Button Placement using BorderLayout

This code displays nothing, I have exhausted many avenues but it does not display anything on the GUI (I have a main class that calls this as well already). Please help. I am trying to put the two JButtons horizontally at the bottom of the page and the JTextField and JLabel at the center of the screen.
package test;
import javax.swing.*;
import java.awt.*;
public class Gui extends JFrame {
private JLabel label;
private JButton clear;
private JButton copy;
private JTextField textfield;
public Gui(){
super("test");
clear = new JButton("Clear");
copy = new JButton("Copy");
label = new JLabel("");
textfield = new JTextField("enter text here");
JPanel bottom = new JPanel(new BorderLayout());
JPanel subBottom = new JPanel();
subBottom.add(copy);
subBottom.add(clear);
JPanel centre = new JPanel (new BorderLayout());
JPanel subCentre = new JPanel();
subCentre.add(label);
subCentre.add(textfield);
bottom.add(subBottom, BorderLayout.PAGE_END);
centre.add(subCentre, BorderLayout.CENTER);
}
}
Your code is a bit over-complicated. You only need two panels, centre, and buttons. There are two reasons your UI is not showing up:
You never added the panels to the frame
You never set visible to true(Achieve this by using setVisible(true)), unless you did this in the class you ran it in.
One simple way to achieve your desired UI is like so(I added a main method to show the window):
import javax.swing.*;
import java.awt.*;
public class test extends JFrame {
public Test() {
super("test");
JPanel buttons = new JPanel();
JPanel centre = new JPanel();
add(buttons, BorderLayout.SOUTH); //these lines add the
add(centre, BorderLayout.CENTER); //panels to the frame
JButton clear = new JButton("Clear"); // No need
JButton copy = new JButton("Copy"); // to declare
JLabel label = new JLabel("Label"); // these
JTextField textfield = new JTextField("enter text here"); // privately
buttons.add(copy);
buttons.add(clear);
centre.add(label);
centre.add(textfield);
pack();
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
} //end constructor
//added main method to run the UI
public static void main(String[] args) {
new Experiments();
} //end main
} //end class
And it shows the window:
I got closer but its not pretty code, the JFrame is 500x500 so this works based on that... any better suggestions than what I have?
package lab6;
import javax.swing.*;
import java.awt.*;
public class Gui extends JFrame {
private JLabel label;
private JButton clear;
private JButton copy;
private JTextField textfield;
public Gui(){
super("test");
clear = new JButton("Clear");
copy = new JButton("Copy");
label = new JLabel("label");
textfield = new JTextField("enter text here");
JPanel masterPanel = new JPanel(new BorderLayout());
JPanel top = new JPanel();
top.setPreferredSize(new Dimension(100, 200));
JPanel bottom = new JPanel();
JPanel subBottom = new JPanel();
subBottom.add(copy);
subBottom.add(clear);
JPanel centre = new JPanel ();
JPanel subCentre = new JPanel();
subCentre.add(label);
subCentre.add(textfield);
bottom.add(subBottom);
centre.add(subCentre);
masterPanel.add(bottom, BorderLayout.PAGE_END);
masterPanel.add(top, BorderLayout.PAGE_START);
masterPanel.add(centre, BorderLayout.CENTER);
add(masterPanel);
}
}

How to give a preffered size to the JButton?

import javax.swing.*;
import java.awt.*;
class MainGui{
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JButton newBut = new JButton("New Game");
JButton continueBut = new JButton("Continue");
JButton exitBut = new JButton("Exit");
JLabel backImage = new JLabel(new ImageIcon("C:\\Users\\BSK\\Desktop\\game5.jpg"));
public MainGui(){
frame.setSize(600,800);
frame.setVisible(true);
frame.setResizable(false);
setButtonSize();
frame.setLayout(new BorderLayout());
frame.setContentPane(backImage);
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
insertBlankArea(frame);
frame.getContentPane().add(newBut);
insertBlankArea(frame);
frame.getContentPane().add(continueBut);
insertBlankArea(frame);
frame.getContentPane().add(exitBut);
frame.setSize(799,800);
}
public void insertBlankArea(JFrame frame){
frame.getContentPane().add(Box.createRigidArea(new Dimension(280,155)));
}
public void setButtonSize(){
Dimension dim = new Dimension(100,100);//here is the problem,i am not getting the desired dimension and the size of buttons remains the default.
newBut.setPreferredSize(dim);
continueBut.setPreferredSize(dim);
exitBut.setPreferredSize(dim);
}
public static void main(String[] args) {
MainGui mainGui = new MainGui();
}
}
So iam not getting the defined size for the buttons but when i set frame.setResizable(false); then when i stretch the screen the button's height increases but its width still remains the same.
So please tell me what is going wrong?
You should take a look at A Visual Guide to Layout Managers and choose the most appropriate one for your situation. You should also avoid explicitly setting sizes (ie: setSize, setMinimumSize, setMaximumSize, and setPreferredSize) because those methods are the responsibility of the layout manager. You may also be interested in reading this question on whether or not the use of the different set size methods should be avoided or not.
Finally, you should not be calling your MainGUI class outside of the Event Dispatch Thread (EDT). Most Swing GUI-related methods are not thread safe and therefore require being executed in the EDT. Below is a corrected version of your main method:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MainGui mainGui = new MainGui();
}
});
}
Just reading your short descrption, I have no idea what your problem is. But based solely on the question title
"How to give a preffered size to the JButton?"
Don't. Let the the layout manager handle this for you. If you want a bigger button, you can use JButton.setMargins(Insets) and/or JButton.setFont(Font) where you specify a bigger font.
If you want you button stretched or not to stretch, You need to select an appropriate layout manager, that will or won't respect the buttons preferred size. For instance, BorderLayout and GridLayout won't respect preferred sizes and will stretch the button the fit, and FlowLayout, BoxLayout, and GridBagLayout will respect the preferred size. As you can see here
See example with GridBagLayout
import javax.swing.*;
import java.awt.*;
class MainGui {
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JButton newBut = new JButton("New Game");
JButton continueBut = new JButton("Continue");
JButton exitBut = new JButton("Exit");
JLabel backImage = new JLabel(new ImageIcon(
getClass().getResource("images.jpg")));
public MainGui() {
backImage.setLayout(new BorderLayout());
frame.setContentPane(backImage);
JPanel mainPanel = new JPanel(new GridBagLayout());
mainPanel.setOpaque(false);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
mainPanel.add(newBut, gbc);
gbc.gridy = 1;
mainPanel.add(continueBut, gbc);
gbc.gridy = 2;
mainPanel.add(exitBut, gbc);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.setSize(250, 275);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
MainGui mainGui = new MainGui();
}
});
}
}
And here's with nesting panels which will give the same result
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
class MainGui {
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JButton newBut = new JButton("New Game");
JButton continueBut = new JButton("Continue");
JButton exitBut = new JButton("Exit");
JLabel backImage = new JLabel(new ImageIcon(
getClass().getResource("images.jpg")));
public MainGui() {
backImage.setLayout(new GridLayout(3,1));
frame.setContentPane(backImage);
JPanel p1= new JPanel(new GridBagLayout());
p1.setOpaque(false);
p1.add(newBut);
JPanel p2 = new JPanel(new GridBagLayout());
p2.setOpaque(false);
p2.add(continueBut);
JPanel p3 = new JPanel(new GridBagLayout());
p3.setOpaque(false);
p3.add(exitBut);
frame.add(p1);
frame.add(p2);
frame.add(p3);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 275);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
MainGui mainGui = new MainGui();
}
});
}
}

CardLayout alignment is not proper

I am a beginner to java. In second cardpanel the username and password alignment is not coming properly. Is there any way to fix it? I would also like to know what is the disadvantage of using multiple frames.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class CardLayoutTest extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel cardPanel, jp1, jp2, buttonPanel;
private JLabel jl1, jl2;
private JTextField jt1;
private JPasswordField jt2;
private JButton btn1, btn2;
private CardLayout cardLayout = new CardLayout();
public CardLayoutTest() {
setTitle("Login");
setSize(400, 300);
cardPanel = new JPanel();
buttonPanel = new JPanel();
cardPanel.setLayout(cardLayout);
jp1 = new JPanel();
jp2 = new JPanel();
jt1=new JTextField();
jt2=new JPasswordField();
jl1 = new JLabel("Username");
jl2 = new JLabel("Password");
//jp1.add(jl1);
jp2.add(jl1);
jp2.add(jt2);
jp2.add(jl2);
jp2.add(jt2);
cardPanel.add(jp1, "1");
cardPanel.add(jp2, "2");
btn2 = new JButton("Show Card 2");
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardPanel, "2");
}
});
buttonPanel.add(btn2);
add(cardPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
CardLayoutTest frame = new CardLayoutTest();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
In second cardpanel the username and password alignment is not coming properly.
By default a JPanel uses a FlowLayout so the components are displayed on a single line.
Is there any way to fix it?
Use an appropriate layout manager (or combination of layout managers) to get the desired alignment.
Read the section from the Swing tutorial on Layout Managers for more information and examples.

Categories