Resizing JButton on JPanel?

Hi all,
I just started to learn to use swing and I ran into problem when I try to change the size of a JButton on JPanel. The following code make sense to me, but it just doesn't work. Am I missing something? Can anyone give me some directions?
import javax.swing.*;
public class TestFrame extends JFrame
     public static void main(String[] args)
          TestFrame myFrame = new TestFrame();
          myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          myFrame.setVisible(true);
     private JPanel myPanel = new JPanel();
     private JButton myBtn = new JButton("Test");
     public TestFrame()
          setSize(300, 300);
          myBtn.setSize(200, 200); // the button size still does not change
          myPanel.add(myBtn);     
          getContentPane().add(myPanel);          
}

use setPreferredSize instead of setSize
import javax.swing.*;
import java.awt.Dimension;
public class TestFrame extends JFrame
     public static void main(String[] args)
          TestFrame myFrame = new TestFrame();
          myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          myFrame.setVisible(true);
     private JPanel myPanel = new JPanel();
     private JButton myBtn = new JButton("Test");
     public TestFrame()
          setSize(300, 300);
          //myBtn.setSize(200, 200); // the button size still does not change
          myBtn.setPreferredSize(new Dimension(200, 200));
          myPanel.add(myBtn);     
          getContentPane().add(myPanel);          
}

