So let's start with some background this is for a first year collage project. the GUI is built so one class, the interface-handler calls all the JPanels and puts them in the right place. This is for structure and so it's easy to maintain.
the problem is the panel holding the menu does't show it's components after it's added. i'll include some image's so it's easier to understand.
The panel in question is called MenuPanel.
so here is the login button which currently only clears the contentpanel and then adds the menupanel.
Login page where the button is located
and here is the menu panel empty
here is the menu panel all empty
the code
The interface handler
you can see me messing around with the .repaint() method in the menu method already.
public class InterfaceHandler {
private static InterfaceHandler singleton;
/**
* Checks if there is already a instance running of InterfaceHandler if so
* return the instance if not create a instance.
*
* #return Instance
*/
public static InterfaceHandler instance() {
if (singleton == null) {
singleton = new InterfaceHandler();
}
return singleton;
}
private ContentPanel contentPanel;
private LoginPanel loginPanel;
private MainFrame mainFrame;
private MainPanel mainPanel;
private MenuPanel menuPanel;
/**
* Initializes default Interface
*/
public InterfaceHandler() {
initComponents();
}
/**
* Initializes GUI Components that will be needed now or in the future.
*/
public void initComponents() {
mainFrame = new MainFrame();
mainPanel = new MainPanel();
contentPanel = new ContentPanel();
loginPanel = new LoginPanel();
menuPanel = new MenuPanel();
contentPanel.setBounds(100, 100, 860, 700);
menuPanel.setBounds(10, 10, 80, 400);
loginPanel.setBounds(280, 250, 300, 200);
mainFrame.add(mainPanel);
mainPanel.add(contentPanel);
mainFrame.setVisible(true);
contentPanel.add(loginPanel);
}
/**
* Clears the ContentPanel of all components
*/
public void clear() {
System.out.println("Clear Ran");
contentPanel.removeAll();
contentPanel.repaint();
}
/**
* Adds the Login Screen.
*/
public void login() {
System.out.println("Login Ran");
contentPanel.add(loginPanel);
contentPanel.repaint();
}
/**
* Adds the menu.
*/
public void menu() {
System.out.println("Menu Ran");
mainPanel.sidePanel.add(menuPanel);
menuPanel.repaint();
mainPanel.repaint();
mainPanel.sidePanel.repaint();
}
}
And here is the code for the panel, Most of it is autogenerated by the netbeans design editor.
so it's ugly (i'm sorry)
public class MenuPanel extends javax.swing.JPanel {
/**
* Creates new form MenuPanel
*/
public MenuPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabel2 = new javax.swing.JLabel();
baggageButton = new javax.swing.JLabel();
jLabel1.setBackground(new java.awt.Color(204, 204, 204));
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Menu");
jSeparator1.setBackground(new java.awt.Color(204, 204, 204));
baggageButton.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
baggageButton.setText("Baggage");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(baggageButton, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 4, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(baggageButton, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JLabel baggageButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JSeparator jSeparator1;
// End of variables declaration
}
just to clarify, the method menu is called from a different class.
If you are adding components to an already visible panel, you need to call validate().
public void menu() {
System.out.println("Menu Ran");
mainPanel.sidePanel.add(menuPanel);
mainPanel.sidePanel.validate(); // try this
menuPanel.repaint();
mainPanel.repaint();
mainPanel.sidePanel.repaint();
}
(This answer is wrong but the ensuing comments do help understand why #whiskeyspider's answer is right)
In this code:
mainFrame.add(mainPanel);
mainPanel.add(contentPanel);
mainFrame.setVisible(true);
contentPanel.add(loginPanel);
You're not adding menuPanel anywhere. It is added (too late) in the menu() method, but that's not being called.
Related
Im trying to learn Java and i have now met Jpanels, and since i'm using Netbeans i can use their "constructor" in which i can design the panel i want inside my frame.
With netbeans i made a panel inside my panel, and now i wonder:
How do i draw on a panel inside a panel?
(The panel i want to draw on is EvoPanel)
This is my current design
The dark gray box is the second panel inside the panel, if i try to draw a line from the top left corner to the bottom right i end up with this
My code:
Vindue.java
package vindue;
import javax.swing.*;
/**
*
* #author BE56df
*/
public class Vindue {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
paneler panel = new paneler();
JFrame vindue = new JFrame("NEZ - Evolution Simulator v0.1");
vindue.add(panel);
vindue.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
vindue.setResizable(false);
vindue.pack();
vindue.setVisible(true);
}
}
Paneler.java
package vindue;
import java.awt.*;
import javax.swing.*;
/**
*
* #author BE56df
*/
public class paneler extends javax.swing.JPanel {
/**
* Creates new form paneler
*/
public paneler() {
initComponents();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawLine(0, 0, 750, 550);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
EvoPanel = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jToggleButton1 = new javax.swing.JToggleButton();
setMaximumSize(new java.awt.Dimension(750, 550));
setMinimumSize(new java.awt.Dimension(750, 550));
setPreferredSize(new java.awt.Dimension(750, 550));
EvoPanel.setBackground(new java.awt.Color(200, 200, 200));
EvoPanel.setMaximumSize(new java.awt.Dimension(550, 550));
EvoPanel.setMinimumSize(new java.awt.Dimension(550, 550));
javax.swing.GroupLayout EvoPanelLayout = new javax.swing.GroupLayout(EvoPanel);
EvoPanel.setLayout(EvoPanelLayout);
EvoPanelLayout.setHorizontalGroup(
EvoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 550, Short.MAX_VALUE)
);
EvoPanelLayout.setVerticalGroup(
EvoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 550, Short.MAX_VALUE)
);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel1.setText("Control panel");
jLabel1.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
jLabel1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToggleButton1.setText("Auto play");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(EvoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(63, 63, 63)
.addComponent(jLabel1)
.addGap(0, 58, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
.addComponent(jToggleButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(EvoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jToggleButton1))
);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JPanel EvoPanel;
private javax.swing.JLabel jLabel1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JToggleButton jToggleButton1;
// End of variables declaration
}
Obviously you paint the line on the main JFrame (paneler panel) when you really wants to paint on EvoPanel. You should create a class EvoPanel (with a paintComponent method) and add after paneler#initComponents.
public paneler() {
initComponents();
EvoPanel evoPanel = new EvoPanel();
add(evoPanel) // properly in a layout
}
Advice: for simple GUI's don't use Mantisse (Netbeans GUI builder tool), it won't give you any benefit.
This is a simple code to clarify my question:
this is the main class from where I declared the two panels.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author sakib
*/
public class MainPane {
private JPanel contentPane;
private Firstcard1 p1;
private SecondCard1 p2;
public void displayGUI()
{
JFrame frame = new JFrame("Card Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
//a=S1;
contentPane.setLayout(new CardLayout());
p1 = new Firstcard1(contentPane);
p2 = new SecondCard1(contentPane);
contentPane.add(p1, "Panel 1");
contentPane.add(p2, "Panel 2");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new MainPane().displayGUI();
}
}
);
}
}
this is the first card:
public class Firstcard1 extends javax.swing.JPanel {
private JPanel contentpane;
/**
* Creates new form Firstcard1
*/
public Firstcard1(JPanel cp) {
this.contentpane=cp;
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
Login = new javax.swing.JButton();
Login.setText("Login");
Login.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoginActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(117, 117, 117)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(158, 158, 158)
.addComponent(Login)))
.addContainerGap(145, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(105, 105, 105)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(Login)
.addContainerGap(134, Short.MAX_VALUE))
);
}// </editor-fold>
private void LoginActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
CardLayout layout = (CardLayout)contentpane.getLayout();
layout.show(contentpane, "Panel 2");
}
// Variables declaration - do not modify
private javax.swing.JButton Login;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
this is the second card:
public class SecondCard1 extends javax.swing.JPanel {
private JPanel contentpane;
/**
* Creates new form SecondCard1
*/
public SecondCard1(JPanel cp) {
this.contentpane=cp;
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
back = new javax.swing.JButton();
back.setText("Back");
back.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(127, 127, 127)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(157, 157, 157)
.addComponent(back)))
.addContainerGap(137, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(121, 121, 121)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(back)
.addContainerGap(102, Short.MAX_VALUE))
);
}// </editor-fold>
private void backActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
CardLayout layout = (CardLayout)contentpane.getLayout();
layout.show(contentpane, "Panel 1");
}
// Variables declaration - do not modify
private javax.swing.JButton back;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
My question is.if I put a value in the textarea of the first card and press the login button.the value will appear in the text area of the second card.how can i do it?
You somehow have to pass a reference of the second panel to the first one:
Main class:
public class MainPane
{
public void displayGUI()
{
....
p1 = new Firstcard1(contentPane);
p2 = new SecondCard1(contentPane);
p1.setSecondCard(p2);
....
}
}
First card:
public class Firstcard1 extends javax.swing.JPanel {
....
private SecondCard secondCard;
void setSecondCard(SecondCard secondCard)
{
this.secondCard = secondCard;
}
....
private void LoginActionPerformed(java.awt.event.ActionEvent evt)
{
CardLayout layout = (CardLayout)contentpane.getLayout();
layout.show(contentpane, "Panel 2");
secondCard.getTextField().setText(jTextField1.getText());
}
}
Second card:
public class SecondCard1 extends javax.swing.JPanel
{
...
JTextField getTextField()
{
return jTextField1;
}
...
}
But when you continue like this, the program will probably become a mess pretty soon. I'd recommend to create these components manually, without using any visual GUI builders.
I have a GUI as shown below. the tabbed pane in the card layout card 1 panel show 1st tab by default. When i navigate to card 2, I would like to know how to make the button there to navigate to card 1 tab 3. I know how to get to card 1 from that button by using getParent(), but I don't know how to show a specific tab I want from there. (Note: card 1 and card 2 are two different JPanel classes, the parent is a JFrame class)
Image: Left side as card 1 with tabbed panel , Right side as card 2
The following is my code:
the main JFrame:
import java.awt.CardLayout;
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jbtCard1 = new javax.swing.JButton();
jbtCard2 = new javax.swing.JButton();
cardPane = new javax.swing.JPanel();
jPanelCard11 = new CardLayoutTest.JPanelCard1();
jPanelCard21 = new CardLayoutTest.JPanelCard2();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jbtCard1.setText("Card 1");
jbtCard1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbtCard1ActionPerformed(evt);
}
});
jbtCard2.setText("Card 2");
jbtCard2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbtCard2ActionPerformed(evt);
}
});
cardPane.setName(""); // NOI18N
cardPane.setLayout(new java.awt.CardLayout());
cardPane.add(jPanelCard11, "card1");
cardPane.add(jPanelCard21, "card2");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(87, 87, 87)
.addComponent(jbtCard1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jbtCard2)
.addGap(80, 80, 80))
.addComponent(cardPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(cardPane, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jbtCard2)
.addComponent(jbtCard1))
.addContainerGap())
);
pack();
}// </editor-fold>
private void jbtCard1ActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout card = (CardLayout) cardPane.getLayout();
card.show(cardPane, "card1");
}
private void jbtCard2ActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout card = (CardLayout) cardPane.getLayout();
card.show(cardPane, "card2");
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel cardPane;
private CardLayoutTest.JPanelCard1 jPanelCard11;
private CardLayoutTest.JPanelCard2 jPanelCard21;
private javax.swing.JButton jbtCard1;
private javax.swing.JButton jbtCard2;
// End of variables declaration
}
Card 1 Panel:
public class JPanelCard1 extends javax.swing.JPanel {
public JPanelCard1() {
initComponents();
}
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel2.setText("card 1 tab 1 ");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(101, 101, 101)
.addComponent(jLabel2)
.addContainerGap(233, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(62, 62, 62)
.addComponent(jLabel2)
.addContainerGap(138, Short.MAX_VALUE))
);
jTabbedPane1.addTab("tab1", jPanel1);
jLabel1.setText("card 1 tab 2");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(73, 73, 73)
.addComponent(jLabel1)
.addContainerGap(264, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(92, 92, 92)
.addComponent(jLabel1)
.addContainerGap(108, Short.MAX_VALUE))
);
jTabbedPane1.addTab("tab2", jPanel2);
jLabel3.setText("card 1 tab 3");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(140, 140, 140)
.addComponent(jLabel3)
.addContainerGap(197, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(71, 71, 71)
.addComponent(jLabel3)
.addContainerGap(129, Short.MAX_VALUE))
);
jTabbedPane1.addTab("tab3", jPanel3);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane1)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 58, Short.MAX_VALUE))
);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JTabbedPane jTabbedPane1;
// End of variables declaration
}
Card 2 Panel:
import java.awt.CardLayout;
import javax.swing.JPanel;
public class JPanelCard2 extends javax.swing.JPanel {
public JPanelCard2() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jButton1.setText("go to Card 1 tab 3");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setText("Card 2");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(261, 261, 261)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addGap(52, 52, 52)
.addComponent(jLabel1)))
.addContainerGap(18, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(48, 48, 48)
.addComponent(jLabel1)
.addGap(75, 75, 75)
.addComponent(jButton1)
.addContainerGap(140, Short.MAX_VALUE))
);
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//show card 1 from here
CardLayout card = (CardLayout) this.getParent().getLayout();
card.show((JPanel) this.getParent(), "card1");
//card1 shown, but how to show specific tab in the tab pane from here?
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
I think you're looking for JTabbedPane.html.setSelectedIndex(int).
The following isn't the most elegant solution, but it should work without requiring a lot of refactoring.
Add a method in NewJFrame:
public CardLayoutTest.JPanelCard1 getJPanelCard11() {
return jPanelCard11;
}
Add a method in JPanelCard1:
public void setTab(int index) {
jTabbedPane1.setSelectedIndex(index);
}
Call these in JPanelCard2:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//show card 1 from here
CardLayout card = (CardLayout) this.getParent().getLayout();
card.show((JPanel) this.getParent(), "card1");
//card1 shown, show specific tab in the tab pane from here:
NewJFrame parent = (NewJFrame) this.getParent();
((JPanelCard1) parent.getJPanelCard11()).setTab(1);
}
Please I have been trying to switch CardLayout from another class (JPanel) which is one of the card on the CardLayout, I have search and made research about this for a very long time but found nothing helpful.
I have a CardLayout and two separate JPanels that I added to the CardLayout, now I want to be able to switch the cards after performing activities on the separate JPanel or separate class, so how do I switch the CardLayout from another class? my code below.
package myApp;
import java.awt.CardLayout;
public class TestmyCard extends javax.swing.JFrame {
/**
* Creates new form TestmyCard
*/
public TestmyCard() {
initComponents();
jPanel1.add(new FirstCard(),"card3");
jPanel1.add(new SecondCard(),"card4");
}
public void chgCard(String nwCard){
CardLayout cl = (CardLayout)(jPanel1.getLayout());
cl.show(jPanel1,nwCard);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setName("Cards");
jPanel1.setLayout(new java.awt.CardLayout());
jPanel2.setName("card2");
jLabel1.setText("second panel");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(119, 119, 119)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(203, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(140, 140, 140)
.addComponent(jLabel1)
.addContainerGap(92, Short.MAX_VALUE))
);
jPanel1.add(jPanel2, "card2");
jPanel3.setBackground(new java.awt.Color(153, 255, 153));
jButton1.setLabel("First Btn");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setLabel("Second Btn");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addContainerGap(181, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap(27, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addGap(20, 20, 20))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 439, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(37, 37, 37)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
CardLayout cl = (CardLayout)(jPanel1.getLayout());
cl.show(jPanel1,"card3");
//cl.next(jPanel1) ;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
CardLayout cl = (CardLayout)(jPanel1.getLayout());
cl.show(jPanel1,"card4");
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TestmyCard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TestmyCard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TestmyCard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TestmyCard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TestmyCard().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
// End of variables declaration
}
FirstCard (separate jpanel)
package myApp;
public class FirstCard extends javax.swing.JPanel {
/**
* Creates new form FirstCard
*/
public FirstCard() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
guName = new javax.swing.JTextField();
guAddrs = new javax.swing.JTextField();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
guOccu = new javax.swing.JTextField();
jLabel16 = new javax.swing.JLabel();
guPhone = new javax.swing.JTextField();
jLabel1.setText("Guarantee Name :");
jLabel14.setText("Address :");
jLabel15.setText("Occupation :");
jLabel16.setText("Phone :");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel14)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(guAddrs, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel16)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(guPhone, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel15)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(guOccu, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(guName, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(228, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(43, 43, 43)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(guName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel15)
.addComponent(guOccu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel14)
.addComponent(guAddrs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16)
.addComponent(guPhone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(135, Short.MAX_VALUE))
);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JTextField guAddrs;
private javax.swing.JTextField guName;
private javax.swing.JTextField guOccu;
private javax.swing.JTextField guPhone;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
// End of variables declaration
}
SecondCard (separate jpanel)
package myApp;
public class SecondCard extends javax.swing.JPanel {
/**
* Creates new form SecondCard
*/
public SecondCard() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel1.setText("this is the second card");
jButton1.setText("SwitchCard");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(120, 120, 120)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1)
.addComponent(jLabel1))
.addContainerGap(173, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(62, 62, 62)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(183, Short.MAX_VALUE))
);
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
TestmyCard nc = new TestmyCard();
nc.chgCard("Card2");
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
In your provided code, you never added FirstCard and SecondCard, to the JPanel having layout set to CardLayout. Since what you writing is this :
jPanel1.add(jPanel2, "card2");
here jPanel2 is an instance of JPanel, as you have initialized this in your TestmyClass Class, as :
jPanel2 = new javax.swing.JPanel();
instead I guess what you should be writing is :
jPanel2 = new SecondCard(passPanelWithCardLayoutAsArgument); // So that you can manoeuvre around b/w other JPanels
Here is a small working example for your help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample
{
private JPanel contentPane;
private MyPanel panel1;
private MyPanel panel2;
private MyPanel panel3;
private void displayGUI()
{
JFrame frame = new JFrame("Card Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
panel1 = new MyPanel(contentPane
, Color.RED.darker().darker());
panel2 = new MyPanel(contentPane
, Color.GREEN.darker().darker());
panel3 = new MyPanel(contentPane
, Color.DARK_GRAY);
contentPane.add(panel1, "Panel 1");
contentPane.add(panel2, "Panel 2");
contentPane.add(panel3, "Panel 3");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel
{
private JButton jcomp1;
private JPanel contentPane;
private Color backgroundColour;
public MyPanel(JPanel panel, Color c)
{
contentPane = panel;
backgroundColour = c;
setOpaque(true);
setBackground(backgroundColour);
//construct components
jcomp1 = new JButton ("Show New Panel");
jcomp1.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
add(jcomp1);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(500, 500));
}
}
LATEST EDIT :
*Using your components and trying to put that into CardLayout, with this code : *
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample
{
private JPanel contentPane;
private FirstCard panel1;
private SecondCard panel2;
private void displayGUI()
{
JFrame frame = new JFrame("Card Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
panel1 = new FirstCard(contentPane);
panel2 = new SecondCard(contentPane);
contentPane.add(panel1, "Panel 1");
contentPane.add(panel2, "Panel 2");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class FirstCard extends javax.swing.JPanel
{
private javax.swing.JTextField addField;
private javax.swing.JTextField nameField;
private javax.swing.JTextField occField;
private javax.swing.JTextField phoneField;
private javax.swing.JLabel nameLabel;
private javax.swing.JLabel addLabel;
private javax.swing.JLabel occLabel;
private javax.swing.JLabel phoneLabel;
private JPanel centerPanel;
private JPanel contentPane;
private JButton nextButton;
public FirstCard(JPanel cp)
{
this.contentPane = cp;
initComponents();
}
private void initComponents()
{
setOpaque(true);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setBackground(Color.RED);
setLayout(new BorderLayout(5, 5));
nameLabel = new javax.swing.JLabel("Guarantee Name : ");
nameField = new javax.swing.JTextField();
addLabel = new javax.swing.JLabel("Address : ");
addField = new javax.swing.JTextField();
occLabel = new javax.swing.JLabel("Occupation : ");
occField = new javax.swing.JTextField();
phoneLabel = new javax.swing.JLabel("Phone : ");
phoneField = new javax.swing.JTextField();
centerPanel = new JPanel();
nextButton = new JButton("Next");
nextButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
nextButtonAction(ae);
}
});
centerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.WHITE);
centerPanel.setLayout(new GridLayout(0, 2, 5, 5));
centerPanel.add(nameLabel);
centerPanel.add(nameField);
centerPanel.add(addLabel);
centerPanel.add(addField);
centerPanel.add(occLabel);
centerPanel.add(occField);
centerPanel.add(phoneLabel);
centerPanel.add(phoneField);
add(centerPanel, BorderLayout.CENTER);
add(nextButton, BorderLayout.PAGE_END);
}
private void nextButtonAction(ActionEvent ae)
{
CardLayout layout = (CardLayout)contentPane.getLayout();
layout.next(contentPane);
}
}
class SecondCard extends javax.swing.JPanel
{
private javax.swing.JButton nextButton;
private javax.swing.JLabel textLabel;
private JPanel contentPane;
public SecondCard(JPanel cp)
{
contentPane = cp;
initComponents();
}
private void initComponents()
{
setOpaque(true);
setBackground(Color.GREEN.darker().darker());
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
textLabel = new JLabel("this is the second card", JLabel.CENTER);
textLabel.setForeground(Color.WHITE);
nextButton = new javax.swing.JButton();
nextButton.setText("SwitchCard");
nextButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
jButton1ActionPerformed(evt);
}
});
add(textLabel);
add(nextButton);
}
private void jButton1ActionPerformed(ActionEvent evt)
{
CardLayout layout = (CardLayout) contentPane.getLayout();
layout.show(contentPane, "Panel 1");
}
}
Method to clear fields
private void clearFields()
{
Component components[] = centerPanel.getComponents();
for (Component comp : components)
{
if (comp instanceof JTextField)
{
JTextField tfield = (JTextField) comp;
tfield.setText("");
}
else if (comp instanceof JComboBox)
{
JComboBox cbox = (JComboBox) comp;
cbox.setSelectedIndex(0);
}
else if (comp instanceof JRadioButton)
{
JRadioButton rbut = (JRadioButton) comp;
rbut.setSelected(false);
}
}
}
And you will call this inside the actionPerformed() method of the Button, which will take you to the next Card.
I'm using the Netbeans GUI builder, but it's a little confusing now. How can I add an image to a panel? I think i'm doing it correct, but it's not showing up. I think it should be in the init() method, but netbeans does not allow me to change that part of the code. This is the code I added for the image:
//these four lines I added to add the image
imageIcon = new ImageIcon("login_icon.png");
image = new JLabel(imageIcon);
image.setToolTipText("SGS Security");
topPanel.add(image);
My Class starts here:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Login.java
*
* Created on Oct 27, 2009, 8:34:15 PM
*/
package sgs;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class Login extends javax.swing.JFrame {
JLabel image;
ImageIcon imageIcon;
/** Creates new form Login */
public Login() {
initComponents();
//these four lines I added to add the image
imageIcon = new ImageIcon("login_icon.png");
image = new JLabel(imageIcon);
image.setToolTipText("SGS Security");
topPanel.add(image);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
topPanel = new javax.swing.JPanel();
userLabel = new javax.swing.JLabel();
passwordLabel = new javax.swing.JLabel();
connectLabel = new javax.swing.JLabel();
forgotPassLabel = new javax.swing.JLabel();
forgotPassCheckBox = new javax.swing.JCheckBox();
cancelButton = new javax.swing.JButton();
okButton = new javax.swing.JButton();
passwordTextField = new javax.swing.JTextField();
userTextField = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(216, 156, 60));
topPanel.setBackground(new java.awt.Color(28, 90, 198));
javax.swing.GroupLayout topPanelLayout = new javax.swing.GroupLayout(topPanel);
topPanel.setLayout(topPanelLayout);
topPanelLayout.setHorizontalGroup(
topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 406, Short.MAX_VALUE)
);
topPanelLayout.setVerticalGroup(
topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 71, Short.MAX_VALUE)
);
userLabel.setText("User name:");
passwordLabel.setText("Password:");
connectLabel.setText("Connect to SGS");
forgotPassLabel.setText("Forgot password");
forgotPassCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
forgotPassCheckBoxActionPerformed(evt);
}
});
cancelButton.setText("Cancel");
okButton.setText("OK");
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
userTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
userTextFieldActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(connectLabel)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(passwordLabel)
.addComponent(userLabel)))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(userTextField)
.addComponent(passwordTextField)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(forgotPassCheckBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(forgotPassLabel))
.addGroup(layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
.addComponent(topPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(topPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27)
.addComponent(connectLabel)
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(userLabel)
.addComponent(userTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(passwordLabel)
.addComponent(passwordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(forgotPassLabel)
.addComponent(forgotPassCheckBox))
.addGap(23, 23, 23)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE))
.addContainerGap())
);
pack();
}// </editor-fold>
private void forgotPassCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void userTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Login().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton cancelButton;
private javax.swing.JLabel connectLabel;
private javax.swing.JCheckBox forgotPassCheckBox;
private javax.swing.JLabel forgotPassLabel;
private javax.swing.JButton okButton;
private javax.swing.JLabel passwordLabel;
private javax.swing.JTextField passwordTextField;
private javax.swing.JPanel topPanel;
private javax.swing.JLabel userLabel;
private javax.swing.JTextField userTextField;
// End of variables declaration
}
Ditch the GUI builder and learn how to create GUIs on your own. That way you spend time learning Java instead of learning an IDE. There is probably some GroupLayout property that is not properly set and since GroupLayout was designed to be used by IDEs and not humans I have no idea what the problem might be.
The other possibility is that the IDE can't find your image. Did you add a System.out.println to diplay the image and make sure its not null.
I suggest you read the section from the Swing tutorial on How to Use Icons for a working example that you can download and test to see if it works. Just replace the icons in the tutorial with your icons to make sure they are found.
Edit:
After having a second look at the code I believe my original suggestion is correct. You attempt to add the label to the panel using a single line of code:
topPanel.add(image);
Look at the code generated by the IDE. The add statements are NOT that simple. If you want to manually add a component after the fact then you need read the section from the tutorial on "How to Use Group Layout" to understand the various constraints and methods used.
Or you need to figure out how to do it in the IDE. Thats why I prefer the do it yourself approach. Then you are responsible for the code, not the IDE.
This is one of the weird behaviors in Java (GUIs). You can manually paint the image on a panel.
Here is what I use:
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2= (Graphics2D) g;
if (currentImage != null) {
g2.drawImage(currentImage, null, 0, 0);
}
}
Also you should create a "ImagePanel" component, which is an JPanel that encapsolates the Image.
The middle arguement for drawImage is null, because I do not intend on performing an image operation on it.