JPanel child zoom

I am trying to get a JPanel to paint its child JPanel according to a certain scale factor which the user selects from a JComboBox that is also in the JPanel, the parent one. The problem is that it's painting funny and not scaling the child JPanel. Please take a look at my code. Thanks.
import javax.swing.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.event.*;
public class ZoomPanel extends JPanel
     private double zoom_factor = 1.0;
     private JComboBox zoom_combo;
     private JPanel widget_panel, child_panel;
     public ZoomPanel( JPanel child )
          super( new BorderLayout() );
          zoom_combo =
               new JComboBox(
                    new Double[]
                         new Double( 0.10 ), new Double( 0.25 ), new Double( 0.33 ),
                         new Double( 0.50 ), new Double( 0.75 ), new Double( 1.00 ),
                         new Double( 1.25 ), new Double( 1.50 ), new Double( 2.00 ),
                         new Double( 3.00 ), new Double( 4.00 ), new Double( 5.00 ),
          zoom_combo.setEditable( true );
          zoom_combo.setSelectedIndex( 5 );
          zoom_combo.addActionListener(
               new ActionListener()
                    public void actionPerformed( ActionEvent ae )
                         zoom_factor = ((Double) zoom_combo.getSelectedItem()).doubleValue();
          widget_panel = new JPanel();
          widget_panel.add( zoom_combo );
          add( widget_panel, BorderLayout.NORTH );
          child_panel = child;
          add( child_panel, BorderLayout.CENTER );
     public JPanel getChild()
          return child_panel;
     * Returns the zoom factor.
     public double getZoom()
          return zoom_factor;
     * Changes zoom factor.
     public void setZoom( final double d )
          zoom_factor = d;
          repaint();
     public void paintChildren( Graphics g )
          widget_panel.repaint();
          ((Graphics2D) child_panel.getGraphics()).setTransform(
               AffineTransform.getScaleInstance(
                    zoom_factor,
                    zoom_factor ) );
          child_panel.repaint();
} // ZoomPanel.java

Ok, I did the following changes to your class : import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.geom.AffineTransform;
import java.awt.event.*;
public class ZoomPanel extends JPanel {
     private JComboBox zoom_combo;
     private JPanel widget_panel;
     private ZoomedPanel child_panel;
     public ZoomPanel(ZoomedPanel child) {
          super(new BorderLayout());
          zoom_combo = new JComboBox(new Double[]{new Double(0.10), new Double(0.25), new Double(0.33), new Double(0.50), new Double(0.75), new Double(1.00), new Double(1.25), new Double(1.50), new Double(2.00), new Double(3.00), new Double(4.00), new Double(5.00), });
          zoom_combo.setEditable(true);
          zoom_combo.setSelectedIndex(5);
          zoom_combo.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent ae) {
                    child_panel.setZoomFactor(((Double)zoom_combo.getSelectedItem()).doubleValue());
                    revalidate();
                    repaint();
          widget_panel = new JPanel();
          widget_panel.add(zoom_combo);
          add(widget_panel, BorderLayout.NORTH);
          child_panel = child;
          JPanel pan1 = new JPanel(new BorderLayout());
          JPanel pan2 = new JPanel(new BorderLayout());
          pan1.add(pan2, BorderLayout.NORTH);
          pan2.add(child_panel, BorderLayout.WEST);
          add(pan1, BorderLayout.CENTER);
     public JPanel getChild() {
          return child_panel;
     private static class ZoomedPanel extends JPanel {
          private double zoomFactor;
          public ZoomedPanel() {
               this(true);
          public ZoomedPanel(boolean isDoubleBuffered) {
               this(new FlowLayout(), isDoubleBuffered);
          public ZoomedPanel(LayoutManager layout) {
               this(layout, true);
          public ZoomedPanel(LayoutManager layout, boolean isDoubleBuffered) {
               super(layout, isDoubleBuffered);
               zoomFactor = 1.0;
          public void setZoomFactor(double aZoomFactor) {
               zoomFactor = aZoomFactor;
          public void paint(Graphics g) {
               int w = getWidth();
               int h = getHeight();
               BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
               Graphics2D g2D = (Graphics2D)bi.getGraphics();
               super.paint(g2D);
               Rectangle clipBounds = g.getClipBounds();
               g.setClip(clipBounds.x, clipBounds.y,
                           (int)(clipBounds.width * zoomFactor),
                           (int)(clipBounds.height * zoomFactor));
               ((Graphics2D)g).drawImage(bi, AffineTransform.getScaleInstance(zoomFactor, zoomFactor), null);
     public static void main(String[] args) {
          final JFrame frame = new JFrame("TestZoomPanel");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          ZoomedPanel insidePanel = new ZoomedPanel(new GridLayout(2, 2));
          insidePanel.add(new JButton("totot"));
          insidePanel.add(new JLabel("tutututu"));
          insidePanel.add(new JTextArea("qmsdfkqsdmlfkqsd\nqsdfqsdfqsdfkqsdf\nqsdfqsdfqsdf\nqsdfqsdfqsdfqsdf"));
          insidePanel.add(new JTextField("sdqsdfqsdf"));
          ZoomPanel zoomPanel = new ZoomPanel(insidePanel);
          frame.setContentPane(zoomPanel);
          SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                    frame.pack();
                    frame.setVisible(true);
} // ZoomPanel.javaThis is only to show you how it can be achieved following the approach you were using (that is, override a paint type method).
However, you have to realize that in no way are the subcomponents scaled according to the zoom value. You should think of a more elaborate solution that would effectively change the size of the subcomponents. They could implement a Scalable interface with a scale(double zoomFactor) method used to modify the size of their font, their preferredSize...

Similar Messages

  • Jpanel child action events

    I have a JPanel that i created which has an interface for choosing a date. I dropped the jpanel into an appointment book program im creating. It resides in the main frame of the appointment book program. The datechooser panel implements actionlistener, and changes the date member data field every time the user clicks on a different date, changes the month, etc...
    What i can't figure out, is how to tell when an event has taken place inside the datechooser panel from the appointment book frame. I need to update the appointment table in the appointment book frame every time the user changes the date by clicking on a new date insdide of the datechooser panel.

    Look at PropertyChangeListener in java.beans package. All swing components have the ability to fire property change ecents. Have your date chooser fire a property change event with the new date. Your frame can register as a PCL with the panel.
    There is also a java.swing.event.SwingPropertyChangeSupport class you might want to look at.
    Cheers
    DB

  • About show scrollbar of the JScrollPane problem.

    Hi,
    JPanel main=new JPanel();
    main.setLayout(null);
    JPanel child=new JPanel();
    child.setBounds(...,...,...,...);
    main.add(child);
    JScrollPane jsp=new JScrollPane();
    jsp.getViewPoint().add(main);The problem is that when the child panel 's bounds is out of the visable region of the main panel ,the jscrollpane doesn't show its scrollbar.
    I want show scrollbar so that I can show the invisable child panel.
    How to resolve it?

    Hi,
    JPanel main=new JPanel();
    main.setLayout(null);WRONG 1.
    JPanel child=new JPanel();
    child.setBounds(...,...,...,...);
    main.add(child);
    JScrollPane jsp=new JScrollPane();
    jsp.getViewPoint().add(main);WRONG 2.
    >
    The problem is that when the child panel 's bounds is
    out of the visable region of the main panel ,the
    jscrollpane doesn't show its scrollbar.
    I want show scrollbar so that I can show the
    invisable child panel.
    How to resolve it?WRONG 3.
    You don't set preferred size for the view component.

  • Problem with jpanel zooming

    friends,
    i have a jpanel with image as background and i am adding jlabels dynamically to the jpanel. i have to move the jlabel on the image so i added mouse listener to jlabel. now i want to add zooming functionality to the jpanel.
    now if zoom out jpanel everything works well but jlabel mouse listener location is not changing so if i click on jlabel its not activating listener - i need to click outside of jlabel/jpanel (its original location when its 100% zoom) to activate the listener. how can i correct this ?
    thanks in advance
    i will add example after i cutdown (its part of big application)

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.*;
    import java.util.ArrayList;
    import java.util.List;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    public class PP3 extends JFrame {
        private JButton btnStart;
        private JButton btnStop;
        private JLabel logoLabel;
        private JSlider zoom;
        private JPanel mainPanel;
        private JPanel btnPanel;
        private JScrollPane jspane;
        private BackPanel3 secondPanel;
        private boolean start = false;
        public PP3() {
            initComponents();
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        private void initComponents() {
            logoLabel = new JLabel();
            mainPanel = new JPanel();
            btnPanel = new JPanel();
            btnStart = new JButton();
            btnStop = new JButton();
            zoom = new JSlider(0,100,100);
            setBackground(Color.white);
            setLayout(new BorderLayout());
            mainPanel.setBackground(Color.white);
            mainPanel.setBorder(new EtchedBorder());
            mainPanel.setPreferredSize(new Dimension(650, 600));
            mainPanel.setLayout(new CardLayout());
            jspane = new JScrollPane(getSecondPanel());
            mainPanel.add(jspane,"Second Panel");
            add(mainPanel, BorderLayout.CENTER);
            btnPanel.setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weighty = 1.0;
            gbc.gridwidth = gbc.REMAINDER;
            btnPanel.setBackground(Color.white);
            btnPanel.setBorder(new EtchedBorder());
            btnPanel.setPreferredSize(new Dimension(150, 600));
            btnStart.setText("Start Labelling");
            btnPanel.add(btnStart, gbc);
            btnStart.setEnabled(true);
            btnStart.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent ae){
                    start = true;
                    btnStart.setEnabled(false);
                    btnStop.setEnabled(true);
                    if(secondPanel != null){
                        secondPanel.setStart(start);
                        Cursor moveCursor = new Cursor(Cursor.TEXT_CURSOR);
                        secondPanel.setCursor(moveCursor);
            btnStop.setText("Done Labelling");
            btnPanel.add(btnStop, gbc);
            btnStop.setEnabled(false);
            btnStop.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent ae){
                    start = false;
                    btnStart.setEnabled(true);
                    btnStop.setEnabled(false);
                    if(secondPanel != null){
                        secondPanel.setStart(start);
                        Cursor moveCursor = new Cursor(Cursor.DEFAULT_CURSOR);
                        secondPanel.setCursor(moveCursor);
            final JLabel zoomLabel = new JLabel("Zoom");
            zoomLabel.setBorder(BorderFactory.createEtchedBorder());
            gbc.weighty = 0;
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            btnPanel.add(zoomLabel, gbc);
            btnPanel.add(zoom, gbc);
            zoom.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent ce) {
                    JSlider source = (JSlider)ce.getSource();
                    if(secondPanel != null) {
                        secondPanel.setZoomFactor((double)source.getValue());
                        zoomLabel.setText("Zoom = " + source.getValue()/100.0);
            String id = "<html><nobr>show label</nobr><br><center>locations";
            JCheckBox check = new JCheckBox(id, secondPanel.showLocations);
            check.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    secondPanel.toggleShowLocations();
            gbc.weighty = 1.0;
            gbc.fill = GridBagConstraints.NONE;
            btnPanel.add(check, gbc);
            add(btnPanel, BorderLayout.EAST);
            pack();
        public JPanel getSecondPanel() {
            if(secondPanel == null) {
                secondPanel = new BackPanel3("images/cougar.jpg", 850, 1100);
                secondPanel.setStart(false);
            return secondPanel;
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new PP3();
    class BackPanel3 extends JPanel implements MouseListener,
                                               MouseMotionListener{
        String imgPath = null;
        BufferedImage image;
        private int width = 0;
        private int height = 0;
        private double zoomFactor = 1.0;
        private boolean start = false;
        private boolean same = false;
        Cursor hourglassCursor = new Cursor(Cursor.MOVE_CURSOR);
        // choose a declaration according to your java version
        List<JLabel> labels;     // declaration for j2se 1.5+
    //    List labels;           // j2se 1.4-
        JLabel lastSelected;
        boolean showLocations;
        JLabel selectedLabel;
        boolean dragging;
        Point offset;
        int count = 0;
        private static String SELECTED = "selected";
        public BackPanel3(String path, int width, int height){
            setLayout(null);
            this.width = width;
            this.height = height;
            setPreferredSize(new Dimension(width,height));
            addMouseListener(this);
            addMouseMotionListener(this);
            // chose an instantiation according to your java version
            labels = new ArrayList<JLabel>();    // j2se 1.5+
    //        labels = new ArrayList();          // j2se 1.4-
            lastSelected = new JLabel();
            lastSelected.putClientProperty(SELECTED, Boolean.FALSE);
            showLocations = true;
            dragging = false;
            offset = new Point();
            this.imgPath = path;
            setImage();
        public void setImage(){
            try{
                image = getImage(imgPath);
            }catch(Exception e){
                System.out.println(" (init) ERROR: " + e);
                e.printStackTrace();
        public void setStart(boolean flag){
            start = flag;
        public void setZoomFactor(double zoom){
            zoomFactor = (zoom/100);
            setPreferredSize(new Dimension((int)(850*zoomFactor), (int)(1100*zoomFactor)));
            repaint();
            revalidate();
        public double getZoomFactor(){
            return zoomFactor;
        public void toggleShowLocations() {
            showLocations = !showLocations;
            repaint();
        public void mouseClicked(MouseEvent e) {
            if(start){
                JLabel msgLabel = new JLabel("Test " + count++);
                this.add(msgLabel);
                Dimension d = msgLabel.getPreferredSize();
                msgLabel.setBounds(e.getX(), e.getY(), d.width, d.height);
                labels.add(msgLabel);
                msgLabel.putClientProperty(SELECTED, Boolean.FALSE);
                return;
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            for(int j = 0; j < labels.size(); j++) {
                JLabel label = (JLabel)labels.get(j);
                Rectangle bounds = label.getBounds();
                AffineTransform at =
                    AffineTransform.getScaleInstance(zoomFactor, zoomFactor);
                Shape xs = at.createTransformedShape(bounds);
                if(xs.contains(p)) {
                    selectedLabel = label;
                    Rectangle r = xs.getBounds();
                    offset.x = p.x - r.x;
                    offset.y = p.y - r.y;
                    dragging = true;
                    break;
        public void mouseReleased(MouseEvent e) {
            dragging = false;
        public void mouseDragged(MouseEvent me){
            if(dragging) {
                Rectangle bounds = selectedLabel.getBounds();
                AffineTransform at =
                    AffineTransform.getScaleInstance(1.0/zoomFactor, 1.0/zoomFactor);
                Point2D p = at.transform(me.getPoint(), null);
                int x = (int)(p.getX() - offset.x);
                int y = (int)(p.getY() - offset.y);
                selectedLabel.setLocation(x, y);
                repaint();
        public void mouseMoved(MouseEvent me){
            if(labels.size() == 0)
                return;
            Point p = me.getPoint();
            boolean hovering = false;
            boolean selectionChanged = false;
            for(int j = 0; j < labels.size(); j++) {
                final JLabel label = (JLabel)labels.get(j);
                Rectangle r = label.getBounds();
                AffineTransform at =
                    AffineTransform.getScaleInstance(zoomFactor, zoomFactor);
                Shape scaledBounds = at.createTransformedShape(r);
                if(scaledBounds.contains(p)) {
                    hovering = true;
                    if(!((Boolean)label.getClientProperty(SELECTED)).booleanValue()) {
                        label.putClientProperty("selected", Boolean.TRUE);
                        setCursor(hourglassCursor);
                        if(lastSelected != label)  // for only one JLabel
                            lastSelected.putClientProperty(SELECTED, Boolean.FALSE);
                        lastSelected = label;
                        selectionChanged = true;
                        break;
            // reset lastSelected when there is no selection/hovering
            if(!hovering &&
                ((Boolean)lastSelected.getClientProperty(SELECTED)).booleanValue()) {
                lastSelected.putClientProperty(SELECTED, Boolean.FALSE);
                setCursor(Cursor.getDefaultCursor());
                selectionChanged = true;
            if(selectionChanged)
                repaint();
        public void mouseEntered(MouseEvent e) { }
        public void mouseExited(MouseEvent e) { }
        protected void paintComponent(Graphics g){
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.scale(zoomFactor, zoomFactor);
            g2.drawImage(image, 0, 0, this);
            if(showLocations) {
                // show bounds of the actual JLabel children
                // components as they exist on this component
                AffineTransform at = AffineTransform.getScaleInstance(1.0/zoomFactor,
                                                                      1.0/zoomFactor);
                g2.setPaint(Color.blue);
                Component[] c = getComponents();
                for(int j = 0; j < c.length; j++)
                    g2.draw(at.createTransformedShape(c[j].getBounds()));
            // show selected label
            g2.setPaint(Color.red);
            for(int j = 0; j < labels.size(); j++) {
                JLabel label = (JLabel)labels.get(j);
                if(((Boolean)label.getClientProperty("selected")).booleanValue()) {
                    g2.draw(label.getBounds());
                    break;
        protected BufferedImage getImage(String path){
            try{
                URL imgURL = BackPanel3.class.getResource(path);
                if (imgURL == null &&
                       (path.indexOf(":\\") > 0 || path.indexOf(":/") > 0))
                    imgURL = new URL("file:///"+path);
                return getImage(imgURL);
            }catch(MalformedURLException mue){
                System.out.println("error "+mue);
            return null;
        protected BufferedImage getImage(URL url){
            try{
                if (url != null) {
                    BufferedImage source = ImageIO.read(url);
                    double xScale = (double)width / source.getWidth();
                    double yScale = (double)height / source.getHeight();
                    double scale = Math.min(xScale, yScale);
                    int w = (int)(scale*source.getWidth());
                    int h = (int)(scale*source.getHeight());
                    BufferedImage scaled = new BufferedImage(w, h, source.getType());
                    Graphics2D g2 = scaled.createGraphics();
                    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                        RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                    // scales faster than getScaledInstance
                    AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
                    g2.drawRenderedImage(source, at);
                    g2.dispose();
                    return scaled;
                }else{
                    return null;
            }catch(IOException ioe){
                System.out.println("read error "+ioe);
                return null;
    }

  • Selective Zoom of A JPanel

    I have an JPanel to which I am drawing an image. It is appearing rather small so I would like
    the user to have control over the image, so a mouse click in a specific location would zoom in on
    that region of the image, and a release would revert the image to it's actual size.
    //Within the JPanel's paintComponent
              if(isZoomed)
                   Graphics2D g2 = (Graphics2D) g;
    //possible translation? here
                   g2.scale(2.0, 2.0);
    //or here?
                   g2.drawImage(Image, 0, 0, getWidth(), getHeight(), this);
    //or here?
    My MouseListeners just relate (evt being the mouseEvent):
              x = evt.getX();
              y = evt.getY();
              isZoomed = !isZoomed;
    In it's current form it just scales the image - as result all I see is the top left corner of the image scaled. As stated
    I would like to make it a more selective and localized zoom, which seems reasonable and fairly easy to implement but confusing to me.
    Thanks!

    See those 0, 0 in the drawImage method call? Calculate negative values to set those two such that the zoomed portion is displayed instead.

  • Zooming a Jpanel that contains Jbutton

    My question is how to zoom a jpanel that contains several jbutton... I am not sure what method to use.... when using a Graphics2D object there seem to be only methods as g.drawString(...)
    g.drawRectangle(..) etc... I am kind of familiar with
    AffineTransform, scaling matrix, etc but not how to zoom a jpanel with jcomponent...
    I hope some one out there understand what i am trying to do...please could you give me any idea
    thanx

    Hello.
    The solution could be the following:
    1. Create interface ZoomPane with the following methods:
    boolean isZoomMode
    float getZoomFactor
    2. ZoomPane interface must be implemented by some JComponent (JPanel will fit, assume it's called JZoomPanel)
    3. the paint method's body of the JZoomPanel should looks like:
    Graphics2D g2 = (Graphics2D)g;
    if(isZoomMode()){
    float zoomFactor = getZoomFactor();
    g2.scale(zoomFactor, zoomFactor);
    super.paint(g);
    4. Use updated RepaintManager.
    This solution solve all painting problem. The mouse event transformation problem can be solved as described above (by means of the glass pane).

  • How to use scale method in Graphics2D for zoom in/out in JPanel.

    Hi All,
    Iam working on zoom functionality, I have JPanel as my Drawing view while creating iam setting scale as 1.0D... if you click on zoom in or zoom out button iam again setting the scale of graphics2D object like below.
    if(!(g instanceof Graphics2D)) {
    super.paint(g);
    return;
    else {
         Graphics2D g2 = (Graphics2D)g;
         g2.scale(m_dMagnitude, m_dMagnitude);
         super.paint(g2);
    As i added my JPanel on JTabbedPane and when i try to zoom out the view you can see the color difference as both have different back ground color. And when iam trying to add any graphics object it's not adding where you click mouse.
    Can any buddy let me know is there any way to do this, if any one have code pls pass to me.

    The only way to access a protected variable is to subclass.
    MyCalendar extends Calendar
    but I doubt you need to do this. If you only want to tell if a Calendar object has a time associated with it, try using
    cal.isSet( Calendar.HOUR );

  • Zoom IN and OUT on a Jpanel

    hello,
    i'm wondering if there is a way to apply zoom in and out features on a Jpanel that contains components.
    i googled it but found no answer.
    thank you

    here is a gd link where u can find a good example: http://coding.derkeiler.com/Archive/Java/comp.lang.java.gui/2004-02/0719.html

  • Zooming a jpanel containing several jbuttons

    My question is how to zoom a jpanel that contains several jbutton... I am not sure what method to use.... when using a Graphics2D object there seem to be only methods as g.drawString(...)
    g.drawRectangle(..) etc... I am kind of familiar with
    AffineTransform, scaling matrix, etc but not how to zoom a jpanel with jcomponent...
    I hope some one out there understand what i am trying to do...please could you give me any idea
    thanx

    hi again
    well that is the point i have written such sub class where i draw a rectangle and then I scale it etc..
    to test paint () etc but that is what i do not want to ....
    what I want to do is to draw is my subclass of Jbutton that has some specific properties I HAVE TO USE THEM... and only zoom these specific button and not everything else on my subclass of Jpanel...
    Spanel extends JPanel
    MybuttonClass m = new MybuttonClass();
    paint()
    how do I draw the myButton on the panel...after zooming in zoomin out...
    there no such thing
    g.draw(myButton);
    does all this make a sense to you..
    i hope so
    thanx

  • Zoom in/out in a JPanel

    Can anyone please tell me how to implement "Zoom in" and "Zoom out" in a Jpanel
    PLease send me the code for doing that
    thanks

    here is a gd link where u can find a good example: http://coding.derkeiler.com/Archive/Java/comp.lang.java.gui/2004-02/0719.html

  • Zooming causes components on JPanel to displace

    Hi friends,
    my english is somewhat weak, but i am trying to clear my point.
    I have a prob regarding zoom. In my application I have A JPanel which is drawing some rectangles on it and having some JLabels. My prob is when i zoomin my JPanel through my zooming code and try to select any of JLabel ,I am not actually selecting labels by just clicking on the label but i have to make some random guess on JPanel to select that label.
    I am not getting what mistake i m making there. may be i would have to move my labels by some distance on zooming(but its only my view). if any of you have some ideas then please do tell me.
    thankyou

    I second camickr's recommendation for you to study the tutorials. A few specifics:
    public void paint(Graphics g){
       g.setColor(Color.black );
       drawDisplay(g);
    }* Don't override the paint method of a JPanel, override the paintComponent method.
    * You will need to call super.paintComponent(g) within your paintComponent override. This may need to be the first line in fact.
    * As noted by camickr, do not place AWT components on a Swing component (JPanel).

  • Zoom JPanel and all its components

    Folkses,
    I have a JPanel which contains a lot of different components, containers with components, etc.
    The components are either images or drawn 'by hand' (overwritten paintComponent).
    Is there a simple way of zooming in/out to get the whole picture larger/smaller? I know Graphics2D.scale() but I'm hestitant to implement this in each and every component of my JPanel.
    Thanx,
    Thomas
    PS: searching the forum I only found answers on zooing images...

    Hello camickr,
    I am also very much interested in this.
    Well, you can create an image of a panel and then zoom the image.But I think this will not increase the components' bounds and components would not respond mouse events etc. correctly. Am I right? Then, what is the way of zooming such that all the components respond to events correctly.
    I hope you have done something like this before and help us.
    Thanks!

  • How to Zoom In/Out on JPanel

    Hi,
    I am working on an application and it that i have created one JPanel and added custom components to it.
    Now my problem is i want scale the JPanel, how an i do that and after scaling the Jpanel i want the all components i added in that also scale and reposined accordingly. Also i want to handle the event from that components after scaleing.
    Thanks in advance.

    all components i added in that also scale and reposined accordingly.Sounds like you want a Layout Manager, possibly GridBagLayout.
    i want to handle the event from that components after scaleing.If I understand that correctly, you want ComponentListener.componentResized and/or componentMoved.
    db

  • Reusing Buttons and JPanels

    Hi,
    I am building a GUI for a project which has a basic view tab and an advanced view tab, using JTabbedPane. The advanced view mode would essentially have all the basic mode buttons and panels and an extra few more features that aren't in the basic mode. The problem is that when I decided to reuse the JButtons and Panels that I built for the baisc mode, all of them get transferred to the the advanced view mode (because it was coded last). And the Basic mode is left bare without its buttons. Is there a way I could clone buttons and panels, etc. I know a simple but tedious fix is to make two of every button and panel that are used in the basic mode, but that is just terrible especially since the listeners will too have to be made twice. Can't I just use the same instance of a button or panel in both modes???
    Another fix I had in mind was have a listener that repaints the advanced view mode whenever its clicked on.
    Thanks all.

    Flouder here is an example, I tried to remove as much irrelevant information buts its a self-contained compilable example that details what I mean. Here are a few points of interest:
    if you comment out code "advancedOptions.add(imageOptions2);", you will see that this panel goes back to basicOptions tab. If you have this code alongside the rest of the code, it will steal that panel and paste it into advancedOptions tab.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class JavaQuestion{
         // Initialize all swing objects.
        private JFrame f = new JFrame("ToolWatchers User Advisor"); //create Frame
        private Container leftContainer = new Container();
        private Container basicOptions = new Container();
        private Container advancedOptions = new Container();
        private JTabbedPane tabbedPane = new JTabbedPane();
        //Intialize Basic Options
        private JButton prevImage = new JButton("Previous Image");
        private JButton nextImage = new JButton("Next Image");
        private JButton processImage = new JButton("Process Image");
        private JButton currentImage = new JButton("Current Image");
        private JButton statOption1 = new JButton("Stat Option 1");
        private JButton statOption2 = new JButton("Stat Option 2");
        private JButton statOption3 = new JButton("Stat Option 3");
        //Intialize Advanced Options
        private JButton captureImage = new JButton("Capture");
        private JButton analyzeImage = new JButton("Analyze Image");
        private JButton selectionTool = new JButton("Selection Tool");
        private JButton zoomTool = new JButton("Zoom Tool");
        private JButton nextProcess = new JButton("Next Image Process");
        /** Constructor for the GUI */
        public JavaQuestion(){
            //Build Main Interface (leftContainer Container)
            buildTabbedPane();
            buildLeftContainer();
            // Setup Main Frame
            f.getContentPane().setLayout(new GridLayout(1, 2));
            f.setSize(900, 700);
            f.add(leftContainer);
            //Allows the Swing App to be closed
            f.addWindowListener(new ListenCloseWdw());
         public void buildTabbedPane() {
              tabbedPane.setAlignmentY(leftContainer.LEFT_ALIGNMENT);
            buildBasicView();
              buildAdvancedView();
         public void buildBasicView() {
              //image_options is the main panel that contains most image buttons
              //image_Options is a child panel that contains  prev,curr,next buttons
              prevImage.setAlignmentY(prevImage.TOP_ALIGNMENT);
              currentImage.setAlignmentY(prevImage.TOP_ALIGNMENT);
              nextImage.setAlignmentY(prevImage.TOP_ALIGNMENT);
              JPanel image_Options = new JPanel();
              image_Options.setLayout(new BoxLayout(image_Options, BoxLayout.X_AXIS));
              image_Options.setMinimumSize(new Dimension(100, 25));
              image_Options.setPreferredSize(new Dimension(450, 30));
              image_Options.setMaximumSize(new Dimension(1024, 30));
              image_Options.setAlignmentX(image_Options.LEFT_ALIGNMENT);
              //Create next, current, previous buttons (put into display options pane)
              image_Options.add(prevImage);
              image_Options.add(Box.createRigidArea(new Dimension(25,0)));
              image_Options.add(currentImage);
              image_Options.add(Box.createRigidArea(new Dimension(25,0)));
              image_Options.add(nextImage);
              image_Options.add(Box.createRigidArea(new Dimension(25,0)));
              processImage.setAlignmentX(processImage.LEFT_ALIGNMENT);
              JPanel image_options = new JPanel();
              image_options.setBorder(BorderFactory.createTitledBorder("Image Options"));
              image_options.setLayout(new BoxLayout(image_options, BoxLayout.Y_AXIS));
              image_options.setAlignmentX(image_options.LEFT_ALIGNMENT);
              image_options.setPreferredSize(new Dimension(450, 100));
              image_options.setMaximumSize(new Dimension(1024, 100));
              image_options.add(image_Options);
              image_options.add(Box.createRigidArea(new Dimension(0,25)));
              image_options.add(processImage);
              JPanel statistics = new JPanel();
              statistics.setBorder(BorderFactory.createTitledBorder("Statisic Options"));
              statistics.setLayout(new BoxLayout(statistics, BoxLayout.X_AXIS));
              statistics.setAlignmentX(statistics.LEFT_ALIGNMENT);
              statistics.setPreferredSize(new Dimension(450, 55));
              statistics.setMaximumSize(new Dimension(450, 55));
              statOption1.setAlignmentY(statOption1.TOP_ALIGNMENT);
              statOption2.setAlignmentY(statOption1.TOP_ALIGNMENT);
              statOption3.setAlignmentY(statOption1.TOP_ALIGNMENT);
              statistics.add(statOption1);
              statistics.add(Box.createRigidArea(new Dimension(25,0)));
              statistics.add(statOption2);
              statistics.add(Box.createRigidArea(new Dimension(25,0)));
              statistics.add(statOption3);
              basicOptions.setLayout(new BoxLayout(basicOptions, BoxLayout.Y_AXIS));
              basicOptions.setMinimumSize(new Dimension(450, 200));
              basicOptions.add(image_options);
              basicOptions.add(statistics);
              tabbedPane.addTab("Basic View", basicOptions);
         public void buildAdvancedView() {
              //Add the Advanced view options which include basic options
              Component imageOptions2 = basicOptions.getComponent(0);
              JPanel toolPane1 = new JPanel();
              toolPane1.setLayout(new BoxLayout(toolPane1, BoxLayout.X_AXIS));
              toolPane1.setAlignmentX(toolPane1.LEFT_ALIGNMENT);
              toolPane1.add(captureImage);
              toolPane1.add(Box.createRigidArea(new Dimension(25, 0)));
              toolPane1.add(analyzeImage);
              toolPane1.add(Box.createRigidArea(new Dimension(25, 0)));
              toolPane1.add(nextProcess);
              toolPane1.add(Box.createRigidArea(new Dimension(25, 0)));
              JPanel toolPane2 = new JPanel();
              toolPane2.setLayout(new BoxLayout(toolPane2, BoxLayout.X_AXIS));
              toolPane2.setAlignmentX(toolPane1.LEFT_ALIGNMENT);
              toolPane2.add(selectionTool);
              toolPane2.add(Box.createRigidArea(new Dimension(25, 0)));
              toolPane2.add(zoomTool);
              toolPane2.add(Box.createRigidArea(new Dimension(25, 0)));
              JPanel imageTools = new JPanel();
              imageTools.setBorder(BorderFactory.createTitledBorder("Image Tools"));
              imageTools.setLayout(new BoxLayout(imageTools, BoxLayout.Y_AXIS));
              imageTools.setAlignmentX(imageTools.LEFT_ALIGNMENT);
              imageTools.add(toolPane1);
              imageTools.add(Box.createRigidArea(new Dimension(0, 25)));
              imageTools.add(toolPane2);
              advancedOptions.setLayout(new BoxLayout(advancedOptions, BoxLayout.Y_AXIS));
              advancedOptions.setMinimumSize(new Dimension(450, 200));
              advancedOptions.add(imageOptions2);
              advancedOptions.add(imageTools);
              //TODO Step through Image processing
              tabbedPane.addTab("Advanced View", advancedOptions);
         public void buildLeftContainer() {
              leftContainer.setLayout(new BoxLayout(leftContainer, BoxLayout.Y_AXIS));
            leftContainer.add(tabbedPane);
        public class ListenMenuQuit implements ActionListener{
            public void actionPerformed(ActionEvent e){
                System.exit(0);        
        public class ListenCloseWdw extends WindowAdapter{
            public void windowClosing(WindowEvent e){
                System.exit(0);        
        public void launchFrame(){
            // Display Frame
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setVisible(true);
        public static void main(String args[]){
            JavaQuestion gui = new JavaQuestion();
            gui.launchFrame();
    }

  • Scaling JFrames/JPanels/JInternalFrames

    Hey,
    After having a lot of trouble trying to scale the contents of JFrames/JInternalFrames using mouse events, I decided that I should try using a popup menu to allow me to specify a certain content ratio to scale the container's contents.
    A little history: I wanted to be able to scale JInternalFrames so that the contents (images) maintain their aspect ratio. I modified my code via some suggestions, but the results were not as good as I wanted them to be. If you have any ideas on mouse scaling, I'd really appreciate them. Here's a link to an old forum thread: http://forum.java.sun.com/thread.jsp?forum=57&thread=149864
    Back to the present: Now the problem I'm having using the popup is that, if I scale to a size greater than 100%, the parent window will scale, but the child components will not scale. I've included a copy of the code below. Your suggestions will be greatly appreciated.
    TJDeep.
    Code:
    //ImagePanel.java
    /* This class defines a generic image panel that allows for:
    * - image resizing
    * - image containment
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class ImagePanel extends JPanel
        implements ComponentListener {
        //variables
        JFrame parent;
        ImagePanelPopupMenu popupMenu;
        JPopupMenuShower popupShower;
        Dimension originalDimension;
        boolean originalSet = false;
        public ImagePanel(JFrame parent) {
            this.parent = parent;
            init();
        private void init() {
            popupMenu = new ImagePanelPopupMenu(this);
            popupShower = new JPopupMenuShower(popupMenu);
            addMouseListener(popupShower);
            setLayout(new BorderLayout());
            addComponentListener(this);
        public void setOriginalDimension(Dimension dim) {
            originalDimension = new Dimension(dim);
        public Dimension getOriginalDimension() {
            return new Dimension(originalDimension);
        public void componentHidden(ComponentEvent ce) { }
        public void componentMoved(ComponentEvent ce) { }
        public void componentShown(ComponentEvent ce) { }
        public synchronized void componentResized(ComponentEvent ce) {
            Point parentOrigin = parent.getLocation();
            Dimension parentSize = parent.getSize();
            Dimension parentContentSize = parent.getContentPane().getSize();
            int deltaWidth = parentSize.width - parentContentSize.width;
            int deltaHeight = parentSize.height - parentContentSize.height;
            parent.getContentPane().setSize(getSize());
            parent.setBounds(parentOrigin.x, parentOrigin.y,
                           getSize().width + deltaWidth,
                           getSize().height + deltaHeight);
        public void paint(Graphics g) {
            g.dispose();
            g.setColor(Color.black);
            g.fillRect(0, 0, getSize().width, getSize().height);
            g.setColor(Color.white);
            g.drawRect(5, 5, getSize().width - 10, getSize().height - 10);
        public static void main(String[] args) {
            JFrame frame = new JFrame("Image Panel Test");
            Container contentPane = frame.getContentPane();
            frame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent we) {
                        System.exit(0);
            ImagePanel imagePanel = new ImagePanel(frame);
            Dimension dim = new Dimension(200, 200);
            imagePanel.setOriginalDimension(dim);
            Dimension dim2 = new Dimension(500, 500);
            //imagePanel.setMaximumSize(dim2);
            imagePanel.setPreferredSize(dim);
            //imagePanel.setSize(dim);
            contentPane.add(imagePanel, BorderLayout.CENTER);
            frame.pack();
            //frame.setResizable(false);
            frame.setVisible(true);
            contentPane.setSize(imagePanel.getSize());
    class ImagePanelPopupMenu extends JPopupMenu
        implements ActionListener {
        //identification
        ImagePanel parent;
        //Menu items
        JMenuItem z050;
        JMenuItem z075;
        JMenuItem z100;
        JMenuItem z150;
        JMenuItem z200;
        JMenuItem zCustom;
        //Miscellaneous configuration
        Font defaultFont = new Font("Helvetica", Font.PLAIN, 10);
        public ImagePanelPopupMenu(ImagePanel parent) {
            super("ZOOM");
            this.parent = parent;
            setFont(defaultFont);
            //configure the menu elements
            z050 = new JMenuItem("50 %");
            z050.setActionCommand("z050");
            z050.setFont(defaultFont);
            z050.addActionListener(this);
            add(z050);
            z075 = new JMenuItem("75 %");
            z075.setActionCommand("z075");
            z075.setFont(defaultFont);
            z075.addActionListener(this);
            add(z075);
            z100 = new JMenuItem("100 %");
            z100.setActionCommand("z100");
            z100.setFont(defaultFont);
            z100.addActionListener(this);
            add(z100);
            z150 = new JMenuItem("150 %");
            z150.setActionCommand("z150");
            z150.setFont(defaultFont);
            z150.addActionListener(this);
            add(z150);
            z200 = new JMenuItem("200 %");
            z200.setActionCommand("z200");
            z200.setFont(defaultFont);
            z200.addActionListener(this);
            add(z200);
            zCustom = new JMenuItem("Custom...");
            zCustom.setActionCommand("zCustom");
            zCustom.setFont(defaultFont);
            zCustom.addActionListener(this);
            addSeparator();
            add(zCustom);
            pack();
        public void actionPerformed(ActionEvent ae) {
            String item = ae.getActionCommand();
            Dimension dim = new Dimension(parent.getSize());
            if (item.equals("z050")) {
                dim = computeDimension(50);
            else if (item.equals("z075")) {
                dim = computeDimension(75);
            else if (item.equals("z100")) {
                dim = computeDimension(100);
            else if (item.equals("z150")) {
                dim = computeDimension(150);
            else if (item.equals("z200")) {
                dim = computeDimension(200);
            else if (item.equals("zCustom")) {
                String inputString =
                    JOptionPane.showInputDialog(this, "Please enter a view percentage:",
                                                "Custom Zoom", JOptionPane.OK_CANCEL_OPTION);
                if (inputString == null) return;
                try {
                    double inputNumber = Double.parseDouble(inputString);
                    dim = computeDimension(inputNumber);
                } catch (NumberFormatException nfe) { }
            parent.setSize(dim);
            //parent.setBounds(0, 0, dim.width, dim.height);
            //modify for use with custom, and captions.
        public Dimension computeDimension(double percent) {
            double factor = percent/100;
            Dimension dim = parent.getOriginalDimension();
            dim.height *= factor;
            dim.width *= factor;
            return dim;
    class JPopupMenuShower extends MouseAdapter {
        private JPopupMenu popup;
        public JPopupMenuShower(JPopupMenu popup) {
            this.popup = popup;
        private void showIfPopupTrigger(MouseEvent me) {
            if (popup.isPopupTrigger(me))
                popup.show(me.getComponent(), me.getX(), me.getY());
        public void mousePressed(MouseEvent me) {
            showIfPopupTrigger(me);
        public void mouseReleased(MouseEvent me) {
            showIfPopupTrigger(me);
    }

    Isn't there anyone out there who can help me with this problem...
    TJDeep

Maybe you are looking for

  • How to embed a Video stored in KM repository on html page

    Hi All, I have a requirement to embed a video stored in KM repository on html page. My html page and related file referred in html code below (highlighted) are stored at following path in KM “root>documents>test” with the same name as mentioned in co

  • MacBook Pro 2ghz and 1366x768 HDTV?

    Can a MacBook Pro 2ghz drive a 1366x768 HDTV? The Displays pane does show 1360x768, but this doesn't look good with a ldc tv with a native resolution of 1366x768. I couldn't find any information on this in the AppleCare area. There is an item that sa

  • Using iWeb with MobileMe family pack

    I just upgraded to the family pack for mobile me. I had been using it for my homepage, but now I'd like to make a homepage for my son, and my wife wants to make a homepage as well. How is this handled in iWeb? I don't see a way to tell it where to pu

  • Hyperlinks in alternate layout folios

    got a vertical layout and an alternate horizontal layout for my ipad folio in the same document. created the internal navigation (eg click shape to return to front cover) on the vertical layout first, works fine. Created horizontal layout and adapted

  • Swap Error: Windows Azure is currently performing an operation on this deployment that requires exclusive access.

    When swapping our deployments for a web role, we are receiving an error, "Windows Azure is currently performing an operation on this deployment that requires exclusive access."  We have been waiting patiently for over 48 hours and the error persists.