Similar Messages

  • 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]

  • Drag and drop JButtons between JPanels

    I'm trying to write an application with some simple drag and drop for JButtons between JPanels. Instead of going through all the hassle with DragSourceListener, DropTargetListener etc, I was thinking about a simple MouseMotionListener which sets a boolean to true when the user is dragging, and let the other panel add a MouseListener which listens for a MouseReleased.
    The drag part is working fine, however the drop is not; in fact, it doesn't register the release. However, when I click and release, it seems to register the release.
    Any suggestions? Thanks in advance.
    Code for Card:
    public Card extends JButton {
    public static boolean drag = false;
         public Card(ImageIcon icon, ImageIcon fullicon)
              addMouseMotionListener(new DragMouseListener());
         class DragMouseListener extends MouseMotionAdapter
              public void mouseDragged(MouseEvent e)
                   System.out.println("Drag register");
                   drag = true;
    }Code for the panel:
    benchpanel.addMouseListener(new MouseAdapter() {
         public void mouseReleased(MouseEvent e)
              if (Card.drag && GUI.getInstance().findComponentAt(e.getPoint()) == GUI.getInstance().benchpanel)
                   System.out.println("Drop registered");
              Card.drag = false;
    });

    Sorry for the double post. I had some experimenting done, and I come up with the following:
    if (Card.drag && GUI.getInstance().benchpanel.getBounds().contains(e.getLocationOnScreen()))
         System.out.println("Drop registered");
    }Here's the problem: The second part of the if-statement never seems to get true; if I write the following:
    System.out.println(e.getPoint());
    System.out.println(benchpanel.getBounds());
    System.out.println(benchpanel.getBounds().contains(e.getPoint()));and i click in the upper left part of the JPanel, i get the following output:
    java.awt.Point[x=9,y=13]
    java.awt.Rectangle[x=210,y=420,width=400,height=108]
    false- so for some reason, the bounds on the JPanel are totally messed up - any ideas on why?
    Edited by: pg-robban on Apr 14, 2009 3:14 AM

  • Problems resizing JButtons

    Hi. I have a GUI with a JPanel to which I have added 43 JButtons. I use a for loop to add the buttons but I cannot set the size of individual buttons. I want two of the buttons to be bigger than the rest. Can anyone please help me

    Hi. I have a GUI with a JPanel to which I have added
    43 JButtons. I use a for loop to add the buttons but I
    cannot set the size of individual buttons. I want two
    of the buttons to be bigger than the rest. Can anyone
    please help meAs some else has mentioned, much depends on your
    layout manager. You be able to do the job with
    GridBagLayout, but if that's too much like hard
    work, you can always turn the panel's layout manager off
    and manually place & size each of your buttons.
    setLayout( null );
    and for each button:
    button.setBounds( x, y, width, height );
    If you do this, the buttons won't move or expand
    when the panel is resized. I reckon that's not
    a bad thing for buttons anyway.

  • Resizing JButtons

    Here's the dilema- I'm trying to make an applet with a lot of buttons in each row, but I don't want the applet to stretch the width of the screen. Some of the buttons don't have anything on them but a "-" or a single digit number. How can I properly size these buttons down so that they don't take up as much space as the larger buttons?
    Here's what I'm dealing with:
    public class inputscreen extends JApplet {
      upstat x;
      String fname;
      String lname;
      String ppg, xft, xfta, home, pos, cl, ht, wt;
      Connection con = null;
      Statement st = null;
      ResultSet rs = null;
      int vfg, vfga, vt3, vt3a, vft, vfta, vrb, vas, vf, vtot;
      String updateString;
      Container cp = getContentPane();
      JTextField ply = new JTextField(3);
      JButton upd = new JButton("UD");
      String sfg;
      JButton fg = new JButton(sfg);
      JButton fgm = new JButton("-");
      String sfga;
      JButton fga = new JButton(sfga);
      JButton fgam = new JButton("-");
      String st3;
      JButton t3 = new JButton(st3);
      JButton t3m = new JButton("-");
      String st3a;
      JButton t3a = new JButton(st3a);
      JButton t3am = new JButton("-");
      String sft;
      JButton ft = new JButton(sft);
      JButton ftm = new JButton("-");
      String sfta;
      JButton fta = new JButton(sfta);
      JButton ftam = new JButton("-");
      String srb;
      JButton rb = new JButton(srb);
      JButton rbm = new JButton("-");
      String sas;
      JButton as = new JButton(sas);
      JButton asm = new JButton("-");
      String sf;
      JButton f = new JButton(sf);
      JButton fm = new JButton("-");
      String stot;
      JTextField tot = new JTextField(4);
      JButton player = new JButton("Player");
      JButton season = new JButton("Season");
      JButton tonight = new JButton("Tonight");
      public void init() {
        JPanel line = new JPanel();
        line.add(ply);
        line.add(upd);
        line.add(fg);
        line.add(fgm);
        line.add(fga);
        line.add(fgam);
        line.add(t3);
        line.add(t3m);
        line.add(t3a);
        line.add(t3am);
        line.add(ft);
        line.add(ftm);
        line.add(fta);
        line.add(ftam);
        line.add(rb);
        line.add(rbm);
        line.add(as);
        line.add(asm);
        line.add(f);
        line.add(fm);
        line.add(tot);
        JPanel lower = new JPanel();
        lower.add(player);
        lower.add(season);
        lower.add(tonight);
        line.setLayout(new GridLayout(2, 21));
        lower.setLayout(new FlowLayout());
        cp.setLayout(new BorderLayout());
        cp.add(line, BorderLayout.NORTH);
        cp.add(lower, BorderLayout.CENTER);
        upd.addActionListener(new ButtonListener());
        fg.addActionListener(new ButtonListener());
        fgm.addActionListener(new ButtonListener());
        fga.addActionListener(new ButtonListener());
        fgam.addActionListener(new ButtonListener());
        t3.addActionListener(new ButtonListener());
        t3m.addActionListener(new ButtonListener());
        t3a.addActionListener(new ButtonListener());
        t3am.addActionListener(new ButtonListener());
        ft.addActionListener(new ButtonListener());
        ftm.addActionListener(new ButtonListener());
        fta.addActionListener(new ButtonListener());
        ftam.addActionListener(new ButtonListener());
        rb.addActionListener(new ButtonListener());
        rbm.addActionListener(new ButtonListener());
        as.addActionListener(new ButtonListener());
        asm.addActionListener(new ButtonListener());
        f.addActionListener(new ButtonListener());
        fm.addActionListener(new ButtonListener());
        player.addActionListener(new ButtonListener());
        season.addActionListener(new ButtonListener());
        tonight.addActionListener(new ButtonListener());
      }I'm trying to figure out JButton.setPreferredSize(new Dimension(x,y)); with no success. If someone could give me an example of how to implement that or another technique of resizing individual buttons, I'd really appreciate it.

    The post by camickr is correct: Java components are sized by the layout manager managing the container in which they reside. Simply, GridLayout attempts to size every component the same -- your precise problem. If you use a GridBagLayout instead, the buttons will all respect their preferred size. See the given link.
    - Steev.

  • Resizing JButtons in a BorderLayout

    Hi, I've been working with a BorderLayout and whenever I try and set a JButton's size or preferredSize, it always ignores what I set it at and puts it's size as filling the entire BorderLayout.CENTER. Any ideas?

    {color:#507C9A}1. In future, post Swing questions in the Swing forum: http://forum.java.sun.com/forum.jspa?forumID=57
    2. The behaviour of a Borderlayout is to ignore a component's preferredSize and stretch it to fill the centre.
    Solution: nest.
    JPanel withBorderLayout = ...
    JButton btn = ...
    //withBorderLayout .add(btn, BorderLayout.CENTER);
    JPanel centrePanel = new JPanel(); //FlowLayout by default, you may want to change this
    centrePanel .add(btn);
    withBorderLayout .add(centrePanel , BorderLayout.CENTER);{color}

  • How to Resize JButton,JTextArea and JTextFields on Mouse Over....

    Hi All...
    Hi friends.. I want to be implement my java swing application Resize the Width and Height wise of JButton,JLabel,JTextFields on mouse over etc.
    ============================
    Arjun Palanichamy.
    Senior Programmer.
    Chennai-India.

    Hi All...
    I am herewith enclosed my sample code for resize the JButton(),But This one resize the when will be extend the Button Caption letters,But i want mouse click resize the without button caption or with caption.
    sample code :
    package Resize;
    import java.awt.Container;
    import java.awt.FlowLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import java.awt.Dimension;
    import java.awt.ComponentOrientation;
    public class ReButton{
    public static boolean RIGHT_TO_LEFT = false;
    public static void addComponents(Container contentPane) {
    if (RIGHT_TO_LEFT) {
    contentPane.setComponentOrientation(
    ComponentOrientation.RIGHT_TO_LEFT);
    contentPane.setLayout(new FlowLayout());
    contentPane.add(new JButton("1"));
    contentPane.add(new JButton("100"));
    contentPane.add(new JButton("100 100"));
    contentPane.add(new JButton("100 100 100"));
    contentPane.add(new JButton("100 100 100 100"));
    contentPane.add(new JButton("5"));
    private static void createAndShowGUI() {
    JFrame frame = new JFrame("FlowLayoutDemo") {
    public Dimension getMinimumSize() {
    Dimension prefSize = getPreferredSize();
    return new Dimension(100, prefSize.height);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Set up the content pane.
    addComponents(frame.getContentPane());
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    for example can you Click this.....
    http://www.eclipse.org/vep/WebContent/docs/testcases/null-layout/null-layout.htm
    Thanks for your time.
    Arjun Palanichamy.
    Chennai-India.

  • Centering JButton in JPanel below JSlider, layout problem.

    Hi,
    I am tring to put together a configuration dialog for mouse double click speed. What I want is a largish JButton centered below a JSlider in the JPanel. So people can try double clicking on it :)
    I have written the code but am a novice to Swing layout. There does not seem to be a layout manager to do the job.
    How do I go about this ?
    Do I have to write my own layout manager, use abosolute positioning or is there a simpler way ?
    Many thanks in advance,
    Aaron Gray - [email protected]

    I apologize. I was not completely correct in what I told you in an earlier post. The BoxLayout always respects a component's minimum and maximum sizes. This means that if you set the preferred size to be bigger that the maximum size, it will not make it larger than the maximum size. To ensure that you get the correct size you should set both the preferred size and the maximum size to the size you want the button to be.
    When I created a layout I got something that seemed to be what you wanted. Below is some code describing what I did, then under that is a crude ascii diagram of what the layout looks like.
    JButton button;
    //Code to inialize button ...
    JSlider slider;
    //Code to initialize slider ...
    JPanel content = new JPanel();
    BoxLayout layout = new BoxLayout(content, BoxLayout.Y_AXIS);
    content.setLayout(layout);
    slider.setAlignmentX(JComponent.CENTER_ALIGNMENT);
    button.setAlignmentX(JComponent.CENTER_ALIGNMENT);
    content.add(slider);
    content.add(button);Ascii diagram
         |                             |
         | <-------[|]---------------> |
         |        ____________         |
         |       |            |        |
         |       | Click Here |        |
         |       |____________|        |
         |_____________________________|Is this what you were thinking of ???

  • Resize JButtons Using FlowLayout ?

    I'm using some images for my Jbuttons and when I use FlowLayout, it sets the buttons dimensions bigger than the images and I can't figure out how to set the dimensions while having FlowLayout set too. They look fine when I use absolute positioning, but I need the flexibility of FlowLayout for different resolutions, etc. Anyonw know how to set the dimensions of a JButton while having FlowLayout set too? Thanks so much!

    As far as I know, FlowLayout doesn't adjust the size of
    components at all. Can you post a short, self-contained,
    compileable example that shows the offending behavour?
    You should be able to do new JButton(myIcon); or
    myButton.setIcon(myIcon); and have it Just Work. The button
    should resize itself to contain the icon.

  • Interchange positions of jbutton inside jpanel

    Hi Friends,
    I'm trying interchange the position of JButtons inside a JPanel and between the Jpanels.
    I'm unable to find the exact releasing positions.
    can anyone help me telling the exact procedure .
    here is the code
    Container con = jb.getParent();     
         con.remove(jb);
    insertPosition2 = con.getComponentZOrder((Container)jb);
    if(con.getComponentCount() == insertPosition2)
                             con.add(jb);
                        else
                             con.add(jb,insertPosition2);
    thanx,
    Sunil.

    I've never tried this myself, but the documentation for Container#getComponentZOrder says:
    The higher a component is in the z-order hierarchy, the lower its index.
    Maybe you could try withinsertPosition2 = con.getComponentZOrder((Container)jb);In any case, the correct approach to this kind of troubleshooting is to insert System.out.println statements in between the lines posted so you can observe whether your assumptions about the values the methods return are correct ones.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    If you require further help, please post a SSCCE
    db

  • Showing palette containing JButton,JLabel,JPanel ... components

    hello, I have created a simple application using jdeveloper, this application contains a simple project then I have created a simple JFrame but when I try to add somes components like JButton, JLabels I didn't
    find the palette from which I can add this components. please help me
    Best Regards.

    1) Create a new java Desktop Application
    2) An Application is created with a project named Client
    3) create a new frame/Dialog based on Client Tier(Swing/AwT).
    Select the newly created file and in the component palette, you would see the required components.
    Thanks,
    Navaneeth

  • How do I chance the place of JLabel and JButton in JPanel.

    I'm using DefaultLayout and I want to give the user the ability to change the place of JLabel and JButton. I managed the DnD part, but when "dropped" the control returns to it's original position.
    I tried using setX() and setY().

    You need to use a null Layout, also known as [url http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html]Absolute Positioning

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

  • How to display a JPanel of JButtons on ImagePanel?

    Hi
    From the Swing Hacks examples, I can display a JButton on an ImagePanel no problem. But when I put this JButton in JPanel, then add the JPanel to the ImagePanel, the JPanel with the JButton is not displayed.
    Can someone please explain why this is?
    Here is the ImagePanel code:
    import java.awt.*;
    import javax.swing.*;
    public class ImagePanel extends JPanel {
        private Image img;
        public ImagePanel(String img) {
            this(new ImageIcon(img).getImage());
        public ImagePanel(Image img) {
            this.img = img;
            Dimension size = new Dimension(img.getWidth(null),img.getHeight(null));
            setPreferredSize(size);
            setMinimumSize(size);
            setMaximumSize(size);
            setSize(size);
            setLayout(null);
        public void paintComponent(Graphics g) {
            g.drawImage(img,0,0,null);
    }And here is the code to add a JButton to a JPanel, then add the JPanel to the ImagePanel:
    import javax.swing.*;
    import java.awt.event.*;
    public class ImageTest {
        public static void main(String[] args) {
           ImagePanel panel = new ImagePanel(new ImageIcon("images/background.png").getImage());
           JPanel buttonPanel = new JPanel()       
            JButton button = new JButton("Button");
            buttonPanel.add(button);
           JFrame frame = new JFrame("Hack #XX: Image Components");
            frame.getContentPane().add(button);    // WORKS!
            //frame.getContentPane().add(buttonPanel);   // NO BUTTON IS DISPLAYED???
           frame.pack();
            frame.setVisible(true);
    }Thanks

    setLayout(null);When you use a null layout then you are responsible for setting the size and location of any component added to the panel. The default location is (0,0) so thats ok, but the default size of the button panel is also (0,0) which is why nothing get painted.
    Don't use a null layout. Let the layout manager layout any component added to it.
    Also, I would override the getPreferredSize() method of your ImagePanel to return the size of the image, instead of setting the preferred size in the constructor.

  • How to dynamically resize JPanel at runtime??

    Hello Sir:
    I met a problem, I need to resize a small JPanel called panel within a main Control JPanel (with null Layout) if I click the mouse then I can Drag and Resize this small JPanel Border to the size I need at runtime, I know I can use panel.setSize() or panel.setPreferredSize() methods at design time,
    But I have no idea how to do it even I search this famous fourm,
    How to dynamically resize JPanel at runtime??
    Can any guru throw some light or good example??
    Thanks

    Why are you using a null layout? Wouldn't having a layout manager help you in this situation?

Maybe you are looking for

  • Is it possible to reduce the number of HTTP calls when using a ReportViewer control?

    My application is written in .Net 4 using Visual Studio 2010 (version 10 of the ReportViewer control). The report in question contains a lot of data in the dropdowns used for parameter selection. For example, one dropdown contains 95k options and ano

  • Discount at header, not reflected at item level

    Hi All; We are using ECC6 There is a bsiness requirement. The vednor gives a discount for some PO's as a lump sum. The user requires to be able to enter the discont at the header level but the system should not divide this discount on all items. i.e.

  • What is the problem with constructor?......

    class sam private String name; private String desgn; public sam(String s){ name=s; } public void showName(){ System.out.println(" Name "+name); } public void setDesgn(String d){ desgn=d; } public void showDesgn(){ System.out.println(" Designation "+d

  • HP 6110 All-in-One Printing from Vista question

    I have recently started using Vista with my printer at home. Whenever I try to print certain webstites that are running programs on ( like one of my work websites) it will print out the HTML code and not what is on the screen. For instance I am looki

  • Code to search for URL

    Hi all im using code to load in text created in notepad which is loadVariablesNum("j:\\Uni work\\Resume_Website\\loads\\SiteFiles\\TextFiles\\Linker.txt", 0); but the finished product will have to be tranported to another computer using probably a ha