Swap Component in JPanel

Hi there,
I have a JPanel that holds several Components (ThumbnailPanel ... own Class for Displaying Thumbs and Infos of a Pic). I want to have a function to sort this Panel. That means I have Arrow Buttons and can shift a ThumbPanel one to the left or to the right. I try to show you here (its better to understand if you see this):
http://www.rebelman.de/images/tpscreenshot.jpg
the arrows to sort are the small buttons in the upper right corner.
Logically the Components (ThumbnailPanels) are stored in a Vector and they are displayed in a JPanel with GridBagLayout. To shift a Component to the right, I have to swap it with its right neighbour. In the Vector its no problem
     public void sortToRight() {
          if(selIndex<currList.getImageCount()-2) {
               //Vector swap
               ImageData startImage     = currList.getImage(selIndex);
               ImageData swappedImage     = currList.getImage(selIndex+1);
               currList.setImage(selIndex, swappedImage);
               currList.setImage(selIndex+1, startImage);
     }But I cant swap the Components in the JPanel where they are displayed. I can get the reference to the component (panelName.getComponent(index)) ... but I cant set the reference e.g. panelName.setComponent(index, Component).
Any working idea? (I just think of swapping the constraint value of gridX ... but how? and does this work? The value for selIndex could point to the wrong component then and selection could run into trouble).
- Frankie
Edit: As mentioned in the last lines, I tried to swap the gridx Value:
Component startComponent = thumbScrollPanel.getComponent(selIndex);
Component swappedComponent = thumbScrollPanel.getComponent(selIndex+1);
GridBagConstraints startConstraints = panelLayout.getConstraints(startComponent);
GridBagConstraints swappedConstraints = panelLayout.getConstraints(swappedComponent);
int startX = startConstraints.gridx;
int swappedX = swappedConstraints.gridx;
startConstraints.gridx = swappedX;
swappedConstraints.gridx = startX;
thumbScrollPanel.validate();This does not work. The order, both Components are displayed is not changing.
Edited by: rebelman on Dec 13, 2007 1:14 AM

Maybe use a GridLayout so you don't have to worry about constraints.
Either way as mentioned above the key is to revalidate() the parent container after you add or remove a component from it. (Sometimes the repaint() is also necessary).

Similar Messages

  • How to drop component on JPanel

    Hi,
    i want to drop some component on JPanel.I'm talking about drag n drop concept, but how to apply it on JPanel.
    For eg how to drag n drop an image from your tool bar to a JPanel.
    Thanks in advance.

    Hi,
    thanks for ur reply.
    But this link is not helping me much...more idea needed....actually my question is to use 'JPanel' to drop component....how to make it work?and also how to resize the component itself by streaching it's border ( something like taht )
    thanks...
    Edited by: DJgpmax on Jun 17, 2008 2:10 AM

  • Swap component positions dynamically

    Hello,
    I want to be able to dynamically swap the postions of any two components within a single container.
    For example, if I have a JPanel that has a BorderLayout, I want to be able to to swap the NORTH and WEST components with each other.
    I find that it is easy to remove them from their current positions.
    However, my problem is how to add them back with the proper layout constraints. I don't see any Container methods that will allow me to get the layout contraints of an existing component so that I can then transfer it when adding another component dynamically.
    After the swap, the components should resize properly when the container is resized, as if each had initially been added to the container with the given layout manager with the other's constraints.
    I would like this to be a general solution that will work for any Container and any LayoutManager.
    Thank you,
    Ted Hill

    For you problem, it will be nice, if each Layout Manager has a method call swapComponent ...
    I do not think there are esay solution for this problem.
    Because most of layout manager, keep those information private!
    Here are some of my ideas :
    (1) Keep the information by youself in your code.
    Well, you can use a hashTable, keep those constraint layout infomation by youself.
    Before or After add the component, save the constraint info.
    And when you need to swap, just use it.
    (2) You still need to keep those information ( may-be by using hashTable ),
    but this time, implement to more generic way.
    ==> subclass all layout managers you are interresting.
    Overriden the addLayoutComponent and removeLayoutComponent,
    make sure you capture the constraint information and save some where.
    Also add new method swapComponent();
    And by subclass, you may access protected method or field (that may related to constraint info... )
    In this way, you just implement once, and you can re-use forever.
    Hope this helps you.

  • Add component to JPanel

    Hello everyone,
    I have a JComboBox, and when i select an Option i would like to add a new component to the JPanel (just below the JComboBox). This is what i have at the moment, but i must be doing something wrong because it does nothing.
    String[] choices = { "Choose option", "Option 1", "Option 2", "Option 3", "Option 4", "Option 5" };
                       mainPanelComponent5 = new JComboBox(choices );
                       mainPanelComponent5.setBounds(100, 70, 150, 20);
                       mainPanelComponent5.addItemListener(new ItemListener() {
                          public void itemStateChanged(ItemEvent e) {
                              if (e.getStateChange() == ItemEvent.SELECTED) {
                                   JLabel compId = new JLabel("TEST");
                                   compId.setBounds(210, 70, 250, 20);
                                   mainPanel.add(compId);
                      });Any help? thanks in advance

    mainPanel.revalidate();Thank you, it works

  • Move component  in JPanel on Top?

    Hi there,
    is there any possibility to move a component in a JPanel on top of all other components in this jpanel?
    So if I move one component over another one the dragged one is on top of all the other ones contained in the same JPanel?
    Sincerely
    Karlheinz Toni

    THx for your post :),
    How could I implement this?
    Should I write a method in the parent panel with LayoutManager null being called when the mouse is pressed on my component I want to move to the top:
       * THis method moves the paramater passed on top of all other parameters included
       * in this panel
       * @param toMove - Container to be moved on top
    public void move_To_Top(Container c){
    java.awt.Component[] tmp = this.getComponents();
        for(int i = 0; i<tmp.length; i++){
          if(tmp.equals(toMove)){
    this.remove(toMove);
    this.validate();
    this.add(toMove,-1);
    }//if
    }//for
    or is this wrong? Is there a faster way to do so? Or is this right? Any other ideas?
    Sincerely
    Karlheinz Toni

  • Get back component from JPanel

    by java
    I know JPanel can get back components by JPanel.getComponents() like
    private JPanel panelCenter = new JPanel ();
    panelCenter.getComponents();
    I want to know is JPanel able to get component just by the specified component's name?
    e.g. panelCenter.getComponent("buttom");
    or like vb.net Me.Controls("buttom").Visible = True
    Thanks
    Francis SZE

    None of JPanel, JComponent, Container or Component have a method to get a component by name.
    You can either:
    1. Keep references to the objects you place in your JPanel (highly recommended :)
    or
    2. Iterate over the result of getComponents() and test for getName().equals(requestedName)

  • Paint component inside JPanel

    Hi guys,
    I will start with the original problem and get to the only option that seems possible before hardcoding everything.
    I need to draw something like a binary tree. Jtree doesn't fall into binary because it does not have the root in the center. <1;2;6;8;9>, where 6 is the root, and 1,2 are its left child's children and 8,9 are right child's children. Since I couldn't find any possible solution of customizing JTree to draw it in binary format, I am left with the following option that is a step towards hardcoding.
    Create a subclass of JPanel and paint inside it. The full hardcode method would be to draw everything right here, ie the lines and the boxes.
    But since I need to listen to box selections using mouse, I was hoping to draw the boxes using JPanel/JLabel and override their paint() method.
    So is there a way to paint components(JLabel/JPanel and lines) into a painted component (JPanel)? Note, the container JPanel is not using any layout. everything is being drawn using paint method.

    You are probably going to want to create smaller objects that handle their own painting. For example... Create an extension of JComponent that handles painting a single node. Then create the JPanel to add those to. You can even go as far as writing your own LayoutManager to handle laying the Components out in your binary layout. This is really the most effective way to do it, especially if you want to be able to detect clicks and what not. You can just add MouseListener's to the individual components than.
    Hope this helps,
    Josh Castagno
    http://www.jdc-software.com

  • Remove component from JPanel

    Hi,
    i've to remove a component from the center (BorderLayout.CENTER) of a JPanel without knowing the name of the component at runtime. I know only that the component is in the center position of the panel. How can i do?
    Thanks
    Luca

    normally what i will do i removeall first and then i add the north or south component so you dont have to worry what is in your center of the panel

  • How to add component to JPanel

    Hello,
    I Try to add a JPnel to other JPnel
    but it works not ther is a error in this code ??
    class MyClass extends JFrame
        Container contentPane;
      public MyClass()
                  contentPane = this.getContentPane();
                  contentPane.setBorderLayout(new BorderLayout());
                 MainPanel();
    puplic void MainPanel()
         Dimension dim = new Dimension(w,h);
         Dimension aDim = new Dimension((w / 2),(h / 2));
         JPanel mainPanel = JPanel();
         mainPanel.setPrefferedSize(dim);
         mainPanel.setLayout(new BorderLayout());
         JPanel pp = getLanguagePanel(aDim);
         pp.revalidate();
         mainPanel.add(pp,BorderLayout.PAGE_END);
         mainPanel.revalidate();
         contentPane.add(mainPanel,BoderLayout.CENTER)
    public JPanel getLanguagePanel(Dimension aDim)
             JPanel retPanel = new JPanel();
         retPanel.setPreferredSize(aDim);
         retPanel.setBorder(null);
         JLabel L = new JLabel("Test Label");
         L.setBounds(50,50,250,30);
         retPanel.add(L);
         retPanel.setBackground(Color.GREEN);
         retPanel.setOpaque(true);
         retPanel.revalidate();
         retPanel.repaint();
         return retPanel;
    }thanks

    contentPane.setBorderLayout(...)There is no such method. Your compiler should be telling you this.
    puplic void MainPanel()There is no such modifier. Your compiler should be telling you this.
    mainPanel.setPrefferedSize(...)There is no such method. Your compiler should be telling you this.
    BoderLayout.CENTERThere is no such class. Your compiler should be telling your this.

  • JPanel won't display my custome component

    Hi,
    I made a custome component class that in its paint method at this stage is suppose to paint a white rectangle on screen. However the when I add this custome component to my JPanel it doesn't show up. Does anybody have a solution for this?
    My code for the custome component is,
    public spaceMediaDisplayObject(mediaObject mo){
         x = mo.getSpaceX();
         y = mo.getSpaceY();
         height = mo.getHeight();
         width = mo.getWidth();
         name = mo.getName();
         System.out.println("Constructor");
         this.repaint();
    public void paint(Graphics g){
         System.out.println("Draw");
         g.setColor(Color.white);
         g.drawRect(x, y, height, width);
    And the fragment of code I am using to try and display in on the panel is as follows,
    spaceMediaDisplayObject smdo = new spaceMediaDisplayObject(toDisplay);
         spaceBodyPanel.add(smdo);
    Please help if able.

    If it's null then you need to set the size of each component explicitly:
    JPanel panel = new JPanel(null);
    Component customComponent = new CustomComponent();
    panel.add(customComponent);
    customComponent.setBounds(0, 0, 100, 100); // For exampleA simple layout manager could be used to make the component fill the panel, for example:
    JPanel panel = new JPanel(new GridLayout(1, 1));
    panel.add(new CustomComponent());Hope this helps.

  • Changing a JPanel, remove () - add () - validate () only works once

    I have a JPanel with several JTextFields. When the user clicks a button, I need to replace it with a different JPanel. I only have two of these JPanels so far, but will add more later. Both of my JPanel objects are singletons; they are created the first time they are used and every time after that the object returns the same instance. I am using the following code to swap from one JPanel to another (the variable dialog is the containing JPanel).
    dialog.remove (0);
    dialog.add (otherPanel, 0);
    dialog.validate ();This works fine, but only the first time. If I continue clicking the button to tell it to swap back and forth, the second panel remains displayed. I have a feeling this has something to do with me using singleton JPanels because after they have both displayed once it stops working, but I can't figure out why it would matter that they are singletons. If you remove a component, can you add that same component back again later? Is there something else I could be missing?

    If you can't use a CardLayout, then the general format of your code should be:
    panel.remove(...);
    panel.add(...);
    panel.revalidate();
    panel.repaint();If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html
    Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
    http://forum.java.sun.com/help.jspa?sec=formatting
    Better late than never :)
    Edited by: camickr on Feb 24, 2008 12:22 AM

  • How to get bounds of a component in FreeDesign layout

    When I try to get bounds of a component that is inside JPanel with FreeDesign layout, I get (0,0,0,0)!
    How can I find out current bounds of those components?

    When I add a component on JPanel with FreeDesign layout (I use NetBeans GUI editor to do it), in generated code I find org.jdesktop.layout.GroupLayout with some HorizontalGroup and VerticalGroup components, and no bounds are ever set!!! When I start the application, a component is shown on JPanel, and definitely bounds are not 0,0,0,0! The components are stretched over window, and everything looks just as I set in GUI editor. A problem is that in runtime I need to know bounds of a component that is showed on screen. A method getBounds() returns (0,0,0,0), so I think that it is not appropriate for this layout.
    So, my question remains: How to find out bounds of a component in FreeDesign layout!
    Thanks!
    Message was edited by:
    mmilic

  • How to resize JPanel at Runtime ??

    Hi,
    Our Project me t a problem as below, we hope to resize JPanel at Runtime , not at design time, ie, when we first click the button called "Move JPanel" , then we click the JPanel, then we can drag it around within main panel, but we hope to resize the size of this JPanel when we point to the border of this JPanel then drag its border to zoom in or zoom out this JPanel.
    Please advice how to do that??
    Thanks in advance.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.border.LineBorder;
    import javax.swing.event.*;
    public class ResizeJPanels extends JPanel
        protected JLabel label1, label2, label3, label4, labeltmp;
        protected JLabel[] labels;
        protected JPanel[] panels;
        protected JPanel selectedJPanel;
        protected JButton btn  = new JButton("Move JPanel");
        int cx, cy;
        protected Vector order = new Vector();      
         public static void main(String[] args)
            JFrame f = new JFrame("Test");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new ResizeJPanels().GroupJLabels());
            f.setSize(600,700);
            f.setLocation(200,200);
            f.setVisible(true);
         private MouseListener ml = new MouseAdapter() {  
              public void mousePressed(MouseEvent e) {   
                   Point p = e.getPoint();      
                   JPanel jp = new JPanel();
                   jp.setLayout(null);
                   Component[] c = ((JPanel)e.getSource()).getComponents();
                   System.out.println("c.length = " + c.length);      
                   for(int j = 0; j < c.length; j++) {        
                        if(c[j].getBounds().contains(p)) {     
                             if(selectedJPanel != null && selectedJPanel != (JPanel)c[j])
                                  selectedJPanel.setBorder(BorderFactory.createEtchedBorder());
                             selectedJPanel = (JPanel)c[j];            
                             selectedJPanel.setBorder(BorderFactory.createLineBorder(Color.green));
                             break;             
                        add(jp);
                        revalidate();
    public JPanel GroupJLabels ()
              setLayout(null);
            addLabels();
            label1.setBounds( 125,  150, 125, 25);
            label2.setBounds(425,  150, 125, 25);
            label3.setBounds( 125, 575, 125, 25);
            label4.setBounds(425, 575, 125, 25);
            //add(btn);
            btn.setBounds(10, 5, 205, 25);
                add(btn);
           determineCenterOfComponents();
            ComponentMover mover = new ComponentMover();
             ActionListener lst = new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                     ComponentMover mover = new ComponentMover();
                           addMouseListener(mover);
                           addMouseMotionListener(mover);
              btn.addActionListener(lst);
              addMouseListener(ml); 
              return this;
        public void paintComponent(final Graphics g)
             super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
             Point[] p;
            g2.setStroke(new BasicStroke(4f));
           for(int i = 0 ; i < order.size()-1; i++) {
                JPanel l1 = (JPanel)order.elementAt(i);
                JPanel l2 = (JPanel)order.elementAt(i+1);
                p = getCenterPoints(l1, l2);
                g2.setColor(Color.black);
               // g2.draw(new Line2D.Double(p[0], p[1]));            
        private Point[] getCenterPoints(Component c1, Component c2)
            Point
                p1 = new Point(),
                p2 = new Point();
            Rectangle
                r1 = c1.getBounds(),
                r2 = c2.getBounds();
                 p1.x = r1.x + r1.width/2;
                 p1.y = r1.y + r1.height/2;
                 p2.x = r2.x + r2.width/2;
                 p2.y = r2.y + r2.height/2;
            return new Point[] {p1, p2};
        private void determineCenterOfComponents()
            int
                xMin = Integer.MAX_VALUE,
                yMin = Integer.MAX_VALUE,
                xMax = 0,
                yMax = 0;
            for(int i = 0; i < labels.length; i++)
                Rectangle r = labels.getBounds();
    if(r.x < xMin)
    xMin = r.x;
    if(r.y < yMin)
    yMin = r.y;
    if(r.x + r.width > xMax)
    xMax = r.x + r.width;
    if(r.y + r.height > yMax)
    yMax = r.y + r.height;
    cx = xMin + (xMax - xMin)/2;
    cy = yMin + (yMax - yMin)/2;
    private class ComponentMover extends MouseInputAdapter
    Point offsetP = new Point();
    boolean dragging;
    public void mousePressed(MouseEvent e)
    Point p = e.getPoint();
    for(int i = 0; i < panels.length; i++)
    Rectangle r = panels[i].getBounds();
    if(r.contains(p))
    selectedJPanel = panels[i];
    order.addElement(panels[i]);
    offsetP.x = p.x - r.x;
    offsetP.y = p.y - r.y;
    dragging = true;
    repaint(); //added
    break;
    public void mouseReleased(MouseEvent e)
    dragging = false;
    public void mouseDragged(MouseEvent e)
    if(dragging)
    Rectangle r = selectedJPanel.getBounds();
    r.x = e.getX() - offsetP.x;
    r.y = e.getY() - offsetP.y;
    selectedJPanel.setBounds(r.x, r.y, r.width, r.height);
    //determineCenterOfComponents();
    repaint();
    private void addLabels()
    label1 = new JLabel("Label 1");
    label2 = new JLabel("Label 2");
    label3 = new JLabel("Label 3");
    label4 = new JLabel("Label 4");
    labels = new JLabel[] {
    label1, label2, label3, label4
    JLabel jl = new JLabel("This is resizeable JPanel at Runtime");
    jl.setBackground(Color.green);
    jl.setOpaque(true);
              jl.setFont(new Font("Helvetica", Font.BOLD, 18));
    JPanel jp = new JPanel();
    jp.setLayout(new BorderLayout());
    panels = new JPanel[]{jp};
              jp.setBorder(new LineBorder(Color.black, 3, false));
    jp.setPreferredSize(new Dimension(400,200));
    jp.add(jl, BorderLayout.NORTH);
    for(int i = 0; i < labels.length; i++)
    labels[i].setHorizontalAlignment(SwingConstants.CENTER);
    labels[i].setBorder(BorderFactory.createEtchedBorder());
    jp.add(labels[i], BorderLayout.CENTER);
    jp.setBounds(100, 100, 400,200);
    add(jp);

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.MouseInputAdapter;
    public class Resizing extends JPanel {
        public Resizing() {
            super(null);
            addPanel();
            PanelControlAdapter control = new PanelControlAdapter(this);
            addMouseListener(control);
            addMouseMotionListener(control);
        private void addPanel() {
            JLabel jl = new JLabel("This is resizeable JPanel at Runtime");
            jl.setBackground(Color.green);
            jl.setOpaque(true);
            jl.setFont(new Font("Helvetica", Font.BOLD, 18));
            JPanel jp = new JPanel();
            jp.setLayout(new BorderLayout());
            jp.setBorder(new LineBorder(Color.black, 3, false));
            jp.add(jl, BorderLayout.NORTH);
            jp.setBounds(50,50,400,200);
            add(jp);
        public static void main(String[] args) {
            JFrame f = new JFrame("Test");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new Resizing());
            f.setSize(500,400);
            f.setLocation(100,100);
            f.setVisible(true);
    class PanelControlAdapter extends MouseInputAdapter {
        Resizing host;
        Component selectedComponent;
        LineBorder black;
        LineBorder green;
        Point offset = new Point();
        Point start = new Point();
        boolean dragging = false;
        boolean resizing = false;
        public PanelControlAdapter(Resizing r) {
            host = r;
            black = new LineBorder(Color.black, 3, false);
            green = new LineBorder(Color.green, 3, false);
        public void mouseMoved(MouseEvent e) {
            Point p = e.getPoint();
            boolean hovering = false;
            Component c = host.getComponent(0);
            Rectangle r = c.getBounds();
            if(r.contains(p)) {
                hovering = true;
                if(selectedComponent != c) {
                    if(selectedComponent != null)  // reset
                        ((JComponent)selectedComponent).setBorder(black);
                    selectedComponent = c;
                    ((JComponent)selectedComponent).setBorder(green);
                if(overBorder(p))
                    setCursor(p);
                else if(selectedComponent.getCursor() != Cursor.getDefaultCursor())
                    selectedComponent.setCursor(Cursor.getDefaultCursor());
            if(!hovering && selectedComponent != null) {
                ((JComponent)selectedComponent).setBorder(black);
                selectedComponent = null;
        private boolean overBorder(Point p) {
            Rectangle r = selectedComponent.getBounds();
            JComponent target = (JComponent)selectedComponent;
            Insets insets = target.getBorder().getBorderInsets(target);
            // Assume uniform border insets.
            r.grow(-insets.left, -insets.top);
            return !r.contains(p);
        private void setCursor(Point p) {
            JComponent target = (JComponent)selectedComponent;
            AbstractBorder border = (AbstractBorder)target.getBorder();
            Rectangle r = target.getBounds();
            Rectangle ir = border.getInteriorRectangle(target, r.x, r.y, r.width, r.height);
            int outcode = ir.outcode(p.x, p.y);
            Cursor cursor;
            switch(outcode) {
                case Rectangle.OUT_TOP:
                    cursor = Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_TOP + Rectangle.OUT_LEFT:
                    cursor = Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_LEFT:
                    cursor = Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_LEFT + Rectangle.OUT_BOTTOM:
                    cursor = Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_BOTTOM:
                    cursor = Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_BOTTOM + Rectangle.OUT_RIGHT:
                    cursor = Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_RIGHT:
                    cursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_RIGHT + Rectangle.OUT_TOP:
                    cursor = Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR);
                    break;
                default:
                    cursor = Cursor.getDefaultCursor();
            selectedComponent.setCursor(cursor);
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            if(selectedComponent != null) {
                Rectangle r = selectedComponent.getBounds();
                if(selectedComponent.getCursor() == Cursor.getDefaultCursor()) {
                    offset.x = p.x - r.x;
                    offset.y = p.y - r.y;
                    dragging = true;
                } else {
                    start = p;
                    resizing = true;
        public void mouseReleased(MouseEvent e) {
            dragging = false;
            resizing = false;
        public void mouseDragged(MouseEvent e) {
            Point p = e.getPoint();
            if(dragging || resizing) {
                Rectangle r = selectedComponent.getBounds();
                if(dragging) {
                    r.x = p.x - offset.x;
                    r.y = p.y - offset.y;
                    selectedComponent.setLocation(r.x, r.y);
                } else if(resizing) {
                    int type = selectedComponent.getCursor().getType();
                    switch(type) {
                        case Cursor.N_RESIZE_CURSOR:
                            r.height -= p.y - start.y;
                            r.y = p.y;
                            break;
                        case Cursor.NW_RESIZE_CURSOR:
                            r.width -= p.x - start.x;
                            r.x = p.x;
                            r.height -= p.y - start.y;
                            r.y = p.y;
                            break;
                        case Cursor.W_RESIZE_CURSOR:
                            r.width -= p.x - start.x;
                            r.x = p.x;
                            break;
                        case Cursor.SW_RESIZE_CURSOR:
                            r.width -= p.x - start.x;
                            r.x = p.x;
                            r.height += p.y - start.y;
                            break;
                        case Cursor.S_RESIZE_CURSOR:
                            r.height += p.y - start.y;
                            break;
                        case Cursor.SE_RESIZE_CURSOR:
                            r.width += p.x - start.x;
                            r.height += p.y - start.y;
                            break;
                        case Cursor.E_RESIZE_CURSOR:
                            r.width += p.x - start.x;
                            break;
                        case Cursor.NE_RESIZE_CURSOR:
                            r.width += p.x - start.x;
                            r.height -= p.y - start.y;
                            r.y = p.y;
                            break;
                        default:
                            System.out.println("Unexpected resize type: " + type);
                    selectedComponent.setBounds(r.x, r.y, r.width, r.height);
                    start = p;
    }

  • JPanel as Image

    Hi everyone....im now writing here cos i m wondering what is the easiest way to save content of JPanel as jpg , gif or any other image...cos thats basically a file with certaing extension.
    I would like to save this content of JPanel through JFile Chooser (file dialog) , but when i try to use for example: File myFile=new File(fileName+fileExtension) nothing happens...no file is created or saved.(?)

    java does not support witing in the .gif format; only reading. I believe .gif writers are available via open source (google). For the .jpg you might try experimenting with different BufferedImage types - see the field summary section of the api for these. Also you might experiment with this (pseudo-code)
    // inside your graphic component, eg JPanel
    GraphicsConfiguration gc = getGraphicsConfiguration();
    BufferedImage compatImage = gc.createCompatibleImage(w, h);
    // get the graphics context reference
    // and hand it to the components paint method
    // and carry on as beforeAnd you might consider setting RenderingHints in your painting code, egs, antialiasing and fractionalmetrics - see api for options.

  • Best way to set layout of custom component

    Hi
    I'm creating a MultiComboBox component made up of a variable number of combo boxes. It's essentially a way for the user to select from a list, then a sub-selection list (then, if appropriate, a sub-sub-selection list etc) until a final selection is made. A sort of category hierarchy thing.
    Anyway, I've got it working, but it's bothering me that the layout (I'm currently using a grid layout) and the border are currently hard-coded in the constructor of the MultiComboBox. This seems to be the way that most custom components are created, although my MultiComboBox could easily work with a number of different layouts, so I'm thinking there must be a better way that would enable the user of the component to set their own layout and border. Is there an effective standard approach for going about this? I'm thinking I should be overriding a few methods of Component / JComponent / JPanel (which my MultiComboBox currently extends), like the getLayout(), getBorder(), so that they either return my default layout, or a layout the user has set with setLayout(). But then would I need to call validate() or something, and where should I be creating my array of combo boxes (currently I'm doing this in the constructor)?
    Any advice appreciated
    Martin

    Hm ...
    I use JTree for example to organize my application - say it is a kind of alternative menu and organizing system. It is a simple to use and very flexible component if you really have studied, how view, model and controller are working together - each of them can be manipulated or even replaced.
    The whole swing architecture is highly reconfigurable - I like it's design very much even so you have to struggle with it when you start using swing components for the first time :) - a very important point is to understand the event handling of the components - some people don't study that and struggle with invalidate() revalidate() and repaint() what is not needed at all, if you have understood which event to fire from which object :)
    greetings Marsian

Maybe you are looking for