Reputation: 2032
I've read a number of threads and questions about this subject but can't seem to come up to a workable solution to the problem. below is the code for the methods used to add and remove the component.
public void addAuxPanel (String pType, int pStart, int pEnd) {
int id = mPanels.size();
int xPos = PANEL_START_X;
int yPos = PANEL_START_Y + (PANEL_HEIGHT * id) + 15;
if (id == 0) {
xPos = PANEL_START_X;
}
String type = pType;
int start = pStart;
int end = pEnd;
AuxPanel p = new AuxPanel(type, start, end, id, this);
mPanels.add(p);
p.setBounds(xPos, yPos, 300, 25);
getRootPane().add(p);
getRootPane().repaint();
getRootPane().revalidate();
}
public void removeAuxPanel (AuxPanel pPanel) {
getRootPane().remove(pPanel);
getRootPane().revalidate();
getRootPane().repaint();
}
Upvotes: 0
Views: 4918
Reputation: 24616
You can simply do frameObject.remove(yourPanel);
than do your normal revalidate() and repaint().
A small code for your help here :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoPanels extends JFrame {
public TwoPanels() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final JPanel panel1 = new JPanel();
panel1.setBackground(Color.RED);
final JPanel panel2 = new JPanel();
panel2.setBackground(Color.BLUE);
JButton button = new JButton("ADD AND REMOVE PANEL");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (panel1.isShowing()) {
remove(panel1);
add(panel2, BorderLayout.CENTER);
revalidate();
repaint();
} else if (panel2.isShowing()) {
remove(panel2);
add(panel1, BorderLayout.CENTER);
revalidate();
repaint();
}
}
});
add(panel1, BorderLayout.CENTER);
add(button, BorderLayout.PAGE_END);
pack();
setLocationByPlatform(true);
setVisible(true);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TwoPanels();
}
});
}
}
If you wanted to remove a component from the JPanel, see this code remove() still works for this :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoPanels extends JFrame {
public TwoPanels() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final JPanel panel1 = new JPanel();
final JLabel label = new JLabel("I am a JLabel");
panel1.setBackground(Color.WHITE);
panel1.add(label);
JButton button = new JButton("ADD AND REMOVE PANEL");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (label.isShowing()) {
panel1.remove(label);
panel1.revalidate();
panel1.repaint();
} else {
panel1.add(label);
panel1.revalidate();
panel1.repaint();
}
}
});
add(panel1, BorderLayout.CENTER);
add(button, BorderLayout.PAGE_END);
pack();
setLocationByPlatform(true);
setVisible(true);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TwoPanels();
}
});
}
}
Upvotes: 2