JPanel dynamically generate outside from its original location - java

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
}

Related

Java : load image in jscrollpanne

i have some problem whene i want to load image
1 class :Draw_Image
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;
public class Draw_Image extends Canvas{
BufferedImage image= null;
//Constructeur, prend une image Buffered
public Draw_Image(BufferedImage img){
//copier l'image dans son attribut
image= img;
}
public void paint(Graphics g){
//Peintre le graphique g d e l'image
g.drawImage(image,0,0,this);
}
}
2 class :choose an image and i try to loaded in Jscrollpan(declared in the Main clas)
import java.awt.BorderLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
public class LoadImage extends JPanel{
private String path1;
private String path2;
private String path3;
NewJFrame j;
private JFileChooser parcourir= new JFileChooser();
BufferedImage img = null;
public LoadImage(){
parcourir.showOpenDialog(null);
if(parcourir.showOpenDialog(null)== JFileChooser.APPROVE_OPTION){
//récupérer image à partir du choix de l'utilisateur
String file2= parcourir.getSelectedFile().getPath();
path2= file2;
try {
img = ImageIO.read(new File(file2));
Draw_Image d1= new Draw_Image(img);
//d1.setSize(j.jScrollPane1.getWidth(),j.jScrollPane1.getHeight());
j.jScrollPane1.removeAll();
j. jScrollPane1.add(d1);
add(d1, BorderLayout.CENTER);
}
catch (IOException ex) {
// Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("err");
}
}
}
}
The Main class
public class Main extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public Main() {
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();
jButton_Open_Image = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton_Open_Image.setText("Open");
jButton_Open_Image.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_Open_ImageActionPerformed(evt);
}
});
jButton2.setText("Gray_Scale");
jMenu1.setText("File");
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)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2)
.addComponent(jButton_Open_Image, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
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(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(53, 53, 53)
.addComponent(jButton_Open_Image)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton_Open_ImageActionPerformed(java.awt.event.ActionEvent evt) {
new LoadImage();
}
/**
* #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(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton_Open_Image;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
protected javax.swing.JScrollPane jScrollPane1;
enter image description here
Thanks .
Never use the add(...) method to add a component to a JScrollPane. The component needs to be added to the JViewport of the scroll panel.
This is done automatically when you create a JScrollPane using:
JScrollPane scrollPane = new JScrollPane( someComponent );
or you can use:
scrollPane.setViewportView( someComponent );
If you want to display an image, there is no need to do custom painting. Just add an ImageIcon to a JLabel and add the label to the scroll pane
JLabel label = new JLabel( new ImageIcon(...) );
JScrollPane scrollPane = new JScrollPane( label );
If you do want to do custom painting the DON'T extend Canvas, that is an AWT component. Instead you can extend JPanel. When you extend JPanel you would then need to override paintComponent(...) and implement getPreferredSize() in order to get the scroll pane to work properly.
Read the section from the Swing tutorial on Custom Painting for more information. Keep a link to the tutorial handy for all the Swing basics.
The tutorial also has a section on How to Use Icons you should read.

GUI wont display

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 :(.

Java Hidden JTabbedPane

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);
}
}

JPanel not showing anything

I have a problem with JComponent's inside a JPanel that are not showing up.
I am using Netbeans' Java GUI Builder partially to build the GUI.
I got a MainFrame class which is build with the GUI Builder to take care of menu items.
I got a MainPanel class which is inside the MainFrame class (under the menu bar).
And then I manually add another JPanel to that MainPanel such that I can have full control of the GUI again without Netbeans GUI bothering me.
However when I add a JButton to that JPanel then nothing is showing up.
MainFrame.java (including Netbeans code):
package gui;
import javax.swing.JFrame;
/**
*
* #author Frank
*/
public class MainFrame extends javax.swing.JFrame {
/**
* Creates new form MainFrame
*/
public MainFrame() {
initComponents();
customInit();
}
private void customInit() {
this.setTitle("Trading Card Game");
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
mainPanel1 = new gui.MainPanel();
jMenuBar1 = new javax.swing.JMenuBar();
menuFile = new javax.swing.JMenu();
menuFileQuit = new javax.swing.JMenuItem();
menuPreview = new javax.swing.JMenu();
menuPreviewStart = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout mainPanel1Layout = new javax.swing.GroupLayout(mainPanel1);
mainPanel1.setLayout(mainPanel1Layout);
mainPanel1Layout.setHorizontalGroup(
mainPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
mainPanel1Layout.setVerticalGroup(
mainPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
);
menuFile.setText("File");
menuFileQuit.setText("Quit");
menuFileQuit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuFileQuitActionPerformed(evt);
}
});
menuFile.add(menuFileQuit);
jMenuBar1.add(menuFile);
menuPreview.setText("Preview");
menuPreviewStart.setText("Start");
menuPreview.add(menuPreviewStart);
jMenuBar1.add(menuPreview);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void menuFileQuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuFileQuitActionPerformed
System.exit(0);
}//GEN-LAST:event_menuFileQuitActionPerformed
/**
* #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() {
#Override
public void run() {
new MainFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuBar jMenuBar1;
private gui.MainPanel mainPanel1;
private javax.swing.JMenu menuFile;
private javax.swing.JMenuItem menuFileQuit;
private javax.swing.JMenu menuPreview;
private javax.swing.JMenuItem menuPreviewStart;
// End of variables declaration//GEN-END:variables
}
MainPanel.java (including Netbeans code):
package gui;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import model.Game;
/**
*
* #author Frank
*/
public class MainPanel extends javax.swing.JPanel {
/**
* Creates new form MainPanel
*/
public MainPanel() {
initComponents();
initPanel();
}
private void initPanel() {
this.setBorder(BorderFactory.createLineBorder(Color.yellow));
this.add(new JButton("Test"), BorderLayout.CENTER);
revalidate();
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
setLayout(new java.awt.BorderLayout());
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
The yellow border is showing up around the JPanel though.
Any clue why the JButton with "Test" is not showing up?
Image describing the situation (look no button!):
Regards.
It is because you are overwriting your layout for mainPanel1.
I commented out these lines in MainFrame.java and the test button showed as expected.
// javax.swing.GroupLayout mainPanel1Layout = new javax.swing.GroupLayout(mainPanel1);
// mainPanel1.setLayout(mainPanel1Layout);
// mainPanel1Layout.setHorizontalGroup(
// mainPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
// .addGap(0, 400, Short.MAX_VALUE)
// );
// mainPanel1Layout.setVerticalGroup(
// mainPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
// .addGap(0, 279, Short.MAX_VALUE)
// );

Java refreshing second form

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.

Categories

Resources