Example usage for javax.swing JLabel setIcon

List of usage examples for javax.swing JLabel setIcon

Introduction

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

Prototype

@BeanProperty(preferred = true, visualUpdate = true, description = "The icon this component will display.")
public void setIcon(Icon icon) 

Source Link

Document

Defines the icon this component will display.

Usage

From source file:net.sourceforge.atunes.kernel.modules.statistics.StatsDialogController.java

/**
 * Puts image with chart in given label, with title and data provided
 * /*www.  j a  v a2  s .com*/
 * @param data
 * @param titleKey
 * @param chartLabel
 */
private void setChart(final List<?> data, final String titleKey, final JLabel chartLabel) {
    DefaultCategoryDataset dataset = getDataSet(data);
    JFreeChart chart = ChartFactory.createStackedBarChart3D(I18nUtils.getString(titleKey), null, null, dataset,
            PlotOrientation.HORIZONTAL, false, false, false);
    chart.setBackgroundPaint(Color.WHITE);
    chart.setPadding(new RectangleInsets(5, 0, 0, 0));
    NumberAxis axis = new NumberAxis();
    axis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    chart.setBackgroundPaint(GuiUtils.getBackgroundColor());
    chart.getTitle().setPaint(GuiUtils.getForegroundColor());
    chart.getCategoryPlot().setRangeAxis(axis);
    chart.getCategoryPlot().setForegroundAlpha(1f);
    chart.getCategoryPlot().getRenderer().setSeriesPaint(0, Color.GREEN);
    chart.getCategoryPlot().getDomainAxis().setTickLabelPaint(GuiUtils.getForegroundColor());
    chart.getCategoryPlot().getRangeAxis().setTickLabelPaint(GuiUtils.getForegroundColor());
    chart.getPlot().setBackgroundPaint(GuiUtils.getBackgroundColor());
    chartLabel.setIcon(new ImageIcon(chart.createBufferedImage(710, 250)));
}

From source file:fr.isen.browser5.Util.UrlLoader.java

