Example usage for javax.swing JLabel setText

List of usage examples for javax.swing JLabel setText

Introduction

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

Prototype

@BeanProperty(preferred = true, visualUpdate = true, description = "Defines the single line of text this component will display.")
public void setText(String text) 

Source Link

Document

Defines the single line of text this component will display.

Usage

From source file:Main.java

private void init() {
    this.setLayout(new BorderLayout());
    JPanel topPanel = new JPanel();
    final JLabel topLabel = new JLabel("North");
    topPanel.add(topLabel);/*w  ww.j a v  a 2 s  .c o m*/
    this.add(topPanel, BorderLayout.NORTH);

    JTabbedPane tabbedPane = new JTabbedPane();
    JPanel firstTabCont = new JPanel();
    firstTabCont.add(new JLabel("First"));
    tabbedPane.addTab("First", firstTabCont);

    JPanel secondTabCont = new JPanel();
    secondTabCont.add(new JLabel("Second"));
    tabbedPane.addTab("Second", secondTabCont);

    this.add(tabbedPane, BorderLayout.CENTER);

    JPanel bottomPanel = new JPanel();
    final JLabel bottomLabel = new JLabel("South");
    bottomPanel.add(bottomLabel);
    this.add(bottomPanel, BorderLayout.SOUTH);

    tabbedPane.addChangeListener(evt -> {
        JTabbedPane pane = (JTabbedPane) evt.getSource();
        int selectedIndex = pane.getSelectedIndex();
        if (selectedIndex == 0) {
            topLabel.setText("");
            topLabel.setText("Hi");

            bottomLabel.setText("");
            bottomLabel.setText("Bye");
        } else {
            topLabel.setText("");
            topLabel.setText("Bye");

            bottomLabel.setText("");
            bottomLabel.setText("Hi");
        }

    });
    this.pack();
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
}

From source file:com.eviware.soapui.support.components.SimpleForm.java

private <T extends JComponent> T append(String name, JComponent label, T component, String alignments,
        int column, int columnSpan) {
    int spaceRowIndex = -1;

    if (rowSpacing > 0 && appended) {
        addSpace(rowSpacing);//from   w w w  .j a  v  a  2  s. c  om
        spaceRowIndex = layout.getRowCount();
    }

    layout.appendRow(rowSpec);
    int row = layout.getRowCount();

    if (label != null) {
        panel.add(label, cc.xy(DEFAULT_LABEL_COLUMN, row));
        component.addComponentListener(new LabelHider(label, spaceRowIndex));
        component.addPropertyChangeListener(ENABLED_PROPERTY_NAME, new LabelEnabler(label));

        if (label instanceof JLabel) {
            JLabel jl = ((JLabel) label);
            jl.setLabelFor(component);
            String text = jl.getText();
            int ix = text.indexOf('&');
            if (ix >= 0) {
                jl.setText(text.substring(0, ix) + text.substring(ix + 1));
                jl.setDisplayedMnemonicIndex(ix);
                jl.setDisplayedMnemonic(text.charAt(ix + 1));
            }

            if (component.getAccessibleContext() != null) {
                component.getAccessibleContext().setAccessibleName(text);
            }
        }
    } else {
        component.addComponentListener(new LabelHider(null, spaceRowIndex));
    }

    addComponentToRow(name, component, alignments, column, row, columnSpan);

    return component;
}

From source file:SimpleFileChooser.java

