Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How does one delete a button?  RSS feed

Avin Sinanan
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello does anyone knwo how to delete a button?
For example consider the following senario -
You have a JFrame, JPanel and a JToolbar attached to the frame
and on the toolbar you have 2 buttons , one when clicked adds a button to the JPanel. The button that is added can move around and if you press the button again another the button is added.
The second button deletes the selected button.
Below I have included the code that addes the button and stuff. Does anyone know how to complete the code that deletes a the selected button on the JPanel? Any help would be greatly appreciated... thanks...
Here is the code -->
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
class DeleteButton
public static int i =0 ;

public static void main(String[] args)

JFrame frame = new JFrame() ;
final JPanel pane = new JPanel();

JToolBar tool = new JToolBar();
JButton addButton = new JButton("Add");
JButton deleteButton = new JButton("Delete");

addButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){

JButton button = new JButton("" + i);
button.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent me) {
me.getComponent().setLocation(me.getComponent().getX() + me.getX(),
me.getComponent().getY() + me.getY());


i++ ;


frame.getContentPane().add("North", tool);

Roy Ben Ami
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
u need to use the remove method found in container.
u can call it from a panel or a frame it doesnt matter.
there r 3 remove methods:
remove(Component n)
remove(int index)
removeAll() removes everything from that panel/frame.
remove(Component e) - for this method u need to pass a refrence to the component u want to remove.
remove(int index) - the best one for u i think, but for this u need to keep an index which has the number of the elemnts u put in the panel (ie. create an int named index and add to it 1 everytime u add a component).
u send to this remove method the number of the index u want to remove (notice that if u put 10 components inside their indexes will be 0 thru 9).

hope it helps u a bit.
Dirk Schreckmann
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Avin,
Here is a link to a previous conversation related to this topic.
Good Luck,
-Dirk Schreckmann
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!