public void setTabTitleFavicon() {
    String title = doc.title();/* w  w w. j a  v  a2  s.  c  om*/
    title = Str.shortenString(title, 12);
    int tabIndex = tabView.getCurrentTabIndex();
    JPanel tabPanel = (JPanel) tabView.getCurrentFrame().getTabPane().getTabComponentAt(tabIndex);
    JLabel titleLabel = (JLabel) tabPanel.getComponent(0);
    titleLabel.setText(title);

    String baseUrl = pageUrl.getProtocol() + "://" + pageUrl.getHost();
    Element element = doc.head().select("link[href~=.*\\.(ico|png)]").first();
    String favicoUrlStr = "";
    if (element != null) {
        favicoUrlStr = element.attr("abs:href");
    } else {
        element = doc.head().select("meta[itemprop=image]").first();
        if (element != null) {
            favicoUrlStr = baseUrl + element.attr("content");
        }
    }

    ImageIcon icon = null;
    try {
        if (!favicoUrlStr.isEmpty()) {
            if (favicoUrlStr.endsWith(".ico")) {
                java.util.List<BufferedImage> imgs = ICODecoder.read(new URL(favicoUrlStr).openStream());
                icon = new ImageIcon(imgs.get(0));
            } else {
                icon = new ImageIcon(new URL(favicoUrlStr));
            }
            icon = new ImageIcon(icon.getImage().getScaledInstance(16, 16, Image.SCALE_DEFAULT));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    titleLabel.setIcon(icon);

    HistoryEntry historyEntry = new HistoryEntry(title, pageUrl.toString(), Instant.now().getEpochSecond(),
            icon, -1L);
    globalHistoryDAO.create(historyEntry);
}

From source file:game.Clue.ClueGameUI.java

private void CreateBoard() {

    //resize and center frame to fit all components of game(board,scorecard,buttons,etc)
    this.setSize(1030, 670);
    Dimension dimension = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    int x = (int) ((dimension.getWidth() - this.getWidth()) / 2);
    int y = (int) ((dimension.getHeight() - this.getHeight()) / 2);
    this.setLocation(x, y);

    NonCornerRoom NonCornerRoom_current;
    // Board gameBoard = new Board();
    ArrayList<String> RoomsAndHallways = new ArrayList<>(Arrays.asList("STUDY", "HALLWAY1", "HALL", "HALLWAY2",
            "LOUNGE", "HALLWAY3", "BLANK", "HALLWAY4", "BLANK", "HALLWAY5", "LIBRARY", "HALLWAY6",
            "BILLIARD ROOM", "HALLWAY7", "DINING ROOM", "HALLWAY8", "BLANK", "HALLWAY9", "BLANK", "HALLWAY10",
            "CONSERVATORY", "HALLWAY11", "BALL ROOM", "HALLWAY12", "KITCHEN"));
    ArrayList<String> RoomNames = new ArrayList<>(
            Arrays.asList("Hall", "Library", "BillardRoom", "BallRoom", "DiningRoom"));
    //RoomNames=["Hall","Library","BillardRoom","BallRoom","DiningRoom"];
    ArrayList<NonCornerRoom> NonCornerRooms = new ArrayList<>(Arrays.asList(new NonCornerRoom(""),
            new NonCornerRoom(""), new NonCornerRoom(""), new NonCornerRoom("")));
    for (int i = 0; i < 4; i++) {
        NonCornerRoom_current = NonCornerRooms.get(i);
        NonCornerRoom_current.setRoomName(RoomNames.get(i));
        System.out.println("jlayer=" + NonCornerRoom_current.getRoomName());

    }/* ww w.j  a  v a  2 s .  c om*/

    gameBoard = new JPanel();
    JPanel gameBoard_background = new JPanel();
    gameBoard_background.setLayout(new BorderLayout(1, 1));
    gameBoard_background.setPreferredSize(new Dimension(701, 590));
    gameBoard_background.setBounds(0, 0, 701, 590);
    jLayeredPane5.add(gameBoard, new Integer(1));
    gameBoard.setLayout(new GridLayout(5, 5));
    gameBoard.setOpaque(false);
    gameBoard.setPreferredSize(new Dimension(701, 590));
    gameBoard.setBounds(0, 0, 701, 590);
    Border roomBoarder = BorderFactory.createLineBorder(Color.white, 2);
    //draw rooms onto board
    for (int i = 0; i < 25; i++) {
        JPanel room_square = new JPanel(new BorderLayout());

        System.out.println(i);
        room_square.setName(RoomsAndHallways.get(i));

        System.out.println(RoomsAndHallways.get(i));
        gameBoard.add(room_square);

        int row = (i / 12) % 2;
        if (row == 0) {
            //room_square.setBackground(i % 2 == 0 ? Color.white : Color.gray);
            //room_square.setBorder(roomBoarder);
            room_square.setOpaque(false);

            //room_square.
            //room_square.add(new JLabel("Room# "+i));
        } else {
            //room_square.setBackground(i % 2 == 0 ? Color.gray : Color.white);
            //room_square.setBorder(roomBoarder);
            room_square.setOpaque(false);
            //room_square.add(new JLabel("Room# "+i));
        }

    }

    //add Players to board (use "for" statement later to reduce lines of code)
    ImageIcon player_icon = new ImageIcon(getClass().getResource("/resources/scarletphoto.png"),
            "MissScarlett");
    JPanel panel = (JPanel) gameBoard.getComponent(3); //MS SCARLET starting position
    player.setIcon(player_icon);
    player.setHorizontalAlignment(SwingConstants.CENTER);
    panel.add(player, SwingConstants.CENTER);

    ImageIcon player2_icon = new ImageIcon(getClass().getResource("/resources/mustardphoto.png"), "Mustard");
    JPanel panel2 = (JPanel) gameBoard.getComponent(9); //ColMustard starting position
    player2.setIcon(player2_icon);
    player2.setHorizontalAlignment(SwingConstants.CENTER);
    panel2.add(player2, SwingConstants.CENTER);
    //panel.add(player, SwingConstants.CENTER);

    ImageIcon player3_icon = new ImageIcon(getClass().getResource("/resources/plumphoto.png"), "ProfessorPlum");
    JPanel panel3 = (JPanel) gameBoard.getComponent(5); //Plum starting position
    player3.setIcon(player3_icon);
    player3.setHorizontalAlignment(SwingConstants.CENTER);
    panel3.add(player3, SwingConstants.CENTER);

    ImageIcon player4_icon = new ImageIcon(getClass().getResource("/resources/peacockphoto.png"), "MsPeacock");
    JPanel panel4 = (JPanel) gameBoard.getComponent(15); //Peacock starting position
    player4.setIcon(player4_icon);
    player4.setHorizontalAlignment(SwingConstants.CENTER);
    panel4.add(player4, SwingConstants.CENTER);

    ImageIcon player5_icon = new ImageIcon(getClass().getResource("/resources/greenphoto.png"), "Mr.Green");
    JPanel panel5 = (JPanel) gameBoard.getComponent(21); //MrGreen starting position
    player5.setIcon(player5_icon);
    player5.setHorizontalAlignment(SwingConstants.CENTER);
    panel5.add(player5, SwingConstants.CENTER);

    ImageIcon player6_icon = new ImageIcon(getClass().getResource("/resources/whitephoto.png"), "Ms.White");
    JPanel panel6 = (JPanel) gameBoard.getComponent(23); //MsWhite starting position
    player6.setIcon(player6_icon);
    player6.setHorizontalAlignment(SwingConstants.CENTER);
    panel6.add(player6, SwingConstants.CENTER);

    ImageIcon room_icon = new ImageIcon(getClass().getResource("/resources/newgamebackground-6.png"));
    JLabel room_icon_label = new JLabel();
    room_icon_label.setIcon(room_icon);

    gameBoard_background.add(room_icon_label);

    jLayeredPane5.add(gameBoard_background, new Integer(0));
    gameBoard_background.setVisible(true);
    room_icon_label.setVisible(true);
    //jLayeredPane5.add(room_icon_label,JLayeredPane.DRAG_LAYER);
    //jLayeredPane5.moveToFront(room_icon_label);

    //jPanel5.add(jLayeredPane1);
    //jPanel5.repaint();
    //jPanel5.setVisible(true);
    //System.out.println("JToggleButton2 Action Performed");
    packageGameState();

    //jPanel3.add(gameBoard, "card4");
}

From source file:net.sf.jabref.gui.FindUnlinkedFilesDialog.java

/**
 * Initialises the combobox that contains the available file types which
 * bibtex entries can be created of./* www . j av  a2 s  .  c  o  m*/
 */
private void createFileTypesCombobox() {

    List<FileFilter> fileFilterList = creatorManager.getFileFilterList();

    Vector<FileFilter> vector = new Vector<>();
    for (FileFilter fileFilter : fileFilterList) {
        vector.add(fileFilter);
    }
    comboBoxFileTypeSelection = new JComboBox<>(vector);

    comboBoxFileTypeSelection.setRenderer(new DefaultListCellRenderer() {

        /* (non-Javadoc)
         * @see javax.swing.DefaultListCellRenderer#getListCellRendererComponent(javax.swing.JList, java.lang.Object, int, boolean, boolean)
         */
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {
            JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected,
                    cellHasFocus);
            if (value instanceof EntryFromFileCreator) {
                EntryFromFileCreator creator = (EntryFromFileCreator) value;
                if (creator.getExternalFileType() != null) {
                    label.setIcon(creator.getExternalFileType().getIcon());
                }
            }
            return label;
        }
    });

}

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 a v  a 2s.c om
            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:forms.frDados.java

private void setLabelValues(javax.swing.JLabel lbl, String image) {
    lbl.setIcon(new ImageIcon(image));
}

From source file:edu.ku.brc.specify.prefs.FormattingPrefsPanel.java

/**
 * Method for enabling a user to choose a toolbar icon.
 * @param appLabel the label used to display the icon.
 * @param clearIconBtn the button used to clear the icon
 *//*from   w ww  . ja v a2s.  co  m*/
protected void chooseToolbarIcon(final JLabel appLabel, final JButton clearIconBtn) {
    FileDialog fileDialog = new FileDialog((Frame) UIRegistry.get(UIRegistry.FRAME),
            getResourceString("PREF_CHOOSE_APPICON_TITLE"), FileDialog.LOAD); //$NON-NLS-1$
    fileDialog.setFilenameFilter(new ImageFilter());
    UIHelper.centerAndShow(fileDialog);
    fileDialog.dispose();

    String path = fileDialog.getDirectory();
    if (StringUtils.isNotEmpty(path)) {
        String fullPath = path + File.separator + fileDialog.getFile();
        File imageFile = new File(fullPath);
        if (imageFile.exists()) {
            ImageIcon newIcon = null;
            ImageIcon icon = new ImageIcon(fullPath);
            if (icon.getIconWidth() != -1 && icon.getIconHeight() != -1) {
                if (icon.getIconWidth() > 32 || icon.getIconHeight() > 32) {
                    Image img = GraphicsUtils.getScaledImage(icon, 32, 32, false);
                    if (img != null) {
                        newIcon = new ImageIcon(img);
                    }
                } else {
                    newIcon = icon;
                }
            }

            ImageIcon appIcon;
            if (newIcon != null) {
                appLabel.setIcon(newIcon);
                clearIconBtn.setEnabled(true);
                String imgBufStr = GraphicsUtils.uuencodeImage(newAppIconName, newIcon);
                AppPreferences.getRemote().put(iconImagePrefName, imgBufStr);
                appIcon = newIcon;

            } else {
                appIcon = IconManager.getIcon("AppIcon");
                appLabel.setIcon(appIcon); //$NON-NLS-1$
                clearIconBtn.setEnabled(false);
                AppPreferences.getRemote().remove(iconImagePrefName);
            }

            IconEntry entry = IconManager.getIconEntryByName(INNER_APPICON_NAME);
            entry.setIcon(appIcon);
            if (entry.getIcons().get(IconManager.IconSize.Std32) != null) {
                entry.getIcons().get(IconManager.IconSize.Std32).setImageIcon(appIcon);
            }

            //((FormViewObj)form).getMVParent().set
            form.getValidator().dataChanged(null, null, null);
        }
    }

}

From source file:App.java

protected void getImageFromHttp(String link, JLabel label) {

    HttpResponse response = null;//  w ww.j  a v a  2  s .  c o  m
    InputStream is = null;
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(link);
    try {
        response = client.execute(request);
        is = response.getEntity().getContent();
        imageResponses = ImageIO.read(is);
    } catch (ClientProtocolException e) {
        try {
            imageResponses = (BufferedImage) ImageIO.read(new File("img/error.png"));
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        e.printStackTrace();
    } catch (IOException e) {
        try {
            imageResponses = (BufferedImage) ImageIO.read(new File("img/error.png"));
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        e.printStackTrace();
    } catch (UnsupportedOperationException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }
    // TODO check the problem with bad urls to webpages, not images
    icon = scaleBufferedImage(imageResponses, label);
    label.setIcon(icon);
}

From source file:com.itemanalysis.jmetrik.gui.Jmetrik.java

public Jmetrik() {
    super("jMetrik");
    setPreferredSize(new Dimension(1024, 650));
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    //properly close database if user closes window
    this.addWindowListener(new WindowAdapter() {
        @Override//w  w w  .ja va2 s . co  m
        public void windowClosing(WindowEvent we) {
            if (workspace != null) {
                workspace.closeDatabase();
            }
            System.exit(0);
        }
    });

    //add statusbar
    statusBar = new StatusBar(1024, 30);
    statusBar.setBorder(new EmptyBorder(2, 2, 2, 2));
    getContentPane().add(statusBar, BorderLayout.SOUTH);

    //start logging
    startLog();

    //left-right splitpane
    JSplitPane splitPane1 = new JSplitPane();
    splitPane1.setDividerLocation(200);

    //setup workspace list
    workspaceList = new JList();
    workspaceList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    workspaceList.setModel(new SortedListModel<DataTableName>());
    workspaceList.addKeyListener(new DeleteKeyListener());
    //        workspaceList.getInsets().set(5, 5, 5, 5);

    //add icon to list cell renderer
    String urlString = "/images/spreadsheet.png";
    URL url = this.getClass().getResource(urlString);
    final ImageIcon tableIcon = new ImageIcon(url, "Table");
    workspaceList.setCellRenderer(new DefaultListCellRenderer() {
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected,
                    cellHasFocus);
            label.setIcon(tableIcon);
            return label;
        }
    });

    JScrollPane scrollPane1 = new JScrollPane(workspaceList);
    scrollPane1.setPreferredSize(new Dimension(200, 698));

    splitPane1.setLeftComponent(scrollPane1);

    //tabbed pane for top pane
    tabbedPane = new JTabbedPane();
    tabbedPane.setTabPlacement(JTabbedPane.BOTTOM);

    //setup data table
    dataTable = new DataTable();
    dataTable.setRowHeight(18);

    //change size of table header and center text
    JTableHeader header = dataTable.getTableHeader();
    header.setDefaultRenderer(new TableHeaderCellRenderer());

    JScrollPane dataScrollPane = new JScrollPane(dataTable);
    tabbedPane.addTab("Data", dataScrollPane);

    //setup variable table
    variableTable = new DataTable();
    variableTable.setRowHeight(18);
    variableTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            super.mouseClicked(e);
            if (e.getClickCount() == 2) {
                JTable target = (JTable) e.getSource();
                int row = target.getSelectedRow();
                int col = target.getSelectedColumn();
                if (col == 0) {
                    if (target.getModel() instanceof VariableModel) {
                        VariableModel vModel = (VariableModel) target.getModel();
                        String s = (String) vModel.getValueAt(row, col);

                        DatabaseName db = workspace.getDatabaseName();
                        DataTableName table = workspace.getCurrentDataTable();

                        RenameVariableDialog renameVariableDialog = new RenameVariableDialog(Jmetrik.this, db,
                                table, s);
                        renameVariableDialog.setVisible(true);

                        if (renameVariableDialog.canRun()) {
                            RenameVariableCommand command = renameVariableDialog.getCommand();
                            workspace.runProcess(command);
                        }

                    } //end instanceof

                } //end if col==0

            } //end if click count==2
        }//end mouse clicked
    });

    //change size of table header and center text
    JTableHeader variableHeader = variableTable.getTableHeader();
    variableHeader.setDefaultRenderer(new TableHeaderCellRenderer());
    variableHeader.setPreferredSize(new Dimension(30, 21));

    JScrollPane variableScrollPane = new JScrollPane(variableTable);
    tabbedPane.addTab("Variables", variableScrollPane);

    splitPane1.setRightComponent(tabbedPane);
    getContentPane().add(splitPane1, BorderLayout.CENTER);

    //add status bar listener - needed to display status message that are generated within this class
    this.addPropertyChangeListener(statusBar.getStatusListener());

    //add listener for displaying error messages - needed to display errors and exceptions
    this.addPropertyChangeListener(new ErrorOccurredPropertyChangeListener());

    //instantiate file utilities
    fileUtils = new JmetrikFileUtils();
    fileUtils.addPropertyChangeListener(statusBar.getStatusListener());

    //set import and export path to user's documents folder
    JFileChooser chooser = new JFileChooser();
    FileSystemView fw = chooser.getFileSystemView();
    importExportPath = fw.getDefaultDirectory().toString().replaceAll("\\\\", "/");

    //create and start a workspace
    startWorkspace();

    //create menu bar and tool bar
    this.setJMenuBar(createMenuBar());

    JToolBar toolBar = createToolBar();
    toolBar.setFloatable(false);
    toolBar.setRollover(true);
    getContentPane().add(toolBar, BorderLayout.PAGE_START);

    pack();

}

From source file:AppSpringLayout.java

protected void displayImage(String link, JLabel label) {

    HttpResponse response = null;/*from ww  w  . java2s  . c o m*/
    InputStream is = null;
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(link);
    try {
        response = client.execute(request);
        is = response.getEntity().getContent();
        imageResponses = ImageIO.read(is);
    } catch (ClientProtocolException e) {
        try {
            imageResponses = (BufferedImage) ImageIO.read(new File("img/error.png"));
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        e.printStackTrace();
    } catch (IOException e) {
        try {
            imageResponses = (BufferedImage) ImageIO.read(new File("img/error.png"));
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        e.printStackTrace();
    } catch (UnsupportedOperationException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }
    // TODO check the problem with bad urls to webpages, not images
    icon = scaleBufferedImage(imageResponses, label);
    label.setIcon(icon);
}