• Java Help
    4 replies, posted
Basically I'm trying to remove JComponents (mainly JButtons) using the remove method of Containers, but this doesn't seem to be working for some reason. The only luck I've had so far is using setVisible to hide them, but the problem with this is that if I want to add more JComponents at a later point they won't overlap and I'll have them appearing farther and farther down the applet window.
Works for me [cpp]public static void main(String[] args) { final JFrame frame = new JFrame(); frame.setLayout(new GridLayout(0, 1)); JButton bt = new JButton("Add button"); bt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JButton r = new JButton("Remove me"); r.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.remove((JComponent) e.getSource()); frame.pack(); } }); frame.add(r); frame.pack(); } }); frame.add(bt); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }[/cpp]
Post your code. I've never had problems removing Components. Are you sure you're removing it from the right container? If it's in a JPanel, you have to remove it from that JPanel, not the JFrame.
Well here's basically what's happening with my code, condensed into a few lines: [cpp]public class RemoveTest extends Program { public void init() { JButton asdf = new JButton("asdf"); add (asdf, WEST); remove(asdf); } public static void main (String [] args) { new RemoveTest().start(); } } [/cpp] I would think this should work since RemoveTest itself is the Container that I'm adding the JButton to, but after running the program the button remains in the applet. There's probably some obvious answer I'm overlooking; my Java proficiency is far from good (as you can probably tell by now).
You probably have to repaint the container afterwards. At least that was a problem with my example code. But I just used pack() because it automatically resized the window too.
Sorry, you need to Log In to post a reply to this thread.