How to zoom a JPanel and its components?

2

I am creating a tag editor in java and I want to make the user zoom in the work area ( JPanel ) as well as the components that are inside.

Here my code:

Graphics2D g2 = (Graphics2D) PPanel1.getGraphics();
int w = PPanel1.getWidth();
int h = PPanel1.getHeight();

double scale = 1.25;

g2.translate(w / 2, h / 2);
g2.scale(scale, scale);
g2.translate(-w / 2, -h / 2);

PPanel1.paintComponents(g2);

PPanel1.updateUI();

PPanel1.setSize(PPanel1.getWidth() * 1.25, PPanel1.getHeight() * 1.25);
            CZoom.setSelectedIndex(cambiarPosicion);

d = new Dimension(PPanel1.getWidth(), PPanel1.getHeight());
PPanel1.setSize(d);

Zooms the components if I do not change the size of the panel, but when I resize, it does not zoom the components.

    
asked by Giovani Preciado Ortiz 05.09.2017 в 16:21
source

1 answer

1

Several things:

PPanel1.setSize(PPanel1.getWidth() * 1.25, PPanel1.getHeight() * 1.25);
CZoom.setSelectedIndex(cambiarPosicion);
  • The first instruction should not work, since the width and height that receive the setSize method are integers (and there you are implicitly converting to double by multiplying by 1.25).
  • CZoom and changePosition are two variables whose origin I do not know.

That said, you do not specify in what kind of event you want the resizing to occur, so I've solved it with MouseEntered and MouseExited (more information < a href="https://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseListener.html" title="Mouse Listener"> here ):

private void etiqueta1MouseEntered(java.awt.event.MouseEvent evt) {                                       
    etiqueta1.setFont(new Font(
            etiqueta1.getFont().getName(),
            etiqueta1.getFont().getStyle(),
            etiqueta1.getFont().getSize() * 2));

    panel1.setSize(panel1.getSize().width + 100, panel1.getSize().height + 100);
    this.setSize(this.getSize().width + 100, this.getSize().height + 100);
}                                      

private void etiqueta1MouseExited(java.awt.event.MouseEvent evt) {                                      
    etiqueta1.setFont(new Font(
            etiqueta1.getFont().getName(),
            etiqueta1.getFont().getStyle(),
            etiqueta1.getFont().getSize() / 2));

    panel1.setSize(panel1.getSize().width - 100, panel1.getSize().height - 100);
    this.setSize(this.getSize().width - 100, this.getSize().height - 100);
}

Initial Status

When I move the mouse over the label, what I do is change the font size to double the current one, and increase the size of the class object JPanel and of its own JFrame in 100 pixels.

When I leave the label I reverse the process, leaving everything as it was.

    
answered by 12.09.2017 в 16:03