I have created JToolBar (Java Swing). I have set a Background image on frame which contains JToolBar. I want my JToolBar to be transparent so that the image kept on frame should be visible. I am using setOpaque(false) but it is not having any effect on my toolbar.. Has anyone delt with this before? My Code is as follows
import javax.swing.ImageIcon;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class NewJFrame extends javax.swing.JFrame {
static NewJFrame dialog = null;
/** Creates new form NewJFrame */
public NewJFrame() {
initComponents();
jToolBar1.setOpaque(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() {
jToolBar1 = new javax.swing.JToolBar();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jToolBar1.setRollover(true);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(275, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
try {
// Set cross-platform Java L&F (also called "Metal")
UIManager.setLookAndFeel(UIManager.
getSystemLookAndFeelClassName());
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ImagePanel panel = new ImagePanel(new ImageIcon("image").getImage());
dialog = new NewJFrame();
dialog.getContentPane().add(panel);
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JToolBar jToolBar1;
// End of variables declaration
}
JToolBar creates JButtons to contain the actions you set on it. By default, JButtons are opaque. To get the effect you're describing, you need to override JToolBar.createActionComponent.
For example:
jToolBar1 = new javax.swing.JToolBar() {
#Override
protected JButton createActionComponent(Action a) {
JButton jb = super.createActionComponent(a);
jb.setOpaque(false);
return jb;
}
};
Note: YMMV depending on the LAF in use.
Related
I'm trying to add this JPanel to JFrame but I can't see him.
When I create new java class and make this frame myself everything's okay.
Code from JFrame form.
public class MainFrame extends javax.swing.JFrame
{
/**
* Creates new form MainFrame
*/
public MainFrame()
{
this.getContentPane().add(firstPanel);
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()
{
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)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, 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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new MainFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
FirstPanel firstPanel = new FirstPanel();
}
Code from JPanel:
public class FirstPanel extends javax.swing.JPanel
{
/**
* Creates new form FirstPanel
*/
public FirstPanel()
{
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();
setBackground(new java.awt.Color(0, 0, 0));
jButton1.setText("jButton1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(164, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(155, 155, 155))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(129, 129, 129)
.addComponent(jButton1)
.addContainerGap(145, Short.MAX_VALUE))
);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration
}
Code from Java class.
public class mainn extends JFrame
{
public mainn()
{ this.setSize(700,600);
this.getContentPane().add(firstPanel);
}
FirstPanel firstPanel = new FirstPanel();
public static void main(String args[])
{
java.awt.EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new mainn().setVisible(true);
}
});
}
}
I can't figure out where's the difference. Can somebody help me?
You also have to call setVisible(true) on your JPanel.
How can I dispose JFrame from another class? My code is listed below.
I use Netbeans generate form for generate window. And I want dispose using another class(name is needDispose).
public class needDispose {
/**
*Call for dispose frame
*/
public static void disposeMyFrame(){
myEasyFrame.getMainFrame.dispose(); // DOESNT WORK
}
}
NETBEANS GENERATE
(important method is getMainFrame() )
import javax.swing.JFrame;
public class myEasyFrame extends javax.swing.JFrame {
/*
* Get frame
*/
public final JFrame getMainFrame() {
return this;
}
/**
* Creates new form myEasyFrame
*/
public myEasyFrame() {
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();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("CLICK");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
needDispose.disposeMyFrame();
}
/**
* #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(myEasyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(myEasyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(myEasyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(myEasyFrame.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 myEasyFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration
}
Here is an example of how to dispose a JFrame from another class which itself is a JFrame:
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Demo
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
FrameA one = new FrameA();
FrameB two = new FrameB(one);
one.setVisible(true);
two.setVisible(true);
}
});
}
}
class FrameA extends JFrame
{
private static final long serialVersionUID = 1812279930292019387L;
public FrameA()
{
super("Frame A");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLocationRelativeTo(null);
setResizable(false);
}
}
class FrameB extends JFrame
{
private static final long serialVersionUID = 5126089271972476434L;
public FrameB(final JFrame otherFrame)
{
super("Frame B");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLayout(new GridBagLayout());
setLocationRelativeTo(otherFrame);
JButton button = new JButton("Dispose Other");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
otherFrame.dispose();
}
});
add(button);
setResizable(false);
}
}
I'm trying to use JSlider for the first time and I tried consulting How to Use Sliders to learn the basics.
But when I try to make the ticks appear like this:
sliderInterior = new JSlider(JSlider.HORIZONTAL,-100,100,0);
sliderInterior.setMinorTickSpacing(5);
sliderInterior.setMajorTickSpacing(10);
sliderInterior.setPaintTicks(true);
The ticks just don't appear. What's the problem?
EDIT
Did a SSCCE as requested. The problem remains, a JSlider with no ticks at all.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Interface;
import javax.swing.JOptionPane;
import javax.swing.JSlider;
public class JSliderTicks extends javax.swing.JDialog {
public JSliderTicks(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
slider = new JSlider(JSlider.HORIZONTAL,0,10,5);
slider.setMinorTickSpacing(1);
slider.setMajorTickSpacing(2);
slider.setPaintTicks(true);
JOptionPane.showMessageDialog(null, slider);
setVisible(true);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
slider = new javax.swing.JSlider();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
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(85, 85, 85)
.addComponent(slider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(115, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(117, 117, 117)
.addComponent(slider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(160, 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(JSliderTicks.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JSliderTicks.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JSliderTicks.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JSliderTicks.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
JSliderTicks dialog = new JSliderTicks(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JSlider slider;
// End of variables declaration
}
I only changed the constructor since I'm using JDialog Form and the rest is implemented automatically.
I just noticed, if I use JOptionPane the JSlider works fine but in the JDialog it stays unaltered.
It works just fine in this SSCCE.
import java.awt.*;
import javax.swing.*;
class SliderTicks {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
JSlider sliderInterior = new JSlider(JSlider.HORIZONTAL, -100, 100, 0);
sliderInterior.setMinorTickSpacing(5);
sliderInterior.setMajorTickSpacing(10);
sliderInterior.setPaintTicks(true);
JOptionPane.showMessageDialog(null, sliderInterior);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
What is happening is that you're creating an new JSlider in the consructor, when one is already create in the initComponents and added. Also, the JOptionPane, messes it up also, as a component can only be added to one parent container. I removed the JOptionPane and re-initialization of the JSlider and it works. I also set the minimum, maximum, and value accordingly.
initComponents();
//slider = new JSlider(JSlider.HORIZONTAL,0,10,5);
slider.setMinimum(0);
slider.setMaximum(10);
slider.setValue(5);
slider.setMinorTickSpacing(1);
slider.setMajorTickSpacing(2);
slider.setPaintTicks(true);
//JOptionPane.showMessageDialog(null, slider);
//setVisible(true); <<---- already set visible
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)
// );
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.