Byte.MAX_VALUE, Integer.MAX_VALUE

hi,
just curious..
byte b = (byte)Byte.MAX_VALUE+1 //does not compile
short s = (short)Short.MAX_VALUE+1 // does not compile
int i = (int)Integer.MAX_VALUE+1 //compiles
can someone tell me why this happens?
thanks,
shishir

thanks.
any idea why adding 1 in int doesn't promot it to
long?[url http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.18.2]JLS 15.182 Additive Operators (+ and -) for Numeric Types says: Binary numeric promotion is performed on the operands (�5.6.2). The type of an additive expression on numeric operands is the promoted type of its operands.
And [url http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#170983]5.6.2 Binary Numeric Promotion says: ...Otherwise, both operands are converted to type int.
So any two integer types yield an int result, unless at least one of them is a long. byte + byte gives int, so the result is an int. int + int (e.g., Integer.MAX_VALUE + 1) yields an int, which just silently wraps around through Integer.MIN_VALUE (0x80000000).

Similar Messages

  • OutOfMemoryError on new byte[Integer.MAX_VALUE]. Why, how to fix?

    Hello,
    I am getting an OutOfMemoryException when I am initializing a new array of bytes:
    byte[] barr = new byte[Integer.MAX_VALUE];
    Why?
    Thanks,
    Corrine

    Well, I am dealing with 32-bit values, and eachelement of the array corresponds to one of twooptions
    for each bit.
    Why are you choosing to do this?Because the array is supposed to be a grayscale map
    for a 32-bit image.Okay, maybe my question wasn't clear enough. Why have
    you set your requirements to use a byte array in which
    each byte serves to represent a single bit as a
    representation of a grayscale map of a 32-bit image?
    Can you post some code? Why have you chosen to
    allocate ~2GB of RAM to work with a single image?
    There has got to be a better way to accomplish what
    you're trying to do.
    The answer to your question is because as I understand it, the structure of the grayscale map that I'm using corresponds to the required specification in defining an associated IndexColorModel.

  • I have doubt regarding the byte to integer conversion.

    In java card epurse application the output we see is in bytes.to convert this byte to integer which is understandable by the end-user what should be done?

    809295 wrote:
    In java card epurse application the output we see is in bytes .
    to convert this byte to integer which is understandable by the end-user what should be done?What do you mean by we ?
    How many bytes ?
    On a java card platform support for integer is optional, you may only have short.
    I assume by understandable by the end-user you mean display as a sequence of decimal digits ?
    So two bytes 0x04 0xd2 (combined to a short 0x04d2 which is 1234 decimal)
    should be presented to the user as 0x31 0x32 0x33 0x34 (ascii values for '1' '2' '3' '4').

  • NotifyAll and wait versus Thread.sleep(Integer.MAX_VALUE) and interrupt

    Please post here:
    http://forum.java.sun.com/thread.jspa?threadID=691544

    And your current wait/notify pair does not work because they are called on different objects.
    X.wait();
    Y.notify();
    X and Y should refer a same object.
    You must read the API documentation for java.lang.Object.wait and notify very closely. Coding wait/notify needs a rigorous discipline.

  • Still null . Uuuuh

    Hello!
    The following program gives null for Integer.getInteger(System property name) but on the other hand System.getProperty("os.name") (say) is giving the correct result. . Why null for Integer.getInteger(spn) instead of an Integer object.
    import java.util.Properties ;
    class IntegerMethods {
    public static void main(String args[]) {
      int  n1 = -1 , n2 = 500 ;  //Change and Check equivalent conversions.
      int ir = 8  ;              //ir = integer radix
      Integer  i1 = new Integer(n1);                
      Integer  i2 = new Integer(n2);
      Integer  is = new Integer("200");
      String sg = new String("10000000");   //Decode range -2147683648  ---   2147483647
      //Properties p = new Properties();
      System.out.println("Integer i1 = " + i1 + " i2 = "+i2+" Radix = "+ir+" radix can be set to values other than 2,8,10,16");
      System.out.println("Integer                            Integer.MIN_VALUE : " + Integer.MIN_VALUE);
      System.out.println("Integer                            Integer.MAX_VALUE : " + Integer.MAX_VALUE);
      System.out.println("Integer                                  i.hashCode(): " + i2.hashCode());
      System.out.println("Integer                            byte i.byteValue(): " + i1.byteValue());
      System.out.println("Integer                              int i.intValue(): " + i1.intValue());
      System.out.println("Integer                          short i.shortValue(): " + i1.shortValue());
      System.out.println("Integer                            long i.longValue(): " + i1.longValue());
      System.out.println("Integer                          float i.floatValue(): " + i1.floatValue());
      System.out.println("Integer                        double i.doubleValue(): " + i1.doubleValue());
      System.out.println("Integer                         boolean I1.equals(I2): " + i1.equals(i2));
      System.out.println("Integer                          int I1.compareTo(I2): " + i1.compareTo(i2));
      try {
      System.out.println("Integer                           int I1.compareTo(O): " + i1.compareTo(i2));
      System.out.println("Integer                      static Integer decode(s): " + Integer.decode(sg));    //Decodable Strings :See JDK1.4 Help
      System.out.println("Integer                        static int parseInt(s): " + Integer.parseInt(sg));
      System.out.println("Integer                      static int parseInt(s,"+ir+"): " + Integer.parseInt(sg,ir));
      System.out.println("Integer                     static Integer valueOf(s): " + Integer.valueOf(sg));
      System.out.println("Integer                   static Integer valueOf(s,"+ir+"): " + Integer.valueOf(sg,ir)); 
      }catch(ClassCastException e) {
       System.out.println("Exception Condition:" + e);
      }catch(NumberFormatException e) {
       System.out.println("Exception Condition:" + e);
      System.out.println("Integer                           String I.toString(): " + i1.toString());
      System.out.println("Integer                 static String I.toString("+ n2 + "): " + Integer.toString(n2));
      System.out.println("Integer               static String I.toString("+n2+","+ir+"): " + Integer.toString(n2,ir));
      System.out.println("Integer             static String toBinaryString("+ n2 + "): " + Integer.toBinaryString(n2));
      System.out.println("Integer              static String toOctalString("+ n2 + "): " + Integer.toOctalString(n2));
      System.out.println("Integer                static String toHexString("+ n2 + "): " + Integer.toHexString(n2));
      System.out.println("Integer        static Integer getInteger(Sys propName): " + Integer.getInteger("os.version"));
      System.out.println("Integer      static Integer getInteger(Sys propName,i): " + Integer.getInteger("os.version",n1));
      System.out.println("Integer      static Integer getInteger(Sys propName,I): " + Integer.getInteger("os.version",i1));
      System.out.println("Integer static Integer getInteger(sun.arch.data.model): " + Integer.getInteger("sun.arch.data.model"));
      System.out.println("Integer             static Integer getInteger(os.arch): " + Integer.getInteger("os.arch"));
      System.out.println("Integer             static Integer getInteger(os.name): " + Integer.getInteger("os.name"));  
      System.out.println("Integer          static Integer getInteger(os.version): " + Integer.getInteger("os.version"));
      System.out.println("Integer            static Integer getInteger(user.dir): " + Integer.getInteger("user.dir")); 
      System.out.println("Integer           static Integer getInteger(user.home): " + Integer.getInteger("user.home"));
      System.out.println("Integer           static Integer getInteger(user.name): " + Integer.getInteger("user.name"));  
      System.out.println("Integer           static Integer getInteger(java.home): " + Integer.getInteger("java.home")); 
      System.out.println("Integer         static Integer getInteger(java.vendor): " + Integer.getInteger("java.vendor"));
      System.out.println("Integer      static Integer getInteger(file.separator): " + Integer.getInteger("file.separator"));
      System.out.println("Integer      static Integer getInteger(path.separator): " + Integer.getInteger("path.separator"));
      System.out.println("Integer      static Integer getInteger(line.separator): " + Integer.getInteger("line.separator"));
      System.out.println("System         static Integer.getInteger(java.vm.name): " + Integer.getInteger("java.vm.name"));
      System.out.println("Integer     static Integer getInteger(java.vendor.url): " + Integer.getInteger("java.vendor.url"));
      System.out.println("Integer     static Integer getInteger(java.class.path): " + Integer.getInteger("java.class.path"));
      System.out.println("Integer  static Integer getInteger(java.class.version): " + Integer.getInteger("java.class.version"));
      System.out.println("System                     System.getProperty(os.name): " + System.getProperty("os.name"));
      System.out.println("System                     System.getProperty(os.arch): " + System.getProperty("os.arch"));
      System.out.println("System                  System.getProperty(os.version): " + System.getProperty("os.version"));
      System.out.println("System                   System.getProperty(user.name): " + System.getProperty("user.name"));
      System.out.println("System                    System.getProperty(user.dir): " + System.getProperty("user.dir"));
      System.out.println("System                   System.getProperty(user.home): " + System.getProperty("user.home"));
      System.out.println("System             System.getProperty(java.class.path): " + System.getProperty("java.class.path"));
      System.out.println("System          System.getProperty(java.class.version): " + System.getProperty("java.class.version"));
      System.out.println("System                   System.getProperty(java.home): " + System.getProperty("java.home"));
      System.out.println("System                System.getProperty(java.vm.name): " + System.getProperty("java.vm.name"));
      System.out.println("System              System.getProperty(java.vm.vendor): " + System.getProperty("java.vm.vendor"));
      System.out.println("System                 System.getProperty(java.vendor): " + System.getProperty("java.vendor"));
      System.out.println("System             System.getProperty(java.vendor.url): " + System.getProperty("java.vendor.url"));
      System.out.println("System                  System.setProperty(os.name,XP): " + System.setProperty("os.name","Windows XP"));
      System.out.println("System                     System.getProperty(os.name): " + System.getProperty("os.name"));
    }

    Thanks for reply to all of you.
    See the first line , giving an Integer value 32 for "sun.arch.data.model". Similarly I expect to get an Integer value for the rest of the properties that can easily be
    checked through
    System.getProperty(property name) ;
    class GetInteger {
    public static void main(String args[]) {
      System.out.println("Integer static Integer getInteger(sun.arch.data.model): " + Integer.getInteger("sun.arch.data.model"));
      System.out.println("Integer             static Integer getInteger(os.arch): " + Integer.getInteger("os.arch"));
      System.out.println("System                     System.getProperty(os.arch): " + System.getProperty("os.arch"));
      System.out.println("Integer             static Integer getInteger(os.name): " + Integer.getInteger("os.name"));
      System.out.println("System                     System.getProperty(os.name): " + System.getProperty("os.name"));
      System.out.println("Integer          static Integer getInteger(os.version): " + Integer.getInteger("os.version"));
      System.out.println("System                  System.getProperty(os.version): " + System.getProperty("os.version"));
      System.out.println("Integer           static Integer getInteger(java.home): " + Integer.getInteger("java.home")); 
      System.out.println("System                   System.getProperty(java.home): " + System.getProperty("java.home"));
    }

  • JCombobox with JMenuBar (as drop down menu)

    Hello, i'm trying to make a new component (as generic as possible) to display a tree structure in a combo-like style.
    So i finally choose a JTextfield to display the current item + a JMenuBar with Menu and MenuItem generated from a TreeModel (i'm not sure this is the better choice to make, but tha's not my present problem).
    2 questions :
    1) am I reinventing the wheel ???
    2) i've got a problem of pack when displaying the compent and i don't find where.
    Thanks. Cyril.
    So, the code... two main classes : TreeComboBox + ArrowMenu
    the TreeComboBox :
    package fr.emanation.util.gui.treeComboBox;
    import javax.swing.*;
    import javax.swing.tree.TreeModel;
    import java.awt.*;
    import java.awt.event.FocusListener;
    public class TreeComboBox<TNode> extends JPanel
      private TNode theSelectedNode;
      private ArrowMenuBar theMenuBar;
      private JTextField theTextField;
      private int theCompactWidth;
      public TreeComboBox(TreeModel aTreeModel)
        new BorderLayout(0, 0);
        theTextField = new JTextField();
        theTextField.setEditable(true);
        theTextField.setBackground(Color.white);
        setFocusable(false);
        add(theTextField, BorderLayout.CENTER);
        MyArrowMenuInvoker anInvoker = new MyArrowMenuInvoker();
        theMenuBar = new ArrowMenuBar<TNode>(anInvoker, aTreeModel);
        JPanel menuBarPanel = new JPanel(new BorderLayout(0, 0));
        menuBarPanel.add(theMenuBar, BorderLayout.CENTER);
        add(menuBarPanel, BorderLayout.EAST);
      public TNode getNode()
        return (TNode) theSelectedNode;
      public void setSelectedNode(TNode aNode)
        theSelectedNode = aNode;
        theTextField.setText(aNode.toString());
      public TreeModel getModel()
        return theMenuBar.getModel();
      public JComponent[] getFocusableComponents()
        return new JComponent[]{theTextField, theMenuBar};
      //-- JComponent overriden methods
      public Dimension getMinimumSize()
        final Dimension minSize = super.getMinimumSize();
        minSize.width = theCompactWidth;
        return minSize;
      public void setCompactWidth(final int aCompactWidth)
        theCompactWidth = aCompactWidth;
      public void setPreferredSize(Dimension aSize)
        super.setPreferredSize(aSize);
        if (theTextField != null)
          theTextField.setPreferredSize(aSize);
      public void setForeground(Color fg)
        super.setForeground(fg);
        if (theMenuBar != null)
          for (int index = 0; index < theMenuBar.getComponentCount(); index++)
            theMenuBar.getComponents()[index].setForeground(fg);
        if (theTextField != null)
          theTextField.setForeground(fg);
      public void setBackground(Color bg)
        super.setBackground(bg);
        if (theMenuBar != null)
          for (int index = 0; index < theMenuBar.getComponentCount(); index++)
            theMenuBar.getComponents()[index].setBackground(bg);
        if (theTextField != null)
          theTextField.setBackground(bg);
      public void setFont(Font aFont)
        super.setFont(aFont);
        if (theMenuBar != null)
          theMenuBar.setFont(aFont);
        if (theTextField != null)
          theTextField.setFont(aFont);
      public void setToolTipText(String aToolTip)
        super.setToolTipText(aToolTip);
        if (theTextField != null)
          theTextField.setToolTipText(aToolTip);
      public void setEnabled(final boolean bEnabled)
        super.setEnabled(bEnabled);
        if (theTextField != null) return;
          theTextField.setEnabled(bEnabled);
          if (bEnabled)
            theTextField.setBackground(Color.WHITE);
          else
            JLabel tmpLabel = new JLabel();
            tmpLabel.setEnabled(false);
            theTextField.setBackground(tmpLabel.getBackground());
        if (theMenuBar != null)
          theMenuBar.setEnabled(bEnabled);
      public synchronized void addFocusListener(FocusListener l)
        super.addFocusListener(l);
        if (theMenuBar != null)
          theMenuBar.addFocusListener(l);
        if (theTextField != null)
          theTextField.addFocusListener(l);
      public synchronized void removeFocusListener(FocusListener l)
        super.removeFocusListener(l);
        if (theMenuBar != null)
          theMenuBar.removeFocusListener(l);
        if (theTextField != null)
          theTextField.removeFocusListener(l);
      public boolean isFocusOwner()
        if (theMenuBar == null || theTextField == null) return super.isFocusOwner();
        boolean bM = (theMenuBar == null) && theMenuBar.isFocusOwner();
        boolean bT = (theTextField == null) && theTextField.isFocusOwner();
        return (bM || bT);
      //-- inner classes
      private class MyArrowMenuInvoker implements IArrowMenuInvoker<TNode>
        public Component getComponent()
          return theTextField;
        public void setNode(TNode aNode)
          setSelectedNode(aNode);
    }the ArrowMenuBar :
    package fr.emanation.util.gui.treeComboBox;
    import javax.swing.*;
    import javax.swing.border.EtchedBorder;
    import javax.swing.plaf.UIResource;
    import javax.swing.tree.TreeModel;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class ArrowMenuBar<TNode> extends JMenuBar
      private NodeMenu theMenu;
      private TreeModel theModel;
      private IArrowMenuInvoker<TNode> theInvoker;
      public ArrowMenuBar(IArrowMenuInvoker<TNode> anInvoker, TreeModel aModel)
        super();
        theModel = aModel;
        theInvoker = anInvoker;
        TNode root = (TNode) theModel.getRoot();
        if (!theModel.isLeaf(root))
          theMenu = new ArrowMenu(root);
          theMenu.setBackground(new JPanel().getBackground());
        MenuItemListener listener = new MenuItemListener();
        setListener(theMenu, listener);
        add(theMenu);
      private void setListener(JMenuItem anItem, ActionListener aListener)
        if (anItem instanceof JMenu)
          JMenu menu = (JMenu) anItem;
          int n = menu.getItemCount();
          for (int index = 0; index < n; index++)
            setListener(menu.getItem(index), aListener);
        else if (anItem != null)
          // null means separator
          anItem.addActionListener(aListener);
      public TreeModel getModel()
        return theModel;
      public Action getLaunchArrowMenuBarAction()
        return new LaunchArrowMenuBarAction();
      //-- overrides JComponent
      public Dimension getPreferredSize()
        return theMenu.getPreferredSize();
      private Dimension getItemSize(JMenu aMenu)
        Dimension dimension = new Dimension(0, 0);
        int n = aMenu.getItemCount();
        for (int index = 0; index < n; index++)
          Dimension itemD;
          JMenuItem item = aMenu.getItem(index);
          if (item instanceof JMenu)
            itemD = getItemSize((JMenu) item);
          else if (item != null)
            itemD = item.getPreferredSize();
          else
            itemD = new Dimension(0, 0); // separator
          dimension.width = Math.max(dimension.width, itemD.width);
          dimension.height = Math.max(dimension.height, itemD.height);
        return dimension;
      //--- inner classes
      private class LaunchArrowMenuBarAction extends AbstractAction
        public LaunchArrowMenuBarAction()
          super("...");
        public void actionPerformed(ActionEvent e)
          if (e.getActionCommand() == "Launch")
            System.out.println("Launch");
      private class MenuItemListener implements ActionListener
        public void actionPerformed(ActionEvent anEvent)
          NodeMenuItem item = (NodeMenuItem) anEvent.getSource();
          theInvoker.setNode(item.getNode());
          theMenu.requestFocus();
      private class NodeMenu extends JMenu
        private TNode theNode;
        public NodeMenu(TNode aNode)
          this(aNode.toString(), aNode);
        public NodeMenu(String theText, TNode aNode)
          super(theText);
          theNode = aNode;
          add(new NodeMenuItem("[.]", aNode));
          for (int index = 0; index < theModel.getChildCount(aNode); index++)
            TNode childNode = (TNode) theModel.getChild(aNode, index);
            if (theModel.isLeaf(childNode))
              add(new NodeMenuItem(childNode));
            else
              add(new NodeMenu(childNode));
        public void setNode(TNode aNode)
          theNode = aNode;
        public TNode getNode()
          return theNode;
      private class NodeMenuItem extends JMenuItem
        private TNode theNode;
        public NodeMenuItem(TNode aNode)
          super(aNode.toString());
          theNode = aNode;
        public NodeMenuItem(String aText, TNode aNode)
          super(aText);
          theNode = aNode;
        public TNode getNode()
          return theNode;
      private class ArrowMenu extends NodeMenu
    //    private ArrowIcon theIconRenderer;
        private Color shadow = UIManager.getColor("controlShadow");
        private Color darkShadow = UIManager.getColor("controlDkShadow");
        private Color highlight = UIManager.getColor("controlLtHighlight");
        public ArrowMenu(TNode aNode)
          super("", aNode);
    //      theIconRenderer = new ArrowIcon(SwingConstants.SOUTH, true);
          setBorder(new EtchedBorder());
    //      setIcon(new BlankIcon(null, 11));
          setHorizontalTextPosition(JButton.LEFT);
          setFocusPainted(true);
        public void paint(Graphics g)
          Color origColor;
          boolean isEnabled;
          int w, h, size;
          w = getSize().width;
          h = getSize().height;
          origColor = g.getColor();
          isEnabled = isEnabled();
          g.setColor(getBackground());
          g.fillRect(1, 1, w - 2, h - 2);
          /// Draw the proper Border
          if (getBorder() != null && !(getBorder() instanceof UIResource))
            paintBorder(g);
          else
            // Using the background color set above
            g.drawLine(0, 0, 0, h - 1);
            g.drawLine(1, 0, w - 2, 0);
            g.setColor(highlight);  // inner 3D border
            g.drawLine(1, 1, 1, h - 3);
            g.drawLine(2, 1, w - 3, 1);
            g.setColor(shadow);     // inner 3D border
            g.drawLine(1, h - 2, w - 2, h - 2);
            g.drawLine(w - 2, 1, w - 2, h - 3);
            g.setColor(darkShadow);   // black drop shadow  __|
            g.drawLine(0, h - 1, w - 1, h - 1);
            g.drawLine(w - 1, h - 1, w - 1, 0);
          // If there's no room to draw arrow, bail
          if (h < 5 || w < 5)
            g.setColor(origColor);
            return;
          // Draw the arrow
          size = Math.min((h - 4) / 3, (w - 4) / 3);
          size = Math.max(size, 2);
          paintTriangle(g, (w - size) / 2, (h - size) / 2,
                  size, SwingConstants.SOUTH, isEnabled);
          // Reset the Graphics back to it's original settings
          g.setColor(origColor);
        public Dimension getPreferredSize()
          return new Dimension(16, 16);
        public Dimension getMinimumSize()
          return new Dimension(5, 5);
        public Dimension getMaximumSize()
          return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
        public void paintTriangle(Graphics g, int x, int y, int size,
                      int direction, boolean isEnabled)
          Color oldColor = g.getColor();
          int mid, i, j;
          j = 0;
          size = Math.max(size, 2);
          mid = (size / 2) - 1;
          g.translate(x, y);
          if (isEnabled)
            g.setColor(darkShadow);
          else
            g.setColor(shadow);
          switch (direction)
            case NORTH:
              for (i = 0; i < size; i++)
                g.drawLine(mid - i, i, mid + i, i);
              if (!isEnabled)
                g.setColor(highlight);
                g.drawLine(mid - i + 2, i, mid + i, i);
              break;
            case SOUTH:
              if (!isEnabled)
                g.translate(1, 1);
                g.setColor(highlight);
                for (i = size - 1; i >= 0; i--)
                  g.drawLine(mid - i, j, mid + i, j);
                  j++;
                g.translate(-1, -1);
                g.setColor(shadow);
              j = 0;
              for (i = size - 1; i >= 0; i--)
                g.drawLine(mid - i, j, mid + i, j);
                j++;
              break;
            case WEST:
              for (i = 0; i < size; i++)
                g.drawLine(i, mid - i, i, mid + i);
              if (!isEnabled)
                g.setColor(highlight);
                g.drawLine(i, mid - i + 2, i, mid + i);
              break;
            case EAST:
              if (!isEnabled)
                g.translate(1, 1);
                g.setColor(highlight);
                for (i = size - 1; i >= 0; i--)
                  g.drawLine(j, mid - i, j, mid + i);
                  j++;
                g.translate(-1, -1);
                g.setColor(shadow);
              j = 0;
              for (i = size - 1; i >= 0; i--)
                g.drawLine(j, mid - i, j, mid + i);
                j++;
              break;
          g.translate(-x, -y);
          g.setColor(oldColor);
    }

    Darkness and blindness are away !
    First line of the constructor :
    public TreeComboBox(TreeModel aTreeModel)
        new BorderLayout(0, 0);
    }I will reborn as a pumpkin !

  • '...' not appearing in obscured table cell when using custom renderer.

    Hello all -
    I am using a custom JPanel as a cell renderer in a JTable to display two icons per cell. Unfortunately, I am running into a problem that occurs when resizing a column such that the width of the column is less than the size of the cell content. Normally, when resizing a cell in this manner, it will start to cut off the text within the cell and add '...' to signify that some material is obscured. However, using my cell renderer, the text simply cuts off with no indication whatsoever there is more content that is being hidden. I have tried looking through the JComponent code to find a function to overload but I haven't had much luck. Does anyone have any suggestions?
    For a simple example, compile and run the following code and try resizing the two columns. You should be able to notice the difference.
    Thanks,
    - Alex
    import java.awt.*;
    import java.awt.image.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TwoIcons extends JFrame {
         public static void main(String[] args){
              createIcons();
              SwingUtilities.invokeLater
                   new Runnable()
                        public void run() {
                             new TwoIcons();
         public TwoIcons(){
              super("Test");
              DefaultTableModel tm = new DefaultTableModel(
                   new Object[][]{
                        {new IconPair("cross", "cross"), "just a string"},
                        {new IconPair("circle", "cross"),"just another string"},
                        {new IconPair("String", "circle"),"yet another string"}
                   }, new String[]{"Two Icons","String"}){
                   public Class getColumnClass(int columnIndex){
                        if(columnIndex==0){
                             return IconPair.class;
                        else
                             return super.getColumnClass(columnIndex);
              JTable table = new JTable(tm);
              final Color bg = table.getBackground();
              table.setDefaultRenderer(IconPair.class, new TableCellRenderer(){
                        RendererPanel renderer = new RendererPanel(bg);
                        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                             renderer.setIcons((IconPair)value);
                             return  renderer;
              JScrollPane scp = new JScrollPane(table);
              add(scp);
              setSize(400,100);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              pack();
              setVisible(true);
         class RendererPanel extends JPanel{
              JLabel icon1, icon2;
              RendererPanel(Color bg){
                   setLayout(new BoxLayout(this,BoxLayout.LINE_AXIS) );
                   icon1=new JLabel();
                   icon2=new JLabel();
                   add(icon1);
                   add(icon2);
                   setBackground(bg);
              public void setIcons(IconPair value) {
                   icon1.setIcon(value.i1);
                   icon1.setToolTipText("Icon 1");
                   icon2.setIcon(value.i2);
                   icon2.setToolTipText("Icon 2");
                   //uncomment next 2 lines if you want text as well
                   icon1.setText(value.s1);
                   icon2.setText(value.s2);
         class IconPair {
              public Icon i1,i2;
              public String s1,s2;
              IconPair(String s1, String s2){
                   this.i1=(Icon)icons.get(s1);
                   this.i2=(Icon)icons.get(s2);
                   this.s1=s1;
                   this.s2=s2;
         static Map icons = new HashMap();
         public static  void createIcons(){
              Image img = new BufferedImage(10,10, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g2=(Graphics2D)(img.getGraphics());
              g2.setColor(Color.BLUE);
              g2.drawLine(0,0,10,10);
              g2.drawLine(0,10,10,0);
              icons.put("cross",new ImageIcon(img));
              img = new BufferedImage(10,10, BufferedImage.TYPE_INT_ARGB);
              g2=(Graphics2D)(img.getGraphics());
              g2.setColor(Color.ORANGE);
              g2.drawOval(1,1,8,8);
              icons.put("circle",new ImageIcon(img));
    }

    Things aren't resizable in your layout for the custom renderer. Here's your code working as you want (I think)
    import java.awt.*;
    import java.awt.image.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TwoIcons extends JFrame {
         public static void main(String[] args){
              createIcons();
              SwingUtilities.invokeLater
                   new Runnable()
                        public void run() {
                             new TwoIcons();
         public TwoIcons(){
              super("Test");
              DefaultTableModel tm = new DefaultTableModel(
                   new Object[][]{
                        {new IconPair("cross", "cross"), "just a string"},
                        {new IconPair("circle", "cross"),"just another string"},
                        {new IconPair("String", "circle"),"yet another string"}
                   }, new String[]{"Two Icons","String"}){
                   public Class getColumnClass(int columnIndex){
                        if(columnIndex==0){
                             return IconPair.class;
                        else
                             return super.getColumnClass(columnIndex);
              JTable table = new JTable(tm);
              final Color bg = table.getBackground();
              table.setDefaultRenderer(IconPair.class, new TableCellRenderer(){
                        RendererPanel renderer = new RendererPanel(bg);
                        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                             renderer.setIcons((IconPair)value);
                             return  renderer;
              JScrollPane scp = new JScrollPane(table);
              getContentPane().add(scp);
              setSize(400,100);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              pack();
              setVisible(true);
         class RendererPanel extends JPanel{
              JLabel icon1, icon2;
              RendererPanel(Color bg){
                   setLayout(new BoxLayout(this,BoxLayout.LINE_AXIS) );
                   icon1=new JLabel();
                   icon2=new JLabel();
                   add(icon1);
                   add(icon2);
                   icon1.setMinimumSize(new Dimension(0, 0));
                   icon2.setMinimumSize(new Dimension(0, 0));
                   icon1.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
                   icon2.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
                   setBackground(bg);
              public void setIcons(IconPair value) {
                   icon1.setIcon(value.i1);
                   icon1.setToolTipText("Icon 1");
                   icon2.setIcon(value.i2);
                   icon2.setToolTipText("Icon 2");
                   //uncomment next 2 lines if you want text as well
                   icon1.setText(value.s1);
                   icon2.setText(value.s2);
         class IconPair {
              public Icon i1,i2;
              public String s1,s2;
              IconPair(String s1, String s2){
                   this.i1=(Icon)icons.get(s1);
                   this.i2=(Icon)icons.get(s2);
                   this.s1=s1;
                   this.s2=s2;
         static Map icons = new HashMap();
         public static  void createIcons(){
              Image img = new BufferedImage(10,10, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g2=(Graphics2D)(img.getGraphics());
              g2.setColor(Color.BLUE);
              g2.drawLine(0,0,10,10);
              g2.drawLine(0,10,10,0);
              icons.put("cross",new ImageIcon(img));
              img = new BufferedImage(10,10, BufferedImage.TYPE_INT_ARGB);
              g2=(Graphics2D)(img.getGraphics());
              g2.setColor(Color.ORANGE);
              g2.drawOval(1,1,8,8);
              icons.put("circle",new ImageIcon(img));
    }Note that the ... is a function of the JLabel when it is too small to render its text.

  • Its seems impossible to center a fixed size image on a container

    Hi,
    I have a fixed sized JPanel that I want to add to the center of a container. I would like my JPanel's center to be fixed to the center of the container.
    I have tried to use GridBagLayout with a GridbagConstraint like follows:
    GridBagLayout gridbag = new GridBagLayout();
    getContentPane().setLayout(gridbag);
    GridBagConstraints c = new GridBagConstraints();
    c.fill = c.CENTER;
    SubPanel subPanel = new SubPanel();
    gridbag.setConstraints(subPanel, c);
    getContentPane().add(subPanel);
    setSize(400, 500);
    setVisible(true);
    But this results in the upper left corner of my JPanel being put in the center of the container. Does anyone know how to get the center of my JPanel being placed in the center?
    The following two suggestions does not work:
    1) This solution put my panel two the right of the center:
    this.setLayout( new Flowlayout( Flowlayout.CENTER ) );
    this.add( subPanel );
    2) This does only work in the special case that the width of my panel is a third of the width of the container:
    Use GridLayout and set the grids, when you add your panel it Should size the cells equal to your largest component which would be the JPanel, then just add blank JLabels to the other cells and add your subpanel to the center cell.

    this is some sample code. It has not been compiled like this, but there should only be minor problems. if it does not work, just post a message...
    ok, here we go:
    import javax.swing.*;
    import java.awt.*;
    public class CenterLayout implements LayoutManager2 {
    // make sure that only one child is added to the container
    public void addLayoutComponent(Component comp, Object constraints) {
    if( comp.getParent().getComponentCount() > 1 )throw new RuntimeException("only one child allowed for this layout");
    // as big as you want...
    public Dimension maximumLayoutSize(Container target) {
    return new Dimension( Integer.MAX_VALUE, Integer.MAX_VALUE);
    public float getLayoutAlignmentX(Container target) {
    return .5f;
    public float getLayoutAlignmentY(Container target) {
    return .5f;
    public void invalidateLayout(Container target) {
    public void addLayoutComponent(String name, Component comp) {
    addLayoutComponent(comp, name);
    public void removeLayoutComponent(Component comp) {
    // this assumes that the preferred size is the preferred size of the single child plus insets...
    public Dimension preferredLayoutSize(Container parent) {
    Insets insets = parent.getInsets();
    int w = insets.left + insets.right;
    int h = insets.top + insets.bottom;
    if (parent.getComponentCount() > 0 ) {
    Dimension childSize = parent.getComponent(0).getPreferredSize();
    return new Dimension(childSize.width + w, childSize.height + h );
    } else {
    return new Dimension(w,h);
    // this assumes that the minimum size is only the minimum size of the single child. if you want insets
    // considered for minimum size, add them here
    public Dimension minimumLayoutSize(Container parent) {
    if (parent.getComponentCount() > 0 ) {
    return parent.getComponent(0).getMinimumSize();
    } else {
    return new Dimension(0,0);
    // this is the important stuff, calculating childs
    // position. It always sets the child to its
    // preferred size and centers it.
    // there may be better strategies handling the case
    // that the containers dimension are smaller than its
    // childs dimensions. you may peek, if the child may be
    // scaled to fit in considering the minimum size of the child.
    // once started, layoutmanager can be improved with
    // more sophisticated algorithms ever on, go and paly
    // around with it :-)
    public void layoutContainer(Container parent) {
    if( parent.getComponentCount() > 0 ){
    Component child = parent.getComponent(0);
    Insets insets = parent.getInsets();
    Dimension size = parent.getSize();
    size.width = size.width - insets.left - insets.right;
    size.height = size.height - insets.top - insets.bottom;
    // put in child scaling here, if needed
    child.setSize(child.getPreferredSize());
    int x = insets.left + (int) ( (size.width - child.getWidth() )/2);
    int y = insets.top + (int) ( (size.height - child.getHeight() )/2);
    child.setLocation(x,y);
    public static void main(String[] args ) {
    JFrame f = new JFrame();
    f.getContentPane().setLayout(new CenterLayout() );
    f.getContentPane().add( new JButton("hello") );
    f.setSize( 200, 200 );
    f.setVisible(true);
    }

  • How to detect if text has been clipped in a JRadioButton ?

    Hi,
    Is there any way to test if the text in a JRadioButton (same holds e.g. for a JCheckBox) has been clipped and contains ellipses ... at the end. For a JLabel, knowing the FontMetrics one can use SwingUtilities.computeStringWidth(). I found the method SwingUtilities.layoutCompoundLabel() but it needs to know also the icon, which is not available by getIcon(), if not explicitly set with setIcon() in the JRadioButton.
    So, is there any way to get info about the default icon used by the current UI in a JRadioButton or JCheckBox ?
    Or better, is there any convenience method I've overseen which may lead to the goal.
    Background info:
    The text for the JRadioButtons (or JCheckBoxes) are read from a database and Tooltips should only be generated, when clipping occured, as a popup with the same text as in the base component doesn't provide so much new information.
    Thanks for your help
    ThomasGrewe

    Hi,
    your problem could be have a solution when you use a right layout manager. You have to use a layout manager wich use the preferredSize from the objects.
    I tryed this code and work, with a BoxLayout. I dont understand yor Problem, maybe you have to write your code here (if it is not too long ;) )
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.Border;
    public class Test extends JFrame{
      private String[] text;
      private int index = 0;
      private MyRadioButton rb;
      public Test(){
        text = new String[]{"Loooooooooooooooong", "mittttel", "Small", "1"};
        JButton changeText = new JButton("Change Text");
        rb = new MyRadioButton("Radio Button");
        changeText.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e){
            if(index >= text.length)
              index = 0;
            rb.setText(text[index++]);
            rb.invalidate();
        getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
        getContentPane().add(changeText);
        getContentPane().add(rb);
      public static void main(String args[]){
        Test f = new Test();
        f.setSize(100,100);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    class MyRadioButton extends JRadioButton{
      public MyRadioButton(String text) {
        super(text);
      // your business methods...
      // set preferred, min, max size
      public Dimension getPreferredSize(){
        // let the UI compute the preferredSize
        return getUI().getPreferredSize(this);
      public Dimension getMinimumSize(){
        return getPreferredSize();
      public Dimension getMaximumSize(){
        return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
    }

  • Setting exact    jtable column width

    I need to set each column width in table 200. Columns are added dynamically. And after one column added the previous one width is become small(about 75).
    There is test code. Please, help, here is last place I can find the answer.
    package visual.jtable;
    import javax.swing.*;
    import javax.swing.filechooser.FileSystemView;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumnModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import java.awt.*;
    import java.io.File;
    import java.util.Arrays;
    import java.util.List;
    import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
    public class TestFrame extends JFrame
        public JTable table;
        public TestFrame()
            super("Test frame");
            createGUI();
        public void createGUI()
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new JPanel();
            panel.setLayout(new BorderLayout());
            table = new JTable();
            table.setBounds(400, 400, 700, 300);
            JScrollPane pane = new JScrollPane(table);
            System.out.println(pane.getLayout().getClass().toString());
            pane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
            pane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            panel.add(pane, BorderLayout.CENTER);
            getContentPane().add(panel);
        static int lastCol = -1;
        static int lastRow = -1;
        static int visibleRows = 13;
        public static void addFile(JTable table, File file)
            DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
            if (lastRow == visibleRows - 1 || lastCol == -1)
                TableColumnModel cm = table.getColumnModel();
                table.getTableHeader().setResizingAllowed(false);
                table.setAutoscrolls(true);
                table.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
                tableModel.addColumn(String.valueOf(lastCol + 1), new File[visibleRows]);
                int index = tableModel.findColumn(String.valueOf(lastCol + 1));
                cm.getColumn(index).setMinWidth(200);
                cm.getColumn(index).setMaxWidth(200);
                cm.getColumn(index).setWidth(200);
                cm.getColumn(index).setPreferredWidth(200);
                cm.getColumn(index).setResizable(false);
                System.out.println("width = " + cm.getColumn(index).getWidth());
                System.out.println(table.getAutoResizeMode());
                lastCol++;
                lastRow = -1;
            lastRow++;
            tableModel.setValueAt(file, lastRow, lastCol);
        public static void main(String[] args) throws Exception
            JFrame.setDefaultLookAndFeelDecorated(true);
            try
                UIManager.setLookAndFeel(new WindowsLookAndFeel());
            catch (Exception e)
            TestFrame frame = new TestFrame();
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            List<File> f = Arrays.asList(FileSystemView.getFileSystemView().getFiles(new File("C:\\Documents and Settings\\Admin\\&#1056;&#1072;&#1073;&#1086;&#1095;&#1080;&#1081; &#1089;&#1090;&#1086;&#1083;"), false));
            for (File file : f)
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
                addFile(frame.table, file);
                Thread.sleep(100);
    class ListViewTableCellRenderer2 extends DefaultTableCellRenderer
       // public ListViewTableCellRenderer(){}
        // implements javax.swing.table.TableCellRenderer
        public Component getTableCellRendererComponent(
                JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
            Component component = super.getTableCellRendererComponent(
                    table, value, isSelected, hasFocus, row, column);
            File file = (File) value;
            JLabel label = (JLabel) component;
            label.setMinimumSize(new Dimension(200, label.getHeight()));
            label.setMaximumSize(new Dimension(200, label.getHeight()));
            label.setPreferredSize(new Dimension(200, label.getHeight()));
            label.setSize(200, label.getHeight());
            label.setMinimumSize(new Dimension(200, label.getHeight()));
            label.setText("<table width=\"200\">" +
                    "  <tr>" +
                    "    <td>Month</td>" +
                    "  </tr>" +
                    "</table>");
            if(file == null)
                label.setIcon(null);
                return label;
            //label.setIcon(ViewManager.getCachedIcon(file));
              label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(file));
            if(file.isHidden())
               label.setText("<html><font color = \"red\">" + file.getName() + "</font></html>");
            label.setText(file.getName());
            label.setText("<table width=\"200\">" +
                    "  <tr>" +
                    "    <td>Month</th>" +
                    "  </tr>" +
                    "</table>");
            return label;
    }

    And after one column added the previous one width is become small(about 75).The model.addColumn() method causes a fireTableStructureChanged event to be generated which causes the TableColumns to be recreated and therefore they default back to their default sizes.
    So you need to prevent the columns from being recreated. You do this by adding:
    JTable table = new JTable(....);
    table.setAutoCreateColumnsFromModel(false);But now you are responsible for adding table columns to the table manually. So your code would be something like;
    int index = model.getColumnCount();
    model.addColumn(...);
    TableColumn tc = new TableColumn(index);
    tc.setHeaderValue("" + index);
    table.addColumn( tc );

  • Any layout suggestions for this?

    How can I place a JCheckBox and JButton components on the area beside the TabbedPane tabs (Top right corner position)?
    Final design should be like this image
    http://www.rejimani.com/backup/tabbed.jpg
    Any suggestions?
    Reji Mani

    * Test_AbsoluteLayout.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test_AbsoluteLayout extends JFrame {
        public Test_AbsoluteLayout() {
            initComponents();
        private void initComponents() {
            checkbox = new JCheckBox();
            button = new JButton();
            tabbedpane = new JTabbedPane();
            panel1 = new JPanel();
            panel2 = new JPanel();
            getContentPane().setLayout(new AbsoluteLayout());
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            checkbox.setPreferredSize(new Dimension(83, 21));
            checkbox.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    checkboxActionPerformed(evt);
            getContentPane().add(checkbox, new AbsoluteConstraints(350, 0, 20, -1));
            button.setText("OK");
            button.setMargin(new Insets(0, 0, 0, 0));
            button.setPreferredSize(new Dimension(71, 21));
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    buttonActionPerformed(evt);
            getContentPane().add(button, new AbsoluteConstraints(370, 0, 30, -1));
            tabbedpane.setPreferredSize(new Dimension(400, 300));
            tabbedpane.addTab("tab1", panel1);
            tabbedpane.addTab("tab2", panel2);
            getContentPane().add(tabbedpane, new AbsoluteConstraints(0, 0, -1, -1));
            pack();
        private void checkboxActionPerformed(ActionEvent evt) {
            System.out.println("check");
        private void buttonActionPerformed(ActionEvent evt) {
            System.out.println("ok");
        public static void main(String args[]) {
            new Test_AbsoluteLayout().setVisible(true);
        private JButton button;
        private JCheckBox checkbox;
        private JPanel panel1;
        private JPanel panel2;
        private JTabbedPane tabbedpane;
    class AbsoluteConstraints implements java.io.Serializable {
        static final long serialVersionUID = 5261460716622152494L;
        public int x;
        public int y;
        public int width = -1;
        public int height = -1;
        public AbsoluteConstraints(Point pos) {
            this(pos.x, pos.y);
        public AbsoluteConstraints(int x, int y) {
            this.x = x;
            this.y = y;
        public AbsoluteConstraints(Point pos, Dimension size) {
            this.x = pos.x;
            this.y = pos.y;
            if (size != null) {
                this.width = size.width;
                this.height = size.height;
        public AbsoluteConstraints(int x, int y, int width, int height) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        public int getX() {
            return x;
        public int getY() {
            return y;
        public int getWidth() {
            return width;
        public int getHeight() {
            return height;
        public String toString() {
            return super.toString() +" [x="+x+", y="+y+", width="+width+", height="+height+"]";
    class AbsoluteLayout implements LayoutManager2, java.io.Serializable {
        static final long serialVersionUID = -1919857869177070440L;
        public void addLayoutComponent(String name, Component comp) {
            throw new IllegalArgumentException();
        public void removeLayoutComponent(Component comp) {
            constraints.remove(comp);
        public Dimension preferredLayoutSize(Container parent) {
            int maxWidth = 0;
            int maxHeight = 0;
            for (java.util.Enumeration e = constraints.keys(); e.hasMoreElements();) {
                Component comp = (Component)e.nextElement();
                AbsoluteConstraints ac = (AbsoluteConstraints)constraints.get(comp);
                Dimension size = comp.getPreferredSize();
                int width = ac.getWidth();
                if (width == -1) width = size.width;
                int height = ac.getHeight();
                if (height == -1) height = size.height;
                if (ac.x + width > maxWidth)
                    maxWidth = ac.x + width;
                if (ac.y + height > maxHeight)
                    maxHeight = ac.y + height;
            return new Dimension(maxWidth, maxHeight);
        public Dimension minimumLayoutSize(Container parent) {
            int maxWidth = 0;
            int maxHeight = 0;
            for (java.util.Enumeration e = constraints.keys(); e.hasMoreElements();) {
                Component comp = (Component)e.nextElement();
                AbsoluteConstraints ac = (AbsoluteConstraints)constraints.get(comp);
                Dimension size = comp.getMinimumSize();
                int width = ac.getWidth();
                if (width == -1) width = size.width;
                int height = ac.getHeight();
                if (height == -1) height = size.height;
                if (ac.x + width > maxWidth)
                    maxWidth = ac.x + width;
                if (ac.y + height > maxHeight)
                    maxHeight = ac.y + height;
            return new Dimension(maxWidth, maxHeight);
        public void layoutContainer(Container parent) {
            for (java.util.Enumeration e = constraints.keys(); e.hasMoreElements();) {
                Component comp = (Component)e.nextElement();
                AbsoluteConstraints ac = (AbsoluteConstraints)constraints.get(comp);
                Dimension size = comp.getPreferredSize();
                int width = ac.getWidth();
                if (width == -1) width = size.width;
                int height = ac.getHeight();
                if (height == -1) height = size.height;
                comp.setBounds(ac.x, ac.y, width, height);
        public void addLayoutComponent(Component comp, Object constr) {
            if (!(constr instanceof AbsoluteConstraints))
                throw new IllegalArgumentException();
            constraints.put(comp, constr);
        public Dimension maximumLayoutSize(Container target) {
            return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
        public float getLayoutAlignmentX(Container target) {
            return 0;
        public float getLayoutAlignmentY(Container target) {
            return 0;
        public void invalidateLayout(Container target) {
        protected java.util.Hashtable constraints = new java.util.Hashtable();
    }

  • Numbers on JButtons and set JButtons to Opaque

    Hi everyone:
    please check for me why numbers(like 1 to 35) don't appears on JButtons, and why I setOpaque(true) to JButtons, it doesn't work. Thanks
    // why I can not see the numbers (1 to 35) in JButtons ????????????
    // and how can I operate setOpaque(true) to JButtons.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.GridLayout;
    public class DrawCalendar extends JPanel{
         private static DrawCalendar dC;
         private static JButton jB1,jB2,jB3;
         private static Dimension dMS;
         private static GridLayout gL;
         private static Container c;
         // why I can not see the numbers (1 to 35) in JButtons ????????????
         public DrawCalendar(){
              JButton j= new JButton("1");
         gL=new GridLayout(5,7,4,4);
              setLayout(gL);
    add(j);
    add(new JButton("2"));
    add(new JButton("3"));
    add(new JButton("4"));
    add(new JButton("5"));
    add(new JButton("6"));
    add(new JButton("7"));
    add(new JButton("8"));
    add(new JButton("9"));
    add(new JButton("10"));
    add(new JButton("11"));
    add(new JButton("12"));
    add(new JButton("12"));
    add(new JButton("14"));
    add(new JButton("15"));
    add(new JButton("16"));
    add(new JButton("17"));
    add(new JButton("18"));
    add(new JButton("19"));
    add(new JButton("20"));
    add(new JButton("21"));
    add(new JButton("22"));
    add(new JButton("23"));
    add(new JButton("24"));
    add(new JButton("25"));
    add(new JButton("26"));
    add(new JButton("27"));
    add(new JButton("28"));
    add(new JButton("29"));
    add(new JButton("30"));
    add(new JButton("31"));
    add(new JButton("32"));
    add(new JButton("33"));
    add(new JButton("34"));
    add(new JButton("35"));
    import java.awt.*;
    import java.awt.Color;
    import javax.swing.*;
    import javax.swing.JButton;
    import javax.swing.JMenuBar;
    public class TestMain extends JFrame{
    private static JButton b1, b2, b3;
    private static TestMain tM;
         private static JPanel jP;
    private static Container c;
    private static DrawCalendar dC;
         public static void main(String[] args){
         tM = new TestMain();
         addItems();
         tM.setVisible(true);
         public TestMain(){
         super(" Test");
         dC=new DrawCalendar();
         setSize(600,600);
    //set up layoutManager
    c=getContentPane();
    c.setLayout ( new GraphPaperLayout(new Dimension (8,20)));
    //set up three Button and one JPanel
    b1=new JButton("1");
    b1.setOpaque(true);
    b2=new JButton("2");
    b2.setOpaque(true);
    b3=new JButton("3");
    b3.setOpaque(true);
    //add the munuBar, the Jpanel and three JButtons
    public static void addItems(){
         c.add(b1, new Rectangle(5,0,1,1));
         c.add(b2, new Rectangle(6,0,1,1));
    c.add(b3, new Rectangle(7,0,1,1));
         c.add(dC, new Rectangle(5,1,3,5));
    import java.awt.*;
    import java.util.Hashtable;
    import java.io.*;
    * The <code>GraphPaperLayout</code> class is a layout manager that
    * lays out a container's components in a rectangular grid, similar
    * to GridLayout. Unlike GridLayout, however, components can take
    * up multiple rows and/or columns. The layout manager acts as a
    * sheet of graph paper. When a component is added to the layout
    * manager, the location and relative size of the component are
    * simply supplied by the constraints as a Rectangle.
    * <p><code><pre>
    * import java.awt.*;
    * import java.applet.Applet;
    * public class ButtonGrid extends Applet {
    * public void init() {
    * setLayout(new GraphPaperLayout(new Dimension(5,5)));
    * // Add a 1x1 Rect at (0,0)
    * add(new Button("1"), new Rectangle(0,0,1,1));
    * // Add a 2x1 Rect at (2,0)
    * add(new Button("2"), new Rectangle(2,0,2,1));
    * // Add a 1x2 Rect at (1,1)
    * add(new Button("3"), new Rectangle(1,1,1,2));
    * // Add a 2x2 Rect at (3,2)
    * add(new Button("4"), new Rectangle(3,2,2,2));
    * // Add a 1x1 Rect at (0,4)
    * add(new Button("5"), new Rectangle(0,4,1,1));
    * // Add a 1x2 Rect at (2,3)
    * add(new Button("6"), new Rectangle(2,3,1,2));
    * </pre></code>
    * @author Michael Martak
    * Updated by Judy Bowen, September 2002 to allow serialization
    public class GraphPaperLayout implements LayoutManager2, Serializable{
    int hgap; //horizontal gap
    int vgap; //vertical gap
    Dimension gridSize; //grid size in logical units (n x m)
    Hashtable compTable; //constraints (Rectangles)
    * Creates a graph paper layout with a default of a 1 x 1 graph, with no
    * vertical or horizontal padding.
    public GraphPaperLayout() {
    this(new Dimension(1,1));
    * Creates a graph paper layout with the given grid size, with no vertical
    * or horizontal padding.
    public GraphPaperLayout(Dimension gridSize) {
    this(gridSize, 0, 0);
    * Creates a graph paper layout with the given grid size and padding.
    * @param gridSize size of the graph paper in logical units (n x m)
    * @param hgap horizontal padding
    * @param vgap vertical padding
    public GraphPaperLayout(Dimension gridSize, int hgap, int vgap) {
    if ((gridSize.width <= 0) || (gridSize.height <= 0)) {
    throw new IllegalArgumentException(
    "dimensions must be greater than zero");
    this.gridSize = new Dimension(gridSize);
    this.hgap = hgap;
    this.vgap = vgap;
    compTable = new Hashtable();
    * @return the size of the graph paper in logical units (n x m)
    public Dimension getGridSize() {
    return new Dimension( gridSize );
    * Set the size of the graph paper in logical units (n x m)
    public void setGridSize( Dimension d ) {
    setGridSize( d.width, d.height );
    * Set the size of the graph paper in logical units (n x m)
    public void setGridSize( int width, int height ) {
    gridSize = new Dimension( width, height );
    public void setConstraints(Component comp, Rectangle constraints) {
    compTable.put(comp, new Rectangle(constraints));
    * Adds the specified component with the specified name to
    * the layout. This does nothing in GraphPaperLayout, since constraints
    * are required.
    public void addLayoutComponent(String name, Component comp) {
    * Removes the specified component from the layout.
    * @param comp the component to be removed
    public void removeLayoutComponent(Component comp) {
    compTable.remove(comp);
    * Calculates the preferred size dimensions for the specified
    * panel given the components in the specified parent container.
    * @param parent the component to be laid out
    * @see #minimumLayoutSize
    public Dimension preferredLayoutSize(Container parent) {
    return getLayoutSize(parent, true);
    * Calculates the minimum size dimensions for the specified
    * panel given the components in the specified parent container.
    * @param parent the component to be laid out
    * @see #preferredLayoutSize
    public Dimension minimumLayoutSize(Container parent) {
    return getLayoutSize(parent, false);
    * Algorithm for calculating layout size (minimum or preferred).
    * <p>
    * The width of a graph paper layout is the largest cell width
    * (calculated in <code>getLargestCellSize()</code> times the number of
    * columns, plus the horizontal padding times the number of columns
    * plus one, plus the left and right insets of the target container.
    * <p>
    * The height of a graph paper layout is the largest cell height
    * (calculated in <code>getLargestCellSize()</code> times the number of
    * rows, plus the vertical padding times the number of rows
    * plus one, plus the top and bottom insets of the target container.
    * @param parent the container in which to do the layout.
    * @param isPreferred true for calculating preferred size, false for
    * calculating minimum size.
    * @return the dimensions to lay out the subcomponents of the specified
    * container.
    * @see java.awt.GraphPaperLayout#getLargestCellSize
    protected Dimension getLayoutSize(Container parent, boolean isPreferred) {
    Dimension largestSize = getLargestCellSize(parent, isPreferred);
    Insets insets = parent.getInsets();
    largestSize.width = ( largestSize.width * gridSize.width ) +
    ( hgap * ( gridSize.width + 1 ) ) + insets.left + insets.right;
    largestSize.height = ( largestSize.height * gridSize.height ) +
    ( vgap * ( gridSize.height + 1 ) ) + insets.top + insets.bottom;
    return largestSize;
    * Algorithm for calculating the largest minimum or preferred cell size.
    * <p>
    * Largest cell size is calculated by getting the applicable size of each
    * component and keeping the maximum value, dividing the component's width
    * by the number of columns it is specified to occupy and dividing the
    * component's height by the number of rows it is specified to occupy.
    * @param parent the container in which to do the layout.
    * @param isPreferred true for calculating preferred size, false for
    * calculating minimum size.
    * @return the largest cell size required.
    protected Dimension getLargestCellSize(Container parent,
    boolean isPreferred) {
    int ncomponents = parent.getComponentCount();
    Dimension maxCellSize = new Dimension(0,0);
    for ( int i = 0; i < ncomponents; i++ ) {
    Component c = parent.getComponent(i);
    Rectangle rect = (Rectangle)compTable.get(c);
    if ( c != null && rect != null ) {
    Dimension componentSize;
    if ( isPreferred ) {
    componentSize = c.getPreferredSize();
    } else {
    componentSize = c.getMinimumSize();
    // Note: rect dimensions are already asserted to be > 0 when the
    // component is added with constraints
    maxCellSize.width = Math.max(maxCellSize.width,
    componentSize.width / rect.width);
    maxCellSize.height = Math.max(maxCellSize.height,
    componentSize.height / rect.height);
    return maxCellSize;
    * Lays out the container in the specified container.
    * @param parent the component which needs to be laid out
    public void layoutContainer(Container parent) {
    synchronized (parent.getTreeLock()) {
    Insets insets = parent.getInsets();
    int ncomponents = parent.getComponentCount();
    if (ncomponents == 0) {
    return;
    // Total parent dimensions
    Dimension size = parent.getSize();
    int totalW = size.width - (insets.left + insets.right);
    int totalH = size.height - (insets.top + insets.bottom);
    // Cell dimensions, including padding
    int totalCellW = totalW / gridSize.width;
    int totalCellH = totalH / gridSize.height;
    // Cell dimensions, without padding
    int cellW = (totalW - ( (gridSize.width + 1) * hgap) )
    / gridSize.width;
    int cellH = (totalH - ( (gridSize.height + 1) * vgap) )
    / gridSize.height;
    for ( int i = 0; i < ncomponents; i++ ) {
    Component c = parent.getComponent(i);
    Rectangle rect = (Rectangle)compTable.get(c);
    if ( rect != null ) {
    int x = insets.left + ( totalCellW * rect.x ) + hgap;
    int y = insets.top + ( totalCellH * rect.y ) + vgap;
    int w = ( cellW * rect.width ) - hgap;
    int h = ( cellH * rect.height ) - vgap;
    c.setBounds(x, y, w, h);
    // LayoutManager2 /////////////////////////////////////////////////////////
    * Adds the specified component to the layout, using the specified
    * constraint object.
    * @param comp the component to be added
    * @param constraints where/how the component is added to the layout.
    public void addLayoutComponent(Component comp, Object constraints) {
    if (constraints instanceof Rectangle) {
    Rectangle rect = (Rectangle)constraints;
    if ( rect.width <= 0 || rect.height <= 0 ) {
    throw new IllegalArgumentException(
    "cannot add to layout: rectangle must have positive width and height");
    if ( rect.x < 0 || rect.y < 0 ) {
    throw new IllegalArgumentException(
    "cannot add to layout: rectangle x and y must be >= 0");
    setConstraints(comp, rect);
    } else if (constraints != null) {
    throw new IllegalArgumentException(
    "cannot add to layout: constraint must be a Rectangle");
    * Returns the maximum size of this component.
    * @see java.awt.Component#getMinimumSize()
    * @see java.awt.Component#getPreferredSize()
    * @see LayoutManager
    public Dimension maximumLayoutSize(Container target) {
    return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
    * Returns the alignment along the x axis. This specifies how
    * the component would like to be aligned relative to other
    * components. The value should be a number between 0 and 1
    * where 0 represents alignment along the origin, 1 is aligned
    * the furthest away from the origin, 0.5 is centered, etc.
    public float getLayoutAlignmentX(Container target) {
    return 0.5f;
    * Returns the alignment along the y axis. This specifies how
    * the component would like to be aligned relative to other
    * components. The value should be a number between 0 and 1
    * where 0 represents alignment along the origin, 1 is aligned
    * the furthest away from the origin, 0.5 is centered, etc.
    public float getLayoutAlignmentY(Container target) {
    return 0.5f;
    * Invalidates the layout, indicating that if the layout manager
    * has cached information it should be discarded.
    public void invalidateLayout(Container target) {
    // Do nothing

    Hello,
    I think you have really a problem with this layout.
    Please first check the standard [url http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html]LayoutManager.
    JButtons are opaque usually and they will be shown if you use another LayoutManager:import java.awt.*;
    import javax.swing.*;
    class DrawCalendar extends JPanel
         private static DrawCalendar dC;
         private static JButton jB1, jB2, jB3;
         private static Dimension dMS;
         private static GridLayout gL;
         private static Container c;
         // why I can not see the numbers (1 to 35) in JButtons ????????????
         public DrawCalendar()
              JButton j = new JButton("1");
              gL = new GridLayout(5, 7, 4, 4);
              setLayout(gL);
              add(j);
              add(new JButton("2"));
              add(new JButton("3"));
              add(new JButton("4"));
              add(new JButton("5"));
              add(new JButton("6"));
              add(new JButton("7"));
              add(new JButton("8"));
              add(new JButton("9"));
              add(new JButton("10"));
              add(new JButton("11"));
              add(new JButton("12"));
              add(new JButton("12"));
              add(new JButton("14"));
              add(new JButton("15"));
              add(new JButton("16"));
              add(new JButton("17"));
              add(new JButton("18"));
              add(new JButton("19"));
              add(new JButton("20"));
              add(new JButton("21"));
              add(new JButton("22"));
              add(new JButton("23"));
              add(new JButton("24"));
              add(new JButton("25"));
              add(new JButton("26"));
              add(new JButton("27"));
              add(new JButton("28"));
              add(new JButton("29"));
              add(new JButton("30"));
              add(new JButton("31"));
              add(new JButton("32"));
              add(new JButton("33"));
              add(new JButton("34"));
              add(new JButton("35"));
    public class TestMain extends JFrame
         private static JButton b1, b2, b3;
         private static TestMain tM;
         private static JPanel jP;
         private static Container c;
         private static DrawCalendar dC;
         public static void main(String[] args)
              tM = new TestMain();
              addItems();
              tM.setVisible(true);
         public TestMain()
              super(" Test");
              dC = new DrawCalendar();
              setSize(600, 600);
              //set up layoutManager
              c = getContentPane();
              c.setLayout(new FlowLayout());
              //set up three Button and one JPanel
              b1 = new JButton("1");
              b1.setOpaque(true);
              b2 = new JButton("2");
              b2.setOpaque(true);
              b3 = new JButton("3");
              b3.setOpaque(true);
         //add the munuBar, the Jpanel and three JButtons
         public static void addItems()
              c.add(b1);
              c.add(b2);
              c.add(b3);
              c.add(dC);
    }regards
    Tim

  • How to Convert Integer to byte[n]!Help

    I have a Integer 314,Convert to hex is 0x13a,I want to convert to byte[2],and byte[0] equals 0x13 and byte[1] equals [0x30];I use this method convert byte[4],
    int iVal = 314;
    byte [] bVals = new byte[4];for( int i=0; i<4; i++ ) { 
    bVals<i> = (byte)(iVal & 255);
    iVal >>= 8;
    Not I want to result.Please help!

    Try:
    int iVal = 0x01FF03F0;
    byte [] bVals = new byte[4];
    for(int i=3; i>=0; i--) {
        bVals[i] = (byte)(iVal & 255);
        iVal >>= 8
    //print results
    for (int i = 0; i < 4; i++) {
       int temp = bVals[i] & 0xFF;  // avoid displaying negative numbers
       System.out.println("byte " + i + " = " +  Integer.toHexString(temp));
    }

  • Send and recieve 2 byte integer values.

    hi,
    basically i'm trying to allow my applet and servlet communicate using 2 byte signed integer values. but i haven't figured out how to store an integer value into a byte array of size 2, or unpack it once it gets there.
    here's some code/psuedocode that i've done so far.
    SERVLET:
    ByteArrayOutputStream bst = new ByteArrayOutputStream(streamsize);
    ServletOutputStream bout;
    byte[] strm = new byte[streamsize];
    byte[] dbyte = new byte[2];
    int[] testarr = new int[10];
    /* fill my testarr with values... */
    bout = response.getOutputStream();
    int l = 0;
    for (int i = 0;i<arraysize;i++){
    getDoubleByteFromInteger(dbyte,testarr)
    strm[l++] = dbyte[0];
    strm[l++] = dbyte[1];
    bst.write(strm,0,streamsize);
    bst.writeTo(bout);
    APPLET:
    /* connect to servlet and get binary stream */
    bytecount = in.read(streamb);
    byte[] db = new byte[2];
    counter = 0;
    while (cursor < bytecount){
    db[0] = streamb[cursor++];
    db[1] = streamb[cursor++];
    array[counter++] = getIntFromByte(db);
    the functions getIntFromByte and getDoubleByteFromInteger haven't been written, can anyone give me a little push? or tell me if this is something possible? thanks for any help
    Matt

    The primitive type short is a two-byte signed integer, so you really don't need to bother with byte arrays - just use DataOutputStream to write it (it has a method called writeShort) and DataInputStream to read it (with readShort()).
    But anyway, getting an int from two bytes and getting two bytes from an int is easy with the bitwise operators:
    int -> byte array
    int i = yourInt;
    byte[] b = new byte[2];
    b[1] = (byte) (i >> 8);
    b[0] = (byte) (i);
    byte array -> int (unsigned)
    int i = ((b[1] & 0xFF) <<8) + (b[0] & 0xFF);
    byte array -> short -> int (signed)
    short s = (short) ((b[1] & 0xFF) <<8) + (b[0] & 0xFF);
    int i = s;

  • Trying to understand the details of converting an int to a byte[] and back

    I found the following code to convert ints into bytes and wanted to understand it better:
    public static final byte[] intToByteArray(int value) {
    return new byte[]{
    (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff) };
    }I understand that an int requires 4 bytes and that each byte allows for a power of 8. But, sadly, I can't figure out how to directly translate the code above? Can someone recommend a site that explains the following:
    1. >>> and >>
    2. Oxff.
    3. Masks vs. casts.
    thanks so much.

    By the way, people often introduce this redundancy (as in your example above):
    (byte)(i >> 8 & 0xFF)When this suffices:
    (byte)(i >> 8)Since by [JLS 5.1.3|http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#25363] :
    A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T.Casting to a byte is merely keeping only the lower order 8 bits, and (anything & 0xFF) is simply clearing all but the lower order 8 bits. So it's redundant. Or I could just show you the more simple proof: try absolutely every value of int as an input and see if they ever differ:
       public static void main(String[] args) {
          for ( int i = Integer.MIN_VALUE;; i++ ) {
             if ( i % 100000000 == 0 ) {
                //report progress
                System.out.println("i=" + i);
             if ( (byte)(i >> 8 & 0xff) != (byte)(i >> 8) ) {
                System.out.println("ANOMOLY: " + i);
             if ( i == Integer.MAX_VALUE ) {
                break;
       }Needless to say, they don't ever differ. Where masking does matter is when you're widening (say from a byte to an int):
       public static void main(String[] args) {
          byte b = -1;
          int i = b;
          int j = b & 0xFF;
          System.out.println("i: " + i + " j: " + j);
       }That's because bytes are signed, and when you widen a signed negative integer to a wider integer, you get 1s in the higher bits, not 0s due to sign-extension. See [http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2]
    Edited by: endasil on 3-Dec-2009 4:53 PM

Maybe you are looking for

  • Upgrading from 10.8.4/Server 2.2.1 to 10.8.5/Server 2.2.2?

    I've got a couple of fairly recent vintage (2011, 2012) Mac minis at work that are currently running Mac OS X 10.8.4 with OS X Server 2.2.1. Software Update keeps trying to lure me into upgrading to 10.8.5, but I'm afraid things will break. Don't I n

  • Problems with iDVD

    HI, I wondered if anyone could help please. I have cut my first movie in iMovie, and transferred it to iDVD to burn a DVD. THe problem is when its transferred across it gets corrupted and when played on the mac (and DVD) the picture is jumping all ov

  • Removing a plant to its current company code

    Hello Gurus, I am working on this request that the old plant will be removed to its current company code and assigned it to new company code. SAP has been using for couple of years already so many data has been created and documents processed. I am a

  • Reg. Price Control V

    Hi All, I have a material which is both Procurred and Produced inhouse. I have Material Master Price control for this material as V (Moving Average). Now when i raise a production order and do a GR for this material, my stock gets updated by the pric

  • Pdf sync after restore...

    I am trying to sync my pdfs after an itunes restore. When I check "Sync" at books tab I get the message that the ipad is synced with another library and it will be erased. If I coninue will all stuff be erased or just ibooks app data (whick is empty