Resizing a JPanel

Heres the problem i'm having:
I'm trying to implement my own tooltips for a bar graph class that i have created. I need tooltips to appear when i move the mouse over the top of each of the bars.
The graph is built from an array of data which is an instance variable of the class. The data in this array is updated periodically (say every 10 secs). The heights of the bars in the graph depend on the height of the panel so are set in the paintComponent method.
Currently in the paintComponent method i also update the instance variable array with the rectangle created for each bar in the graph so that the mouseMotionListener (a subclass of this class) can check if the mouse is within the rectangle.
This works fine until the data in the instance varible array is updated. Here null pointers are set for each of the rectangles until a repaint is called and the rectangles are updated. This means that before a repaint takes place, the mouseListener can try and access the rectangles in the array and get a nullPointerException
Is there a better way of doing this? I dont think that i should be updating the data array from the paintComponent method but cant think of another way to do it as the bars depend on the height...
Any help is greatly appreciated.

Why not make the bars jcomponents and use the native tool tip?
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.util.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.awt.*;
import java.awt.event.*;
public class Demo extends JFrame
    public Demo()
        super( "Demo");
        setDefaultCloseOperation( EXIT_ON_CLOSE );
        setContentPane( new GraphPanel() );
        setSize( 500 , 500 );
        show();
    public static void main(String[] args)
        try
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        catch( Exception e )
        new Demo();
    public class GraphPanel extends JPanel implements ComponentListener
        ArrayList bars = new ArrayList();
        Random rand = new Random();
        public GraphPanel()
            setLayout( null );
            addBar( Color.blue, 50 );
            addBar( Color.red,  50 );
            addBar( Color.yellow, 50 );
            addBar( Color.green,  50 );
            addComponentListener( this );
            javax.swing.Timer timer = new javax.swing.Timer( 2000, new ActionListener(){
                     * Invoked when an action occurs.
                    public void actionPerformed(ActionEvent e)
                        randomAdjust();
            timer.start();
        private void addBar( Color color, int value )
            bars.add( new BarPanel( color, value ) );
            layoutBars();
        private void layoutBars()
            removeAll();
            int max = 0;
            for( int i = 0; i < bars.size(); i ++ )
                int value = ((BarPanel) bars.get( i )).getValue();
                max = value > max?value:max;
            Dimension d = getSize();
            int spacer = d.width/100 +1;
            int width = (d.width-spacer)/bars.size();
            for( int i = 0; i < bars.size(); i ++ )
                BarPanel bp =(BarPanel) bars.get( i );
                double bpWeight =  1 - (max-bp.getValue())/(double)max;
                int bpHeight =  (int)(bpWeight * d.height);
                bp.setBounds((i+1)*spacer + i*width,
                             d.height-bpHeight,
                             width,
                             bpHeight);
                add( bp );
            revalidate();
            repaint();
        private void randomAdjust()
            for( int i = 0; i < bars.size(); i ++ )
                int adjust = rand.nextInt( 100 )-50;
                BarPanel bp = (BarPanel) bars.get( i );
                bp.setValue( bp.getValue()+adjust );
                if( bp.getValue() < 0 )
                         bp.setValue( 0 );
            layoutBars();
         * Invoked when the component's size changes.
        public void componentResized(ComponentEvent e)
            layoutBars();
         * Invoked when the component's position changes.
        public void componentMoved(ComponentEvent e)
         * Invoked when the component has been made visible.
        public void componentShown(ComponentEvent e)
            layoutBars();
         * Invoked when the component has been made invisible.
        public void componentHidden(ComponentEvent e)
    public class BarPanel extends JPanel
        private Color color;
        private int value;
        public BarPanel( Color color, int value )
            this.color = color;
            setValue( value );
            setBackground( color );
        public int getValue()
            return( value );
        public void setValue( int value )
             setToolTipText( "Value = "+value );
             this.value = value;
}By the way... That was fun to write and is the fist time I have ever found a use for a null layout.
Hope this helps,
Todd

Similar Messages

  • Cannot resize a JPanel???

    I'm having trouble resizing a JPanel in my gui. I'm adding 4 JPanels to the contentPane which extends JApplet. I'm using a BorderLayout but the JPanel I'm inserting in BorderLayout.CENTER is defaulting itself to only take up half of the border.
    I've tried setBounds(Rectangle r), setPreferredSize(Dimension d), setSize() and everything else but nothing works.
    Can anyone please help

    Can you post your code? This may help.

  • Resize a JPAnel (use of scale)

    Hello everybody,
    Here's my problem: I have a panel full of components. This panel
    can be scaled. So its size can vary. I have to modify the size of this panel (to make a zomm).
    In the printing advanced
    tutorial they say that I just have to resize the graphics in the print method with:
    g2.scale(xScaleFactor,yScaleFactor);
    But it only works for Graphics and no for JPanel..
    My questions are:
    how can I resize my Jpanel ?
    Does it scales all the components in the panel?
    Best Regards
    Peio / [email protected]

    You have to overwrite the paint method from your Painter component. For example a JFrame:
    public void paint(Graphics g){
      Graphics2D g2d = (Graphics2D)g;
      int count = getComponentCount();
      g2d.scale(scaleX, scaleY);
      for(int i = 0; i < count; i++){
        Component comp = getComponent(i);
        comp.paint(g2d);
      // Undo all
      g2d.scale(1/scaleX, 1/scaleY);
    public Dimension getPreferredSize(){
      Dimension dim = getPreferredSize();
      return new Dimension(((int)dim.getWidth() * scaleX), ((int)dim.getHeight() * scaly));
    }Good, if you have a scrollpanel... hmmm... you have to work a little more ;)

  • Center the component without resize in JPanel

    Hi, I have a JPanel in a JFrame. I put in this JPanel objects that extends from a JPanel. It works all ok, but I want to center the components that I include. I use the BorderLayout.CENTER , but the components automaticly have resize it and this is verry bad.
    How can I make the center position of the components witchout to resize it?
    Thanks verry much!
    Nikolay

    BoxLayout is good. We use that almost exclusively for our GUI layouts.
    To centre both horizontally and vertically you can do this:panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS);
    panel.add(Box.createGlue());
    panel.add(component);
    panel.add(Box.createGlue());Regards,
    Tim

  • How to avoid auto resizing the JPanel

    I have JFrame as main window. This JFrame consist of statusbar at the bottom of the JFrame. The statusbar has implemented as a panel that uses BorderLayout. This statusbar has two JPanels as children.
    1) the first child panel(label panel) has 3 labels on it.
    2) the second child panel(image panel) has only one label with a image and this second panel is added to statusbar to the next of the first child.
    3) all panels use BorderLayout.
    If I resize the JFrame by dragging its right border (right to left) both the panels on the statusbar are auto resizing. But I don't want to resize the image panel on the statusbar. I mean even if I resize the frame the size of the image panel should not change. It has to always visible completly.
    Any help is heighly appreciated.
    Regards
    Venkat

    There could be several different ways to achieve this, but it all boils down to using appropriate layouts and/or preferredSizes.
    The Java&#8482; Tutorials: [Laying Out Components Within a Container|http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html]
    db

  • Dynamically resizing a JPanel when drawing

    Hi guys,
    Well, what I want to do is draw a train on a JPanel. its working perfectly. And I have a Scroller on it. The JPanel is STARTING_HEIGHT & STARTING_WIDTH at the begining. But, I want a check which will increase the size of the Panel if the train is too big.
    Does ANYONE know how to do this?! Ive been trying everything I can for ages and nothing is working!
    Cheers
    R
    if (train.length()/SCALE_DIVIDER > this.getSize().getWidth()-1000) {  // IE, the train doesnt have at least 500 pixels on each side
    setMinimumSize(new Dimension((int)train.length()/SCALE_DIVIDER+100000,STARTING_HEIGHT));
    setPreferredSize(new Dimension((int)train.length()/SCALE_DIVIDER+100000,STARTING_HEIGHT));
    System.out.println((int)train.length()/SCALE_DIVIDER+1000);
    int tSize = train.size();

    You should perhaps call frame.pack() or dialog.pack(), depending on what container you're using. It'll resize the window, so that all its components have at least their preferred size.
    Eugene

  • I want to keep the content when resizing the JPanel

    I draw some shade random on a JPanel.
    when I resize or maxium or minum the JFrame which the Jpanel is on , all the shades disppeared.
    How can I keep it?is there a simple way?
    maybe this question has been asked many times, but I searched nothing
    need help

    You must override the method paint(Graphics g) in your application and redraw the shades there. This implies that you must save the shade state.
    Regards

  • How to resize a JPanel within another JPanel

    I have a JApplet that contains contains a JPanel which has several other components on the JPanel.
    The JApplet is an image query front-end which can be used to find images based on a single geographic point, a geographic rectangle or a geographic point and a radius (in meters). I have a JComboBox that the user uses to select which type of query they would like to perform. To enter the query information, I have a separate JPanel that contains the query parameters.
    For the single geographic point, it is just a simple row with JLabels and JTextFields for the latitude and longitude.
    For the rectangle, it is essentially a 3x3 grid to handle the JLabels and JTextFileds for the latitude and longitude of the upper left and lower right corners.
    For the geographic point and radius, I reuse the JPanel for the single geographic point and add a new row for the radius.
    In my ChangeListener for the JComboBox, I first call parentPanel.remove (queryPanel) then call a method to create the specific queryPanel and call parentPanel.add (queryPanel). The only thing that happens when I change the JComboBox to a different query type is the portion of the queryPanel that was covered by the selection of the JComboBox never gets repainted and doesn't change to the new queryPanel.
    I wish I could provide code examples, but the computer that I am developing on is not on the Internet and it is extremely difficult to get anything off of it to put out on the Internet.
    Hopefully, someone can help me figure out what is going on and why my parentPanel is not updating to reflect the new queryPanel.

    GoDonkeys wrote:
    Sorry, but what is the EDT?Please start here: [Concurrency in Swing|http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html]

  • Dynamically resizing a jpanel

    i have a Jframe. at first i add a panel say panel 1 to it.When a button in panel 1 is pressed another panel Panel2 is loaded.inside panel2 i have Jtable...My doubt is whether it is possible to set the size of jframe or panel2 depending on the size of jtable...i have used setSize() for frame and panel.

    thank you for da reply.I want the frame to resize not to the preferred size but to the size of the jtable .the size of jtable vary according to the data inside it..Is there anny methos for that.

  • How do we resize a  JPanel?

    Hi,
    I have 2 two JPanels and when I stick them onto a JFrame (size fixed to something), the panel on the right hand side has this annoying excess grey background. I cannot seem to remove this excess. After all, the panel on the right only contains a single column of buttons.
    How do I remove the excess space??
    Help

    You should use a more convenient layout manager for your JFrame.
    Denis

  • How do I resize this JPanel withou cutting off content?

    I need to make this JPanel smaller vertically. Every time I do it cuts off the bottom of the graph. How can I make it shorter without losing content?
    TIA
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Graph extends JFrame implements ActionListener {
         JButton button;
         int []bar = new int[4];
         float []flote = {1395,1296,1402,1522};
         String []valuesInput = {"1395","1296","1402","1522"};
         String str = "", title="Title goes here";
         String []barLabels = {"pp01, Oct. 2003","pp02, Oct. 2003","pp01, Nov. 2003","pp02, Nov. 2003"};
         String []percent = {"","","",""};
         JLabel []JLab = new JLabel[4];
         JTextField titletxt;
         JTextField []Text = new JTextField[5];
         JTextField []labeltxt = new JTextField[5];
         boolean pieChart;
         public Graph() {
              Container c = getContentPane();
              JPanel panel = new JPanel(){
                     public void paintComponent(Graphics g) {
                        Graphics2D g2 = (Graphics2D)g;
                        g2.setColor(new Color(223,222,224));
                        g2.fillRect(0,0,550,400);
                        g2.setColor(Color.orange);
                        if(pieChart) {
                             g2.fillArc(30, 130, 220, 220, 90, -bar[0]);
                             g2.fillRect(270, 170, 30, 20);
                        else g2.fillRect(30, 150, bar[0], 30);
                        g2.setColor(Color.green);
                        if(pieChart) {
                             g2.fillArc(30, 130, 220, 220, 90-bar[0], -bar[1]);
                             g2.fillRect(270, 210, 30, 20);
                        else g2.fillRect(30, 190, bar[1], 30);
                        g2.setColor(Color.red);
                        if(pieChart) {
                             g2.fillArc(30, 130, 220, 220, 90-(bar[0]+bar[1]), -bar[2]);
                             g2.fillRect(270, 250, 30, 20);
                        else g2.fillRect(30, 230, bar[2], 30);
                        g2.setColor(Color.blue);
                        if(pieChart) {
                             g2.fillArc(30, 130, 220, 220, 90-(bar[0]+bar[1]+bar[2]), -bar[3]);
                             g2.fillRect(270, 290, 30, 20);
                        else g2.fillRect(30, 270, bar[3], 30);
                        g2.setColor(Color.black);
                        g2.setFont(new Font("Arial", Font.BOLD, 18));
                        if(pieChart) g2.drawString(title, 220, 142);
                        else g2.drawString(title, 50, 132);
                        g2.setFont(new Font("Arial", Font.PLAIN,16));
                        int temp=0;
                        if(pieChart) temp = 185;
                        else temp = 172;
                        for(int j=0; j <4; j++) {
                        if(pieChart) g2.drawString("$"+valuesInput[j]+" "+barLabels[j]+percent[j], 305, temp);//XXXXXXXXXXXXXXX
                        else g2.drawString("$"+valuesInput[j]+" "+barLabels[j]+percent[j], bar[j]+40, temp);
                        temp += 40;
                        if(!pieChart){
                             g2.drawLine(30, 130, 30, 300);
                             g2.drawLine(30, 300, 430, 300);
                             //g2.drawLine(210, 345, 210, 350);
                             //g2.drawLine(390, 345, 390, 350);
                             g2.setFont(new Font("Arial", Font.PLAIN,12));
                        super.paintComponent(g2);
              panel.setOpaque(false);
              panel.setLayout(new FlowLayout() );
              button = new JButton("Bar Graph");
              button.addActionListener(this);
              for (int k=0; k<4; k++){
                   str = Integer.toString(k+1);
              panel.add(button);
              c.add(panel);
         public void actionPerformed(ActionEvent e) {
              String command = e.getActionCommand();
              if(command.equals("Bar Graph")){
                   button.setText("Pie Chart");
                   pieChart=false;
                   try {
                        int temp =0;
                        java.text.DecimalFormat df = new java.text.DecimalFormat("#0.#");
                        for (int j=0; j<4; j++){
                             //flote[j] = Float.parseFloat(Text[j].getText());//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                             temp += (int)((flote[j]) +0.5);
                        for (int k=0; k<4; k++){
                        bar[k] = (int)(((flote[k]/temp) * 360)+0.5);
                             //barLabels[k] = labeltxt[k].getText();XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                             flote[k] = (flote[k]/temp) *100;
                             percent[k] = ": "+df.format(flote[k])+"%";
                   catch(Exception message){
                        title = "Oops! Complete all fields, enter numbers only";
              if(command.equals("Pie Chart")){
                   button.setText("Bar Graph");
                   pieChart=true;
              repaint();
         public static void main(String[] args) {
         Graph frame = new Graph();
         frame.setSize(550,400);
         //frame.setLocation(200, 200);
         frame.setResizable(false);
         frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
         frame.setVisible(true);

    Try with this (it really works!):
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Graph extends JFrame implements ActionListener {   
        int width;
        int height;
         JButton button;
         int []bar = new int[4];
         float []flote = {1395,1296,1402,1522};
         String []valuesInput = {"1395","1296","1402","1522"};
         String str = "", title="Title goes here";
         String []barLabels = {"pp01, Oct. 2003","pp02, Oct. 2003","pp01, Nov. 2003","pp02, Nov. 2003"};
         String []percent = {"","","",""};
         JLabel []JLab = new JLabel[4];
         JTextField titletxt;
         JTextField []Text = new JTextField[5];
         JTextField []labeltxt = new JTextField[5];
         boolean pieChart;
         public Graph() {
              Container c = getContentPane();
              JPanel panel = new JPanel(){
                     public void paintComponent(Graphics g) {
                         width = getWidth();
                         height = getHeight();
                        Graphics2D g2 = (Graphics2D)g;
                        //g2.scale(.95,.95);
                        g2.setColor(new Color(223,222,224));
                        g2.fillRect(0,0,width,height);
                        g2.setColor(Color.orange);
                        if(pieChart) {
                             g2.fillArc(getW(30), getH(130), getW(220), getH(220), 90, -bar[0]);
                             g2.fillRect(getW(270), getH(170), getW(30), getH(20));
                        else g2.fillRect(getW(30), getH(150), getW(bar[0]), getH(30));
                        g2.setColor(Color.green);
                        if(pieChart) {
                             g2.fillArc(getW(30), getH(130), getW(220), getH(220), 90-bar[0], -bar[1]);
                             g2.fillRect(getW(270), getH(210), getW(30), getH(20));
                        else g2.fillRect(getW(30), getH(190), getW(bar[1]), getH(30));
                        g2.setColor(Color.red);
                        if(pieChart) {
                             g2.fillArc(getW(30), getH(130), getW(220), getH(220), 90-(bar[0]+bar[1]), -bar[2]);
                             g2.fillRect(getW(270), getH(250), getW(30), getH(20));
                        else g2.fillRect(getW(30), getH(230), getW(bar[2]), getH(30));
                        g2.setColor(Color.blue);
                        if(pieChart) {
                             g2.fillArc(getW(30), getH(130), getW(220), getH(220), 90-(bar[0]+bar[1]+bar[2]), -bar[3]);
                             g2.fillRect(getW(270), getH(290), getW(30), getH(20));
                        else g2.fillRect(getW(30), getH(270), getW(bar[3]), getH(30));
                        g2.setColor(Color.black);
                        g2.setFont(new Font("Arial", Font.BOLD, 18));
                        if(pieChart) g2.drawString(title, getW(220), getH(142));
                        else g2.drawString(title, getW(50), getH(132));
                        g2.setFont(new Font("Arial", Font.PLAIN,16));
                        int temp=0;
                        if(pieChart) temp = 185;
                        else temp = 172;
                        for(int j=0; j <4; j++) {
                        if(pieChart) g2.drawString("$"+valuesInput[j]+" "+barLabels[j]+percent[j], getW(305), getH(temp));//XXXXXXXXXXXXXXX
                        else g2.drawString("$"+valuesInput[j]+" "+barLabels[j]+percent[j], getW(bar[j]+40), getH(temp));
                        temp += 40;
                        if(!pieChart){
                             g2.drawLine(getW(30), getH(130), getW(30), getH(300));
                             g2.drawLine(getW(30), getH(300), getW(430), getH(300));
                             //g2.drawLine(210, 345, 210, 350);
                             //g2.drawLine(390, 345, 390, 350);
                             g2.setFont(new Font("Arial", Font.PLAIN,12));
                        super.paintComponent(g2);
              panel.setOpaque(false);
              panel.setLayout(new FlowLayout() );
              button = new JButton("Bar Graph");
              button.addActionListener(this);
              for (int k=0; k<4; k++){
                   str = Integer.toString(k+1);               
              panel.add(button);
              c.add(panel);
         private int getW(int dx) {
             return (dx * width) / 550;
         private int getH(int dy) {
             return (dy * height) / 400;
         public void actionPerformed(ActionEvent e) {
              String command = e.getActionCommand();
              if(command.equals("Bar Graph")){
                   button.setText("Pie Chart");
                   pieChart=false;
                   try {
                        int temp =0;
                        java.text.DecimalFormat df = new java.text.DecimalFormat("#0.#");
                        for (int j=0; j<4; j++){
                             //flote[j] = Float.parseFloat(Text[j].getText());//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                             temp += (int)((flote[j]) +0.5);
                        for (int k=0; k<4; k++){
                        bar[k] = (int)(((flote[k]/temp) * 360)+0.5);
                             //barLabels[k] = labeltxt[k].getText();XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                             flote[k] = (flote[k]/temp) *100;
                             percent[k] = ": "+df.format(flote[k])+"%";
                   catch(Exception message){
                        title = "Oops! Complete all fields, enter numbers only";
              if(command.equals("Pie Chart")){
                   button.setText("Bar Graph");
                   pieChart=true;
              repaint();
        public static void main(String[] args) {
            Graph frame = new Graph();
            frame.setSize(550,400);
            //frame.setLocation(200, 200);
            frame.setResizable(true);
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.setVisible(true);

  • Resize of JPanel

    Hi
    Anyone have any idea how to size a JPanel? I've got a JLabel and JList in each Panel and I hope to get it to fit only on a certain width in the program GUI. Currently, they are placed in a BorderLayout.EAST.
    Please help
    Tanks

    maybe try:
    jpanel.setPreferredSize(new Dimension(x, y));
    or setMaximumSize, or setMinimumSize, etc..

  • 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;
    }

  • Resizing JFrames and JPanels !!!

    Hi Experts,
    I had one JFrame in which there are three objects, these objects are of those classes which extends JPanel. So, in short in one JFrame there are three JPanels.
    My all JPanels using GridBagLayout and JFrame also using same. When I resize my JFrame ,it also resize my all objects.
    My Problem is how should i allow user to resize JPanels in JFrame also?? and if user is resizing one JPanel than other should adjust according to new size ...
    Plese guide me, how should i do this ...
    Thanknig Java Community,
    Dhwanit Shah

    Hey there, thanx for your kind intereset.
    Here is sample code .
    In which there is JFrame, JPanel and in JPanel ther is one JButton.Jpanel is added to JFrame.
    I want to resize JPanel within JFrame,I am able to do resize JFrame and JPanel sets accroding to it.
    import java.awt.*;
    import javax.swing.*;
    import com.borland.jbcl.layout.*;
    public class FramePanel extends JFrame {
    JPanel contentPane;
    GridBagLayout gridBagLayout1 = new GridBagLayout();
    public FramePanel() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    public static void main(String[] args) {
    FramePanel framePanel = new FramePanel();
    private void jbInit() throws Exception {
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(gridBagLayout1);
    this.setSize(new Dimension(296, 284));
    this.setTitle("Frame and Panel Together");
    MyPanel myPanel = new MyPanel();
    this.getContentPane().add(myPanel);
    this.setVisible(true);
    class MyPanel extends JPanel {
    public MyPanel() {
    this.setSize(200,200);
    this.setLayout(new FlowLayout());
    this.setBackground(Color.black);
    this.setVisible(true);
    this.add(new JButton("Dhwanit Shah"));
    I think i might explained my problem
    Dhwanit Shah
    [email protected]

  • Resizing JPanels using a mouse?

    I have a program that draws on a BufferedImage, but I want to be able to resize the image. At the minute it is on a JPanel, which in turn will be placed in a JScrollPane, but I was wondering if there was a way of resizing the JPanel using the mouse, like you can with a JFrame.
    If not, is there another way I can do this?
    Thanks in advance.

    Thanks for the replies so far.
    I'm trying to write a basic drawing program, and the plan was that the image size (and also its observer component) are not fixed and are independent of the frame (or other component) in which they are located. That was where I assumed the JScrollPane would come in, as this way all the image can be accessed if I make the main window small, for example.
    I've not had a lot of experience doing this kind of thing though, so I'm still not sure of the best way to go about it. As I see it, the JSplitPane is only resizable in one axis. A JSplitPane can effectively be resized in both axes by nesting JSplitPanes, but I feel that this will look a bit untidy.

Maybe you are looking for