I want when I click on tab1 or tab2. Japel display will hide or show,I want the results shown in Figure 2.I use the command jPanel2.setPreferredSize(new Dimension(0, 0));
Ex: If I have 10,I need setPreferredSize for 10 japanel with each tab.I want to ask a much easier way.
Events to click on my tab does not work properly.Please help me
/*
* 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 main;
import java.awt.Dimension;
/**
*
* #author KhongTuyen
*/
public class demo extends javax.swing.JFrame {
/**
* Creates new form demo
*/
public demo() {
initComponents();
jPanel2.setVisible(false);
}
/**
* 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() {
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel4 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTabbedPane1.setTabPlacement(javax.swing.JTabbedPane.BOTTOM);
jTabbedPane1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTabbedPane1MouseClicked(evt);
}
});
jTabbedPane1.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jTabbedPane1StateChanged(evt);
}
});
jPanel4.setPreferredSize(new java.awt.Dimension(395, 0));
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 395, Short.MAX_VALUE)
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jTabbedPane1.addTab("tab1", jPanel4);
jPanel1.setPreferredSize(new java.awt.Dimension(395, 0));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 395, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jTabbedPane1.addTab("tab2", jPanel1);
getContentPane().add(jTabbedPane1, java.awt.BorderLayout.PAGE_START);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 253, Short.MAX_VALUE)
);
getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>
private void jTabbedPane1MouseClicked(java.awt.event.MouseEvent evt) {
int count = 0;
if (count % 2 != 0) {
jPanel2.setPreferredSize(new Dimension(0, 100));
jPanel1.setPreferredSize(new Dimension(0, 100));
} else {
jPanel2.setPreferredSize(new Dimension(0, 0));
jPanel1.setPreferredSize(new Dimension(0, 0));
}
count++;
}
private void jTabbedPane1StateChanged(javax.swing.event.ChangeEvent evt) {
// TODO add your handling code here:
}
/**
* #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(demo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(demo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(demo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(demo.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 demo().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel4;
private javax.swing.JTabbedPane jTabbedPane1;
// End of variables declaration
}
Use a JSplitPane. You can click on a button on the divider to have the divider go to the minimum or maximum value of the divider.
However, in order for the divider to go to the minimum the getMinimumSize() method must return a Dimension of (0, 0).
Read the section from the Swing tutorial on How to Use Split Panes for more information and examples.
Did you mean something like this
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TabSample {
static void add(JTabbedPane tabbedPane, String text) {
String text1 = "";
JPanel panel = new JPanel();
if (text.equals("tab1")){
text1 = "";
}
else
{
text1 = text;
}
JLabel label = new JLabel(text1);
label.setFont(new Font(null,Font.BOLD,30));
label.setText(text1);
panel.add(label);
tabbedPane.addTab(text,label);
}
public static void main(String args[]) {
JFrame frame = new JFrame("Tabbed Pane Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setTabPlacement(JTabbedPane.BOTTOM);
String titles[] = { "tab1", "Jpanel Display 2"};
for (int i = 0, n = titles.length; i < n; i++) {
add(tabbedPane, titles[i]);
}
ChangeListener changeListener = new ChangeListener() {
public void stateChanged(ChangeEvent changeEvent) {
JTabbedPane sourceTabbedPane = (JTabbedPane) changeEvent.getSource();
int index = sourceTabbedPane.getSelectedIndex();
System.out.println("Tab changed to: " + sourceTabbedPane.getTitleAt(index));
}
};
tabbedPane.addChangeListener(changeListener);
frame.add(tabbedPane, BorderLayout.CENTER);
frame.setSize(400, 150);
frame.setVisible(true);
}
}
Related
(Edited)
I'm creating a small project with dynamically changing panels.
I've been able to write code that can call a JPanel using an action event from a button within the the JFrame (ManagerScreen). For example:
package route66.JFrames;
import route66.pannels.BuyReserve;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import route66.pannels.Buy;
import route66.pannels.BuyReport;
import route66.pannels.CustomerDetails;
import route66.pannels.NewUser;
import route66.pannels.QuotPanel;
import route66.pannels.ReportPanel;
import route66.pannels.Salaries_Com;
import route66.pannels.SaleSucces;
/**
*
* #author Vavu
*/
public class ManagerScreen extends javax.swing.JFrame {
GridBagLayout layout = new GridBagLayout();
Buy BuyPanel = new Buy();
Buy b = new Buy();
BuyReserve buyR = new BuyReserve();
BuyReport brep = new BuyReport();
CustomerDetails cusD = new CustomerDetails();
QuotPanel QP = new QuotPanel();
ReportPanel RP = new ReportPanel();
NewUser NW = new NewUser();
Salaries_Com SalCom = new Salaries_Com();
SaleSucces SalS = new SaleSucces();
boolean visible;
/**
* Creates new form ManagerScreen
* #param pabel
*/
public ManagerScreen() {
initComponents();
DynamicPanel.setLayout(layout);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
DynamicPanel.add(b,c);
DynamicPanel.add(buyR,c);
DynamicPanel.add(brep,c);
DynamicPanel.add(cusD,c);
DynamicPanel.add(QP,c);
DynamicPanel.add(RP,c);
DynamicPanel.add(NW,c);
DynamicPanel.add(SalCom,c);
DynamicPanel.add(SalS,c);
b.setVisible(false);
buyR.setVisible(false);
brep.setVisible(false);
cusD.setVisible(false);
QP.setVisible(false);
RP.setVisible(false);
NW.setVisible(false);
SalCom.setVisible(false);
SalS.setVisible(false);
}
/**
* 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() {
DynamicPanel = new javax.swing.JPanel();
MSbuy = new javax.swing.JButton();
MSQuotation = new javax.swing.JButton();
MSReserve = new javax.swing.JButton();
MSSalCom = new javax.swing.JButton();
MSReport = new javax.swing.JButton();
MSCreateNew = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setMinimumSize(new java.awt.Dimension(980, 740));
getContentPane().setLayout(null);
DynamicPanel.setBackground(new java.awt.Color(255, 0, 0));
DynamicPanel.setMaximumSize(new java.awt.Dimension(500, 500));
DynamicPanel.setMinimumSize(new java.awt.Dimension(500, 500));
DynamicPanel.setPreferredSize(new java.awt.Dimension(700, 500));
javax.swing.GroupLayout DynamicPanelLayout = new javax.swing.GroupLayout(DynamicPanel);
DynamicPanel.setLayout(DynamicPanelLayout);
DynamicPanelLayout.setHorizontalGroup(
DynamicPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 700, Short.MAX_VALUE)
);
DynamicPanelLayout.setVerticalGroup(
DynamicPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 500, Short.MAX_VALUE)
);
getContentPane().add(DynamicPanel);
DynamicPanel.setBounds(330, 260, 700, 500);
MSbuy.setText("Buy");
MSbuy.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MSbuyActionPerformed(evt);
}
});
getContentPane().add(MSbuy);
MSbuy.setBounds(70, 480, 188, 29);
MSQuotation.setText("Quotation");
MSQuotation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MSQuotationActionPerformed(evt);
}
});
getContentPane().add(MSQuotation);
MSQuotation.setBounds(70, 520, 188, 29);
MSReserve.setText("Reserve");
MSReserve.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MSReserveActionPerformed(evt);
}
});
getContentPane().add(MSReserve);
MSReserve.setBounds(70, 440, 188, 29);
MSSalCom.setText("Salaries & Commission");
MSSalCom.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MSSalComActionPerformed(evt);
}
});
getContentPane().add(MSSalCom);
MSSalCom.setBounds(70, 400, 188, 29);
MSReport.setText("Report");
MSReport.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MSReportActionPerformed(evt);
}
});
getContentPane().add(MSReport);
MSReport.setBounds(70, 560, 187, 29);
MSCreateNew.setText("Create New User");
MSCreateNew.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MSCreateNewActionPerformed(evt);
}
});
getContentPane().add(MSCreateNew);
MSCreateNew.setBounds(70, 600, 187, 29);
jLabel1.setFont(new java.awt.Font("Lucida Grande", 0, 48)); // NOI18N
jLabel1.setForeground(new java.awt.Color(0, 0, 204));
jLabel1.setText("ROUTE66 CAR DEALERSHIP");
getContentPane().add(jLabel1);
jLabel1.setBounds(330, 0, 650, 130);
jLabel3.setText(".");
getContentPane().add(jLabel3);
jLabel3.setBounds(0, 0, 330, 260);
jLabel2.setText(".");
getContentPane().add(jLabel2);
jLabel2.setBounds(330, 90, 650, 210);
pack();
}// </editor-fold>
private void MSbuyActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
b.setVisible(false);
buyR.setVisible(true);
brep.setVisible(false);
cusD.setVisible(false);
QP.setVisible(false);
RP.setVisible(false);
NW.setVisible(false);
SalCom.setVisible(false);
SalS.setVisible(false);
}
private void MSSalComActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
b.setVisible(false);
buyR.setVisible(false);
brep.setVisible(false);
cusD.setVisible(false);
QP.setVisible(false);
RP.setVisible(false);
NW.setVisible(false);
SalCom.setVisible(true);
SalS.setVisible(false);
}
private void MSReserveActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
b.setVisible(false);
buyR.setVisible(false);
brep.setVisible(false);
cusD.setVisible(false);
QP.setVisible(false);
RP.setVisible(true);
NW.setVisible(false);
SalCom.setVisible(false);
SalS.setVisible(false);
}
private void MSQuotationActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void MSReportActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void MSCreateNewActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #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(ManagerScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ManagerScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ManagerScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ManagerScreen.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 ManagerScreen().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel DynamicPanel;
private javax.swing.JButton MSCreateNew;
private javax.swing.JButton MSQuotation;
private javax.swing.JButton MSReport;
private javax.swing.JButton MSReserve;
private javax.swing.JButton MSSalCom;
private javax.swing.JButton MSbuy;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
// End of variables declaration
}
My problem is that the BR panel (buyReserve()), containing two buttons - within the JFrame, is supposed to be able to call either the buy panel or brep panel (BuyReport()) from the within the DynamicPanel() or at least thats what I think, if that makes sense.
so basically I've tried somethings including the following:
package route66.pannels;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import route66.pannels.BuyReport;
import route66.pannels.CustomerDetails;
/**
*
* #author Vavu
*/
public class BuyReserve extends javax.swing.JPanel {
GridBagLayout layout = new GridBagLayout();
Buy BuyPanel = new Buy();
Buy b = new Buy();
BuyReserve buyR = new BuyReserve();
BuyReport brep = new BuyReport();
CustomerDetails cusD = new CustomerDetails();
QuotPanel QP = new QuotPanel();
ReportPanel RP = new ReportPanel();
NewUser NW = new NewUser();
Salaries_Com SalCom = new Salaries_Com();
SaleSucces SalS = new SaleSucces();
/**
* Creates new form BuyReserve
*/
public BuyReserve() {
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() {
btnBuy = new javax.swing.JButton();
btnReserve = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
btnBuy.setText("New Client");
btnBuy.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBuyActionPerformed(evt);
}
});
btnReserve.setText("Reserve Client");
jLabel1.setText("Select Option");
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(144, 144, 144)
.addComponent(btnBuy)
.addGap(35, 35, 35)
.addComponent(btnReserve))
.addGroup(layout.createSequentialGroup()
.addGap(230, 230, 230)
.addComponent(jLabel1)))
.addContainerGap(162, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(62, 62, 62)
.addComponent(jLabel1)
.addGap(72, 72, 72)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnBuy)
.addComponent(btnReserve))
.addContainerGap(201, Short.MAX_VALUE))
);
}// </editor-fold>
private void btnBuyActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
b.setVisible(true);
}
// Variables declaration - do not modify
private javax.swing.JButton btnBuy;
private javax.swing.JButton btnReserve;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
If I run the ManagerScreen with the inclusion of the second code snippet I get an error. I've also tried other types of code that end up saying things like the jpanel doesn't have a main class n so on.
So, hopefully by this stage I've been able to get my point across to be to able ask (again); how do I call a panel, within a panel that is inside a JFrame?
You state that you want to "call" JPanels, but this doesn't really have any meaning. If your goal is to swap JPanel views, then the simplest and easiest way is to use a CardLayout. For more on this useful tool, please see the CardLayout Tutorial.
For example:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class ManagerPanel extends JPanel {
private CardLayout cardLayout = new CardLayout();
private JPanel cardLayoutPanel = new JPanel(cardLayout);
private BuyPanel buyPanel = new BuyPanel(this);
private BuyReportPanel buyReportPanel = new BuyReportPanel(this);
private DefaultComboBoxModel<String> comboModel = new DefaultComboBoxModel<>();
private JComboBox<String> panelComboBox = new JComboBox<>(comboModel);
public ManagerPanel() {
comboModel.addElement(BuyPanel.BUY);
comboModel.addElement(BuyReportPanel.BUY_REPORT);
panelComboBox.addActionListener(evt -> {
String key = panelComboBox.getSelectedItem().toString();
cardLayout.show(cardLayoutPanel, key);
});
JPanel comboPanel = new JPanel();
comboPanel.add(panelComboBox);
cardLayoutPanel.add(buyPanel, BuyPanel.BUY);
cardLayoutPanel.add(buyReportPanel, BuyReportPanel.BUY_REPORT);
setLayout(new BorderLayout());
add(cardLayoutPanel, BorderLayout.CENTER);
add(comboPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
ManagerPanel mainPanel = new ManagerPanel();
JFrame frame = new JFrame("ManagerPanel");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
public void nextPanel() {
cardLayout.next(cardLayoutPanel);
}
}
class BuyReportPanel extends JPanel {
public final static String BUY_REPORT = "Buy Report";
private ManagerPanel managerPanel;
public BuyReportPanel(ManagerPanel managerPanel) {
this.managerPanel = managerPanel;
add(new JLabel(BUY_REPORT), SwingConstants.CENTER);
add(new JButton(new NextPanelAction(managerPanel)));
}
}
class BuyPanel extends JPanel {
public final static String BUY = "Buy";
private ManagerPanel managerPanel;
public BuyPanel(ManagerPanel managerPanel) {
setPreferredSize(new Dimension(400, 300));
this.managerPanel = managerPanel;
add(new JLabel(BUY), SwingConstants.CENTER);
add(new JButton(new NextPanelAction(managerPanel)));
}
}
class NextPanelAction extends AbstractAction {
private ManagerPanel managerPanel;
public NextPanelAction(ManagerPanel managerPanel) {
super("Next Panel");
this.managerPanel = managerPanel;
}
#Override
public void actionPerformed(ActionEvent e) {
managerPanel.nextPanel();
}
}
Note that I've passed my main class, here ManagerPanel, into other classes, and so they can call any of its public methods including nextPanel(), as needed.
public class NewClass extends javax.swing.JFrame {
/**
* Creates new form NewClass
*/
public NewClass() {
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() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton1.setText("jButton1");
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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(82, 82, 82)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 583, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(285, 285, 285)
.addComponent(jButton1)))
.addContainerGap(60, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(39, Short.MAX_VALUE)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 506, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #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(NewClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewClass.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 NewClass().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
Guys this is the first time I try to create a GUI from Netbeans generator, there is not compilation error but nothing shows pops up. This is not my code is the code auto generated after creating the design part. However I tried manually same no compilation error but nothing pops up
/*
* 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 assigment1;
import java.awt.*;
import javax.swing.*;
public class RectangleProgram extends JFrame
{
private static final int WIDTH = 400;
private static final int HEIGHT = 300;
private JLabel lengthL, widthL, areaL, perimeterL;
private JTextField lengthTF, widthTF, areaTF, perimeterTF;
private JButton calculateB, exitB;
public RectangleProgram()
{
//Instantiate the labels:
lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
areaL = new JLabel("Area: ", SwingConstants.RIGHT);
perimeterL = new JLabel("Perimeter: ", SwingConstants.RIGHT);
//Text fields next:
lengthTF = new JTextField(10);
widthTF = new JTextField(10);
areaTF = new JTextField(10);
perimeterTF = new JTextField(10);
//Buttons too:
calculateB = new JButton("Calculate");
exitB = new JButton("Exit");
//Set the window's title.
setTitle("Sample Title: Area of a Rectangle");
//Get the content pane (CP).
Container pane = getContentPane();
//Set the layout.
pane.setLayout(new GridLayout(5, 2));
//Other JFrame stuff.
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
This is another example code that wont pop up or show any error message, this is the first time that a use NetBeans in this computer, is a new Computer by the way.
What to do :(.
I am trying to write a Java program which, when you click a button, hides the button and displays an image. I have made it so that the button disappears but the label does not appear. Here is my code:
final JLabel label = new JLabel(image, JLabel.CENTER);
label.setAlignmentX(0);
label.setAlignmentY(0);
label.setVisible(false);
label.setIcon(image);
final JButton button = new JButton("CLICK");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
button.setVisible(false);
label.setVisible(true);
}
});
The solution is to place both the button and the label on the same panel. Initially hide the label. Then, when button is clicked, hide button and unhide the label.
Here is an example:
public class MagicButton {
public static void main(String[] args) {
// Components
final JFrame frame = new JFrame("Magic Button");
final JButton btn = new JButton("Now, you see me!");
final JLabel label = new JLabel("Now, you don't!");
// Arrangement
frame.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
frame.add(label);
frame.add(btn);
// Make Label invisible
label.setVisible(false);
// When button clicked: hide button, show label, repack frame
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btn.setVisible(false);
label.setVisible(true);
frame.pack();
}
});
// pack and display
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Place all items on a JFrame and do a revalidate() on the JFrame to get the changes displayed.
Try this one...
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
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() {
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton1MouseClicked(evt);
}
});
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/1371634490.png"))); // NOI18N
jLabel1.setText("jLabel1");
jLabel1.setVisible(false);
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()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(159, 159, 159))
.addGroup(layout.createSequentialGroup()
.addGap(148, 148, 148)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(120, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(48, 48, 48)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(91, 91, 91))
);
pack();
}// </editor-fold>
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
jLabel1.setVisible(true);
jButton1.setVisible(false);
}
/**
* #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(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.JButton jButton1;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
I'm dynamically generating some text boxes and labels inside a JPanel but when I place that panel inside a JTabbedPane it's not generate inside its original location. it always go to somewhere else.
Code inside JFrame class constructor:
panel = jPanel1;
panel.setLayout(new FlowLayout());
add(panel, BorderLayout.LINE_START);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
Code inside a JButton:
JLabel lbl = new JLabel();
lbl.setText("Label");
panel.add(lbl);
JTextField txt = new JTextField(12);
txt.setText("Text field");
panel.add(txt);
panel.revalidate();
validate();
The button is use to generate text boxes and labels dynamically. jPanel1 is a panel placed inside a frame. its works perfectly with directly placed inside a frame but after it is placed inside a tabbed pane it's messing around.
Is there a method to refresh panel and remove components inside it after generating components inside it?
here is the complete Jframe class:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author sajithru
*/
public class DynamicTextboxes extends javax.swing.JFrame {
/**
* Creates new form DynamicTextboxes
*/
private JPanel panel;
public DynamicTextboxes() {
initComponents();
panel = jPanel1;
panel.setLayout(new FlowLayout());
add(panel, BorderLayout.LINE_START);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
/**
* 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();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
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)
.addGap(0, 206, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 258, Short.MAX_VALUE)
);
jTabbedPane1.addTab("tab1", jPanel1);
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(190, 190, 190)
.addComponent(jButton1)
.addContainerGap(216, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addContainerGap(40, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JLabel lbl = new JLabel();
lbl.setText("Label");
panel.add(lbl);
JTextField txt = new JTextField(12);
txt.setText("Text field");
panel.add(txt);
panel.revalidate();
validate();
}
/**
* #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(DynamicTextboxes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DynamicTextboxes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DynamicTextboxes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DynamicTextboxes.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 DynamicTextboxes().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JTabbedPane jTabbedPane1;
// End of variables declaration
}
I suspect that you are using setBounds(), or something similar, to position components in a Container that has some (default) layout lying in wait for your call to revalidate(). Instead, invoke pack() on the enclosing Window before calling setVisible().
Addendum: I tried using pack() … but result is still the same.
Your layout is cutting off the new rows. The example below uses pack() to resize the enclosing Window. This related example illustrates revalidate() and repaint(). Also consider using a JScrollPane, seen here.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* #see https://stackoverflow.com/a/17165034/230513
*/
public class DynamicTextboxes extends javax.swing.JFrame {
/**
* Creates new form DynamicTextboxes
*/
public DynamicTextboxes() {
initComponents();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void initComponents() {
jButton1 = new javax.swing.JButton();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel(new GridLayout(0, 1));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(createPanel());
jTabbedPane1.addTab("tab1", jPanel1);
add(jTabbedPane1);
JPanel p = new JPanel();
p.add(jButton1);
add(p, BorderLayout.SOUTH);
pack();
setLocationByPlatform(true);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jPanel1.add(createPanel());
pack();
}
private JPanel createPanel() {
JPanel p = new JPanel();
JLabel lbl = new JLabel();
lbl.setText("Label");
p.add(lbl);
JTextField txt = new JTextField(12);
txt.setText("Text field");
p.add(txt);
return p;
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new DynamicTextboxes().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JTabbedPane jTabbedPane1;
// End of variables declaration
}
I have two forms. First one is to decide numbers of button by using jslider. Second form is to display jbuttons according to jslider value. When i click jbutton2, the second form shows and display buttons. It is working perfectly. However, I want to create jbutton on the second form without clicking jbutton2 in the first form.
Instead, when I change jslider, it should create jbuttons on the second form at the run time and once i change jslider it should create that amount of button again on the second form and refreshing the second form button numbers according to jslider value.
I have tried revalidate();, repaint(); but they do not work, they dont refresh the second form.
So, How can I refresh second form when the jslider ,that is on the first form, changes ? Please help.....
Edit:I am using default Jframe of netbeans....
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
public class NewJFrame7 extends javax.swing.JFrame {
/**
* Creates new form NewJFrame7
*/
public NewJFrame7() {
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() {
jSlider1 = new javax.swing.JSlider();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jSlider1.setMajorTickSpacing(2);
jSlider1.setMaximum(20);
jSlider1.setMinimum(1);
jSlider1.setPaintLabels(true);
jSlider1.setPaintTicks(true);
jSlider1.setToolTipText("");
jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jSlider1StateChanged(evt);
}
});
jButton2.setText("jButton2");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(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()
.addGap(29, 29, 29)
.addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(273, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(262, 262, 262)
.addComponent(jButton2)
.addContainerGap(262, Short.MAX_VALUE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(87, 87, 87)
.addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(168, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(138, 138, 138)
.addComponent(jButton2)
.addContainerGap(139, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>
private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {
// TODO add your handling code here:
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
form2 = true;
new NewJFrame8().setVisible(true);
}
/**
* #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(NewJFrame7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame7.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 NewJFrame7().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton2;
private javax.swing.JSlider jSlider1;
// End of variables declaration
}
2.form
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class NewJFrame8 extends javax.swing.JFrame {
/**
* Creates new form NewJFrame8
*/
public NewJFrame8() {
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() {
jPanel1 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
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()
.addContainerGap(371, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(19, 19, 19))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(48, 48, 48)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(242, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #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(NewJFrame8.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame8.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame8.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame8.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 NewJFrame8().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
One layout constraint (BorderLayout.CENTER) to place them, and one component to appear therein. (With apologies to Tolkien.)
Do check this sample Program, is this what you need. revalidate() and repaint() is what works here for this.
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
public class SliderExample
{
private JSlider slider;
private static final int MIN_BUTTONS = 2;
private static final int SOME_BUTTONS = 4;
private static final int MAX_BUTTONS = 6;
private void createAndDisplayGUI()
{
ButtonPanel bp = new ButtonPanel();
JFrame frame = new JFrame("JSlider Example : ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel contentPane = new JPanel();
slider = new JSlider(JSlider.HORIZONTAL, MIN_BUTTONS, MAX_BUTTONS
, SOME_BUTTONS);
slider.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent ce)
{
int value = (int) slider.getValue();
ButtonPanel.panel.removeAll();
for (int i = 0; i < value; i++)
{
ButtonPanel.panel.add(new JButton("JButton " + i));
}
ButtonPanel.panel.revalidate();
ButtonPanel.panel.repaint();
}
});
contentPane.add(slider);
frame.getContentPane().add(contentPane);
frame.pack();
frame.setVisible(true);
frame.requestFocusInWindow();
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
new SliderExample().createAndDisplayGUI();
}
};
SwingUtilities.invokeLater(runnable);
}
}
class ButtonPanel extends JFrame
{
public static JPanel panel;
public ButtonPanel()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
panel = new JPanel();
panel.setLayout(new GridLayout(0, 2));
getContentPane().add(panel);
setSize(300, 300);
setVisible(true);
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;
public class SliderExample
{
private JSlider slider;
private static final int MIN_BUTTONS = 2;
private static final int SOME_BUTTONS = 4;
private static final int MAX_BUTTONS = 6;
private JButton[] buttonArray;
private ActionListener actionButton = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
System.out.println(button.getText());
}
};
private void createAndDisplayGUI()
{
ButtonPanel bp = new ButtonPanel();
JFrame frame = new JFrame("JSlider Example : ");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel contentPane = new JPanel();
slider = new JSlider(JSlider.HORIZONTAL, MIN_BUTTONS, MAX_BUTTONS
, SOME_BUTTONS);
slider.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent ce)
{
int value = (int) slider.getValue();
ButtonPanel.panel.removeAll();
buttonArray = new JButton[value];
for (int i = 0; i < value; i++)
{
buttonArray[i] = new JButton(String.valueOf(i));
buttonArray[i].addActionListener(actionButton);
ButtonPanel.panel.add(buttonArray[i]);
}
ButtonPanel.panel.revalidate();
ButtonPanel.panel.repaint();
}
});
contentPane.add(slider);
frame.getContentPane().add(contentPane);
frame.pack();
frame.setVisible(true);
frame.requestFocusInWindow();
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
new SliderExample().createAndDisplayGUI();
}
};
SwingUtilities.invokeLater(runnable);
}
}
class ButtonPanel extends JFrame
{
public static JPanel panel;
public ButtonPanel()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
panel = new JPanel();
panel.setLayout(new GridLayout(0, 2));
getContentPane().add(panel);
setSize(300, 300);
setVisible(true);
}
}
For your statement this.buttonArray[i].addActionListener(this);, the reason as to why this is not working, is because, you are inside the object of anonymous class new ChangeListener(), which doesn't have anything named buttonArray[i] inside itself, it's the Instance Variable of SliderExample class, so either place an object of SliderExample class or if you are referring to your code, then use the Object of the class which initializes the array like inside inside NewFrame8 you had written JButton[] buttonArray = new JButton[120];, so use NewFrame8's object instead of this to refer to the buttonArray[i] thingy.