Panel listeners

I am probably doing something wrong because most of the listeners are not working for me.
I have a panel.
Inside the panel node I created a node listeners
Inisde the listenrees I added properties for hide, beforehide and show.
When I do on the panel's tabpanel
tabpanel.hideTabStripItem(tabIndex);
tabpanel.hideTabStripItem(tabIndex);
None of the above mentioned events hide, beforehide and show is fired.
What are the expected events to be fired when calling the tabpanel.hideTabStripItem;;;
the listeners seems to be a big mystery for CQ5, I am trying for over a month to find some information, without any luck.
thank you
Nikolas

Does no one have an answer to this?????

Similar Messages

  • Detect Focus transfer between JPanels

    I have an app that has a scrollpane containing a JPanel (A), that contains a bunch of JPanels (B) - each of which contains multiple controls, panels, etc....
    I want to make sure that whichever JPanel (B) has the focus in it, and use the viewPort.scrollToVisible() to make sure that panel is fully displayed.
    So far, the only way I've seen to do that is to add a FocusListener to each and every control and check to see which panel it's in.
    BLECH!
    Is there an easier way?
    I'd really like some kind of listener that is just notified whenever focus transfers between the upper level Panels.

    Thanks to all. Re-read those sections, and came up with this little utility class to do what I needed.
    It listens for focus changes between panels, and notifies a listener of these changes.
    import java.awt.Component;
    import java.awt.KeyboardFocusManager;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.util.ArrayList;
    import javax.swing.JPanel;
    * Tracks the focus for Panels.  If the focus enters or leaves the panel (i.e. focus goes
    * to/from any component in the panel, and from/to anything outside the panel)
    * It notifies any listeners of the event.
    * @author jlussmyer
    public class PanelFocusTracker {
        /** Array of panels we are tracking focus changes for. */
        private JPanel[] panels = new JPanel[0];
        /** Which of our tracked panels currently has the focus */
        private JPanel curFocus = null;
         * Constructor.  Ties into focus handling system.
        public PanelFocusTracker() {
            KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            focusManager.addPropertyChangeListener(
                    new PropertyChangeListener() {
                        @Override
                        public void propertyChange(PropertyChangeEvent e) {
                            String prop = e.getPropertyName();
                            if (("focusOwner".equals(prop)) && ((e.getNewValue()) instanceof Component)) {
                                Component comp = (Component) e.getNewValue();
                                checkForPanelChange(comp);
            return;
         * Check to see if focus going to his component changes which containing
         * panel has the focus.
         * @param comp Component that is gaining focus.
        private void checkForPanelChange(Component comp) {
            JPanel gainPanel = getPanelForComponent(comp);
            if (gainPanel == curFocus) {
                return; // no change, nothing to do.
            if (curFocus != null) {
                notifyListeners(curFocus, false); // This panel lost focus
            if (gainPanel != null) {
                notifyListeners(gainPanel, true); // This panel gained focus
            curFocus = gainPanel;
            return;
         * Finds which of the panels we are tracking contains the given component.
         * @param comp Component to find containing panel for
         * @return Containing Panel, null if it isn't in one of the panels being tracked.
        private JPanel getPanelForComponent(Component comp) {
            JPanel result = null;
            while ((comp != null) && (result == null)) {
                if (isBeingTracked(comp)) {
                    result = (JPanel) comp;
                } else {
                    comp = comp.getParent();
            return result;
         * Checks to see if this is one of the JPanels we are tracking.
         * @param comp Component to check
         * @return true if it's a JPanel that we are tracking.
        private boolean isBeingTracked(Component comp) {
            boolean result = false;
            for (int idx = 0; (idx < panels.length); idx++) {
                if (comp == panels[idx]) {
                    result = true;
                    break;
            return result;
         * Add a panel to the list of panels being tracked for Panel Focus
         * changes.
         * @param panel Panel to track focus for.
        public void addPanel(JPanel panel) {
            // Don't allow the same panel to be added multiple times.
            for (int idx = 0; (idx < panels.length); idx++) {
                if (panel == panels[idx]) {
                    panel = null;
                    break;
            if (panel != null) {
                JPanel[] temp = new JPanel[panels.length + 1];
                System.arraycopy(panels, 0, temp, 0, panels.length);
                temp[panels.length] = panel;
                panels = temp;
            return;
         * Remove a panel from the list of panels being tracked for Panel Focus
         * changes.
         * @param panel Panel to stop tracking focus for.
         * @return true if panel was being tracked, false otherwise.
        public boolean removePanel(JPanel panel) {
            boolean found = false;
            for (int idx = 0; (idx < panels.length); idx++) {
                if (panel == panels[idx]) {
                    found = true;
                    JPanel[] temp = new JPanel[panels.length - 1];
                    if (idx == 0) { // removing first entry
                        if (temp.length > 0) {
                            System.arraycopy(panels, 1, temp, 0, temp.length);
                    } else if (idx == (panels.length - 1)) { // remove last entry
                        System.arraycopy(panels, 0, temp, 0, temp.length);
                    } else { // Remove something in the middle
                        System.arraycopy(panels, 0, temp, 0, idx);
                        System.arraycopy(panels, idx + 1, temp, idx + 1, temp.length - idx);
                    break;
            return found;
         * Remove all JPanels from focus tracking.
        public void removeAllPanels() {
            panels = new JPanel[0];
            curFocus = null;
            return;
         * Interface for listeners to be notified of focus being gained/lost by
         * any of the panels being tracked.
        public interface Listener {
            /** Focus Lost by given panel */
            void panelFocusLost(JPanel panel);
            /** Focus gained by given panel */
            void panelFocusGained(JPanel panel);
        /** Listeners to be notified of Panel Focus changes */
        private ArrayList<Listener> focusListeners = new ArrayList<Listener>();
         * Add a listener to be notified of changes to the Focus for any Panel
         * being tracked.
         * @param listener Listener to be notified for Panel Focus changes.
        public void addListener(Listener listener) {
            focusListeners.add(listener);
            return;
         * Remove a Panel Focus listener.
         * @param listener listener to no longer be notified of Focus changes.
         * @return true if listener found, false otherwise.
        public boolean removeListener(Listener listener) {
            return focusListeners.remove(listener);
         * Notify all registered listeners of a Panel Focus change.
         * @param panel panel that gained/lost focus.
         * @param gained true if focus gained, false if focus lost.
        private void notifyListeners(JPanel panel, boolean gained) {
            Listener[] list = focusListeners.toArray(new Listener[focusListeners.size()]);
            for (int idx = 0; (idx < list.length); idx++) {
                if (gained) {
                    list[idx].panelFocusGained(panel);
                } else {
                    list[idx].panelFocusLost(panel);
            return;
    }

  • Podcast: Listeners also subscribed panel not present

    Hi,
    I have a fortnightly podcast Called Tektronic. http://itunes.apple.com/gb/podcast/tektronic-the-beginning/id486329726
    We have be getting quiet a lot downloads each month but still do not have the 'Listeners also subscribed to' panel on the podcast page.
    Why is this?

    Does no one have an answer to this?????

  • How to combine the menu, frame, panel,button n their action/mouse listeners

    Hi there,
    I have my code below and I wish to make a program in which you have to click somewhere in the window and it will generate either an ellipse or rectangle. I tried to do that by making radio buttons for ellipse and rectangle. So if the user chooses any of the above and clicks somewhere inside the window then it draws that shape on the particular location clicked at. You can also set the color of the shape by clicking onto the color menu (either red,blue or green). But i am unable to implement the mouselistener as i am confused where should i implement it. In the rectangle panel or in constructor. Basically i get confused as to where i should put a particular listener. here is my example below and i compiled it but it doesn't work as required givin me errors.
    Thank You
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.GridLayout;
    import java.awt.Rectangle;
    import java.awt.geom.Rectangle2D;
    import java.awt.geom.Ellipse2D;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.MouseAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.ButtonGroup;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.border.EtchedBorder;
    import javax.swing.border.TitledBorder;
    import javax.swing.JFrame;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.*;
    import javax.swing.JMenu;
    import javax.swing.*;
    import javax.swing.JMenuItem;
    import java.awt.event.MouseEvent;
    import java.util.Random;
    public class A2
    This program tests the MenuFrame.
         public static void main(String[] args)
    A2Frame frame = new A2Frame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.show();
    class A2Frame extends JFrame
    public A2Frame()
    final int DEFAULT_FRAME_WIDTH = 600;
    final int DEFAULT_FRAME_HEIGHT = 600;
    setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT);
    addWindowListener(new WindowCloser());
    // add drawing panel to content pane
    JPanel panel = new RectanglePanel();
    Container contentPane = getContentPane();
    contentPane.add(panel, BorderLayout.CENTER);
    //contentPane.add(controlPanel, BorderLayout.SOUTH);
    // construct menu
    JMenuBar menuBar1 = new JMenuBar();
    setJMenuBar(menuBar1);
    JMenu fileMenu = new JMenu("File");
    menuBar1.add(fileMenu);
    JMenu colourMenu = new JMenu("Colour");
    menuBar1.add(colourMenu);
    JMenu editMenu = new JMenu("Edit");
    menuBar1.add(editMenu);
    //MenuListener listener = new MenuListener();
    JMenuItem newMenuItem = new JMenuItem("New");
    fileMenu.add(newMenuItem);
    newMenuItem.addActionListener(listener);
    JMenuItem exitMenuItem = new JMenuItem("Exit");
    fileMenu.add(exitMenuItem);
    exitMenuItem.addActionListener(listener);
    JMenuItem randomizeMenuItem = new JMenuItem("Randomize");
    editMenu.add(randomizeMenuItem);
    randomizeMenuItem.addActionListener(listener);
    JMenuItem redMenuItem = new JMenuItem("Red");
    colourMenu.add(redMenuItem);
    redMenuItem.addActionListener(listener);
    JMenuItem greenMenuItem = new JMenuItem("Green");
    colourMenu.add(greenMenuItem);
    greenMenuItem.addActionListener(listener);
    JMenuItem blueMenuItem = new JMenuItem("Blue");
    colourMenu.add(blueMenuItem);
    blueMenuItem.addActionListener(listener);
    class MenuListener implements ActionListener
    public void actionPerformed(ActionEvent event)
    // find the menu that was selected
    Object source = event.getSource();
    if (source == exitMenuItem)
    System.exit(0);
    else if (source == newMenuItem)
    panel.reset();
    else if (source == randomizeMenuItem)
    panel.randomize();
    else if (source == redMenuItem)
    panel.setRed();
    else if (source == greenMenuItem)
         panel.setGreen();
    else if (source == blueMenuItem)
              panel.setBlue();
    MenuListener listener = new MenuListener();
    class ChoiceListener implements ActionListener
    public void actionPerformed(ActionEvent event)
    if (rectangleButton.isSelected())
    g2.draw(new Rectangle2D.Double(0,0,5,5));
    else if (ellipseButton.isSelected())
    g2.draw(new Ellipse2D.Double (0,0,5,5));
    rect.repaint();
    ChoiceListener listener2 = new ChoiceListener();
    ControlPanel();
    pack();
    private RectanglePanel panel;
    private class WindowCloser extends WindowAdapter
    public void windowClosing(WindowEvent event)
    System.exit(0);
    public void ControlPanel()
    JPanel shapeGroupPanel = createRadioButtons();
    JPanel controlPanel = new JPanel();
    controlPanel.setLayout(new GridLayout(1, 1));
    controlPanel.add(shapeGroupPanel);
    contentPane.add(controlPanel, BorderLayout.SOUTH);
    public JPanel createRadioButtons()
    JRadioButton rectangleButton = new JRadioButton("Rectangle");
    rectangleButton.addActionListener(listener2);
    JRadioButton ellipseButton = new JRadioButton("Ellipse");
    ellipseButton.addActionListener(listener2);
    rectangleButton.setSelected(true);
    // add radio buttons to button group
    ButtonGroup group = new ButtonGroup();
    group.add(rectangleButton);
    group.add(ellipseButton);
    JPanel panel = new JPanel();
    panel.add(rectangleButton);
    panel.add(ellipseButton);
    panel.setBorder (new TitledBorder(new EtchedBorder(), "Shape"));
    //return panel;
    class RectanglePanel extends JPanel
    public RectanglePanel()
    rect = new Rectangle(0, 0, RECT_WIDTH, RECT_HEIGHT);
    color = Color.white ;
    class ShapeListener implements MouseListener
    public void mousePressed(MouseEvent event)
    int x = event.getX();
    int y = event.getY();
    rect.setLocation(x,y);
    repaint();
    public void mouseClicked(MouseEvent event) {}
    public void mouseEntered(MouseEvent event) {}
    public void mouseExited(MouseEvent event) {}
    public void mouseReleased(MouseEvent event) {}
    ShapeListener listener1 = new ShapeListener();
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setColor(color);
    g2.fill(rect);
    g2.draw(rect);
    public void reset()
    rect.setLocation(0, 0);
    repaint();
    public void randomize()
    Random generator = new Random();
    rect.setLocation(generator.nextInt(getWidth()),generator.nextInt(getHeight()));
    repaint();
    public void setRed()
    color = Color.red;
    repaint();
    public void setGreen()
    color = Color.green;
    repaint();
    public void setBlue()
    color = Color.blue;
    repaint();
    private Rectangle rect;
    private static final int RECT_WIDTH = 20;
    private static final int RECT_HEIGHT = 30;
    private Color color ;
    private Random random;
    public void setShape()
    if (rectangleButton.isSelected())
    g2.draw(new Rectangle2D.Double(0,0,5,5));
    else if (ellipseButton.isSelected())
    g2.draw(new Ellipse2D.Double (0,0,5,5));
    rect.repaint();
    private JRadioButton rectangleButton;
    private JRadioButton ellipseButton;
    private ActionListener listener;
    private JMenuItem exitMenuItem;
    private JMenuItem newMenuItem;
    private JMenuItem redMenuItem;
    private JMenuItem greenMenuItem;
    private JMenuItem blueMenuItem;
    private JMenuItem randomizeMenuItem;
    }

    grammer corrected.
    I posted a program that lays out buttons based on mouse actions on JButton Adding Problem - reply 5. It uses MouseInputAdapter and Container.addMouseListener. It watches for mousePressed and mouseReleased events to get the limits for the button. The same could be used for ellipses.

  • Event listeners on custom panels

    I have a class (C) which extends JPanel, on this i have a textbox. I also have a dialog which i have added class (C) to the container object. I want the textbox on the jPanel to keylisten, so where do i put the event handler? - at the moment i have it in class (C)... and its not being activated.

    A keylistening textbox? You can type in them already if thats what you need. Did you use addKeyListener( ) on the textbox? Are you sure that the textbox has focus?

  • Dragiing entire Panel in Mac

    Hi,
    I am running below given drag and drop program in Windows and Linux it is working fine but i run in Mac entire Panel is moving i am not getting the proper cursors.
    Program is :*
    * This component can operate in two modes. In "draw mode", it allows the user
    * to scribble with the mouse. In "drag mode", it allows the user to drag
    * scribbles with the mouse. Regardless of the mode, it always allows scribbles
    * to be dropped on it from other applications.
    public class ScribbleDragAndDrop extends JComponent implements
    DragGestureListener, // For recognizing the start of drags
    DragSourceListener, // For processing drag source events
    DropTargetListener, // For processing drop target events
    MouseListener, // For processing mouse clicks
    MouseMotionListener // For processing mouse drags
    ArrayList scribbles = new ArrayList(); // A list of Scribbles to draw
    Scribble currentScribble; // The scribble in progress
    Scribble beingDragged; // The scribble being dragged
    DragSource dragSource; // A central DnD object
    boolean dragMode; // Are we dragging or scribbling?
    // These are some constants we use
    static final int LINEWIDTH = 3;
    static final BasicStroke linestyle = new BasicStroke(LINEWIDTH);
    static final Border normalBorder = new BevelBorder(BevelBorder.LOWERED);
    static final Border dropBorder = new BevelBorder(BevelBorder.RAISED);
    /** The constructor: set up drag-and-drop stuff */
    public ScribbleDragAndDrop() {
    // Give ourselves a nice default border.
    // We'll change this border during drag-and-drop.
    setBorder(normalBorder);
    // Register listeners to handle drawing
    addMouseListener(this);
    addMouseMotionListener(this);
    // Create a DragSource and DragGestureRecognizer to listen for drags
    // The DragGestureRecognizer will notify the DragGestureListener
    // when the user tries to drag an object
    dragSource = DragSource.getDefaultDragSource();
    dragSource.createDefaultDragGestureRecognizer(this, // What component
    DnDConstants.ACTION_COPY_OR_MOVE, // What drag types?
    this);// the listener
    // Create and set up a DropTarget that will listen for drags and
    // drops over this component, and will notify the DropTargetListener
    DropTarget dropTarget = new DropTarget(this, // component to monitor
    this); // listener to notify
    this.setDropTarget(dropTarget); // Tell the component about it.
    * The component draws itself by drawing each of the Scribble objects.
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setStroke(linestyle); // Specify wide lines
    int numScribbles = scribbles.size();
    for (int i = 0; i < numScribbles; i++) {
    Scribble s = (Scribble) scribbles.get(i);
    g2.draw(s); // Draw the scribble
    public void setDragMode(boolean dragMode) {
    this.dragMode = dragMode;
    public boolean getDragMode() {
    return dragMode;
    * This method, and the following four methods are from the MouseListener
    * interface. If we're in drawing mode, this method handles mouse down
    * events and starts a new scribble.
    public void mousePressed(MouseEvent e) {
    if (dragMode)
    return;
    currentScribble = new Scribble();
    scribbles.add(currentScribble);
    currentScribble.moveto(e.getX(), e.getY());
    public void mouseReleased(MouseEvent e) {
    public void mouseClicked(MouseEvent e) {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    * This method and mouseMoved() below are from the MouseMotionListener
    * interface. If we're in drawing mode, this method adds a new point to the
    * current scribble and requests a redraw
    public void mouseDragged(MouseEvent e) {
    if (dragMode)
    return;
    currentScribble.lineto(e.getX(), e.getY());
    repaint();
    public void mouseMoved(MouseEvent e) {
    * This method implements the DragGestureListener interface. It will be
    * invoked when the DragGestureRecognizer thinks that the user has initiated
    * a drag. If we're not in drawing mode, then this method will try to figure
    * out which Scribble object is being dragged, and will initiate a drag on
    * that object.
    public void dragGestureRecognized(DragGestureEvent e) {
    // Don't drag if we're not in drag mode
    if (!dragMode)
    return;
    // Figure out where the drag started
    MouseEvent inputEvent = (MouseEvent) e.getTriggerEvent();
    int x = inputEvent.getX();
    int y = inputEvent.getY();
    // Figure out which scribble was clicked on, if any by creating a
    // small rectangle around the point and testing for intersection.
    Rectangle r = new Rectangle(x - LINEWIDTH, y - LINEWIDTH,
    LINEWIDTH * 2, LINEWIDTH * 2);
    int numScribbles = scribbles.size();
    for (int i = 0; i < numScribbles; i++) { // Loop through the scribbles
    Scribble s = (Scribble) scribbles.get(i);
    if (s.intersects(r)) {
    // The user started the drag on top of this scribble, so
    // start to drag it.
    // First, remember which scribble is being dragged, so we can
    // delete it later (if this is a move rather than a copy)
    beingDragged = s;
    // Next, create a copy that will be the one dragged
    Scribble dragScribble = (Scribble) s.clone();
    // Adjust the origin to the point the user clicked on.
    dragScribble.translate(-x, -y);
    // Choose a cursor based on the type of drag the user initiated
    Cursor cursor;
    switch (e.getDragAction()) {
    case DnDConstants.ACTION_COPY:
    cursor = DragSource.DefaultCopyDrop;
    System.out.println(DnDConstants.ACTION_COPY+"....."+cursor);
    break;
    case DnDConstants.ACTION_MOVE:
    cursor = DragSource.DefaultMoveDrop;
    System.out.println(DnDConstants.ACTION_MOVE+"*****"+cursor);
    break;
    default:
    return; // We only support move and copys
    // Some systems allow us to drag an image along with the
    // cursor. If so, create an image of the scribble to drag
    if (dragSource.isDragImageSupported()) {
    Rectangle scribbleBox = dragScribble.getBounds();
    Image dragImage = this.createImage(scribbleBox.width,
    scribbleBox.height);
    Graphics2D g = (Graphics2D) dragImage.getGraphics();
    g.setColor(new Color(0, 0, 0, 0)); // transparent background
    g.fillRect(0, 0, scribbleBox.width, scribbleBox.height);
    g.setColor(Color.black);
    g.setStroke(linestyle);
    g.translate(-scribbleBox.x, -scribbleBox.y);
    g.draw(dragScribble);
    Point hotspot = new Point(-scribbleBox.x, -scribbleBox.y);
    // Now start dragging, using the image.
    e.startDrag(cursor, dragImage, hotspot, dragScribble, this);
    } else {
    // Or start the drag without an image
    e.startDrag(cursor, dragScribble, this);
    // After we've started dragging one scribble, stop looking
    return;
    * This method, and the four unused methods that follow it implement the
    * DragSourceListener interface. dragDropEnd() is invoked when the user
    * drops the scribble she was dragging. If the drop was successful, and if
    * the user did a "move" rather than a "copy", then we delete the dragged
    * scribble from the list of scribbles to draw.
    public void dragDropEnd(DragSourceDropEvent e) {
    if (!e.getDropSuccess())
    return;
    int action = e.getDropAction();
    if (action == DnDConstants.ACTION_MOVE) {
    scribbles.remove(beingDragged);
    beingDragged = null;
    repaint();
    // These methods are also part of DragSourceListener.
    // They are invoked at interesting points during the drag, and can be
    // used to perform "drag over" effects, such as changing the drag cursor
    // or drag image.
    public void dragEnter(DragSourceDragEvent e) {
    public void dragExit(DragSourceEvent e) {
    public void dropActionChanged(DragSourceDragEvent e) {
    public void dragOver(DragSourceDragEvent e) {
    // The next five methods implement DropTargetListener
    * This method is invoked when the user first drags something over us. If we
    * understand the data type being dragged, then call acceptDrag() to tell
    * the system that we're receptive. Also, we change our border as a "drag
    * under" effect to signal that we can accept the drop.
    public void dragEnter(DropTargetDragEvent e) {
    if (e.isDataFlavorSupported(Scribble.scribbleDataFlavor)
    || e.isDataFlavorSupported(DataFlavor.stringFlavor)) {
    e.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
    this.setBorder(dropBorder);
    /** The user is no longer dragging over us, so restore the border */
    public void dragExit(DropTargetEvent e) {
    this.setBorder(normalBorder);
    * This is the key method of DropTargetListener. It is invoked when the user
    * drops something on us.
    public void drop(DropTargetDropEvent e) {
    this.setBorder(normalBorder); // Restore the default border
    // First, check whether we understand the data that was dropped.
    // If we supports our data flavors, accept the drop, otherwise reject.
    if (e.isDataFlavorSupported(Scribble.scribbleDataFlavor)
    || e.isDataFlavorSupported(DataFlavor.stringFlavor)) {
    e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
    } else {
    e.rejectDrop();
    return;
    // We've accepted the drop, so now we attempt to get the dropped data
    // from the Transferable object.
    Transferable t = e.getTransferable(); // Holds the dropped data
    Scribble droppedScribble; // This will hold the Scribble object
    // First, try to get the data directly as a scribble object
    try {
    droppedScribble = (Scribble) t
    .getTransferData(Scribble.scribbleDataFlavor);
    } catch (Exception ex) { // unsupported flavor, IO exception, etc.
    // If that doesn't work, try to get it as a String and parse it
    try {
    String s = (String) t.getTransferData(DataFlavor.stringFlavor);
    droppedScribble = Scribble.parse(s);
    } catch (Exception ex2) {
    // If we still couldn't get the data, tell the system we failed
    e.dropComplete(false);
    return;
    // If we get here, we've got the Scribble object
    Point p = e.getLocation(); // Where did the drop happen?
    droppedScribble.translate(p.getX(), p.getY()); // Move it there
    scribbles.add(droppedScribble); // add to display list
    repaint(); // ask for redraw
    e.dropComplete(true); // signal success!
    // These are unused DropTargetListener methods
    public void dragOver(DropTargetDragEvent e) {
    public void dropActionChanged(DropTargetDragEvent e) {
    * The main method. Creates a simple application using this class. Note the
    * buttons for switching between draw mode and drag mode.
    public static void main(String[] args) {
    // Create a frame and put a scribble pane in it
    JFrame frame = new JFrame("ScribbleDragAndDrop");
    final ScribbleDragAndDrop scribblePane = new ScribbleDragAndDrop();
    frame.getContentPane().add(scribblePane, BorderLayout.CENTER);
    // Create two buttons for switching modes
    JToolBar toolbar = new JToolBar();
    ButtonGroup group = new ButtonGroup();
    JToggleButton draw = new JToggleButton("Draw");
    JToggleButton drag = new JToggleButton("Drag");
    draw.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    scribblePane.setDragMode(false);
    drag.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    scribblePane.setDragMode(true);
    group.add(draw);
    group.add(drag);
    toolbar.add(draw);
    toolbar.add(drag);
    frame.getContentPane().add(toolbar, BorderLayout.NORTH);
    // Start off in drawing mode
    draw.setSelected(true);
    scribblePane.setDragMode(false);
    // Pop up the window
    frame.setSize(400, 400);
    frame.setVisible(true);
    class Scribble implements Shape, Transferable, Serializable, Cloneable {
    protected double[] points = new double[64]; // The scribble data
    protected int numPoints = 0; // The current number of points
    double maxX = Double.NEGATIVE_INFINITY; // The bounding box
    double maxY = Double.NEGATIVE_INFINITY;
    double minX = Double.POSITIVE_INFINITY;
    double minY = Double.POSITIVE_INFINITY;
    * Begin a new polyline at (x,y). Note the use of Double.NaN in the points
    * array to mark the beginning of a new polyline
    public void moveto(double x, double y) {
    if (numPoints + 3 > points.length)
    reallocate();
    // Mark this as the beginning of a new line
    points[numPoints++] = Double.NaN;
    // The rest of this method is just like lineto();
    lineto(x, y);
    * Add the point (x,y) to the end of the current polyline
    public void lineto(double x, double y) {
    if (numPoints + 2 > points.length)
    reallocate();
    points[numPoints++] = x;
    points[numPoints++] = y;
    // See if the point enlarges our bounding box
    if (x > maxX)
    maxX = x;
    if (x < minX)
    minX = x;
    if (y > maxY)
    maxY = y;
    if (y < minY)
    minY = y;
    * Append the Scribble s to this Scribble
    public void append(Scribble s) {
    int n = numPoints + s.numPoints;
    double[] newpoints = new double[n];
    System.arraycopy(points, 0, newpoints, 0, numPoints);
    System.arraycopy(s.points, 0, newpoints, numPoints, s.numPoints);
    points = newpoints;
    numPoints = n;
    minX = Math.min(minX, s.minX);
    maxX = Math.max(maxX, s.maxX);
    minY = Math.min(minY, s.minY);
    maxY = Math.max(maxY, s.maxY);
    * Translate the coordinates of all points in the Scribble by x,y
    public void translate(double x, double y) {
    for (int i = 0; i < numPoints; i++) {
    if (Double.isNaN(points))
    continue;
    points[i++] += x;
    points[i] += y;
    minX += x;
    maxX += x;
    minY += y;
    maxY += y;
    /** An internal method to make more room in the data array */
    protected void reallocate() {
    double[] newpoints = new double[points.length * 2];
    System.arraycopy(points, 0, newpoints, 0, numPoints);
    points = newpoints;
    /** Clone a Scribble object and its internal array of data */
    public Object clone() {
    try {
    Scribble s = (Scribble) super.clone(); // make a copy of all fields
    s.points = (double[]) points.clone(); // copy the entire array
    return s;
    } catch (CloneNotSupportedException e) { // This should never happen
    return this;
    /** Convert the scribble data to a textual format */
    public String toString() {
    StringBuffer b = new StringBuffer();
    for (int i = 0; i < numPoints; i++) {
    if (Double.isNaN(points[i])) {
    b.append("m ");
    } else {
    b.append(points[i]);
    b.append(' ');
    return b.toString();
    * Create a new Scribble object and initialize it by parsing a string of
    * coordinate data in the format produced by toString()
    public static Scribble parse(String s) throws NumberFormatException {
    StringTokenizer st = new StringTokenizer(s);
    Scribble scribble = new Scribble();
    while (st.hasMoreTokens()) {
    String t = st.nextToken();
    if (t.charAt(0) == 'm') {
    scribble.moveto(Double.parseDouble(st.nextToken()), Double
    .parseDouble(st.nextToken()));
    } else {
    scribble.lineto(Double.parseDouble(t), Double.parseDouble(st
    .nextToken()));
    return scribble;
    // ========= The following methods implement the Shape interface ========
    /** Return the bounding box of the Shape */
    public Rectangle getBounds() {
    return new Rectangle((int) (minX - 0.5f), (int) (minY - 0.5f),
    (int) (maxX - minX + 0.5f), (int) (maxY - minY + 0.5f));
    /** Return the bounding box of the Shape */
    public Rectangle2D getBounds2D() {
    return new Rectangle2D.Double(minX, minY, maxX - minX, maxY - minY);
    /** Our shape is an open curve, so it never contains anything */
    public boolean contains(Point2D p) {
    return false;
    public boolean contains(Rectangle2D r) {
    return false;
    public boolean contains(double x, double y) {
    return false;
    public boolean contains(double x, double y, double w, double h) {
    return false;
    * Determine if the scribble intersects the specified rectangle by testing
    * each line segment individually
    public boolean intersects(Rectangle2D r) {
    if (numPoints < 4)
    return false;
    int i = 0;
    double x1, y1, x2 = 0.0, y2 = 0.0;
    while (i < numPoints) {
    if (Double.isNaN(points[i])) { // If we're beginning a new line
    i++; // Skip the NaN
    x2 = points[i++];
    y2 = points[i++];
    } else {
    x1 = x2;
    y1 = y2;
    x2 = points[i++];
    y2 = points[i++];
    if (r.intersectsLine(x1, y1, x2, y2))
    return true;
    return false;
    /** Test for intersection by invoking the method above */
    public boolean intersects(double x, double y, double w, double h) {
    return intersects(new Rectangle2D.Double(x, y, w, h));
    * Return a PathIterator object that tells Java2D how to draw this scribble
    public PathIterator getPathIterator(AffineTransform at) {
    return new ScribbleIterator(at);
    * Return a PathIterator that doesn't include curves. Ours never does.
    public PathIterator getPathIterator(AffineTransform at, double flatness) {
    return getPathIterator(at);
    * This inner class implements the PathIterator interface to describe the
    * shape of a scribble. Since a Scribble is composed of arbitrary movetos
    * and linetos, we simply return their coordinates
    public class ScribbleIterator implements PathIterator {
    protected int i = 0; // Position in array
    protected AffineTransform transform;
    public ScribbleIterator(AffineTransform transform) {
    this.transform = transform;
    /** How to determine insideness and outsideness for this shape */
    public int getWindingRule() {
    return PathIterator.WIND_NON_ZERO;
    /** Have we reached the end of the scribble path yet? */
    public boolean isDone() {
    return i >= numPoints;
    /** Move on to the next segment of the path */
    public void next() {
    if (Double.isNaN(points[i]))
    i += 3;
    else
    i += 2;
    * Get the coordinates of the current moveto or lineto as floats
    public int currentSegment(float[] coords) {
    int retval;
    if (Double.isNaN(points[i])) { // If its a moveto
    coords[0] = (float) points[i + 1];
    coords[1] = (float) points[i + 2];
    retval = SEG_MOVETO;
    } else {
    coords[0] = (float) points[i];
    coords[1] = (float) points[i + 1];
    retval = SEG_LINETO;
    // If a transform was specified, use it on the coordinates
    if (transform != null)
    transform.transform(coords, 0, coords, 0, 1);
    return retval;
    * Get the coordinates of the current moveto or lineto as doubles
    public int currentSegment(double[] coords) {
    int retval;
    if (Double.isNaN(points[i])) {
    coords[0] = points[i + 1];
    coords[1] = points[i + 2];
    retval = SEG_MOVETO;
    } else {
    coords[0] = points[i];
    coords[1] = points[i + 1];
    retval = SEG_LINETO;
    if (transform != null)
    transform.transform(coords, 0, coords, 0, 1);
    return retval;
    //====== The following methods implement the Transferable interface =====
    // This is the custom DataFlavor for Scribble objects
    public static DataFlavor scribbleDataFlavor = new DataFlavor(
    Scribble.class, "Scribble");
    // This is a list of the flavors we know how to work with
    public static DataFlavor[] supportedFlavors = { scribbleDataFlavor,
    DataFlavor.stringFlavor };
    /** Return the data formats or "flavors" we know how to transfer */
    public DataFlavor[] getTransferDataFlavors() {
    return (DataFlavor[]) supportedFlavors.clone();
    /** Check whether we support a given flavor */
    public boolean isDataFlavorSupported(DataFlavor flavor) {
    return (flavor.equals(scribbleDataFlavor) || flavor
    .equals(DataFlavor.stringFlavor));
    * Return the scribble data in the requested format, or throw an exception
    * if we don't support the requested format
    public Object getTransferData(DataFlavor flavor)
    throws UnsupportedFlavorException {
    if (flavor.equals(scribbleDataFlavor)) {
    return this;
    } else if (flavor.equals(DataFlavor.stringFlavor)) {
    return toString();
    } else
    throw new UnsupportedFlavorException(flavor);
    Regards
    Siva prasad
    Edited by: [email protected] on Mar 31, 2008 6:01 AM
    Edited by: [email protected] on Apr 8, 2008 2:53 AM
    Edited by: [email protected] on Apr 8, 2008 2:56 AM

    Also, I'm using iTunes 11.0.5, the latest version as far as I know.

  • Custom painting/ graphics in a panel

    Ten Duke Dollars for whoever gives the best high level solution for my problem.
    I'm writing a small application that displays music notation on screen and lets the user move the notes vertically to the desired locations on the staves. The user can then do various kinds of analysis on each example. The analysis stuff is done, but I'm having trouble finding an approach that will work for the graphics.
    My basic approach so far is to subclass JPanel and use it to handle all the custom painting. I'm planning to add all needed JPEG's to JLabels. Some of the images (e.g. treble and bass clef images) will always be in a fixed location, while others (note images) will move vertically when the user drags them. For the lines on the staves and the measure lines, I'm planning to use g.drawLine.
    The following questions occur to me:
    1. How will I prevent the note images from hiding the lines? Will I need to make the images transparent GIFs or something? Or can I set some layering property in the JPanel to build up a layered drawing?
    2. to detect mouse events, should I attach mouse listeners to my panel, or to each label that contains a note image? (I considered using Ellipse objects for the note heads and lines for the stems, but this will not give me a high enough quality of image.)
    3. I will probably need to use absolute positioning in the panel class rather than FlowLayout or whatever, but I'm having trouble getting rid of the layout manager. Can you give me a few lines of code to do this?
    4. Is my overall approach correct? Is there a better, easier way to accomplish what I'm trying to do?
    thanks,
    Eric

    >
    The following questions occur to me:
    1. How will I prevent the note images from hiding the
    lines? Will I need to make the images transparent GIFs
    or something? Or can I set some layering property in
    the JPanel to build up a layered drawing?If you are going to use images (probably BufferedImages), their Transparency will probably be BITMASK or TRANSLUSCENT.
    2. to detect mouse events, should I attach mouse
    listeners to my panel, or to each label that contains
    a note image? (I considered using Ellipse objects for
    the note heads and lines for the stems, but this will
    not give me a high enough quality of image.)I don't think using JLabel objects is a good idea. Instead of add labels to a panel, I would define a custom JComponent that did its own painting in paintComponent.
    >
    3. I will probably need to use absolute positioning in
    the panel class rather than FlowLayout or whatever,
    but I'm having trouble getting rid of the layout
    manager. Can you give me a few lines of code to do
    this?If you follow my last comment, your component isn't being used as a container, so this is not relevant.
    >
    4. Is my overall approach correct? Is there a better,
    easier way to accomplish what I'm trying to do?
    thanks,
    EricCheck out forum Java 2D. That's where this topic belongs. You also need to learn the 2D API. Search for some text book references in that forum.
    From the Imipolex G keyboard of...
    Lazlo Jamf

  • "Best practice" for components calling components on different panels.

    I'm very new to Swing. I have been learning from tutorials, but these are always relatively simple interfaces , in which every component and container is initialised and added in the constructor of a main JFrame (extension) object.
    I would assume that more complex, real-world examples would have JPanels initialise themselves. For example, I am working on a project in which the JFrame holds multiple JPanels. One of these Panels holds a group of JToggleButtons (grouped in a ButtonGroup). The action event for each button involves calling the repaint method of one of the other Panels.
    Obviously, if you initialise everything in the JFrame, you can simply have the ActionListener refer to the other JPanel directly, by making the ActionListener a nested class within the JFrame class. However, I would like the JPanels to initialise their own components, including setting the button actions, by using an extension of class JPanel which includes the ActionListeners as nested classes. Therefore the ActionListener has no direct access to JPanel it needs to repaint.
    What, then, is considered "best practice" for allowing these components to interact (not simply in this situation, but more generally)? Should I pass a reference to the JPanel that needs to be repainted to the JPanel that contains the ActionListeners? Should I notify the main JFrame that the Action event has fired, and then have that call "repaint"? Or is there a more common or more correct way of doing this?
    Similarly, one of the JPanels needs to use a field belonging to the JFrame that holds it. Should I pass a reference to this object to the JPanel, or should I have the JPanel use "getParent()", or some other method?
    I realise there are no concrete answers to this query, but I am wondering whether there are accepted practices for achieving this. My instinct is to simply pass a JPanel reference to the JPanel that needs to call repaint, but I am unsure how extensible this would be, how tightly coupled these classes would become.
    Any advice anybody could give me would be much appreciated. Sorry the question is so long-winded. :)

    Hello,
    nice to get feedback.
    I've been looking at a few resources on this issue from my last post. In my application I have been using the Observer and Observable classes to implement the MVC pattern suggested by T.PD.(...)
    Two issues (not fatal, but annoying) with this are:
    -Observable is a class, not an interface; since most of my Observers already extend JPanel (or some such), I have had to create inner classes.
    -If an Observer is observing multiple Observables, it will have to determine which Observer called its update() method (by using reference equality or class comparison or whatever). Again, a very minor issue, but something to keep in mind.I don't deem those issues are minor. The second one in particular, is rather annoying in terms of maintenance ("Err, remind me, which widget is calling this "update()" method?").
    In addition to that, the Observable/Observer are legacy non-generified classes, that incurr a loosely-typed approach (the subject and context arguments to the update(Observable subject, Object context) methods give hardly any info in themselves, and they generally have to be cast to provide app-specific information.
    Note that the "notification model" from AWT and Swing widgets is not Observer-Observable, but merely EventListener . Although we can only guess what reasons made them develop a specific notification model, I deem this essentially stems from those reasons.
    The contrasting appraoches are discussed in this article from Bill Venners: The Event Generator Idiom (http://www.artima.com/designtechniques/eventgenP.html).
    N.B.: this article is from a previous-millenary series of "Design Techniques" articles that I found very useful when I learned OO design (GUI or not).
    One last nail against the Observer/Observable model: these are general classes that can be used regardless of the context (GUI/non-GUI code), so this makes it easier to forget about Swing threading rules when using them (essentially: is the update method called in the EDT or not).
    If anybody has any information on the performance or efficiency of using Observable/ObserverI would be very surprised if this had any performance impact. If it had, that would mean that you have either:
    - a lot of widgets that are listening to one another (and then the Mediator pattern is almost a must to structure such entangled dependencies). And even then I don't think there could be any impact below a few thousands widgets.
    - expensive or long-running computation in the update methods. That's unrelated to the notification model itself.
    - a lot of non-GUI components that use the Observer/Observable to communicate among themselves - all the more risk then, to have a GUI update() called outside the EDT, see remark above.
    (or whether there are inbuilt equivalents for Swing components)See discussion above.
    As far as your remark 2 goes (if one observer observes more than one subjects, the update() method contains branching logic) : this also occurs with the Event Delegation model indeed: for example, it is quite common that people complain that their actionPerformed() method becomes unwieldy when the same class listens for several JButtons.
    The usual advice for this is, use anonymous listeners, each of which handles the event from only one source (and generally very close in code to the definition of that source), and that simply translates the "generic" event notification method into a specific method call of a Controller or Mediator .
    Best regards.
    J.
    Edited by: jduprez on May 9, 2011 10:10 AM

  • Changing a panel in a frame at runtime

    I have a frame setup with buttons on the BorderLayout.WEST area. Now for each clicked event those buttons generate I want to add a panel to the SOUTH area depending on which button was pressed.
    I have all the action listeners setup, and when a button is clicked the following code is executed
    getContentPane().add(new buttonPanel(),BorderLayout.SOUTH)
    The code seems to be executing but nothing will show up in my JFrame.....
    The buttonPanel object works and if I add to the SOUTH section during design time it will show up ok. But I need to be able to change this panel to buttonPanel2() whenever the user clicks the appropriate button...

    okay that worked, the correct panels will come up, but when I click on one of the buttons that was just created, one of the previous buttons will come onto the foreground. Do I need to destroy the previous panel?
    and if so, how do i do that generically? So that I can destroy any object in the BorderLayout.SOUTH region.

  • How do I get my panels to display?

    Hi,
    I've written this code to display 4 panels but nothing apart my title bar is appearing, I know it;s something minor. I appreciate your help, thanks, fiona
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Color.*;
    public class CDCollection1 extends JFrame implements ActionListener
    private JTextField title;
         private JTextField artist;
         private JTextField year;
         private JTextField genre;
         private JTextField label;
         private JLabel ltitle;
         private JLabel lartist;
         private JLabel lyear;
         private JLabel lgenre;
         private JLabel llabel;
         private JCheckBox excellent;
         private JCheckBox good;
         private JCheckBox fair;
         private JCheckBox poor;
         private JButton enter;
         private JButton edit;
         private JLabel pic;
         private JPanel images;
         private JPanel details;
         private JPanel ratings;
         private JPanel buttons;
         ItemListener handler = new CheckBoxHandler();
    public CDCollection1()
         super("The ultimate cd organizer");
                   pack();
         setSize(700, 600);
              setVisible(true);
              getContentPane().setLayout(new BorderLayout());
              title = new JTextField("Enter the title of cd ");                    
              artist = new JTextField();
              year = new JTextField();
              genre = new JTextField();
              label = new JTextField();          
              ltitle = new JLabel("Title: ");     
              lartist = new JLabel("Artist: ");
              lyear = new JLabel("Year: ");
              lgenre = new JLabel("Genre: ");
              llabel = new JLabel("Label: ");                         
              excellent = new JCheckBox("Excellent", true);
              good = new JCheckBox("Good");
              fair = new JCheckBox("Fair");
              poor = new JCheckBox("Poor");           
              enter = new JButton("Enter Details");
              edit = new JButton("Edit Details");
         pic = new JLabel("",new ImageIcon("desktop/pic.jpg"),
              JLabel.CENTER);
              buildImagesPanel();                                                                                                                             
              buildDetailsPanel();
              buildRatingsPanel();
              buildButtonsPanel();
              add(details, BorderLayout.NORTH);
              add(images, BorderLayout.CENTER);
              add(ratings, BorderLayout.EAST);
              add(buttons, BorderLayout.SOUTH);
    private void buildImagesPanel()                                                            
              images = new JPanel();
                   images.setLayout(new FlowLayout() );
                   images.add(pic);
                   this.setContentPane(images);
         private void buildDetailsPanel()                                                                                                                                                                                    
              details = new JPanel();
                   details.setLayout(new GridLayout(2, 4, 20, 20 ) );
                   details.add(ltitle);
                   details.add(title);
                   details.add(lartist);
                   details.add(artist);
                   details.add(lyear);
                   details.add(year);
                   details.add(lgenre);
                   details.add(genre);
                   details.add(llabel);
                   details.add(label);     
                   details.setBorder(BorderFactory.createTitledBorder(
                   "Cd Details"));
                   title.addActionListener( this );
                   artist.addActionListener( this );
                   year.addActionListener( this );
                   genre.addActionListener( this );
                   label.addActionListener( this );      
                   this.setContentPane(details);                                              
         private void buildRatingsPanel()     
              ratings = new JPanel();
              ratings.setLayout(new GridLayout(5, 1, 10, 20 ) );
              ratings.setBorder(BorderFactory.createTitledBorder("Cd Ratings")); //Adds listeners to checkbox items
              excellent.addItemListener(handler);
              good.addItemListener(handler);
              fair.addItemListener(handler);
              poor.addItemListener(handler);
              this.setContentPane(ratings);           
              } //Closes method
         private void buildButtonsPanel()
              buttons = new JPanel();
              enter.setBorder(BorderFactory.createRaisedBevelBorder());
              edit.setBorder(BorderFactory.createRaisedBevelBorder());
              enter.addActionListener( this );
              edit.addActionListener( this );
    this.setContentPane(buttons);
         public void actionPerformed(ActionEvent evt)
         {if ((evt.getSource() == title) || (evt.getSource() == enter))
                   {String titleText = title.getText();          
                   ltitle.setText("Title:    " + titleText);               //After printing text to JLabel, hides the textfield            
                   title.setVisible(false);          
         if ((evt.getSource() == artist) || (evt.getSource() == enter))
         {String artistText = artist.getText();
                 lartist.setText("Artist:    " + artistText);         
                 artist.setVisible(false);      
         if ((evt.getSource() == year) || (evt.getSource() == enter))
    {String yearText = year.getText();             
                   lyear.setText("Year:  " + yearText);            
                   year.setVisible(false);                 
         if ((evt.getSource() == genre) || (evt.getSource() == enter))
                   {String genreText = genre.getText();              
                  lgenre.setText("Genre:     " + genreText);            
                   genre.setVisible(false);               
         if ((evt.getSource() == label) || (evt.getSource() == enter))
              {String labelText = label.getText();            
                    llabel.setText("Label:   " + labelText);              
                    label.setVisible(false);                  
         if (evt.getSource() == edit)
              {title.setVisible(true);
                     artist.setVisible(true);
                     year.setVisible(true);
                     genre.setVisible(true);
                     label.setVisible(true);
    private class CheckBoxHandler implements ItemListener
         public void itemStateChanged (ItemEvent e)
         if ( e.getSource() == excellent )
         if ( e.getStateChange() == ItemEvent.SELECTED )
         excellent.setForeground(Color.blue);
         else
         excellent.setForeground(Color.black);
         if ( e.getSource() == good )
         if ( e.getStateChange() == ItemEvent.SELECTED )
         good.setForeground(Color.blue);
         else
         good.setForeground(Color.black);
         if ( e.getSource() == fair )
         if ( e.getStateChange() == ItemEvent.SELECTED )
         fair.setForeground(Color.blue);
         else
         fair.setForeground(Color.black);
         if ( e.getSource() == poor )
         if ( e.getStateChange() == ItemEvent.SELECTED )
         poor.setForeground(Color.blue);
         else
         poor.setForeground(Color.black);
         public static void main(String[] args){ 
    CDCollection1 cd = new CDCollection1();
                   cd.getContentPane();
    }

    I would suggest setting the minimum sizes for the panels etc. Otherwise the minimum size can default to 1 pixel x 1 pixel.

  • Event handling with multiple panels

    Hi there,
    Like many here, I'm very new to this stuff so please bear with me..
    I've been building a gui, using a main "parent" JPanel and several
    subpanels. The main reason for creating subpanels was to help me
    with the layout (someone might let me know if this was a bad idea!).
    Now, all of the subpanels generate events in one form or another. What I'd
    like to do is find out the best way to handle ALL of the events that
    can be generated from my various subpanels from the "parent" panel. Hopefully
    this makes sense :) Could anyone offer any suggestions as to the best way
    to achieve this?
    For example, panel1 is a JPanel contains a slider and a button.
    multipanel is another JPanel that contains 6 panel1's. finally
    the main (parent) panel contains the multipanel.
    So, a program that creates an instance of the parent panel wants to know
    the value that one of the sliders on one of the panels in the multipanel
    has (!). How does it get the value?
    I hope I explained myself! Many thanks in advance for any advice offered,
    dan

    class InnerPanel extends JPanel {
    Vector listeners;
    public void add(SwingEventListener lsnr) {
    listeners.add(lsnr);
    protected void notifyListeners(AWTEvent ev) {
    for (Iterator i = listeners.iterator();i.hasNext();) {
    SwingEventListener lsnr = (SwingEventListener) i.next();
    lsnr.eventPeformed(ev);
    public void actionPerformed(ActionEvent ev) {
    notifyListener(ev);
    Your SwingEventListener will be
    interface SwingEventListener {
    public void eventPefromed(AWTEvent event);
    public ParentPanel extends JPanel implements SwingEventListener {
    public void eventPerformed(AWTEvent event) {
    ... do what is required.

  • How can I relay Events to other Listeners?

    Hello,
    I'm writing an application consisting of one JFrame that holds 2 JPanels, a Panel with my "Tools" and a Panel that works as "Worksheet". I implented the feature, that you can drag a Tool from the Tools-Panel to the Worksheet-Panel.
    Now, additionally, I want to implement the feature in the Worksheet-Panel that you can replace an element by mouseDragged(..). I tried to implement this by using the GlasPane from the JFrame ...
    My Problem: The GlassPane seems to catch all events from both Panels and now the Drag&Drop feature from the Tools-Panel don't work any more.
    My Question: How can I relay the Mouse-Events catched by the GlassPane to all other MouseEvent-Listeners?
    Here my Worksheet-Panel, it add itself to the GlasPane-MouseListener List
    public class Worksheet_Panel extends javax.swing.JPanel implements WorksheetInterface {
        public Worksheet_Panel(Component GlasPane) {
             GlasPane.addMouseListener(listener);
             GlasPane.setVisible(true);
        public void mousePressed(MouseEvent e) {
        }Thanks for any help
    Edited by: AddForumListener on Feb 10, 2008 4:06 AM

    AddForumListener wrote:
    thanks. it's an interest method.
    but i think that don't work for my situation because the Class where the event is handled don't know which other components has an interest on that event.
    I think I will try to create an own glasspane which covers my worksheet-panel and its components.
    greetingsI do not know if this will be useful because I did not understand what you are trying to achieve since I did not see your code fully. However you can reach the other components which are interested in listening the mouse events of the source component that created the mouse event. What I mean is you can add the following in the mousePressed method of your glasspane component for instance:
    public void mousePressed(MouseEvent e)
         Component source = (Component) e.getSource();
         MouseListener[] listeners = source.getMouseListeners();
         // Iterate through the mouse listeners, determine to which listener
         // you would like to relay the mouse event and relay it as I mentioned above.
         for (int i = 0; i < listeners.length; i++)
    } Anyway, good luck!!!

  • Setenabled works but not on panel initialization

    I have a panel with several components.
    I have 2 radio buttons that control some logic, and depending on which radio button is selected, different components are enabled
    I have a listener that fires for the radio buttons, and the application seems to work correctly at run time,
    so that the right conmponents do get enabled and disabled when the buttons are manually clicked.
    My problem though is that I need to set which one is enabled by default upon initialization,
    but calling setEnabled(false) does not seem to have any effect in my initialization code,
    but it does work when called from the listeners when each radio button is clicked.
    I dont have a easy example to post as the class is pretty big...
    I'm just checking if there is anything obvious to look for?
    Edited by: dingfelder on Apr 1, 2008 11:38 AM

    For instance, this is an SSCCE of sorts that does nothing but enables and disables JPanels on pressing a JRadioButton. It defaults to the middle button being selected:
    import java.awt.Component;
    import java.awt.GridLayout;
    import javax.swing.BorderFactory;
    import javax.swing.BoxLayout;
    import javax.swing.ButtonGroup;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    class FuSwing1 extends JPanel
        private static final int BTN_COUNT = 3;
        private JRadioButton[] rBtns = new JRadioButton[BTN_COUNT];
        private JPanel[] btnPnls = new JPanel[BTN_COUNT];
        FuSwing1()
            setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
            ButtonGroup btnGrp = new ButtonGroup();
            for (int i = 0; i < rBtns.length; i++)
                rBtns[i] = new JRadioButton("Radio Button " + (i + 1));
                btnGrp.add(rBtns);
    JPanel panel = new JPanel();
    panel.add(rBtns[i]);
    btnPnls[i] = createBtnPanel();
    if (i == BTN_COUNT / 2) // select middle button on startup
    btnPnls[i].setEnabled(true);
    rBtns[i].setSelected(true);
    else
    btnPnls[i].setEnabled(false);
    btnPnls[i].setBorder(BorderFactory.createTitledBorder("Button Panel " + (i + 1)));
    panel.add(btnPnls[i]);
    final int index = i;
    rBtns[i].addChangeListener(new ChangeListener()
    public void stateChanged(ChangeEvent e)
    JRadioButton rBtn = (JRadioButton)e.getSource();
    if (rBtn.isSelected())
    btnPnls[index].setEnabled(true);
    else
    btnPnls[index].setEnabled(false);
    add(panel);
    private JPanel createBtnPanel()
    JPanel bp = new JPanel()
    @Override // since panels don't disable children by default
    public void setEnabled(boolean enabled)
    Component[] components = getComponents();
    for (Component component : components)
    component.setEnabled(enabled);
    super.setEnabled(enabled);
    bp.setLayout(new GridLayout(0, 2, 20, 20));
    for (int i = 0; i < 4; i++)
    JButton btn = new JButton("Button " + i);
    bp.add(btn);
    return bp;
    private static void createAndShowGUI()
    JFrame frame = new JFrame("FuSwing1 Application");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(new FuSwing1());
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    public static void main(String[] args)
    javax.swing.SwingUtilities.invokeLater(new Runnable()
    public void run()
    createAndShowGUI();

  • Spry Repeat Accordeon Panels

    This code here repeats the accordeons panel but all opened
    and innactive.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
    Transitional//EN" "
    http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="
    http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html;
    charset=iso-8859-1" />
    <title>Products Demo</title>
    <link href="css/accordion.css" rel="stylesheet"
    type="text/css" />
    <script type="text/javascript"
    src="../../includes/xpath.js"></script>
    <script type="text/javascript"
    src="../../includes/SpryData.js"></script>
    <script type="text/javascript"
    src="../includes/SpryEffects.js"></script>
    <script type="text/javascript"
    src="../includes/SpryAccordion.js"></script>
    <script type="text/javascript"
    src="../../includes/gallery.js"></script>
    <script type="text/javascript">
    var dsProducts = new Spry.Data.XMLDataSet("products.xml",
    "products/product")
    var dsProductFeatures = new
    Spry.Data.XMLDataSet("products.xml",
    "products/product/features/feature")
    </script>
    <link href="../css/screen.css" rel="stylesheet"
    type="text/css" />
    </head>
    <body>
    <div id="wrap">
    <div id="sidebar">
    <table spryregion="dsProductFeatures" id="products">
    <caption>
    {@Departure}
    </caption>
    </table>
    <div spryregion="dsProductFeatures" id="content">
    tetette
    <p>
    <img src="
    http://staticcontent.exitravel.com/StaticContent/EN/DBImages/Common/Image/Hotel/{@OrgID}/{ @HotelID}_1.jpg"
    id="mainImage" alt="main image" width="120" height="120" />
    </div>
    <div id="Acc1" class="Accordion">
    <div spryregion="dsProductFeatures"
    class="AccordionPanel">
    <div spryrepeat="dsProductFeatures">
    <div class="AccordionPanelLabel">
    {@Destination}
    </div>
    <div class="AccordionPanelContent">
    {@Price}
    </div>
    </div>
    </div>
    </div>
    </div>
    </div>
    <script type="text/javascript">
    <!--
    var Acc1 = new Spry.Widget.Accordion("Acc1");
    -->
    </script>
    </body>
    </html>
    Does that mean that Spry accordeons cant be duplicated that
    way?

    Actually, you can generate the panels dynamically, but there
    are a couple of things you have to keep in mind. There is an
    expected markup structure for the accordion. The divs that make up
    the accordion follow a pattern that looks like this:
    Accordion
    Accordion Panel
    Accordion Panel Label
    Accordion Panel Content
    Accordion Panel
    Accordion Panel Label
    Accordion Panel Content
    Inserting extra divs between and around some of these
    structures will only confuse the Accordion behavior code.
    Since you are trying to repeat accordion panels, you want to
    put the spryregion attribute on the Accordion itself, and then put
    a spryrepeat on the actual div that is the panel.
    The next thing to consider, is that anytime Spry regenerates
    the markup for a widget, you have to re-attach all of the widget
    behaviors to the widget. To accomplish this, we have to place a
    listener on the data set. The idea is that every time the data set
    notifies listeners that its data has changed, we know the widget
    markup will be re-generated, so we have to call the constructor for
    the Accordion.
    Here's some actual markup that I whipped up that works:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
    Transitional//EN" "
    http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="
    http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html;
    charset=iso-8859-1" />
    <title>Dynamic Accordion</title>
    <link href="../../css/accordion.css" rel="stylesheet"
    type="text/css" />
    <script language="JavaScript" type="text/javascript"
    src="../../includes/xpath.js"></script>
    <script language="JavaScript" type="text/javascript"
    src="../../includes/SpryData.js"></script>
    <script language="JavaScript" type="text/javascript"
    src="../../includes/SpryEffects.js"></script>
    <script language="JavaScript" type="text/javascript"
    src="../../includes/SpryAccordion.js"></script>
    <script language="JavaScript" type="text/javascript">
    // Step 1: Define the data set:
    var dsAirports = new
    Spry.Data.XMLDataSet("../../data/airports.xml",
    "/airports/airport");
    // Step 2: Register a listener on dsAirports so that we can
    auto-attach the
    // Accordion behaviors.
    dsAirports.addDataChangedObserver("accordionObserver", {
    onDataChanged: function(ds, dcType) { setTimeout(function() { var
    acc = new Spry.Widget.Accordion("Acc1"); }, 0); } });
    </script>
    </head>
    <body>
    <div id="Acc1" class="Accordion"
    spry:region="dsAirports">
    <div class="AccordionPanel" spry:repeat="dsAirports">
    <div class="AccordionPanelLabel">
    <h3>{code}</h3>
    </div>
    <div class="AccordionPanelContent">
    <div>{name}</div>
    </div>
    </div>
    </div>
    </body>
    </html>
    Note the use of a timer in the listener callback. This is
    necessary to force the Accordion call to be triggered *after* the
    dynamic region has been re-generated. This won't be necessary once
    we implement the dynamic region observers mechanism.
    --== Kin ==--

  • Loading/Unloading a .swf that adds event listeners to the Stage

    Hi all,
    Disclaimer
    Apologies if I suck so bad at using forum search that the answer to this is on page 1 somewhere; I tried...
    Question
    I am loading and unloading a .swf to which I do not have source code access. This .swf places several event listeners on the stage, as far as I can tell. When the .swf is unloaded, the event listeners placed upon the stage still seem to be in effect. Using unloadAndStop doesn't seem to do it, and I have to target Flash Player 9, anyway, so can't really use it. Is there any other way I can keep this external .swf from holding onto my main movie's stage?
    Additional info
    All eventListeners and references being set by my code are removed.
    I've managed a little contact with the author of the .swf:
    I've requested he provide a dispose() method I can call to get all the listeners removed, and send an updated .swf.
    He's suggested that I should be able to avoid the problem by loading into a unique ApplicationDomain. I'm not terribly familiar with this, but have given it a try without much success. Is this a valid solution - can I really protect my 'stage' by properly using ApplicationDomains - or do I need to persist in trying to get a public dispose() method built in?
    Thanks in advance!
    Cheers, John

    thanks for reply sir
    sir actually, i have not any problem with loading any file but i need to go back to intro.swf file when i click on clsbtn of main.swf, i want unload the main.swf file and panel.swf file
    actually i did was, i have intro.swf file and there is button by clicking load main.swf file (where is timeline controling butons) and in the main file automatically load panel.swf file ( where is all animation)
    its all play gud , no problem
    but my problem is there is a clsbtn in main.swf file and when i click on that button everything should be unload and it should return on the previous position in intro.swf
    i hope u understand what i am trying to say

Maybe you are looking for

  • Since update to iOS7 my iPhone the music player does not play music videos in landscape/fullscreen anymore, how can this be fixed?

    The music player only shows all the album covers but doesn't play the video. Only in portait mode it plays the video in a very small window. Makes no sense at all, worked perfectly in iOS6.

  • MIRO for Planned delivery cost

    Hello, Its Raw material  PO with Freight  & unloading Charges codition.Excise duty applicable only for Raw material . service tax applicable for Freight & unloading charges vendor. while booking MIRO for  Raw material ,excise accounts should be hit 

  • Instrument control fundamentals

    Hi,       I need some help regarding instrument control.I want to control instruments uing labVIEW8.6.I'm new to the job.can anybody tell me what are all the requirements(like installing instrument divers, labview 8.6) inorder to control an instrumen

  • Location services when abroad

    I am currently abroad in Canada from the UK, and want to use location services but only using wifi not to use the data/cell tower information as this costs extra money on my contract plan.  Any ideas?  I have turned data off, so if I turn location on

  • Checkbox value is backwards

    JHeadstart 10.1.3.2.52 Info from Application Definition Editor Java Type: Number Display Type: checkBox Domain : Static values (0,1) Default Display Value: 0 When I run the app the checked value is 0 and unchecked is 1. I want that reversed.