public SimpleFileChooser() {
    super("File Chooser Test Frame");
    setSize(350, 200);/*from ww  w .  j  av a  2 s .  co  m*/
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    Container c = getContentPane();
    c.setLayout(new FlowLayout());

    JButton openButton = new JButton("Open");
    JButton saveButton = new JButton("Save");
    JButton dirButton = new JButton("Pick Dir");
    final JLabel statusbar = new JLabel("Output of your selection will go here");

    // Create a file chooser that opens up as an Open dialog
    openButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(true);
            int option = chooser.showOpenDialog(SimpleFileChooser.this);
            if (option == JFileChooser.APPROVE_OPTION) {
                File[] sf = chooser.getSelectedFiles();
                String filelist = "nothing";
                if (sf.length > 0)
                    filelist = sf[0].getName();
                for (int i = 1; i < sf.length; i++) {
                    filelist += ", " + sf[i].getName();
                }
                statusbar.setText("You chose " + filelist);
            } else {
                statusbar.setText("You canceled.");
            }
        }
    });

    // Create a file chooser that opens up as a Save dialog
    saveButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            int option = chooser.showSaveDialog(SimpleFileChooser.this);
            if (option == JFileChooser.APPROVE_OPTION) {
                statusbar.setText("You saved "
                        + ((chooser.getSelectedFile() != null) ? chooser.getSelectedFile().getName()
                                : "nothing"));
            } else {
                statusbar.setText("You canceled.");
            }
        }
    });

    // Create a file chooser that allows you to pick a directory
    // rather than a file
    dirButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int option = chooser.showOpenDialog(SimpleFileChooser.this);
            if (option == JFileChooser.APPROVE_OPTION) {
                statusbar.setText("You opened "
                        + ((chooser.getSelectedFile() != null) ? chooser.getSelectedFile().getName()
                                : "nothing"));
            } else {
                statusbar.setText("You canceled.");
            }
        }
    });

    c.add(openButton);
    c.add(saveButton);
    c.add(dirButton);
    c.add(statusbar);
}

From source file:com.view.TradeWindow.java

private void TraderBlockOrdersActionPerformed(java.awt.event.ActionEvent evt) {
    TableModel dtm = (TableModel) TraderIncomingRequestsTable.getModel();
    int nRow = dtm.getRowCount();
    int nCol = dtm.getColumnCount();
    Object[][] tableData = new Object[nRow][nCol];
    ArrayList<SingleOrder> parsedOrders = new ArrayList();
    ControllerBlockOrders control = new ControllerBlockOrders();

    for (int i = 0; i < nRow; i++) {
        for (int j = 0; j < nCol; j++) {
            tableData[i][j] = dtm.getValueAt(i, j);
        }//ww  w .  j  a v  a2  s . c  o  m
        SingleOrder o = new SingleOrder();
        o.SingleOrderMakeBlocks(tableData[i]);
        parsedOrders.add(o);
    }
    singleOrderLists = control.MakeBlock(parsedOrders);
    showMessageDialog(null, "Blocks have been successfully completed.");
    //dtm.setRowCount(0);
    TraderPlatformBlockedRequests.setLayout(new BorderLayout());
    int count = 1;
    ArrayList<JScrollPane> paneList = new ArrayList<JScrollPane>();
    for (ArrayList<SingleOrder> b : singleOrderLists) {
        JTable jTable = new JTable();
        jTable.setModel(CTraderBlockOrder.getTableModel(b));
        Dimension d = jTable.getPreferredSize();
        // System.out.println(d);
        int rows = jTable.getRowCount();
        // System.out.println(rows);
        JScrollPane jPane = new JScrollPane();
        jPane.setPreferredSize(new Dimension(d.width, jTable.getRowHeight() * rows + 50));
        jPane.add(jTable);
        jPane.setViewportView(jTable);
        paneList.add(jPane);
        count++;
    }

    test.add(blockOptions);
    int i = 0;
    for (final JScrollPane j : paneList) {
        //   JButton btn = new JButton();
        //  btn.setText("Split Block");
        //     btn.setName(""+i);

        JPanel cPanel = new JPanel();
        /*  btn.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            JViewport viewport = j.getViewport(); 
            final JTable mytable = (JTable)viewport.getView();
            final ArrayList<Integer> index = new ArrayList<Integer>();
            for(int row = 0;row<mytable.getRowCount();row++){
                  if((boolean)mytable.getValueAt(row, 11)){
                     index.add(row);
                  }
            }
             SplitBlockActionPerformed(evt,index,cPanel,test);
         }
          });*/
        JCheckBox check = new JCheckBox();
        JLabel label = new JLabel();
        label.setText("Select Block");
        check.setName("" + i);
        check.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SelectBlockActionPerformed(evt);
            }
        });
        JPanel splitOptions = new JPanel();
        splitOptions.add(label);
        splitOptions.add(check);
        splitOptions.setName("splitOpt");
        //  splitOptions.add(btn);
        cPanel.setName("cPanel" + i);
        cPanel.add(splitOptions);
        cPanel.add(j);
        cPanel.setLayout(new BoxLayout(cPanel, BoxLayout.Y_AXIS));
        test.add(cPanel);
        cPanelList.add(cPanel);
        i++;
    }

    test.setLayout(new BoxLayout(test, BoxLayout.Y_AXIS));
    JScrollPane p = new JScrollPane(test);
    p.setName("ParentP");
    TraderPlatformBlockedRequests.add(p);
    TraderPlatformBlockedRequests.validate();
    TraderPlatformTabbedPane.setSelectedIndex(TraderPlatformTabbedPane.getSelectedIndex() + 1);

}

