I am a Beginner in Java using NetBeans as my IDE...
I am trying to make a custom shaped JFrame that is shaped like the Image I will be creating... I found a solution here and here but I can't figure out how to apply it in Netbeans..
Took me hours and hours of research but to no avail.. So I asked it here hoping someone would enlighten me... I also hope you explain the codes used and how it worked so I would also learn and just copy pasting...
I also hope you explain the codes used and how it worked
That is the benefit of a tutorial. Read the section from the Swing tutorial on How to Create Translucent and Shaped Windows for information and working examples.
I can't figure out how to apply it in Netbeans
Don't use the IDE to generate your code. If you ever switch IDE's then you need to learn a new one. Instead spend the time learning Java/Swing, not the IDE.
After a couple of hours Playing around with NetBeans after reading and watching couple of tutorials I have found, I finally got a simple solution...
Here is the code:
package testPack;
import java.awt.Color;
import javax.swing.*;
import java.awt.Dimension;
/**
*
* #author Karyuu Ouji
*/
public class TestPanel extends javax.swing.JPanel {
/**
* Creates new form TestPanel
*/
public TestPanel() {
initComponents();
this.setPreferredSize(new Dimension(704,182));
this.setOpaque(false);
this.setDoubleBuffered(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();
jLabel1 = new javax.swing.JLabel();
setLayout(null);
jButton1.setText("Close");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
jButton1MouseReleased(evt);
}
});
add(jButton1);
jButton1.setBounds(593, 0, 110, 23);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/testPack/sao.png"))); // NOI18N
jLabel1.setText("jLabel1");
add(jLabel1);
jLabel1.setBounds(0, 0, 704, 180);
}// </editor-fold>
private void jButton1MouseReleased(java.awt.event.MouseEvent evt) {
System.exit(0);
}
public static void main(String[] args) {
JFrame frmMain = new JFrame();
frmMain.setUndecorated(true);
frmMain.setBackground(new Color(0,0,0,0));
frmMain.add(new TestPanel());
frmMain.pack();
frmMain.setLocationRelativeTo(null);
frmMain.setVisible(true);
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
Note: Most of the code are generated by NetBeans
All I did was add a JLabel from the component pallet and set the size of the JPanel and JLabel the same as the image size.
Then I put on the image in the JLabel via the Icon property.
Setting Icon/Image
And here is what it looks like when I run the app.
Running
I hope this will help someone like me in the future... :)
Related
I have the following code where I try to place a JLabel in a custom location on a JFrame.
public class GUI extends JFrame
{
/**
*
* #param args
*/
public static void main(String args[])
{
new GUI();
}
/**
*
*/
public GUI()
{
JLabel addLbl = new JLabel("Add: ");
add(addLbl);
addLbl.setLocation(200, 300);
this.setSize(400, 400);
// pack();
setVisible(true);
}
}
It doesn't seem to be moving to where I want it.
The problem is that the LayoutManager of the panel is setting the location of the label for you.
What you need to do is set the layout to null:
public GUI() {
setLayout(null);
}
This will make it so the frame does not try to layout the components by itself.
Then call setBounds(Rectangle) on the label. Like so:
addLbl.setBounds(new Rectangle(new Point(200, 300), addLbl.getPreferredSize()));
This should place the component where you want it.
However, if you don't have a really great reason to lay out the components by yourself, it's usually a better idea to use LayoutManagers to work in your favor.
Here is a great tutorial on getting started with using LayoutManagers.
If you must go without a LayoutManager here is a good tutorial for going without one.
You put the location code under the frame and it will work but if you want it to work for sure
put the location code in a run while loop. That's what I did to figure it out and it works.
BACKGROUND:-
I am required to make a Swing GUI using Netbeans GUI Builder. The first sub-task is to display an image in the entire background.
I have followed a tutorial to get that done. I have basically made a JFrame, set its layout to GridBagLayout and then added a transparent (by unchecking the opaque property) JPanel to it. (Question 1)
After that I added a JLabel to the JFrame, Removed its text and added an image to it. (Question 2)
QUESTIONS:-
First, when I add the JPanel, it does not show its resize handles. I
Googled a bit and found this tutorial, in which it can be seen
that when they create a JPanel, it automatically shows its resize
handles, which can be dragged to resize it.
But mine doesn't (screenshot below) So is there some property or something which can
be adjusted so that I can resize it? Because my intention is to use
this transparent panels to contain components (buttons etc.) on the
background, so it should elapse the entire screen/window/JFrame
parent.
Second, since the image I am using has some 1024x768 dimensions, so
it appears to be way bigger than its parent components.
Since I am a noob and I am not sure if the size of the background
image needs to be adjusted by somehow measuring the pixel width and
pixel height of the parent and then converting the actual image's
size to that size in some program like Adobe Photoshop. But I am
sure there must a more practical way to do that.
I want the image to automatically resize itself according to the size of the parent when it is initially placed on on its parent
JLabel. How can I do that? Please tell me the easiest way,
preferably in the GUI Builder.
I also want to ensure that the image size, its parent JLabel's size, JPanel's size will all adjust to the frame when the I change the size of the window later when using this application, or if there is a way to disable the sizing of the window completely.
EDIT1 #Braj
/*
* 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 com.dev_nna.dbp;
public class JFrameParent extends javax.swing.JFrame {
/**
* Creates new form JFrameParent
*/
public JFrameParent() {
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();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.GridBagLayout());
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
getContentPane().add(jPanel1, new java.awt.GridBagConstraints());
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/dev_nna/dbp/scheduler/resources/Abstract-white-and-blue-backgrounds.jpg"))); // NOI18N
jLabel1.setText("jLabel1");
getContentPane().add(jLabel1, new java.awt.GridBagConstraints());
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(JFrameParent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JFrameParent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JFrameParent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JFrameParent.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 JFrameParent().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
" or if there is a way to disable the sizing of the window completely."
You can set the resizable property of the frame to false. From NetBeans GUI Builder
Highlight/select the frame component from the design view, or from the navigator window.
Go to the properties window on the right and look for the property resizable and make sure it's unchecked
"I also want to ensure that the image size, its parent JLabel's size, JPanel's size will all adjust to the frame when the I change the size of the window"
One way is to paint the background onto the background panel, instead of using a label with an icon. You can see an example of that here. For the GUI Builder, the easiest way (without having to edit the auto-generated code, which I don't recommend, if you don't know what you are doing) is to use a JPanel form instead of a JFrame form. Paint on the JPanel form, then you can add that JPanel form to the JFrame form. You can see here for an easy way to add the JPanel form to the JFrame form.
See Performing Custom Painting to learn more about painting
Can also have a look at this StretchIcon that you can use with a label.
UPDATE
So your JPanel form class will ultimately look something like this
public class PanelForm extends javax.swing.JPanel {
private BufferedImage image;
public PanelForm() {
try {
image = ImageIO.read(getClass().getResource("/path/to/image/png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JFrame frame = new JFrame();
frame.add(new PanelForm()); // <--- add it here
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
ContainerPanel is a custom JPanel class using a BorderLayout. The SOUTH contains a JPanel with a button. I want the CENTER to be an instance of another custom JPanel, say AbstractPanel, which provides an abstract method which will be called when the button is clicked. I also want to set this JPanel programmatically (at run-time). So far, I can do all of this as you can see in the following code (some of which is generated by the NetBeans GUI Builder):
package jpaneldemo;
import java.awt.BorderLayout;
public class ContainerPanel extends javax.swing.JPanel {
public ContainerPanel() {
initComponents();
}
public ContainerPanel(AbstractPanel abPanel) {
initComponents();
this.abPanel = abPanel;
this.add(this.abPanel, BorderLayout.SOUTH);
}
/**
* 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")
private void initComponents() {
buttonPanel = new javax.swing.JPanel();
okButton = new javax.swing.JButton();
setLayout(new java.awt.BorderLayout());
okButton.setText("OK");
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
buttonPanel.add(okButton);
add(buttonPanel, java.awt.BorderLayout.PAGE_END);
}
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {
this.abPanel.abstractMethod();
}
// Variables declaration - do not modify
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton okButton;
// End of variables declaration
private AbstractPanel abPanel = null;
}
I also created the AbstractPanel class:
package jpaneldemo;
public abstract class AbstractPanel extends javax.swing.JPanel {
public AbstractPanel() {
initComponents();
}
protected abstract void abstractMethod();
/**
* 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")
private void initComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.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)
);
}
// Variables declaration - do not modify
// End of variables declaration
}
Now I want to create subclasses of this AbstractPanel class which I can edit in the NetBeans GUI. Typically, I right-click on a package name in the Projects window and then navigate to "New -> JPanel..." to create a custom JPanel. How do I get AbstractPanel to appear in the "New" menu so that I can edit the new class with the NetBeansGUI Builder? Or is there another way to accomplish the same thing?
If your intention is to provide a "template" component that can then be added to the palette and included in other containers, then yes you can.
Have a read through FaqFormCustomContainerBean
The basic idea (apart from creating a BeanDescriptor is you will need to provide a "content" panel of some kind, where additional content can be added at design time.
Now, if you're interested in providing a custom template, that's something I've not done before.
You could try reading through http://netbeans.org/competition/win-with-netbeans/customize-java-template.html. It may be a little out of date, but might help you in the right direction
So recently I've started learning some Java , I've had experience in other languages (mostly web oriented ones like PHP , HTML etc. ) . So I started with some small project to like simple launcher / desktop overlay. Based on JPanel and here it started to get problematic .
I wanted to achieve something like windows 7 task-bar with applications that I can pin onto. So I started to look around for way to look for "extracting" icon from exe file into Java. Found some topic on this site most of the answers is just URL to this site.
All of these work but the problem is , when I call for these functions (like getSystemIcon) it makes all panels above (parents ) disappear. I can get all of them back by repainting , but is there another solution to that or I'm just doing something wrong?
Code:
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Graphics;
import java.io.File;
import javax.swing.Icon;
import javax.swing.JPanel;
import javax.swing.filechooser.FileSystemView;
public class Startbar extends JPanel{
private static final long serialVersionUID = 1L;
Config cfg = new Config();
public Startbar() {
setPreferredSize(new Dimension(cfg.Resx,35));
setBounds(0,1015,cfg.Resx,35);
setVisible(true);
this.setLayout(null);
StartbarClock clock = new StartbarClock();
clock.setBounds(cfg.Resx-135,0, 135, 35);
this.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
add(clock);
AddPins();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.fillRect(0, 0, cfg.Resx, 35);
repaint();
}
public void AddPins(){
String filename = "C:/Program Files (x86)/Skype/Phone/Skype.exe";
Icon ico = FileSystemView.getFileSystemView().getSystemIcon(new File(filename));
System.out.println(ico.getIconHeight());
}
}
EDIT :
After adding timeout of 1 sec to the function everything works as it should ... wtf ?
Some code :
public class Startbar extends JPanel{
ActionListener listener = new ActionListener(){
public void actionPerformed(ActionEvent event){
pin();
}
};
Timer timer = new Timer(1000 ,listener);
private static final long serialVersionUID = 1L;
Config cfg = new Config();
public Startbar() {
setPreferredSize(new Dimension(cfg.Resx,35));
setBounds(0,1015,cfg.Resx,35);
setVisible(true);
setBackground(Color.black);
this.setLayout(null);
StartbarClock clock = new StartbarClock();
add(clock);
timer.start();
//pin();
}
public void pin(){
String filename = "C:/Program Files (x86)/Skype/Phone/Skype.exe";
FileSystemView view = FileSystemView.getFileSystemView();
Icon icon = view.getSystemIcon(new File(filename));
System.out.println(icon.getIconHeight());
timer.stop();
}
}
For what you are trying to do, set StartBar's background to black, then you don't need to overwrite paintComponet.
Don't set StartBar's bounds, use set/getPreferredSize instead. This will allow the parent container the oppurtunity to calculate the best size for the component (which might explain your problem)
You seriously should conisder the use of layout managers.
I'd have two child panels (content & task). I'd place all the application icons in the content, probably with a flow layout & the clock as/in the task, again, probably using a flow layout. Then I'd use either a grid bag layout or a border layout to add them to the task bar panel.
It might not seem like it, but ts going to make your life so much easier in the long run
UPDATE
Okay, then please explain to me why mine works then:
And look, no need to override paintComponent or repaint in sight.
public class TaskBarPane extends javax.swing.JPanel {
/**
* Creates new form TaskBarPane
*/
public TaskBarPane() {
initComponents();
setPreferredSize(new Dimension(800, 24));
pinTask(new File("C:/Program Files/BabyCounter/BabyCounter x64.exe"));
}
protected void pinTask(File task) {
pnlContent.add(new TaskPane(task));
}
/**
* 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() {
pnlContent = new javax.swing.JPanel();
pnlClock = new test.ClockPane();
setBackground(new java.awt.Color(0, 0, 0));
setLayout(new java.awt.BorderLayout());
pnlContent.setOpaque(false);
java.awt.FlowLayout flowLayout1 = new java.awt.FlowLayout(java.awt.FlowLayout.LEFT);
flowLayout1.setAlignOnBaseline(true);
pnlContent.setLayout(flowLayout1);
add(pnlContent, java.awt.BorderLayout.CENTER);
pnlClock.setOpaque(false);
add(pnlClock, java.awt.BorderLayout.EAST);
}// </editor-fold>
// Variables declaration - do not modify
private test.ClockPane pnlClock;
private javax.swing.JPanel pnlContent;
// End of variables declaration
}
..
public class ClockPane extends javax.swing.JPanel {
/**
* Creates new form ClockPane
*/
public ClockPane() {
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() {
java.awt.GridBagConstraints gridBagConstraints;
jLabel1 = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Hello World");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 100;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 8);
add(jLabel1, gridBagConstraints);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
..
public class TaskPane extends javax.swing.JPanel {
/**
* Creates new form TaskPane
*/
public TaskPane() {
initComponents();
}
public TaskPane(File task) {
this();
Icon ico = FileSystemView.getFileSystemView().getSystemIcon(task);
lblIcon.setIcon(ico);
}
/**
* 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() {
lblIcon = new javax.swing.JLabel();
setOpaque(false);
setLayout(new java.awt.GridBagLayout());
lblIcon.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblIcon.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
lblIcon.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
add(lblIcon, new java.awt.GridBagConstraints());
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JLabel lblIcon;
// End of variables declaration
}
...
public class TestFrame extends javax.swing.JFrame {
/**
* Creates new form TestFrame
*/
public TestFrame() {
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() {
pnlTaskBar = new test.TaskBarPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().add(pnlTaskBar, java.awt.BorderLayout.CENTER);
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 {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TestFrame.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 TestFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private test.TaskBarPane pnlTaskBar;
// End of variables declaration
}
It took me 10 mins to put together (had to feed my 11 week old daughter, sorry)
I added System.out.println("inRepaint") into your paintComponent method and ran the code...
16
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
inRepaint
...
My CPU usage ramped up to 85% before I killed it.
When I took it out, I got 4-5 as I resized the window with a cpu of around 7% before it went back to 1%
So, yeah, your code broke.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Does anyone know how to work with the Card Layout in the NetBeans GUI builder tool? I want to show panels as per the JRadioButton selection, so I want to lay this out using the Card Layout.
card.next(yourPanel); will loop through all the components in your mainpanel then come to first one. To show a component with your own desire try following (think if there are 5 components and you are on the 2 and want to show first then you have to go through rest of all in the Vincent Ramdhanie's example, JRL's answer is good according to that gives a quick jump to one you want, but here is another way.
import javax.swing.JLabel;
import javax.swing.JPanel;
public class myJFrame extends javax.swing.JFrame {
private JPanel panel1, panel2;
/**
* Creates new form myJFrame
*/
public myJFrame() {
initComponents();
panel1=new JPanel();
panel2=new JPanel();
JLabel lb1=new JLabel("This is panel 1");
JLabel lb2=new JLabel("This is panel 2");
panel1.add(lb1);
panel2.add(lb2);
//make more if you want
// contentPanel.add(panel1);//show any of the panel first
}
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
buttonPanel1 = new javax.swing.JButton();
buttonPanel2 = new javax.swing.JButton();
contentPanel = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
buttonPanel1.setText("Panel 1");
buttonPanel1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonPanel1ActionPerformed(evt);
}
});
buttonPanel2.setText("Panel 2");
buttonPanel2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonPanel2ActionPerformed(evt);
}
});
....
}
private void buttonPanel2ActionPerformed(java.awt.event.ActionEvent evt) {
contentPanel.removeAll();
contentPanel.add(panel2);
contentPanel.repaint();
contentPanel.revalidate();
}
private void buttonPanel1ActionPerformed(java.awt.event.ActionEvent evt) {
contentPanel.removeAll();
contentPanel.add(panel1);
contentPanel.repaint();
contentPanel.revalidate();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new myJFrame().setVisible(true);
}
});
}
private javax.swing.JButton buttonPanel1;
private javax.swing.JButton buttonPanel2;
private javax.swing.JPanel contentPanel;
private javax.swing.JPanel jPanel1;
}
This way is used when you have a tree and show a panel or component on a tree selection. It shows directly that component. On the tree add a value change listener and get the selection item and show appropriate panel.