Example usage for javax.swing JLabel getWidth

List of usage examples for javax.swing JLabel getWidth

Introduction

In this page you can find the example usage for javax.swing JLabel getWidth.

Prototype

@BeanProperty(bound = false)
public int getWidth() 

Source Link

Document

Returns the current width of this component.

Usage

From source file:Main.java

public static void main(String[] args) {
    String s = "The quick brown fox jumps over the lazy dog!";
    BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.getGraphics();
    FontMetrics fm = g.getFontMetrics();
    Rectangle2D b = fm.getStringBounds(s, g);
    System.out.println(b);//from w ww .  j av  a 2  s.  co m
    bi = new BufferedImage((int) b.getWidth(), (int) (b.getHeight() + fm.getDescent()),
            BufferedImage.TYPE_INT_RGB);
    g = bi.getGraphics();
    g.drawString(s, 0, (int) b.getHeight());

    JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(bi)));

    // Technique 3 - JLabel
    JLabel l = new JLabel(s);
    l.setSize(l.getPreferredSize());
    bi = new BufferedImage(l.getWidth(), l.getHeight(), BufferedImage.TYPE_INT_RGB);
    g = bi.getGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, 400, 100);
    l.paint(g);

    JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(bi)));
}

From source file:Main.java

public static Rectangle getTextRectangle(JLabel label) {

    String text = label.getText();
    Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon();

    if ((icon == null) && (text == null)) {
        return null;
    }/* w w  w  . j  av a  2s .c  o m*/

    Rectangle paintIconR = new Rectangle();
    Rectangle paintTextR = new Rectangle();
    Rectangle paintViewR = new Rectangle();
    Insets paintViewInsets = new Insets(0, 0, 0, 0);

    paintViewInsets = label.getInsets(paintViewInsets);
    paintViewR.x = paintViewInsets.left;
    paintViewR.y = paintViewInsets.top;
    paintViewR.width = label.getWidth() - (paintViewInsets.left + paintViewInsets.right);
    paintViewR.height = label.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);

    Graphics g = label.getGraphics();
    if (g == null) {
        return null;
    }
    String clippedText = SwingUtilities.layoutCompoundLabel(label, g.getFontMetrics(), text, icon,
            label.getVerticalAlignment(), label.getHorizontalAlignment(), label.getVerticalTextPosition(),
            label.getHorizontalTextPosition(), paintViewR, paintIconR, paintTextR, label.getIconTextGap());

    return paintTextR;
}

From source file:de.mprengemann.intellij.plugin.androidicons.images.ImageUtils.java