From source file:MyFilterChooser.java

public MyFilterChooser() {
    super("Filter Test Frame");
    setSize(350, 200);//w ww.  j a  v a2 s .  co m
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    Container c = getContentPane();
    c.setLayout(new FlowLayout());

    JButton openButton = new JButton("Open");
    final JLabel statusbar = new JLabel("Output of your selection will go here");

    openButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            String[] pics = new String[] { "gif", "jpg", "tif" };
            String[] audios = new String[] { "au", "aiff", "wav" };
            JFileChooser chooser = new JFileChooser();
            chooser.addChoosableFileFilter(new SimpleFileFilter(pics, "Images (*.gif, *.jpg, *.tif)"));
            chooser.addChoosableFileFilter(new SimpleFileFilter(".MOV"));
            chooser.addChoosableFileFilter(new SimpleFileFilter(audios, "Sounds (*.aiff, *.au, *.wav)"));
            int option = chooser.showOpenDialog(MyFilterChooser.this);
            if (option == JFileChooser.APPROVE_OPTION) {
                if (chooser.getSelectedFile() != null)
                    statusbar.setText("You chose " + chooser.getSelectedFile().getName());
            } else {
                statusbar.setText("You canceled.");
            }
        }
    });

    c.add(openButton);
    c.add(statusbar);
    setVisible(true);
}

From source file:com.floreantpos.ui.views.payment.GroupSettleTicketDialog.java

