TextIcon

Why this not working??
Using JLabel passing TextIcon as the constructor and its width, height is -1. Anyone know what I'am doing wrong?
import java.awt.*;
import javax.swing.*;
* Sometimes you want text to be an icon to be rendered as an Image <br>
* You can then rotate it or even rendered label to have different colors for example
public class TextIcon implements Icon {
   private String text = null;
   private Color color = null; 
   private int width = -1;
   private int height = -1;
   public TextIcon(String text) {
      this.text = text;
      color = Color.black;
   public void setColor(Color color) {
      this.color = color;
   public void paintIcon(Component c, Graphics g, int x, int y) {
      g.setColor(color);
      g.drawString(text, x, y);
      FontMetrics fm = g.getFontMetrics();
      width = fm.stringWidth(text);
      height = fm.getHeight();
      System.out.println("g.drawString(" + text + ", " + x + ", " + y + ");");
      System.out.println("width: " + width);
      System.out.println("height: " + height + "\n");
   public int getIconWidth() {
      System.out.println("getIconWidth() = " + width);
      return width;
   public int getIconHeight() {
      System.out.println("getIconHeight() = " + height);
      return height;

does it work with JLabel alignments of SwingConstants.LEFT and SwingConstants.RIGHT?I think you have a misunderstanding of how the alignment of left/right works. If the preferred size of a label is 100, but the actual size of the label is 200, then the painting of the label is aligned to the LEFT/RIGHT edge of the label as defined by the alignment.
What you want is the setHorizontalTextPosition() which will control whether the text or icon is painted first.
Anyway, here's some code that uses your first approach to paint the icon:
import java.awt.*;
import javax.swing.*;
* Sometimes you want text to be an icon to be rendered as an Image <br>
* You can then rotate it or even rendered label to have different colors for example
public class TextIcon implements Icon
    private String text;
    private Color color;
    private int width;
    private int height;
    private int ascent;
    public TextIcon(String text)
        this.text = text;
        color = Color.black;
        JLabel label = new JLabel(text);
        width = label.getPreferredSize().width;
        height = label.getPreferredSize().height;
        FontMetrics fm = label.getFontMetrics(label.getFont());
        ascent = fm.getAscent();
    public void setColor(Color color)
        this.color = color;
    public void paintIcon(Component c, Graphics g, int x, int y)
        g.setColor(color);
        g.drawString(text, x, y + ascent);
    public int getIconWidth()
        return width;
    public int getIconHeight()
        return height;
    public static void main(String[] args)
        TextIcon textIcon = new TextIcon("Text icon");
        JLabel justIcon = new JLabel(textIcon);
        justIcon.setBorder(BorderFactory.createLineBorder(Color.green));
        JLabel labelLeftAndIcon = new JLabel("Label align left: ", textIcon, SwingConstants.CENTER);
        labelLeftAndIcon.setHorizontalTextPosition(JLabel.LEFT);
        labelLeftAndIcon.setBorder(BorderFactory.createLineBorder(Color.red));
        JLabel labelRightAndIcon = new JLabel("Label align right: ", textIcon, SwingConstants.CENTER);
        labelRightAndIcon.setBorder(BorderFactory.createLineBorder(Color.blue));
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 0));
        // Add just an icon to test by itself
        panel.add(justIcon);
        // Add with label align left and icon
        panel.add(labelLeftAndIcon);
        // Add with label align right and icon
        panel.add(labelRightAndIcon);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(panel);
        f.setSize(640, 400);
        f.setLocationRelativeTo( null );
        f.setVisible(true);
}Note: you will probably want to add a setFont() method so you can better control the size of the text rather than always using the label default font.

Similar Messages

  • How to fix 'class' or 'interface' expected for jsp

    below is the stack trace
    org.apache.jasper.JasperException: Unable to compile class for JSP
    Generated servlet error:
    /home/sherali/.netbeans/5.5/apache-tomcat-5.5.17_base/work/Catalina/localhost/UVSDataSearch/org/apache/jsp/pager_002ddemo_jsp.java:7: 'class' or 'interface' expected
    import java.util.*;
    ^
    Generated servlet error:
    /home/sherali/.netbeans/5.5/apache-tomcat-5.5.17_base/work/Catalina/localhost/UVSDataSearch/org/apache/jsp/pager_002ddemo_jsp.java:8: 'class' or 'interface' expected
    import java.io.*;
    ^
    2 errors
    thanks a lot in advance.
    my jsp is
    <%@ page session="false" %>
    <%@ page import="tauvex.*;" %>
    <%@ page import="java.util.*" %>
    <%@ page import="java.io.*" %>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <%@ taglib uri="http://jsptags.com/tags/navigation/pager" prefix="pg" %>
    <html>
    <head>
    <title>Tauvex Search Results</title>
    <%
    * Pager Tag Library
    * Copyright (C) 2002 James Klicman <[email protected]>
    * The latest release of this tag library can be found at
    * http://jsptags.com/tags/navigation/pager/
    * This library is free software; you can redistribute it and/or
    * modify it under the terms of the GNU Lesser General Public
    * License as published by the Free Software Foundation; either
    * version 2.1 of the License, or (at your option) any later version.
    * This library is distributed in the hope that it will be useful,
    * but WITHOUT ANY WARRANTY; without even the implied warranty of
    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
    * Lesser General Public License for more details.
    * You should have received a copy of the GNU Lesser General Public
    * License along with this library; if not, write to the Free Software
    * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
    %>
    <style type="text/css">
    A.nodec { text-decoration: none; }
    </style>
    </head>
    <body bgcolor="#ffffff">
    <%
    String style = getParam(request, "style", "simple");
    String position = getParam(request, "position", "top");
    String index = getParam(request, "index", "center");
    int maxPageItems = getParam(request, "maxPageItems", 3);
    int maxIndexPages = getParam(request, "maxIndexPages", 3);
    %>
    <%
    String query1=(String)request.getAttribute("query1");
    String query=(String)request.getAttribute("query");
    String ShowFile=(String)request.getAttribute("ShowFile");
    String ShowRA=(String)request.getAttribute("ShowRA");
    String ShowDEC=(String)request.getAttribute("ShowDEC");
    String Telescope=(String)request.getAttribute("Telescope");
    String ObservationDates=(String)request.getAttribute("ObservationDates");
    String Filter=(String)request.getAttribute("Filter");
    String RA=(String)request.getAttribute("RA");
    String DEC=(String)request.getAttribute("DEC");
    String DATE=(String)request.getAttribute("DATE");
    String DATE1=(String)request.getAttribute("DATE1");
    String Radious=(String)request.getAttribute("Radious");
    String FILTER[]=(String[])request.getAttribute("FILTER");
    String OrderBy1=(String)request.getAttribute("OrderBy1");
    String OrderBy2=(String)request.getAttribute("OrderBy2");
    String OrderBy3=(String)request.getAttribute("OrderBy3");
    %>
    <%
    out.println("<form action=\"PlainSQLQuery\" method=POST>");
    out.println("<textarea rows = 5 cols = 40 name=query id=\"query\">");
    out.println(query);
    out.println("</textarea>");
    out.println("<input type = submit value = \"Submit\">");
    out.println("<input type = reset value = \"Reset\">");
    out.println("</form>");
    %>
    <center>
    <table border="0" width="90%" cellpadding="4">
    <tr>
    <td colspan="2" align="left" valign="top">
    <table border="0" cellspacing="2" cellpadding="0">
    <tr><td>Max. Page Items </td>
    <td><input type="text" size="4" name="maxPageItems" value="<%= maxPageItems %>" onChange="this.form.submit();"></td></tr>
    <tr><td>Max. Index Pages </td>
    <td><input type="text" size="4" name="maxIndexPages" value="<%= maxIndexPages %>" onChange="this.form.submit();"></td></tr>
    </table>
    </td>
    </tr>
    </table>
    <pg:pager
    index="<%= index %>"
    maxPageItems="<%= maxPageItems %>"
    maxIndexPages="<%= maxIndexPages %>"
    url="TauvexDataServlet"
    export="offset,currentPageNumber=pageNumber"
    scope="request">
    <%-- keep track of preference --%>
    <pg:param name="style"/>
    <pg:param name="position"/>
    <pg:param name="index"/>
    <pg:param name="maxPageItems"/>
    <pg:param name="maxIndexPages"/>
    <pg:param name="RA"/>
    <pg:param name="DEC"/>
    <pg:param name="DATE"/>
    <pg:param name="DATE1"/>
    <pg:param name="Radious"/>
    <pg:param name="FILTER"/>
    <pg:param name="ShowRA"/>
    <pg:param name="ShowDEC"/>
    <pg:param name="Telescope"/>
    <pg:param name="ObservationDates"/>
    <pg:param name="Filter"/>
    <pg:param name="OrderBy1"/>
    <pg:param name="OrderBy2"/>
    <pg:param name="OrderBy3"/>
    <%-- save pager offset during form changes --%>
    <input type="hidden" name="pager.offset" value="<%= offset %>">
    <%-- warn if offset is not a multiple of maxPageItems --%>
    <% if (offset.intValue() % maxPageItems != 0 &&
    ("alltheweb".equals(style) || "lycos".equals(style)) )
    %>
    <p>Warning: The current page offset is not a multiple of Max. Page Items.
    <br>Please
    <pg:first><a href="<%= pageUrl %>">return to the first page</a></pg:first>
    if any displayed range numbers appear incorrect.</p>
    <% } %>
    <%-- the pg:pager items attribute must be set to the total number of
    items for index before items to work properly --%>
    <% if ("top".equals(position) || "both".equals(position)) { %>
    <br>
    <pg:index>
    <% if ("texticon".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/texticon.jsp" flush="true"/>
    <% } else if ("jsptags".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/jsptags.jsp" flush="true"/>
    <% } else if ("google".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/google.jsp" flush="true"/>
    <% } else if ("altavista".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/altavista.jsp" flush="true"/>
    <% } else if ("lycos".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/lycos.jsp" flush="true"/>
    <% } else if ("yahoo".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/yahoo.jsp" flush="true"/>
    <% } else if ("alltheweb".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/alltheweb.jsp" flush="true"/>
    <% } else { %>
    <jsp:include page="/WEB-INF/jsp/simple.jsp" flush="true"/>
    <% } %>
    </pg:index>
    <% } %>
    <hr>
    <form action="ZipServlet" method="get" name="download" onsubmit="return Form1_Validator(this)">
    <table id="output">
    <CAPTION><EM>Fits file Search Results</EM></CAPTION><tr>
    <%
    out.println("<th>Check Box</th>");
    out.println("<th>File Name</th>");
    if(ShowRA != null && "on".equals(ShowRA))
    out.println("<th>RA_START</th>");
    if(ShowRA != null && "on".equals(ShowRA))
    out.println("<th>RA_END</th>");
    if(ShowDEC != null && "on".equals(ShowDEC))
    out.println("<th>DEC_START</th>");
    if(ShowDEC != null && "on".equals(ShowDEC))
    out.println("<th>DEC_END</th>");
    if(Telescope!=null && "on".equals(Telescope))
    out.println("<th>Telescope</th>");
    if(ObservationDates !=null && "on".equals(ObservationDates))
    out.println("<th>STARTOBS</th>");
    if(ObservationDates !=null && "on".equals(ObservationDates))
    out.println("<th>ENDOBS</th>");
    if(Filter!=null && "on".equals(Filter))
    out.println("<th>FILTER</th>");
    out.println("</tr>");
    %>
    <%--
    <table width="90%" cellspacing="4" cellpadding="4">
    Since the data source is static, it's easy to offset and limit the
    loop for efficiency. If the data set size is not known or cannot
    be easily offset, the pager tag library can count the items and display
    the correct subset for you.
    The following is an example using an enumeration data source of
    unknown size. The pg:pager items and isOffset attributes must
    not be set for this example:
    --%>
    <%
    Enumeration myDataList1 = (Enumeration)request.getAttribute("myDataList1");
    if (myDataList1 == null)
    throw new RuntimeException("myDataList1 is null");
    %>
    <% while (myDataList1.hasMoreElements()) { %>
    <% TauvexData elem = (TauvexData)myDataList1.nextElement(); %>
    <pg:item> <%
    out.println("<tr>");
    %>
    <td><input type= "checkbox" name="cb" value="<%=elem.getDownload()%>"></td>
    <td><a href="<%= elem.getDownload() %>"><%= elem.Fitsfilename %></a></td>
    <%
    // out.println("<td> "+elem.Fitsfilename+" </td>");
    if(ShowRA != null && "on".equals(ShowRA))
    out.println("<td> "+elem.RA_START+" </td>");
    if(ShowRA != null && "on".equals(ShowRA))
    out.println("<td> "+elem.RA_END+"</td>");
    if(ShowDEC != null && "on".equals(ShowDEC))
    out.println("<td> "+elem.DEC_START+" </td>");
    if(ShowDEC != null && "on".equals(ShowDEC))
    out.println("<td> "+elem.DEC_END+" </td>");
    if(Telescope!=null && "on".equals(Telescope))
    out.println("<td> "+elem.telescope+" </td>");
    if(ObservationDates !=null && "on".equals(ObservationDates))
    out.println("<td> "+elem.STARTOBS+" </td>");
    if(ObservationDates !=null && "on".equals(ObservationDates))
    out.println(" <td> "+elem.ENDOBS+" </td>");
    if(Filter!=null && "on".equals(Filter))
    out.println("<td> "+elem.FILTER+" </td>");
    out.println("</tr>");
    %> </pg:item>
    <% } %>
    </table>
    <input type="button" name="CheckAll" value="Check All Boxes" onclick="modify_boxes(true,3)">
    <input type="button" name="UnCheckAll" value="UnCheck All Boxes" onclick="modify_boxes(false,3)">
    <input type="submit" value="Download">
    </form>
    <hr>
    <pg:pages>
    <a href="<%= pageUrl %>"><%= pageNumber %></a>
    </pg:pages>
    <pg:last>
    <a href="<%= pageUrl %>">[ Last >| (<%= pageNumber %>) ]</a>
    </pg:last>
    <% if ("bottom".equals(position) || "both".equals(position)) { %>
    <pg:index>
    <% if ("texticon".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/texticon.jsp" flush="true"/>
    <% } else if ("jsptags".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/jsptags.jsp" flush="true"/>
    <% } else if ("google".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/google.jsp" flush="true"/>
    <% } else if ("altavista".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/altavista.jsp" flush="true"/>
    <% } else if ("lycos".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/lycos.jsp" flush="true"/>
    <% } else if ("yahoo".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/yahoo.jsp" flush="true"/>
    <% } else if ("alltheweb".equals(style)) { %>
    <jsp:include page="/WEB-INF/jsp/alltheweb.jsp" flush="true"/>
    <% } else { %>
    <jsp:include page="/WEB-INF/jsp/simple.jsp" flush="true"/>
    <% } %>
    </pg:index>
    <% } %>
    </pg:pager>
    </center>
    </body>
    </html>
    <%!
    private static int num =1;
    private static String getName(){
    String str="cb";
    str=str+num;
    num++;
    return str ;
    private static final String getParam(ServletRequest request, String name,
    String defval)
    String param = request.getParameter(name);
    return (param != null ? param : defval);
    private static final int getParam(ServletRequest request, String name,
    int defval)
    String param = request.getParameter(name);
    int value = defval;
    if (param != null) {
    try { value = Integer.parseInt(param); }
    catch (NumberFormatException ignore) { }
    return value;
    private static void radio(PageContext pc, String name, String value,
    boolean isDefault) throws java.io.IOException
    JspWriter out = pc.getOut();
    String param = pc.getRequest().getParameter(name);
    out.write("<input type=\"radio\" name=\"");
    out.write(name);
    out.write("\" value=\"");
    out.write(value);
    out.write("\" onChange=\"this.form.submit();\"");
    if (value.equals(param) || (isDefault && param == null))
    out.write(" checked");
    out.write('>');
    %>

    Well, putting all that Java code into a JSP was a bad idea in the first place, just on general design principles. But you've done it in such a way that the result of compiling the JSP is malformed Java code. Frankly I would just throw it away and put the Java code into a servlet or some other Java class, where it belongs.
    But if you're really working in a place where nobody has learned anything since 2003, and you're forced to support that old junk, then I would point out that the error occurs before the place which generates this line:
    import java.util.*;You only need to look at two of the thousand lines of code you posted.

  • Icon of a node changes when I edit its content

    I have a JTree that represent an xml document.
    and I have a TreeCellRenderer that sets the Icon of the node according to its type:
    public class XmlTreeCellRenderer extends DefaultTreeCellRenderer {
          * Overrides this method to display the apropriate icon according
          * to the type of the <code>Node</code>.
         @Override
         @SuppressWarnings("hiding")
         public Component getTreeCellRendererComponent(
                   JTree tree, Object value, boolean sel,
                   boolean expanded, boolean leaf, int row, boolean hasFocus) {
              super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf,
                        row, hasFocus);
              if (!(value instanceof XmlTreeNode)) {
                   return this;
              // retrieves the type of the node
              XmlTreeNode treeNode = (XmlTreeNode) value;
              short nodeType = treeNode.getNodeType();
              // sets the icon of the node and the foreground color
              // according to the type
              switch (nodeType) {
              case Node.ELEMENT_NODE:
                   setForeground(Color.BLACK);
                   setIcon(ELEMENT_ICON);
                   break;
              case Node.TEXT_NODE:
                   setForeground(Color.BLUE);
                   setIcon(TEXT_ICON);               
                   break;
              case Node.COMMENT_NODE:
                   setForeground(Color.GREEN);
                   setIcon(COMMENT_ICON);               
                   break;
              default:
                   setToolTipText("This is an unknown node");
                   break;
              return this;
         // the image resources
         private static final ImageIcon TEXT_ICON =
              new ImageIcon("resource/images/TextIcon.jpg");
         private static final ImageIcon COMMENT_ICON =
              new ImageIcon("resource/images/CommentIcon.jpg");
         private static final ImageIcon ELEMENT_ICON =
              new ImageIcon("resource/images/ElementIcon.jpg");
    }Now the problem is when I edit a node's content the icon changes back
    to the default icon, like this.
    This is before I edit the node's content:
    http://img140.imageshack.us/my.php?image=before6zj.jpg
    This is after:
    http://img89.imageshack.us/my.php?image=after2xd.jpg
    Notice how the "E" changed to the folder icon.
    How do I disable it?
    I want it to stay with the "E" icon even when I edit the node's content.
    I tried in the XmlTreeCellRenderer to use setClosedIcon and setOpenIcon
    but it didn't work.

    I have a JTree that represent an xml document.
    and I have a TreeCellRenderer that sets the Icon of
    the node according to its type:<snip>
    Now the problem is when I edit a node's content the
    icon changes backIt's a bug. See:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4663832

  • Vertical text in JTabbedPanes on MAC

    Hi all,
    I use the CrossPlatformLookAndFeel for my Java application and I want to have vertical text in tabs with are placed on the left side. For displaying the vertical text I use a special TabbedPanUI (see code below) which rotates the text. This works fine on Linux and Windows platforms, but on Mac the text is not readable.
    Anyone got a clue about this??
    Thank for your help
    import java.awt.AlphaComposite;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Insets;
    import java.awt.Rectangle;
    import java.awt.image.BufferedImage;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JTabbedPane;
    import javax.swing.UIManager;
    import javax.swing.plaf.basic.BasicGraphicsUtils;
    import javax.swing.plaf.basic.BasicTabbedPaneUI;
    * @author elkes
    public class DOOCSTabbedPaneUI extends BasicTabbedPaneUI {
        /** Creates a new instance of DOOCSTabbedPaneUI */
        public DOOCSTabbedPaneUI() {
            super();
        private Image getVerticalImage(int tabIndex) {
            ImageIcon iconNormale = (ImageIcon) tabPane.getIconAt(tabIndex);
            int iconWidth = (iconNormale != null) ? iconNormale.getIconHeight() : 0;
            int iconHeight = (iconNormale != null) ? iconNormale.getIconWidth() : 0;
            String title = tabPane.getTitleAt(tabIndex);
            FontMetrics metrics = getFontMetrics();
            int titleWidth = (title != null) ? metrics.stringWidth(title) : 0;
            int titleHeight = (title != null) ? metrics.getHeight() : 0;
            int height = iconWidth + titleWidth + textIconGap + 1;
            int width = Math.max(iconHeight, titleHeight);
            if (width==0) width=1;
            boolean isSelected = (tabPane.getSelectedIndex() == tabIndex);
            int tabPlacement = tabPane.getTabPlacement();
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2 = image.createGraphics();
            g2.setComposite(AlphaComposite.Src);
            if (tabPlacement == JTabbedPane.LEFT) {
                g2.translate(0, height);
                g2.rotate(-Math.PI / 2);
            } else {
                g2.translate(width, 0);
                g2.rotate(Math.PI / 2);
            Color background = (isSelected) ? UIManager.getColor("TabbedPane.selected")
                    : tabPane.getBackgroundAt(tabIndex);
            g2.setColor(background);
            g2.fillRect(0, 0, height, width);
            if (iconNormale != null) {
                g2.drawImage(iconNormale.getImage(), 0, 0, null);
            if (title != null) {
                g2.setFont(metrics.getFont());
                g2.setColor(tabPane.getForegroundAt(tabIndex));
                int mnemIndex = tabPane.getDisplayedMnemonicIndexAt(tabIndex);
                BasicGraphicsUtils.drawStringUnderlineCharAt(g2, title, mnemIndex, iconWidth + textIconGap, metrics.getAscent());
            g2.dispose();
            return image;
        private boolean isBottomOrTop() {
            int tabPlacement = tabPane.getTabPlacement();
            return tabPlacement == JTabbedPane.TOP || tabPlacement == JTabbedPane.BOTTOM;
        protected int calculateTabHeight(int tabPlacement, int tabIndex, int fontHeight) {
            if (isBottomOrTop()) {
                return super.calculateTabHeight(tabPlacement, tabIndex, fontHeight);
            return super.calculateTabWidth(tabPlacement, tabIndex, getFontMetrics());
        protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) {
            if (isBottomOrTop()) {
                return super.calculateTabWidth(tabPlacement, tabIndex, metrics);
            return getVerticalImage(tabIndex).getWidth(null);
        protected void paintText(Graphics g, int tabPlacement, Font font, FontMetrics metrics, int tabIndex, String title, Rectangle textRect, boolean isSelected) {
            if (isBottomOrTop()) {
                super.paintText(g, tabPlacement, font, metrics, tabIndex, title, textRect, isSelected);
            } else {
                Image image = getVerticalImage(tabIndex);
                Rectangle r = getTabBounds(tabPane, tabIndex);
                Insets insets = getTabAreaInsets(tabPlacement);
                int dx = r.x + insets.top;
                int dy = r.y;
                if (tabPlacement == JTabbedPane.LEFT) {
                    dy += insets.left;
                } else {
                    dy += insets.right;
                g.drawImage(image, dx, dy, null);
        protected void paintIcon(Graphics g, int tabPlacement, int tabIndex,
                Icon icon, Rectangle iconRect, boolean isSelected) {
            if (!isBottomOrTop()) {
                return;
            super.paintIcon(g, tabPlacement, tabIndex, icon, iconRect, isSelected);
    }

    Maybe the approach of using a [url http://tips4java.wordpress.com/2009/04/06/rotated-icon/]Rotated Icon along with the TextIcon, will work on all platforms without using a custom UI.

  • Slow Applet init in IE

    Hi dudes,
    i have a problem with applet.. it's no a true problem, but it's an annoying problem. I have an applet that work in IE. When it's start with focus on and with maximixe window the applet load very slowly and CPU usage in very busy (88%-100%). When i start the applet with window minimized, it's load very fastly. It's a problem becuase my application needs to start in full screen mode....
    You have some suggestions?
    Thank you. Matte

    I can't post it beacuase it's a commercial program for my company.
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
            enableEvents(AWTEvent.WINDOW_EVENT_MASK);
            Container contentPane  = this.getContentPane();
            contentPane.setLayout(null);
            String value = (String)this.getParameter("file");
            event_root1 = DNDTree.createTree(true,1,null,1);
            eventi1.addMouseListener(new Editor_eventi1_mouseAdapter(this));
            (DefaultMutableTreeNode) eventi1.getModel().getRoot(),new ArrayList());
            event_root2 = DNDTree.createTree(false,1,null,1);
            eventi2 = new DNDTree(event_root2,2);
            jScrollPane1 = new JScrollPane(tree1);
            jScrollPane2 = new JScrollPane(tree2);
            jScrollPane1.setViewportBorder(null);
            jScrollPane1.setAutoscrolls(true);
            jScrollPane1.setBorder(border2);
            jScrollPane1.setToolTipText("");
            jScrollPane1.setBounds(new Rectangle(50, 10, 320, 390));
            jScrollPane2.getViewport().setBackground(Color.white);
            jScrollPane2.setBorder(border2);
            jScrollPane2.setBounds(new Rectangle(400, 10, 320, 390));
            jScrollPane5 = new JScrollPane(eventi1);
            jScrollPane5.getViewport().setBackground(Color.white);
            jScrollPane5.setBorder(border2);
            jScrollPane5.setBounds(new Rectangle(50, 10, 320, 390));
            jScrollPane6= new JScrollPane(eventi2);
            jScrollPane6.getViewport().setBackground(Color.white);
            jScrollPane6.setBorder(border2);
            jScrollPane6.setBounds(new Rectangle(400, 10, 320, 390));
            Menu_Disponibili = new JPopupMenu();
            Menu_Disponibili.setBackground(new Color(212, 208, 200));
            Menu_Disponibili.setFont(new java.awt.Font("Tahoma", Font.PLAIN, 11));
            Menu_Disponibili.setToolTipText("Opzioni di inserimento");
            Menu_Disponibili.setInvoker(null);
            Menu_Disponibili.addMouseListener(new Editor_Menu_Disponibili_mouseAdapter(this));
            Item_Expande.setText("Espandi");
            Item_Expande.addActionListener(new Editor_Item_Expande_actionAdapter(this));
            Item_Collapse.setText("Compatta");
            Item_Collapse.addActionListener(new Editor_Item_Collapse_actionAdapter(this));
            Item_Add.setText("Aggiungi");
            Item_Add.addActionListener(new Editor_Item_Add_actionAdapter(this));
            VTextIcon textIcon = new VTextIcon(jLabel1, "OGGETTI DISPONIBILI",VTextIcon.ROTATE_NONE,220,220,198);
            jLabel1 = new JLabel(textIcon);
            jLabel1.setBackground(Color.darkGray);
            jLabel1.setFont(new java.awt.Font("Tahoma", Font.BOLD, 12));
            jLabel1.setForeground(Color.darkGray);
            jLabel1.setBorder(border2);
            jLabel1.setDisabledIcon(textIcon);
            jLabel1.setBounds(new Rectangle(31, 10, 20, 390));
            VTextIcon textIcon2 = new VTextIcon(jLabel2, "OGGETTI SELEZIONATI",VTextIcon.ROTATE_NONE,220,220,198);
            jLabel2 = new JLabel(textIcon2);
            jLabel2.setFont(new java.awt.Font("Tahoma", Font.BOLD, 12));
            jLabel2.setForeground(Color.darkGray);
            jLabel2.setBorder(border2);
            jLabel2.setHorizontalAlignment(SwingConstants.CENTER);
            jLabel2.setHorizontalTextPosition(SwingConstants.CENTER);
            jLabel2.setVerticalAlignment(SwingConstants.CENTER);
            jLabel2.setBounds(new Rectangle(719, 10, 20, 390));
            VTextIcon textIcon3 = new VTextIcon(jLabel6, "GRUPPI",VTextIcon.ROTATE_NONE,220,220,198);
            jLabel6 = new JLabel(textIcon3);
            jLabel6.setBackground(Color.darkGray);
            jLabel6.setFont(new java.awt.Font("Tahoma", Font.BOLD, 12));
            jLabel6.setForeground(Color.darkGray);
            jLabel6.setBorder(border2);
            jLabel6.setText("");
            jLabel6.setBounds(new Rectangle(31, 10, 20, 390));
            progressBarControl = new ProgressBarControl(ProgressBar,ProgressLabel);
            progressBarControl.reset();
            jTabbedPane1.setSelectedIndex(0);It's very strange, because it's works perfectly when execute it on a minimize window (CPU USAGE DOWN TO 40%-55%), while with a maximized window it's works very slowly and cpu usage go to 95%-100% it's very frustrating....

  • Queue/Array into JTable

    Hi, I am reading some data from a database and I have got it stored locally inside a queue. What i want to do is read in the queue (already got a mehtod for this) but then add each object in the queue, into a row in my JTable. also I want to be able to delete a row of a jtable when i am finished with it. any help very much apprecaited. all i have got so far is declaring the JTable and jscrollpane etc. i sint too crash hot on swing so you might have to make it obvious. thanks.

    Right, I seem to have got myself into a mess with this. i dont think i'm too far off though. if i get this bit then i should have cracked it. I am getting a null pointer exception as i try to enter my first string into the TableModel. PS Its a bit of a hashed together attempt so any tips of how to improve the class generally, greatly appreciated.
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ProtocolGUI extends JPanel implements ActionListener
              private JPanel menuPanel;
              private JMenuBar menuBar;
            private JMenu fileMenu;
            private JMenu helpMenu;
              private JMenuItem startMon;
             private JMenuItem exitItem;
            private JMenuItem about;
            private JTabbedPane tabbedPane;
              private JPanel graphicsPanel;
              private JPanel textPanel;
            private JTable pclTable;
         public ProtocolGUI()
            super(new BorderLayout());
            menuBar = new JMenuBar();
            fileMenu = new JMenu("File");
            helpMenu = new JMenu("Help");
            startMon = new JMenuItem("Start");
             exitItem = new JMenuItem("Exit");
            about = new JMenu("About");
            menuPanel= new JPanel();
            menuPanel.setLayout(new BorderLayout());
            this.add(menuPanel, BorderLayout.NORTH);
            exitItem.addActionListener(this);
            fileMenu.add(startMon);
            fileMenu.add(exitItem);
            helpMenu.add(about);
            menuBar.add(fileMenu);
            menuBar.add(helpMenu);
            menuPanel.add(menuBar, BorderLayout.NORTH);
              ///////////end of menu///////////////
            tabbedPane = new JTabbedPane();
              ImageIcon graphIcon = createImageIcon("images/graphtab.gif");
              ImageIcon textIcon = createImageIcon("images/texttab.gif");
            graphIcon = new ImageIcon("images/graphtab.gif");
            textIcon = new ImageIcon("images/texttab.gif");
            graphicsPanel = new JPanel();
            textPanel = new JPanel();
              tabbedPane.addTab("Graphical", graphIcon, graphicsPanel,
                              "Swaps to graphical output");
            tabbedPane.addTab("Text", textIcon, textPanel,
                              "Swaps to text output");
            /*TableModel dataModel = new AbstractTableModel()
              public int getColumnCount()
                     return 6;
              public int getRowCount()
                     return 20;
              public Object getValueAt(int row, int col)
                     return new Integer(row*col);
              //pclTable = new JTable(dataModel);
            MessageSet ms2 = new MessageSet();
              textPanel.add(new JScrollPane(createTable(ms2.getArray())));
            //Add the tabbed pane to the outer panel.
              add(tabbedPane, BorderLayout.CENTER);
            setPreferredSize(new Dimension(500, 500));
            //Uncomment the following line to use scrolling tabs.
            //tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        // Creates a JTable and returns it
         private JTable createTable(Message[] theArray)
              // Define empty data for model creation
              String[][] cellData = new String[0][6];
              String[] colNames = { "ID", "Sent To", "Sent From", "Command", "Data Ref", "Monitored" };
              // Create the table model
              DefaultTableModel tableModel = new DefaultTableModel(cellData, colNames);
              // Create some records and add them to the model
              String[] record = new String[6];
              for (int row=0; row<=theArray.length; row++)
                record[0] = Integer.toString(theArray[row].getID());
                record[1] = theArray[row].getToSection_ID();
                   record[2] = theArray[row].getFromSection_ID();
                   record[3] = Integer.toString(theArray[row].getType_ID());
                   record[4] = theArray[row].getDataRef();
                   record[5] = Integer.toString(theArray[row].getMonitored());
                   tableModel.addRow(record);
              // Create the table and return it
              return new JTable(tableModel);
        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path)
            java.net.URL imgURL = ProtocolGUI.class.getResource(path);
            if (imgURL != null)
                return new ImageIcon(imgURL);
              else
                System.err.println("Couldn't find file: " + path);
                return null;
        public void actionPerformed(ActionEvent e)
            Object source = e.getSource();
            if (source == exitItem)
                System.exit(0);
         private static void createAndShowGUI()
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("Protocol GUI");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new ProtocolGUI();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.getContentPane().add(new ProtocolGUI(),
                                     BorderLayout.CENTER);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args)
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

Maybe you are looking for