public static void updateImage(JLabel imageContainer, File imageFile) {
    if (!imageFile.exists()) {
        return;/*from w  w  w.j a v  a  2s.co m*/
    }
    BufferedImage img = null;
    try {
        img = ImageIO.read(imageFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (img == null) {
        return;
    }
    int imageWidth = img.getWidth();
    int imageHeight = img.getHeight();
    int imageViewWidth = imageContainer.getWidth();
    int imageViewHeight = imageContainer.getHeight();
    double factor = getScaleFactorToFit(new Dimension(imageWidth, imageHeight),
            new Dimension(imageViewWidth, imageViewHeight));
    factor = Math.min(factor, 1f);
    imageWidth = (int) (factor * imageWidth);
    imageHeight = (int) (factor * imageHeight);
    if (imageWidth <= 0 || imageHeight <= 0 || imageViewWidth <= 0 || imageViewHeight <= 0) {
        return;
    }
    BufferedImage tmp = UIUtil.createImage(imageViewWidth, imageViewHeight, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = tmp.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    int x = (imageViewWidth - imageWidth) / 2;
    int y = (imageViewHeight - imageHeight) / 2;
    g2.drawImage(img, x, y, imageWidth, imageHeight, null);
    g2.dispose();
    imageContainer.setIcon(new ImageIcon(tmp));
}

From source file:AppSpringLayout.java

protected ImageIcon scaleBufferedImage(BufferedImage img, JLabel label) {

    ImageIcon icon = null;/*from w ww .jav  a  2  s  .c o  m*/
    try {
        icon = new ImageIcon(img);
        double width = icon.getIconWidth();
        double height = icon.getIconHeight();
        double labelWidth = label.getWidth();
        double labelHight = label.getHeight();
        double scaleWidth = width / labelWidth;
        double scaleHeight = height / labelHight;

        if (width >= height) {
            // horizontal image
            double newWidth = width / scaleWidth;
            icon = new ImageIcon(icon.getImage().getScaledInstance((int) newWidth, -1, Image.SCALE_SMOOTH));
        } else {
            // vertical image
            double newHeight = height / scaleHeight;
            icon = new ImageIcon(icon.getImage().getScaledInstance(-1, (int) newHeight, Image.SCALE_SMOOTH));
        }
    } catch (NullPointerException e) {
        try {
            originalImage = (BufferedImage) ImageIO.read(new File("img/error.png"));
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        e.printStackTrace();
    }

    return icon;
}

From source file:com.openbravo.pos.util.ThumbNailBuilder.java

public Image getThumbNailText(Image img, String text) {
    /*/*from  w w w  .j a  v a  2 s. c om*/
     * Create an image containing a thumbnail of the product image,
     * or default image.
     * 
     * Then apply the text of the product name. Use text wrapping.
     * 
     * If the product name is too big for the label, ensure that
     * the first part is displayed.
     */

    img = getThumbNail(img);

    BufferedImage imgtext = new BufferedImage(img.getWidth(null), img.getHeight(null),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = imgtext.createGraphics();

    // The text
    // <p style="width: 100px"> DOES NOT WORK PROPERLY.
    // use width= instead.
    String html = "<html><p style=\"text-align:center\" width=\"" + imgtext.getWidth() + "\">"
            + StringEscapeUtils.escapeHtml(text) + "</p>";

    JLabel label = new JLabel(html);
    label.setOpaque(false);
    //label.setText("<html><center>Line1<br>Line2");
    label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    label.setVerticalAlignment(javax.swing.SwingConstants.TOP);
    Dimension d = label.getPreferredSize();
    label.setBounds(0, 0, imgtext.getWidth(), d.height);

    // The background
    Color c1 = new Color(0xff, 0xff, 0xff, 0x40);
    Color c2 = new Color(0xff, 0xff, 0xff, 0xd0);

    //        Point2D center = new Point2D.Float(imgtext.getWidth() / 2, label.getHeight());
    //        float radius = imgtext.getWidth() / 3;
    //        float[] dist = {0.1f, 1.0f};
    //        Color[] colors = {c2, c1};        
    //        Paint gpaint = new RadialGradientPaint(center, radius, dist, colors);
    Paint gpaint = new GradientPaint(new Point(0, 0), c1, new Point(label.getWidth() / 2, 0), c2, true);

    g2d.drawImage(img, 0, 0, null);
    int ypos = imgtext.getHeight() - label.getHeight();
    int ypos_min = -4; // todo: configurable
    if (ypos < ypos_min)
        ypos = ypos_min; // Clamp label
    g2d.translate(0, ypos);
    g2d.setPaint(gpaint);
    g2d.fillRect(0, 0, imgtext.getWidth(), label.getHeight());
    label.paint(g2d);

    g2d.dispose();

    return imgtext;
}

From source file:generadorqr.jifrNuevoQr.java

void CargarImagen(JLabel label, Integer identificador) {
    int resultado;
    // ventana = new CargarFoto();
    JFileChooser jfchCargarfoto = new JFileChooser();
    FileNameExtensionFilter filtro = new FileNameExtensionFilter("JPG", "jpg");
    jfchCargarfoto.setFileFilter(filtro);
    resultado = jfchCargarfoto.showOpenDialog(null);
    if (JFileChooser.APPROVE_OPTION == resultado) {
        fichero = jfchCargarfoto.getSelectedFile();
        try {/*from   w  w  w.j av  a 2  s  .com*/
            tempImagen[identificador] = fichero.getPath();
            tempNombreArchivo[identificador] = fichero.getName();
            ImageIcon icon = new ImageIcon(fichero.toString());
            Icon icono = new ImageIcon(icon.getImage().getScaledInstance(label.getWidth(), label.getHeight(),
                    Image.SCALE_DEFAULT));
            label.setText(null);
            label.setIcon(icono);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error abriendo la imagen" + ex);
        }
    }
}

From source file:Form.Principal.java

public void PanelUsuarios() {
    int i = 0;//w w  w  .java2  s. co  m
    int Altura = 0;
    Color gris = new Color(44, 44, 44);
    Color azul = new Color(0, 153, 255);
    Color rojo = new Color(221, 76, 76);
    try {
        //Consultamos todos los clientes
        ResultSet Comandos = Funcion.Select(st, "SELECT * FROM usuarios where Tipo!='Administrador';");
        //Ciclo para crear un panel para cada uno
        while (Comandos.next()) {
            //Creamos un panel con alineacion a la izquierda
            JPanel Panel = new JPanel();
            Panel.setLayout(null);
            jPanel12.add(Panel);
            //Tamao del panel
            Panel.setSize(500, 200);
            // La posicion y del panel ira incrementando para que no se encimen
            Altura = 40 + (i * 220);
            Panel.setLocation(175, Altura);
            Panel.setBackground(Color.white);
            Panel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
            //Creamos label para mostrar los datos del cliente, el codigo html es para que al llegar al final del panel
            //se pase a la siguiente linea y para el margen izquierdo
            JLabel Foto = new JLabel();
            Foto.setSize(150, 150);
            File FotoPerfil = new File("Imagenes/Fotos Perfil/" + Comandos.getInt("id") + ".png");
            File FotoPerfil2 = new File("Imagenes/Fotos Perfil/" + Comandos.getInt("id") + ".jpg");
            if (FotoPerfil.exists()) {
                ImageIcon Imagen = new ImageIcon("Imagenes/Fotos Perfil/" + Comandos.getInt("id") + ".png");
                Image ImagenEscalada = Imagen.getImage().getScaledInstance(Foto.getWidth(), Foto.getHeight(),
                        Image.SCALE_SMOOTH);
                Icon IconoEscalado = new ImageIcon(ImagenEscalada);
                Foto.setIcon(IconoEscalado);
            } else if (FotoPerfil2.exists()) {
                ImageIcon Imagen = new ImageIcon("Imagenes/Fotos Perfil/" + Comandos.getInt("id") + ".jpg");
                Image ImagenEscalada = Imagen.getImage().getScaledInstance(Foto.getWidth(), Foto.getHeight(),
                        Image.SCALE_SMOOTH);
                Icon IconoEscalado = new ImageIcon(ImagenEscalada);
                Foto.setIcon(IconoEscalado);
            } else {
                ImageIcon Imagen = new ImageIcon(getClass().getResource("/Imagen/Default.png"));
                Image ImagenEscalada = Imagen.getImage().getScaledInstance(Foto.getWidth(), Foto.getHeight(),
                        Image.SCALE_SMOOTH);
                Icon IconoEscalado = new ImageIcon(ImagenEscalada);
                Foto.setIcon(IconoEscalado);
            }
            JLabel Nombre = new JLabel();
            Nombre.setText("Nombre de Usuario: " + Comandos.getString("Nombre"));
            JLabel Contrasena = new JLabel();
            Contrasena.setText(("Contrasea: " + Comandos.getString("contrasena")));
            JButton Editar = new JButton();
            Editar.setText("Editar");
            Editar.setName(Comandos.getString("id"));
            Editar.setBackground(azul);
            JButton Eliminar = new JButton();
            Eliminar.setText("Eliminar");
            Eliminar.setName(Comandos.getString("id"));
            Eliminar.setBackground(rojo);
            MouseListener mlEditar = new MouseListener() {
                @Override
                public void mouseReleased(MouseEvent e) {
                    //System.out.println("Released!");
                }

                @Override
                public void mousePressed(MouseEvent e) {
                    //System.out.println("Pressed!");
                }

                @Override
                public void mouseExited(MouseEvent e) {
                    //System.out.println("Exited!");
                }

                @Override
                public void mouseEntered(MouseEvent e) {
                    //System.out.println("Entered!");
                }

                @Override
                public void mouseClicked(MouseEvent e) {
                    presionadoactual = 24;
                    Color azul = new Color(0, 182, 230);
                    jButton24.setBackground(azul);
                    JButton source = (JButton) e.getSource();
                    System.out.println(source.getName());
                    jPanel17.setVisible(false);
                    jButton30.setLocation(470, 480);
                    jButton31.setLocation(270, 480);
                    jLabel2.setToolTipText(null);
                    jTabbedPane2.setSelectedIndex(5);
                    editando = true;
                    PerfilUsuario(Integer.parseInt(source.getName()));
                    Color gris = new Color(44, 44, 44);
                    jButton4.setBackground(gris);
                }
            };
            MouseListener mlEliminar = new MouseListener() {
                @Override
                public void mouseReleased(MouseEvent e) {
                    //System.out.println("Released!");
                }

                @Override
                public void mousePressed(MouseEvent e) {
                    //System.out.println("Pressed!");
                }

                @Override
                public void mouseExited(MouseEvent e) {
                    //System.out.println("Exited!");
                }

                @Override
                public void mouseEntered(MouseEvent e) {
                    //System.out.println("Entered!");
                }

                @Override
                public void mouseClicked(MouseEvent e) {
                    JButton source = (JButton) e.getSource();
                    System.out.println(source.getName());
                    Funcion.Update(st, "DELETE FROM usuarios WHERE id = " + source.getName() + ";");
                    jPanel12.removeAll();
                    PanelUsuarios();
                    jPanel12.repaint();
                }
            };
            Editar.addMouseListener(mlEditar);
            Eliminar.addMouseListener(mlEliminar);
            //Fuente del texto;
            Nombre.setFont(new Font("Verdana", Font.PLAIN, 15));
            Nombre.setForeground(gris);
            Contrasena.setFont(new Font("Verdana", Font.PLAIN, 15));
            Contrasena.setForeground(gris);
            Editar.setFont(new Font("Verdana", Font.PLAIN, 15));
            Editar.setForeground(Color.white);
            Eliminar.setFont(new Font("Verdana", Font.PLAIN, 15));
            Eliminar.setForeground(Color.white);
            //Aadimos los label al panel correspondiente del cliente
            Panel.add(Foto);
            Panel.add(Nombre);
            Panel.add(Contrasena);
            Panel.add(Editar);
            Panel.add(Eliminar);
            Foto.setLocation(10, 20);
            Nombre.setLocation(170, 30);
            Nombre.setSize(300, 45);
            Contrasena.setLocation(170, 60);
            Contrasena.setSize(300, 45);
            Editar.setLocation(170, 100);
            Editar.setSize(120, 40);
            Eliminar.setLocation(315, 100);
            Eliminar.setSize(120, 40);
            i++;
        }
    } catch (SQLException ex) {
        Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
    }
    //Dependiendo de cuantos clientes se agregaron, se ajusta el tamao del panel principal para que el scroll llegue hasta ahi
    jPanel12.setPreferredSize(new Dimension(jPanel12.getWidth(), Altura + 150));

}