private JPanel createTotalViewerPanel() {

    JLabel lblSubtotal = new javax.swing.JLabel();
    lblSubtotal.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    lblSubtotal.setText(com.floreantpos.POSConstants.SUBTOTAL + ":" + " " + CurrencyUtil.getCurrencySymbol()); //$NON-NLS-1$ //$NON-NLS-2$

    tfSubtotal = new javax.swing.JTextField(10);
    tfSubtotal.setHorizontalAlignment(SwingConstants.TRAILING);
    tfSubtotal.setEditable(false);/*from   w w w  .  jav a 2s  .com*/

    JLabel lblDiscount = new javax.swing.JLabel();
    lblDiscount.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    lblDiscount.setText(Messages.getString("TicketView.9") + " " + CurrencyUtil.getCurrencySymbol()); //$NON-NLS-1$ //$NON-NLS-2$

    tfDiscount = new javax.swing.JTextField(10);
    tfDiscount.setHorizontalAlignment(SwingConstants.TRAILING);
    tfDiscount.setEditable(false);

    JLabel lblDeliveryCharge = new javax.swing.JLabel();
    lblDeliveryCharge.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    lblDeliveryCharge.setText("Delivery Charge:" + " " + CurrencyUtil.getCurrencySymbol()); //$NON-NLS-1$ //$NON-NLS-2$

    tfDeliveryCharge = new JTextField(10);
    tfDeliveryCharge.setHorizontalAlignment(SwingConstants.TRAILING);
    tfDeliveryCharge.setEditable(false);

    JLabel lblTax = new javax.swing.JLabel();
    lblTax.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    lblTax.setText(com.floreantpos.POSConstants.TAX + ":" + " " + CurrencyUtil.getCurrencySymbol()); //$NON-NLS-1$ //$NON-NLS-2$

    tfTax = new javax.swing.JTextField();
    tfTax.setEditable(false);
    tfTax.setHorizontalAlignment(SwingConstants.TRAILING);

    JLabel lblGratuity = new javax.swing.JLabel();
    lblGratuity.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    lblGratuity
            .setText(Messages.getString("SettleTicketDialog.5") + ":" + " " + CurrencyUtil.getCurrencySymbol()); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$

    tfGratuity = new javax.swing.JTextField();
    tfGratuity.setEditable(false);
    tfGratuity.setHorizontalAlignment(SwingConstants.TRAILING);

    JLabel lblTotal = new javax.swing.JLabel();
    lblTotal.setFont(lblTotal.getFont().deriveFont(Font.BOLD, 18));
    lblTotal.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    lblTotal.setText(com.floreantpos.POSConstants.TOTAL + ":" + " " + CurrencyUtil.getCurrencySymbol()); //$NON-NLS-1$ //$NON-NLS-2$

    tfTotal = new javax.swing.JTextField(10);
    tfTotal.setFont(tfTotal.getFont().deriveFont(Font.BOLD, 18));
    tfTotal.setHorizontalAlignment(SwingConstants.TRAILING);
    tfTotal.setEditable(false);

    JPanel ticketAmountPanel = new com.floreantpos.swing.TransparentPanel(
            new MigLayout("hidemode 3,ins 2 2 3 2,alignx trailing,fill", "[grow][]", "")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    ticketAmountPanel.add(lblSubtotal, "growx,aligny center"); //$NON-NLS-1$
    ticketAmountPanel.add(tfSubtotal, "growx,aligny center"); //$NON-NLS-1$
    ticketAmountPanel.add(lblDiscount, "newline,growx,aligny center"); //$NON-NLS-1$ //$NON-NLS-2$
    ticketAmountPanel.add(tfDiscount, "growx,aligny center"); //$NON-NLS-1$
    ticketAmountPanel.add(lblTax, "newline,growx,aligny center"); //$NON-NLS-1$
    ticketAmountPanel.add(tfTax, "growx,aligny center"); //$NON-NLS-1$
    ticketAmountPanel.add(lblDeliveryCharge, "newline,growx,aligny center"); //$NON-NLS-1$
    ticketAmountPanel.add(tfDeliveryCharge, "growx,aligny center"); //$NON-NLS-1$
    ticketAmountPanel.add(lblGratuity, "newline,growx,aligny center"); //$NON-NLS-1$
    ticketAmountPanel.add(tfGratuity, "growx,aligny center"); //$NON-NLS-1$
    ticketAmountPanel.add(lblTotal, "newline,growx,aligny center"); //$NON-NLS-1$
    ticketAmountPanel.add(tfTotal, "growx,aligny center"); //$NON-NLS-1$

    return ticketAmountPanel;
}

From source file:com.sec.ose.osi.ui.frm.main.report.JPanExportReport.java

private JPanel getJPanelReportTypeInfo() {
    if (jPanelReportTypeInfo == null) {
        jPanelReportTypeInfo = new JPanel();
        jPanelReportTypeInfo.setLayout(new GridBagLayout());

        JLabel jLabelBoth = new JLabel();
        jLabelBoth.setText("Generate Both Report (Identify and SPDX)");
        jLabelBoth.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                mEventHandler.handle(EventHandler.BTN_BOTH_REPORT);
            }//from  w  w  w .  ja v  a  2 s.c  o m
        });

        JLabel jLabelIdentify = new JLabel();
        jLabelIdentify.setText("Generate Identify Report (*.xlsx)");
        jLabelIdentify.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                mEventHandler.handle(EventHandler.BTN_IDENTIFY_REPORT);
            }
        });

        JLabel jLabelSPDX = new JLabel();
        jLabelSPDX.setText("Generate SPDX Report (*.rdf)");
        jLabelSPDX.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                mEventHandler.handle(EventHandler.BTN_SPDX_REPORT);
            }
        });

        GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
        gridBagConstraints11.gridx = 0;
        gridBagConstraints11.gridy = 0;
        GridBagConstraints gridBagConstraints12 = new GridBagConstraints();
        gridBagConstraints12.fill = GridBagConstraints.HORIZONTAL;
        gridBagConstraints12.insets = new Insets(0, 0, 0, 0);
        gridBagConstraints12.gridx = 1;
        gridBagConstraints12.gridy = 0;
        GridBagConstraints gridBagConstraints21 = new GridBagConstraints();
        gridBagConstraints21.gridx = 0;
        gridBagConstraints21.gridy = 1;
        GridBagConstraints gridBagConstraints22 = new GridBagConstraints();
        gridBagConstraints22.fill = GridBagConstraints.HORIZONTAL;
        gridBagConstraints22.insets = new Insets(0, 0, 0, 70);
        gridBagConstraints22.gridx = 1;
        gridBagConstraints22.gridy = 1;
        GridBagConstraints gridBagConstraints31 = new GridBagConstraints();
        gridBagConstraints31.gridx = 0;
        gridBagConstraints31.gridy = 2;
        GridBagConstraints gridBagConstraints32 = new GridBagConstraints();
        gridBagConstraints32.fill = GridBagConstraints.HORIZONTAL;
        gridBagConstraints32.insets = new Insets(0, 0, 0, 0);
        gridBagConstraints32.gridx = 1;
        gridBagConstraints32.gridy = 2;

        jPanelReportTypeInfo.add(getJRadioButtonBoth(), gridBagConstraints11);
        jPanelReportTypeInfo.add(jLabelBoth, gridBagConstraints12);
        jPanelReportTypeInfo.add(getJRadioButtonIdentify(), gridBagConstraints21);
        jPanelReportTypeInfo.add(jLabelIdentify, gridBagConstraints22);
        jPanelReportTypeInfo.add(getJRadioButtonSPDX(), gridBagConstraints31);
        jPanelReportTypeInfo.add(jLabelSPDX, gridBagConstraints32);

        selectedBothReport();
    }
    return jPanelReportTypeInfo;
}

