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.
Related
I am trying to make an app for communicating between different running instances of a thread. I have a jFrame that has a jTextField and a jButton. In the jTextField I type the number of threads that I want to run and after I press the jButton the threads run. Each thread contains a jFrame with a jButton. So if I type 3 in the jTextField and then press OK, three different jFrames pop out that have an own jButton. If I press the jButton in one of the jFrames of the threads, the jButton is set to disabled (setEnabled(false)). This should happen to each jButton of the jFrames from within the threads when pressed but the one from the last jFrame that is still not pressed.
This is the window class for the thread:
public class Window extends JFrame implements Runnable {
JFrame jr;
JButton bt;
public void run() {
jr=new JFrame();
bt=new jButton();
bt.setTitle("Press Me");
jr.setLayout(new FlowLayout());
jr.add(bt);
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
bt.setEnabled(false);
}
});
jr.setVisible(true);
}
}
Now this is how I run multiple instances of this thread. i is the number of the thread instances that is taken from the jTextField:
( int i=Integer.parseInt(jTextField1.gettext()) )
for (int a=0;a<i;a++) {
Runnable thr=new Window(a);
executor.execute(thr);
}
This is what I want to do: After I press the jButton on every jFrame that is within the thread instances and it is set to setEnabled(false) I get to the last jFrame that is popped up whose jButton is still unpressed. When I press this last JButton I want that all the JButtons on every jFrame to be set back to setEnabled(true). How can I do that?
This is the main class it works 100 % now!
import java.awt.Color;
import java.awt.Image;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
*
* #author oliver
*/
public class Hauptklasse extends javax.swing.JFrame {
static int i = 0;
static Random r;
static boolean OkApasat=false;
static int c;
public static Fereastra[] thread;
public Hauptklasse() throws IOException {
initComponents();
Image logo;
logo = ImageIO.read(getClass().getResource("resurse/logo.png"));
jLabel4.setIcon(new ImageIcon(logo));
jLabel4.setVisible(true);
setLocation(200,100);
jPanel1.setBackground(Color.cyan);
jTextField1.setEditable(false);
jButton2.setEnabled(false);
r=new Random();
}
/**
* 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();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setPreferredSize(new java.awt.Dimension(549, 448));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton1.setText("Pornire");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextArea1.setBackground(new java.awt.Color(0, 0, 0));
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Andale Mono", 0, 11)); // NOI18N
jTextArea1.setForeground(new java.awt.Color(255, 255, 255));
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setText("Numar maxim de ferestre");
jButton2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton2.setText("OK");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(44, 44, 44)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 486, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton2)))
.addContainerGap(31, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2))
.addGap(22, 22, 22)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 561, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setEditable(true);
jButton1.setEnabled(false);
jButton2.setEnabled(true);
jTextArea1.append("\n Welcome! :)");
jTextArea1.append("\n The following app tests the communication between threads");
jTextArea1.append("\n Please enter maximum number of windows to be opened");
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
OkApasat=true;
}
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String args[]) throws IOException {
final Hauptklasse main1 = new Hauptklasse();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
main1.setVisible(true);
}
});
while (true){
if (OkApasat==true){
if (Integer.parseInt(jTextField1.getText())>=3){
i= (Integer.parseInt(jTextField1.getText()));
main1.jTextArea1.append("\n"+i+" windows opened");
Fereastra[] thr=new Fereastra[i];
for (c = 0; c < i; c++) {
thr[c]=new Fereastra(thr);
thr[c].run();
}
OkApasat=false;
main1.jButton2.setEnabled(false);
main1.jTextField1.setEditable(false);
}
else jTextArea1.append("\n Wrong maximum number of windows-must be at least 3");
OkApasat=false;
}
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(Hauptklasse.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextArea jTextArea1;
public static javax.swing.JTextField jTextField1;
// End of variables declaration
}
THIS IS THE WINDOW CLASS, WORKS 100 %:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
*
* #author oliver
*/
public class Fereastra extends JFrame implements Runnable {
public JFrame jr;
public JButton bt;
public JLabel l;
public JLabel l2;
public Fereastra[] thread;
public boolean deblocat = true;
public Fereastra(Fereastra[] thread) {
this.thread = thread;
jr = new JFrame();
jr.setSize(250, 250);
jr.setLayout(new FlowLayout());
bt = new JButton();
jr.add(bt);
bt.setText("OK");
bt.setBackground(Color.cyan);
l2 = new JLabel();
l2.setText("Buton activ");
jr.add(l2);
jr.setVisible(true);
}
public void run() {
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bt.setEnabled(false);
deblocat = true;
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null && thread[c].bt.isEnabled()) {
deblocat = false;
break;
}
}
if (deblocat == true) {
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null) {
thread[c].bt.setEnabled(true);
}
}
}
}
});
}
}
My classes:
1) The Window class (Fereastra means window, deblocat means unlocked, buton activ means Button is enabled)
package concurenta;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
*
* #author oliver
*/
public class Fereastra extends JFrame implements Runnable {
public static JFrame jr;
public static JButton bt;
public static JLabel l;
public static JLabel l2;
public static Fereastra[] thread;
public boolean deblocat = true;
public Fereastra(Fereastra[] thread) {
this.thread = thread;
jr = new JFrame();
jr.setSize(250, 250);
jr.setLayout(new FlowLayout());
bt = new JButton();
jr.add(bt);
bt.setText("OK");
bt.setBackground(Color.cyan);
l2 = new JLabel();
l2.setText("Buton activ");
jr.add(l2);
jr.setVisible(true);
}
public void run() {
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bt.setEnabled(false);
deblocat = true;
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null && thread[c].bt.isEnabled()) {
deblocat = false;
break;
}
}
if (deblocat == true) {
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null) {
thread[c].bt.setEnabled(true);
}
}
}
}
});
}
}
2) The Main Class(a.k.a Hauptklasse, okApasat means ok is pressed):
/*
* 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.
*/
package concurenta;
import java.awt.Color;
import java.awt.Image;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
*
* #author oliver
*/
public class Hauptklasse extends javax.swing.JFrame {
static int i = 0;
static Random r;
static boolean OkApasat=false;
static int c;
public static Fereastra[] thread;
public Hauptklasse() throws IOException {
initComponents();
Image logo;
logo = ImageIO.read(getClass().getResource("resurse/logo.png"));
jLabel4.setIcon(new ImageIcon(logo));
jLabel4.setVisible(true);
setLocation(200,100);
jPanel1.setBackground(Color.cyan);
jTextField1.setEditable(false);
jButton2.setEnabled(false);
r=new Random();
}
/**
* 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();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setPreferredSize(new java.awt.Dimension(549, 448));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton1.setText("Pornire");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextArea1.setBackground(new java.awt.Color(0, 0, 0));
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Andale Mono", 0, 11)); // NOI18N
jTextArea1.setForeground(new java.awt.Color(255, 255, 255));
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setText("Numar maxim de ferestre");
jButton2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton2.setText("OK");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(44, 44, 44)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 486, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton2)))
.addContainerGap(31, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2))
.addGap(22, 22, 22)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 561, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setEditable(true);
jButton1.setEnabled(false);
jButton2.setEnabled(true);
jTextArea1.append("\n Welcome! :)");
jTextArea1.append("\n The following app tests the communication between threads");
jTextArea1.append("\n Please enter maximum number of windows to be opened");
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
OkApasat=true;
}
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String args[]) throws IOException {
final Hauptklasse main1 = new Hauptklasse();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
main1.setVisible(true);
}
});
while (true){
if (OkApasat==true){
if (Integer.parseInt(jTextField1.getText())>=3){
i= (int) (Math.random() * (Integer.parseInt(jTextField1.getText()) - 3)) + 3;
main1.jTextArea1.append("\n"+i+" windows opened");
Fereastra[] thr=new Fereastra[i];
for (c = 0; c < i; c++) {
thr[c]=new Fereastra(thr);
thr[c].run();
}
OkApasat=false;
main1.jButton2.setEnabled(false);
main1.jTextField1.setEditable(false);
}
else jTextArea1.append("\n Wrong maximum number of windows-must be at least 3");
OkApasat=false;
}
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(Hauptklasse.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextArea jTextArea1;
public static javax.swing.JTextField jTextField1;
// End of variables declaration
}
I have a problem with my project. I would like to create new Panel in my Frame after click the button. Here's a part of a code:
private class ComponentListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(newGameItem))
{
System.out.println("dasda");
gamePanel = new GamePanel();
cont.add(gamePanel);
}
if (e.getSource().equals(stopItem)) {
gamePanel.stopGame();
}
}
}
GamePanel gamePanel;
Container cont = this.getContentPane();
When I click the button I see the text in console, also when I'm starting project already with this Panel everything is okay.
I guess this problem is simple but I can't figure out what's going on :( .
I see "dasda" so it means that method actionPerformed works correctly.
miniwolf where should I invoke repaint? In actionPerformed?
Okay, I found a solution. I should have added gamePanel.revalidate() in actionPerformed. Thanks for your help
I have to refresh this topic, cause I have a problem with change JPanel in JFrame form.
When I click the button I want to change a panel but I can't see it, but when I create JFrame (java class) and write code by myself everything's okay.
This is a code from JFrame (java class) made by me.
public class main extends JFrame
{
public main()
{
frameSettings();
this.getContentPane().add(panel1);
panel1.add(button);
panel1.setBackground(Color.red);
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e)
{
gamePanel = new GamePanel();
container.add(gamePanel);
gamePanel.startGame();
gamePanel.revalidate();
gamePanel.requestFocus();
}
});
}
private void frameSettings() {
int szer = Toolkit.getDefaultToolkit().getScreenSize().width;
int wys = Toolkit.getDefaultToolkit().getScreenSize().height;
this.setTitle("Pong");
this.setSize(700, 600);
this.setResizable(false);
int szerRamki = this.getSize().width;
int wysRamki = this.getSize().height;
this.setDefaultCloseOperation(3);
this.setLocation((szer - szerRamki) / 2, (wys - wysRamki) / 2);
}
JPanel panel1 = new JPanel();
JButton button = new JButton();
GamePanel gamePanel;
Container container = this.getContentPane();
public static void main(String args[])
{
java.awt.EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new main().setVisible(true);
}
});
}
}
And this is a code from JFrame form
public class MainFrame extends javax.swing.JFrame
{
/**
* Creates new form MainFrame
*/
public MainFrame()
{
initComponents();
frameSettings();
}
private void frameSettings()
{
int szer = Toolkit.getDefaultToolkit().getScreenSize().width;
int wys = Toolkit.getDefaultToolkit().getScreenSize().height;
this.setTitle("Pong");
this.setSize(700, 600);
this.setResizable(false);
int szerRamki = this.getSize().width;
int wysRamki = this.getSize().height;
this.setDefaultCloseOperation(3);
this.setLocation((szer - szerRamki) / 2, (wys - wysRamki) / 2);
}
/**
* 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();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(0, 0, 0));
jLabel1.setFont(new java.awt.Font("Monospaced", 3, 160)); // NOI18N
jLabel1.setForeground(new java.awt.Color(51, 255, 255));
jLabel1.setText("Pong");
jLabel2.setFont(new java.awt.Font("Monospaced", 3, 48)); // NOI18N
jLabel2.setForeground(new java.awt.Color(102, 255, 0));
jLabel2.setText("Nowa Gra");
jLabel3.setFont(new java.awt.Font("Monospaced", 3, 48)); // NOI18N
jLabel3.setForeground(new java.awt.Color(102, 255, 0));
jLabel3.setText("Ranking");
jLabel4.setFont(new java.awt.Font("Monospaced", 3, 48)); // NOI18N
jLabel4.setForeground(new java.awt.Color(102, 255, 0));
jLabel4.setText("Wyjście");
jLabel5.setFont(new java.awt.Font("Monospaced", 3, 18)); // NOI18N
jLabel5.setForeground(new java.awt.Color(153, 255, 0));
jLabel5.setText("Najlepszy gracz:");
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(237, 237, 237)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel3)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(227, 227, 227)
.addComponent(jLabel2)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(148, 148, 148)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 131, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(102, 102, 102))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(57, 57, 57)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(jButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5))
);
jMenu1.setText("File");
jMenuItem1.setText("Nowa Gra");
jMenu1.add(jMenuItem1);
jMenuItem2.setText("jMenuItem2");
jMenu1.add(jMenuItem2);
jMenuItem3.setText("jMenuItem3");
jMenu1.add(jMenuItem3);
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
System.out.println("askdalk");
gamePanel = new GamePanel();
container.add(gamePanel);
gamePanel.startGame();
gamePanel.revalidate();
gamePanel.requestFocus();
}
/**
* #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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(MainFrame.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 MainFrame().setVisible(true);
}
});
}
private Container container = this.getContentPane();
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JPanel jPanel1;
// End of variables declaration
private GamePanel gamePanel;
}
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);
}
I've created and application in which there are two tabs titled Tabbedpane 1 and Tabbedpane 2. In one tab body Tabbedpane 1 contains a JInternalFrame in which there is a search button. On clicking the button another JInternalFrame opens within the main JInternalFrame.
Can anyone please tell me how to close the said opened JInternalFrame ie the search JInternalFrame while clicking on to the second tab titled Tabbedpane 2
I've tried .setClosed(true) and .setVisible(true) on property change still it does'nt works for me.
Use a ChangeListener which will get notified when JTabbedPane state changes (i.e tabs switched):
final JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
//tab has been changed
}
});
The problem is we will need a way to monitor the previous tab i.e the tab we were on before it was changed this can be done via:
tabbedPane.addChangeListener(new ChangeListener() {
int prev_index = 0;
int curr_index = 0;
public void stateChanged(ChangeEvent e) {
prev_index = curr_index;
curr_index = tabbedPane.getSelectedIndex();
System.out.println("Tab (Current): " + curr_index);
System.out.println("Tab (Previous): " + prev_index);
}
});
UPDATE 1:
To close JInternalFrame I'd suggest calling dispose() on its instance
UPDATE 2:
Here is your fixed code, basically added a getter for Search class, thus JIFrame1 has a getSearch() method which allows us to gaim access to the Search classes current instance created in JIFrame1, in changedState(..) I call jiFrame1.getSearch().dispose() which will make sure we dispose of the instance that has already been created:
import java.awt.Container;
import java.awt.event.MouseListener;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Sample extends javax.swing.JFrame {
JIFrame1 jiframe1 = new JIFrame1();
public Sample() {
initComponents();
Container jiframe1cont = tab1;
for (MouseListener listener : ((javax.swing.plaf.basic.BasicInternalFrameUI) jiframe1.getUI()).getNorthPane().getMouseListeners()) {
((javax.swing.plaf.basic.BasicInternalFrameUI) jiframe1.getUI()).getNorthPane().removeMouseListener(listener);
}
jiframe1.setLocation(10, 10);
jiframe1cont.add(jiframe1);
jiframe1.setVisible(true);
JIFrame2 jiframe2 = new JIFrame2();
Container jiframe2cont = tab2;
for (MouseListener listener : ((javax.swing.plaf.basic.BasicInternalFrameUI) jiframe2.getUI()).getNorthPane().getMouseListeners()) {
((javax.swing.plaf.basic.BasicInternalFrameUI) jiframe2.getUI()).getNorthPane().removeMouseListener(listener);
}
jiframe2.setLocation(10, 10);
jiframe2cont.add(jiframe2);
jiframe2.setVisible(true);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tab1 = new javax.swing.JDesktopPane();
tab2 = new javax.swing.JDesktopPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
tabbedPane.setTabPlacement(javax.swing.JTabbedPane.LEFT);
tabbedPane.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
tabbedPaneStateChanged(evt);
}
});
tab1.setBackground(new java.awt.Color(240, 240, 240));
tabbedPane.addTab("Tabbedpane 1", tab1);
tab2.setBackground(javax.swing.UIManager.getDefaults().getColor("Button.background"));
tabbedPane.addTab("Tabbedpane 2", tab2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 731, Short.MAX_VALUE));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 503, Short.MAX_VALUE));
pack();
}// </editor-fold>
private void tabbedPaneStateChanged(javax.swing.event.ChangeEvent evt) {
try {
jiframe1.getSearch().dispose();
} catch (Exception ex) {
Logger.getLogger(Sample.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Sample().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JDesktopPane tab1;
private javax.swing.JDesktopPane tab2;
private final javax.swing.JTabbedPane tabbedPane = new javax.swing.JTabbedPane();
// End of variables declaration
}
class Search extends javax.swing.JInternalFrame {
public Search() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jTextField1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object[][]{
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String[]{
"Title 1", "Title 2", "Title 3", "Title 4"
}));
jScrollPane1.setViewportView(jTable1);
jButton1.setText("CLOSE");
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(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(205, Short.MAX_VALUE))))
.addGroup(layout.createSequentialGroup()
.addGap(158, 158, 158)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(172, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
class JIFrame1 extends javax.swing.JInternalFrame {
public JIFrame1() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
pane = new javax.swing.JDesktopPane();
jButton1 = new javax.swing.JButton();
pane.setBackground(new java.awt.Color(240, 240, 240));
jButton1.setText("SEARCH");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton1.setBounds(170, 60, 90, 23);
pane.add(jButton1, javax.swing.JLayeredPane.DEFAULT_LAYER);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pane, javax.swing.GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pane, javax.swing.GroupLayout.DEFAULT_SIZE, 322, Short.MAX_VALUE));
pack();
}// </editor-fold>
private Search search;
public Search getSearch() {
return search;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
search = new Search();
Container searchcont = pane;
for (MouseListener listener : ((javax.swing.plaf.basic.BasicInternalFrameUI) search.getUI()).getNorthPane().getMouseListeners()) {
((javax.swing.plaf.basic.BasicInternalFrameUI) search.getUI()).getNorthPane().removeMouseListener(listener);
}
search.setLocation(10, 10);
searchcont.add(search);
search.setVisible(true);
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JDesktopPane pane;
// End of variables declaration
}
class JIFrame2 extends javax.swing.JInternalFrame {
public JIFrame2() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel1.setText("JIFrame2..............");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(100, 100, 100)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(137, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(86, 86, 86)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(145, Short.MAX_VALUE)));
pack();
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
UPDATE 3:
The reason for NPE is here:
private void tabbedPaneStateChanged(javax.swing.event.ChangeEvent evt) {
try {
jiframe1.getSearch().dispose();
} catch (Exception ex) {
Logger.getLogger(Sample.class.getName()).log(Level.SEVERE, null, ex);
}
}
change to this:
private void tabbedPaneStateChanged(javax.swing.event.ChangeEvent evt) {
try {
Search s=jiframe1.getSearch();
if(s!=null)
s.dispose();
} catch (Exception ex) {
Logger.getLogger(Sample.class.getName()).log(Level.SEVERE, null, ex);
}
}