From source file:SortableTable.java

/**
 * Returns the renderer component.//from   w  w w  .  j av a2s.co m
 *
 * @param table      the table.
 * @param value      the value.
 * @param isSelected selected?
 * @param hasFocus   focussed?
 * @param row        the row.
 * @param column     the column.
 * @return the renderer.
 */
public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected,
        final boolean hasFocus, final int row, final int column) {

    if (table == null) {
        throw new NullPointerException("Table must not be null.");
    }

    final JComponent component;
    final SortableTableModel model = (SortableTableModel) table.getModel();
    final int cc = table.convertColumnIndexToModel(column);
    final boolean isSorting = (model.getSortingColumn() == cc);
    final boolean isAscending = model.isAscending();

    final JTableHeader header = table.getTableHeader();
    final boolean isPressed = (cc == this.pressedColumn);

    if (this.useLabels) {
        final JLabel label = getRendererLabel(isSorting, isAscending);
        label.setText((value == null) ? "" : value.toString());
        component = label;
    } else {
        final JButton button = getRendererButton(isSorting, isAscending);
        button.setText((value == null) ? "" : value.toString());
        button.getModel().setPressed(isPressed);
        button.getModel().setArmed(isPressed);
        component = button;
    }

    if (header != null) {
        component.setForeground(header.getForeground());
        component.setBackground(header.getBackground());
        component.setFont(header.getFont());
    }
    return component;
}

From source file:gate.gui.docview.AnnotationStack.java

/**
 * Draw the annotation stack in a JPanel with a GridBagLayout.
 *//*from   www. j  ava 2  s.co m*/
public void drawStack() {

    // clear the panel
    removeAll();

    boolean textTooLong = text.length() > maxTextLength;
    int upperBound = text.length() - (maxTextLength / 2);

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.BOTH;

    /**********************
     * First row of text *
     *********************/

    gbc.gridwidth = 1;
    gbc.insets = new java.awt.Insets(10, 10, 10, 10);
    JLabel labelTitle = new JLabel("Context");
    labelTitle.setOpaque(true);
    labelTitle.setBackground(Color.WHITE);
    labelTitle.setBorder(new CompoundBorder(
            new EtchedBorder(EtchedBorder.LOWERED, new Color(250, 250, 250), new Color(250, 250, 250).darker()),
            new EmptyBorder(new Insets(0, 2, 0, 2))));
    labelTitle.setToolTipText("Expression and its context.");
    add(labelTitle, gbc);
    gbc.insets = new java.awt.Insets(10, 0, 10, 0);

    int expressionStart = contextBeforeSize;
    int expressionEnd = text.length() - contextAfterSize;

    // for each character
    for (int charNum = 0; charNum < text.length(); charNum++) {

        gbc.gridx = charNum + 1;
        if (textTooLong) {
            if (charNum == maxTextLength / 2) {
                // add ellipsis dots in case of a too long text displayed
                add(new JLabel("..."), gbc);
                // skip the middle part of the text if too long
                charNum = upperBound + 1;
                continue;
            } else if (charNum > upperBound) {
                gbc.gridx -= upperBound - (maxTextLength / 2) + 1;
            }
        }

        // set the text and color of the feature value
        JLabel label = new JLabel(text.substring(charNum, charNum + 1));
        if (charNum >= expressionStart && charNum < expressionEnd) {
            // this part is matched by the pattern, color it
            label.setBackground(new Color(240, 201, 184));
        } else {
            // this part is the context, no color
            label.setBackground(Color.WHITE);
        }
        label.setOpaque(true);

        // get the word from which belongs the current character charNum
        int start = text.lastIndexOf(" ", charNum);
        int end = text.indexOf(" ", charNum);
        String word = text.substring((start == -1) ? 0 : start, (end == -1) ? text.length() : end);
        // add a mouse listener that modify the query
        label.addMouseListener(textMouseListener.createListener(word));
        add(label, gbc);
    }

    /************************************
     * Subsequent rows with annotations *
     ************************************/

    // for each row to display
    for (StackRow stackRow : stackRows) {
        String type = stackRow.getType();
        String feature = stackRow.getFeature();
        if (feature == null) {
            feature = "";
        }
        String shortcut = stackRow.getShortcut();
        if (shortcut == null) {
            shortcut = "";
        }

        gbc.gridy++;
        gbc.gridx = 0;
        gbc.gridwidth = 1;
        gbc.insets = new Insets(0, 0, 3, 0);

        // add the header of the row
        JLabel annotationTypeAndFeature = new JLabel();
        String typeAndFeature = type + (feature.equals("") ? "" : ".") + feature;
        annotationTypeAndFeature.setText(!shortcut.equals("") ? shortcut
                : stackRow.getSet() != null ? stackRow.getSet() + "#" + typeAndFeature : typeAndFeature);
        annotationTypeAndFeature.setOpaque(true);
        annotationTypeAndFeature.setBackground(Color.WHITE);
        annotationTypeAndFeature
                .setBorder(new CompoundBorder(new EtchedBorder(EtchedBorder.LOWERED, new Color(250, 250, 250),
                        new Color(250, 250, 250).darker()), new EmptyBorder(new Insets(0, 2, 0, 2))));
        if (feature.equals("")) {
            annotationTypeAndFeature.addMouseListener(headerMouseListener.createListener(type));
        } else {
            annotationTypeAndFeature.addMouseListener(headerMouseListener.createListener(type, feature));
        }
        gbc.insets = new java.awt.Insets(0, 10, 3, 10);
        add(annotationTypeAndFeature, gbc);
        gbc.insets = new java.awt.Insets(0, 0, 3, 0);

        // add all annotations for this row
        HashMap<Integer, TreeSet<Integer>> gridSet = new HashMap<Integer, TreeSet<Integer>>();
        int gridyMax = gbc.gridy;
        for (StackAnnotation ann : stackRow.getAnnotations()) {
            gbc.gridx = ann.getStartNode().getOffset().intValue() - expressionStartOffset + contextBeforeSize
                    + 1;
            gbc.gridwidth = ann.getEndNode().getOffset().intValue() - ann.getStartNode().getOffset().intValue();
            if (gbc.gridx == 0) {
                // column 0 is already the row header
                gbc.gridwidth -= 1;
                gbc.gridx = 1;
            } else if (gbc.gridx < 0) {
                // annotation starts before displayed text
                gbc.gridwidth += gbc.gridx - 1;
                gbc.gridx = 1;
            }
            if (gbc.gridx + gbc.gridwidth > text.length()) {
                // annotation ends after displayed text
                gbc.gridwidth = text.length() - gbc.gridx + 1;
            }
            if (textTooLong) {
                if (gbc.gridx > (upperBound + 1)) {
                    // x starts after the hidden middle part
                    gbc.gridx -= upperBound - (maxTextLength / 2) + 1;
                } else if (gbc.gridx > (maxTextLength / 2)) {
                    // x starts in the hidden middle part
                    if (gbc.gridx + gbc.gridwidth <= (upperBound + 3)) {
                        // x ends in the hidden middle part
                        continue; // skip the middle part of the text
                    } else {
                        // x ends after the hidden middle part
                        gbc.gridwidth -= upperBound - gbc.gridx + 2;
                        gbc.gridx = (maxTextLength / 2) + 2;
                    }
                } else {
                    // x starts before the hidden middle part
                    if (gbc.gridx + gbc.gridwidth < (maxTextLength / 2)) {
                        // x ends before the hidden middle part
                        // do nothing
                    } else if (gbc.gridx + gbc.gridwidth < upperBound) {
                        // x ends in the hidden middle part
                        gbc.gridwidth = (maxTextLength / 2) - gbc.gridx + 1;
                    } else {
                        // x ends after the hidden middle part
                        gbc.gridwidth -= upperBound - (maxTextLength / 2) + 1;
                    }
                }
            }
            if (gbc.gridwidth == 0) {
                gbc.gridwidth = 1;
            }

            JLabel label = new JLabel();
            Object object = ann.getFeatures().get(feature);
            String value = (object == null) ? " " : Strings.toString(object);
            if (value.length() > maxFeatureValueLength) {
                // show the full text in the tooltip
                label.setToolTipText((value.length() > 500)
                        ? "<html><textarea rows=\"30\" cols=\"40\" readonly=\"readonly\">"
                                + value.replaceAll("(.{50,60})\\b", "$1\n") + "</textarea></html>"
                        : ((value.length() > 100)
                                ? "<html><table width=\"500\" border=\"0\" cellspacing=\"0\">" + "<tr><td>"
                                        + value.replaceAll("\n", "<br>") + "</td></tr></table></html>"
                                : value));
                if (stackRow.getCrop() == CROP_START) {
                    value = "..." + value.substring(value.length() - maxFeatureValueLength - 1);
                } else if (stackRow.getCrop() == CROP_END) {
                    value = value.substring(0, maxFeatureValueLength - 2) + "...";
                } else {// cut in the middle
                    value = value.substring(0, maxFeatureValueLength / 2) + "..."
                            + value.substring(value.length() - (maxFeatureValueLength / 2));
                }
            }
            label.setText(value);
            label.setBackground(AnnotationSetsView.getColor(stackRow.getSet(), ann.getType()));
            label.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
            label.setOpaque(true);

            label.addMouseListener(annotationMouseListener.createListener(stackRow.getSet(), type,
                    String.valueOf(ann.getId())));

            // show the feature values in the tooltip
            if (!ann.getFeatures().isEmpty()) {
                String width = (Strings.toString(ann.getFeatures()).length() > 100) ? "500" : "100%";
                String toolTip = "<html><table width=\"" + width
                        + "\" border=\"0\" cellspacing=\"0\" cellpadding=\"4\">";
                Color color = (Color) UIManager.get("ToolTip.background");
                float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null);
                color = Color.getHSBColor(hsb[0], hsb[1], Math.max(0f, hsb[2] - hsb[2] * 0.075f)); // darken the color
                String hexColor = Integer.toHexString(color.getRed()) + Integer.toHexString(color.getGreen())
                        + Integer.toHexString(color.getBlue());
                boolean odd = false; // alternate background color every other row

                List<Object> features = new ArrayList<Object>(ann.getFeatures().keySet());
                //sort the features into alphabetical order
                Collections.sort(features, new Comparator<Object>() {
                    @Override
                    public int compare(Object o1, Object o2) {
                        return o1.toString().compareToIgnoreCase(o2.toString());
                    }
                });

                for (Object key : features) {
                    String fv = Strings.toString(ann.getFeatures().get(key));
                    toolTip += "<tr align=\"left\"" + (odd ? " bgcolor=\"#" + hexColor + "\"" : "")
                            + "><td><strong>" + key + "</strong></td><td>"
                            + ((fv.length() > 500)
                                    ? "<textarea rows=\"20\" cols=\"40\" cellspacing=\"0\">" + StringEscapeUtils
                                            .escapeHtml(fv.replaceAll("(.{50,60})\\b", "$1\n")) + "</textarea>"
                                    : StringEscapeUtils.escapeHtml(fv).replaceAll("\n", "<br>"))
                            + "</td></tr>";
                    odd = !odd;
                }
                label.setToolTipText(toolTip + "</table></html>");
            } else {
                label.setToolTipText("No features.");
            }

            if (!feature.equals("")) {
                label.addMouseListener(annotationMouseListener.createListener(stackRow.getSet(), type, feature,
                        Strings.toString(ann.getFeatures().get(feature)), String.valueOf(ann.getId())));
            }
            // find the first empty row span for this annotation
            int oldGridy = gbc.gridy;
            for (int y = oldGridy; y <= (gridyMax + 1); y++) {
                // for each cell of this row where spans the annotation
                boolean xSpanIsEmpty = true;
                for (int x = gbc.gridx; (x < (gbc.gridx + gbc.gridwidth)) && xSpanIsEmpty; x++) {
                    xSpanIsEmpty = !(gridSet.containsKey(x) && gridSet.get(x).contains(y));
                }
                if (xSpanIsEmpty) {
                    gbc.gridy = y;
                    break;
                }
            }
            // save the column x and row y of the current value
            TreeSet<Integer> ts;
            for (int x = gbc.gridx; x < (gbc.gridx + gbc.gridwidth); x++) {
                ts = gridSet.get(x);
                if (ts == null) {
                    ts = new TreeSet<Integer>();
                }
                ts.add(gbc.gridy);
                gridSet.put(x, ts);
            }
            add(label, gbc);
            gridyMax = Math.max(gridyMax, gbc.gridy);
            gbc.gridy = oldGridy;
        }

        // add a button at the end of the row
        gbc.gridwidth = 1;
        if (stackRow.getLastColumnButton() != null) {
            // last cell of the row
            gbc.gridx = Math.min(text.length(), maxTextLength) + 1;
            gbc.insets = new Insets(0, 10, 3, 0);
            gbc.fill = GridBagConstraints.NONE;
            gbc.anchor = GridBagConstraints.WEST;
            add(stackRow.getLastColumnButton(), gbc);
            gbc.insets = new Insets(0, 0, 3, 0);
            gbc.fill = GridBagConstraints.BOTH;
            gbc.anchor = GridBagConstraints.CENTER;
        }

        // set the new gridy to the maximum row we put a value
        gbc.gridy = gridyMax;
    }

    if (lastRowButton != null) {
        // add a configuration button on the last row
        gbc.insets = new java.awt.Insets(0, 10, 0, 10);
        gbc.gridx = 0;
        gbc.gridy++;
        add(lastRowButton, gbc);
    }

    // add an empty cell that takes all remaining space to
    // align the visible cells at the top-left corner
    gbc.gridy++;
    gbc.gridx = Math.min(text.length(), maxTextLength) + 1;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.gridheight = GridBagConstraints.REMAINDER;
    gbc.weightx = 1;
    gbc.weighty = 1;
    add(new JLabel(""), gbc);

    validate();
    updateUI();
}

From source file:ca.phon.app.project.RecentProjectListCellRenderer.java

@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
        boolean cellHasFocus) {
    JLabel comp = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

    //      comp.setVerticalTextPosition(JLabel.BOTTOM);
    //      comp.setHorizontalTextPosition(JLabel.CENTER);

    // if the file string stats with RMI, show the remote project icon,
    // otherwise, show the default project icon
    if (value.toString().startsWith("rmi://"))
        comp.setIcon(remoteProjectIcon);
    else/*from   w  w  w .ja  va  2s. com*/
        comp.setIcon(localProjectIcon);

    int numChars = 20;
    int numBreaks = value.toString().length() / numChars;

    //      String compString = new String();
    //      for(int i = 0; i < numBreaks; i++) {
    //         compString += value.toString().substring(i*numChars, i*numChars+numChars) + "<br>";
    //      }
    //      compString += value.toString().substring(numBreaks*numChars, 
    //            value.toString().length());

    comp.setText("<html><center>" + StringUtils.abbreviate(value.toString(), 60) + "</center></html>");

    return comp;
}