JScrollBar on a JComponent

Hi,
in my JFrame I have a JComponent that does my graphic output (lines and stuff).
To this JComponent i want to add 2 JScrollBars so that i can scroll the contents of the JC. I dont want to use a JScrollPane because i dont want to scroll over the JC, I only need the Adjustment Event from the Scrollbars so that i can decide which part to draw.
Any Ideas?
Thanks !

what you described is what i dont want / can't do...
My JComponent is fixed size (640x480 atm) but the graphics i want to display on that component are many times larger. I can't use the ScrollPane because i cant hold the full graphic in memory.
I need the scrollbars to get the AdjustmentEvents, with which i can decide which part to draw (and which parts to preload etc.)
its not scrolling in the original sense...i just need the events to know weather the user wants to scroll left/right etc...
hope that clears things up ^^

Similar Messages

  • Centering a JComponent inside a JScrollPane

    I've got an instance of a subclass of JComponent (DrawCanvas) inside an instance of JScrollPane (scpEasel). scpEasel is itself in an instance of JInternalFrame (ifEasel) that used a GridLayout.
    When the DrawCanvas object can fit inside the JInternalFrame, it needs to be centered inside the JScrollPane object. If the canvas is wider than the window, it must be centered vertically. If it has a greater height than the window, it must be centered horizontally. When the canvas is, both horizontally and vertically bigger than the window, no centering is needed.
    I made a subclass of ScrollPaneLayout that does just that, but when only one of the scrollbars is visible, it doesn't want to scroll (whether I click on the arrows, or drag the box, etc.).
    How do I keep the scrollbars from jamming?
    Here's the code to the instance of ScrollPaneLayout:
    EaselLayout = new ScrollPaneLayout() {
        public void layoutContainer(Container parent) {
            super.layoutContainer(parent);
            Component Canvas = parent.getComponent(0);
            JScrollBar HSB = getHorizontalScrollBar(),
                       VSB = getVerticalScrollBar();
            int scpWidth = parent.getSize().width,
                scpHeight = parent.getSize().height,
                cX = Canvas.getLocation().x,
                cY = Canvas.getLocation().y,
                cWidth = Canvas.getPreferredSize().width,
                cHeight = Canvas.getPreferredSize().height;
            if (!HSB.isVisible() && !VSB.isVisible()) {
                Canvas.setLocation((scpWidth / 2) - (cWidth / 2), (scpHeight / 2) - (cHeight / 2));
            } else if (!HSB.isVisible()) {
                Canvas.setLocation((scpWidth / 2) - (cWidth / 2), cY);
            } else if (!VSB.isVisible()) {
                Canvas.setLocation(cX, (scpHeight / 2) - (cHeight / 2));
    };Please respond ASAP. Thanx.

    Please, I beg of you...someone help!!
    Here I have created a LayoutManager that is to be used within a JViewport to solve the issue of Centering the JComponent inside a JScrollPane.
    However, it works every time except the first time.
    The code for this LayoutManager (called CenteredLayoutManager) is in the first class.
    The second and third classes provide an application I wrote to test it.
    You type an integer value representing the percentage you want to zoom and press ENTER. The DrawingPanel will zoom the image for you.
    But, as you can see, the first time the image is in the upper left hand of the frame. All the other times, it is centered, but not the first time.
    Could someone explain why it doesn't do it the first time?
    Thank you for your help.
    // standard imports
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.JTextComponent;
    * A Layout that handles centering if the view is smaller than the
    * JViewPort.
    final class CenteredViewportLayout extends ViewportLayout
       private Rectangle clientArea = new Rectangle(),
       parentArea = new Rectangle();
       private Dimension dimens = new Dimension();
        * This does the centering for the layout.
       public void layoutContainer(Container p)
          JViewport parent = (JViewport)p;
          JComponent client = (JComponent)parent.getView();
          SwingUtilities.calculateInnerArea(parent, parentArea);
          clientArea.setBounds(parentArea);
          clientArea.setSize(client.getPreferredSize());
           * If the client is smaller than the parent scrollPane, then center it
           * within the parent. Otherwise, do the normal thing.
          if (parentArea.contains(clientArea))
             Point point = new Point((clientArea.width/2) - (parentArea.width/2),
                                     (clientArea.height/2) - (parentArea.height/2));
             parent.setViewPosition(point);
             parent.setViewSize(parent.getSize(dimens));
          else
             super.layoutContainer(p);
    class DrawingPanel extends JComponent implements Scrollable
       BufferedImage origImage;
       double        theZoom;    // the zoom factor
       Dimension     unitScroll; // used for correct scrolling...
       public DrawingPanel(BufferedImage img)
          origImage = img;
          unitScroll = new Dimension();
          zoomMe(100);
        * Changes the zoom factor.
        * @param val  the percentage of the zoom.
       public void zoomMe(int val)
          if (val < 1) val = 100;
          theZoom = val / 100.0;
          Dimension d = new Dimension((int)(origImage.getWidth()   * theZoom),
                                      (int)(origImage.getHeight()  * theZoom));
          unitScroll.setSize(d.width / 10, d.height / 10); // scroll 1/10 the way.
          setPreferredSize(d);
          revalidate();
       // EXTENDS JComponent
       // Draws the zoomed image.
       public void paintComponent(Graphics g)
          super.paintComponent(g);
          if (Math.abs(theZoom - 1) > 0.01)
             Graphics2D g2 = (Graphics2D)g;
             g2.scale(theZoom, theZoom);
          g.drawImage(origImage, 0, 0, null);
       // IMPLEMENTS Scrollable
       public Dimension getPreferredScrollableViewportSize()
          return getPreferredSize();
       public int getScrollableUnitIncrement(Rectangle visibleRect,
             int orientation,
             int direction)
          return (orientation == SwingConstants.HORIZONTAL) ? unitScroll.width :
                                                              unitScroll.height;
       public int getScrollableBlockIncrement(Rectangle visibleRect,
                                              int orientation,
                                              int direction)
          return (orientation == SwingConstants.HORIZONTAL) ? visibleRect.width :
                                                              visibleRect.height;
       public boolean getScrollableTracksViewportWidth() { return false; }
       public boolean getScrollableTracksViewportHeight() { return false; }
    * Main class.
    * @author J. Logan
    * @since 1.0 (2003-11-04)
    public class IndexColorTest
       // CONSTANTS
       static final IndexColorModel BASIC_COLOR_MODEL;
       // STATIC METHODS
       public static void main(String [] args)
          JFrame f  = new JFrame("ImageTest");
          f.setSize(400, 400);
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          final BufferedImage img = createImage(100, 100);
          final DrawingPanel p = new DrawingPanel(img);
          // This is me using the new layout for the scroll pane's viewport.
          JScrollPane jsp = new JScrollPane();
          JViewport vp = jsp.getViewport();
          vp.setLayout(new CenteredViewportLayout());
          jsp.setViewportView(p);
          f.getContentPane().add(jsp);
          // This is the text field you use to change the zoomed value.
          JTextField jtf  = new JTextField("100", 3);
          jtf.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent evt)
                      JTextComponent c = (JTextComponent)evt.getSource();
                      int val = Integer.parseInt(c.getText());
                      p.zoomMe(val);
          f.getContentPane().add(jtf, BorderLayout.NORTH);
          f.setVisible(true);
        * This just creates the image to be used in the zooming.
       private static BufferedImage createImage(int width, int height)
          BufferedImage img = new BufferedImage(width, height,
                                                BufferedImage.TYPE_BYTE_INDEXED,
                                                BASIC_COLOR_MODEL);
          DataBufferByte db = (DataBufferByte)img.getRaster().getDataBuffer();
          byte [] data = db.getData();
          int val = 0;
          for (int i = 0, max = data.length; i < max; ++i)
             val = i % 100;
             if ( val < 25 ) data[i] = 60;
             else if (val < 50)  data[i] = 120;
             else if (val < 75)  data[i] = (byte)180;
             else data[i] = (byte)240;
          return img;
       // This block just creates the ColorModel to use...unimportant for
       // question.
       static
          final byte [] colors = new byte[256];
          final int start = 20, end = 256;
          final double ratio = ((end) - start) / (double)(colors.length - 1);
          double val = start;
          for (int i = 1, max = colors.length; i < max; ++i)
             colors[i] = (byte)(val += ratio);
          BASIC_COLOR_MODEL = new IndexColorModel(8, colors.length,
                                                  colors, colors, colors);
    }Can someone please tell me why it does not work the first time.
    Thanks for your help.

  • How do I change the color of a JSCrollBar

    Hi all,
    How do I change the color of a JScrollBar. I was able to change the color of the background, but not the scrollbar itself.
    Can anyone help?
    Thanks,
    R.

    Hi,
    Thanks for all your help. I actually found the sun bug report about this problem. The fix is to create a class for the JScrollBar extending JComponent and then override the setUI method.
    Here is the code for anyone who needs it:
    /* class custom JScrollBar **/
    class myScrollBar extends JScrollBar
    public myScrollBar(int orientation){
    super(orientation);
    public void setUI(BasicScrollBarUI ui) {
    super.setUI(ui);
    /* class MyUI**/
    class MyUI extends BasicScrollBarUI
    Color barColor = new Color(51,172,49);
    Color bgColor = new Color(245,245,245);
    protected JButton createDecreaseButton(int orientation) {
    return new ArrowButton(orientation);
    protected JButton createIncreaseButton(int orientation){
    return new ArrowButton(orientation);
    JButton up_button = (JButton)createIncreaseButton(SwingConstants.NORTH);
    JButton down_button = (JButton)createDecreaseButton(SwingConstants.SOUTH);
    JButton left_button = (JButton)createDecreaseButton(SwingConstants.WEST);
    JButton right_button = (JButton)createIncreaseButton(SwingConstants.EAST);
    protected void paintThumb(Graphics g,JComponent c,Rectangle thumbBounds)
    g.setColor(barColor);
    g.fill3DRect((int)thumbBounds.getX(),(int)thumbBounds.getY(),
    (int)thumbBounds.getWidth(),(int)thumbBounds.getHeight(),true);
    protected void paintTrack(Graphics g,JComponent c,Rectangle trackBounds)
    g.setColor(bgColor);
    g.fillRect((int)trackBounds.getX(),(int)trackBounds.getY(),
    (int)trackBounds.getWidth(),(int)trackBounds.getHeight());
    * ArrowButton is used for the buttons to position the
    * document up/down. It differs from BasicArrowButton in that the
    * preferred size is always a square.
    private class ArrowButton extends BasicArrowButton {
    public ArrowButton(int direction) {
    super(direction);
    public void paint(Graphics g) {
    System.out.println("i am inside the button paint");
    g.setColor(new Color(51,172,49));
    g.fill3DRect(0, 0, this.getSize().width, this.getSize().height, true);
    int w = this.getSize().width;
    int h = this.getSize().height;
    int size = Math.min((h - 4) / 3, (w - 4) / 3);
    size = Math.max(size, 2);
    g.setColor((new Color(0,0,0,0)).darker());
    paintTriangle(g,(w - size) / 2,(h - size) / 2,size+1,this.direction,true);
    public void paintTriangle(Graphics g,int x,int y,int size,int direction,boolean isEnabled){
    g.setColor((new Color(0,0,0,0)).darker());
    super.paintTriangle(g,x,y,size,direction,isEnabled);
    public Dimension getPreferredSize() {
    int size = 16;
    if (scrollbar != null) {
    switch (scrollbar.getOrientation()) {
    case JScrollBar.VERTICAL:
    size = scrollbar.getWidth();
    break;
    case JScrollBar.HORIZONTAL:
    size = scrollbar.getHeight();
    break;
    size = Math.max(size, 5);
    return new Dimension(size, size);
    in init():
    //setting the scrollbars
    MyScrollBar vertical = new MyScrollBar(JScrollBar.VERTICAL);
    MyScrollBar horizontal = new myScrollBar(JScrollBar.HORIZONTAL);
    horizontal.addAdjustmentListener(new ScrollHandler());
    vertical.addAdjustmentListener(new ScrollHandler());
    vertical.setUI(new MyUI());
    horizontal.setUI(new MyUI());
    vertical.setBorder(BorderFactory.createLineBorder(grayColor));
    horizontal.setBorder(BorderFactory.createLineBorder(grayColor));
    scrollPane.setHorizontalScrollBar(horizontal);
    scrollPane.setVerticalScrollBar(vertical);
    I hope it helps others.
    R.

  • Jscrollbar problem

    Hii there,
    I'm having a JInternalFrame, and within that frame, I added a jlabel. the jlabel contains several images that is being added dynamically. I've added a horizontal scrollbar that is working. but my problem is with the vertical scrollbar. The thing is whenever an image added to jlabel, height of the label increases and the label exceeds to internalframe. The vertivcal scrollbar does not working to see the exceeded part of the jlabel,
    My code is something like this:
                            dpane.setDesktopManager(new DefaultDesktopManager());
                            iframe=new JInternalFrame("Image Frame" ,true,true,true,true);  
                            vScrollBar = new JScrollBar(JScrollBar.VERTICAL);
                            vScrollBar.setValue(jLabel.getHeight());
                            vScrollBar.setValueIsAdjusting(true);                      
                            iframe.getContentPane().add(vScrollBar,BorderLayout.EAST);
                            iframe.getContentPane().add(jLabel,BorderLayout.CENTER);                                                                                                        
                            dpane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
                            dpane.add(iframe);               
                            iframe.setVisible(true);
                            add(dpane);could you else please help me!
    thanks in advance...
    Dev

    You haven't written the code that links scroll bar and its target view component.
    Use JScrollPane and a simple container JPanel.
    Forget your scroll bar and the label.

  • Trying to scroll a JComponent with JScrollPane but can't do it. :(

    Hi, what im trying to do seems to be simple but I gave up after trying the whole day and I beg you guys help.
    I created a JComponent that is my map ( the map consists only in squared cells ). but the map might be too big for the screen, so I want to be able to scroll it. If the map is smaller than the screen,
    everything works perfect, i just add the map to the frame container and it shows perfect. But if I add the map to the ScrollPane and them add the ScrollPane to the container, it doesnt work.
    below is the code for both classes Map and the MainWindow. Thanks in advance
    package main;
    import java.awt.Color;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowStateListener;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JViewport;
    public class MainWindow implements WindowStateListener {
         private JFrame frame;
         private static MainWindow instance = null;
         private MenuBar menu;
         public Map map = new Map();
         public JScrollPane Scroller =
              new JScrollPane( map,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
         public JViewport viewport = new JViewport();
         private MainWindow(int width, int height) {
              frame = new JFrame("Editor de Cen�rios v1.0");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(width,height);
              frame.setVisible(true);
              menu = MenuBar.createMenuBar();
              JFrame.setDefaultLookAndFeelDecorated(false);
              frame.setJMenuBar(menu.create());
              frame.setBackground(Color.WHITE);
              frame.getContentPane().setBackground(Color.WHITE);
                                    // HERE IS THE PROBLEM, THIS DOESNT WORKS   <---------------------------------------------------------------------------------------
              frame.getContentPane().add(Scroller);
              frame.addWindowStateListener(this);
    public static MainWindow createMainWindow(int width, int height)
         if(instance == null)
              instance = new MainWindow(width,height);
              return instance;               
         else
              return instance;
    public static MainWindow returnMainWindow()
         return instance;
    public static void main(String[] args) {
         MainWindow mWindow = createMainWindow(800,600);
    public JFrame getFrame() {
         return frame;
    public Map getMap(){
         return map;
    @Override
    public void windowStateChanged(WindowEvent arg0) {
         map.repaint();
    package main;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import javax.swing.JComponent;
    import javax.swing.Scrollable;
    public class Map extends JComponent  implements Scrollable{
         private Cell [] mapCells;
         private String mapPixels;
         private String mapAltura;
         private String mapLargura;
         public void createMap(String pixels , String altura, String largura)
              mapPixels = pixels;
              mapAltura = altura;
              mapLargura = largura;
              int cells = Integer.parseInt(altura) * Integer.parseInt(largura);
              mapCells = new Cell[cells];
              //MainWindow.returnMainWindow().getFrame().getContentPane().add(this);
              Graphics2D grafico = (Graphics2D)getGraphics();
              for(int i=0, horiz = 0 , vert = 0; i < mapCells.length; i++)
                   mapCells[i] = new Cell( horiz, vert,Integer.parseInt(mapPixels));
                   MainWindow.returnMainWindow().getFrame().getContentPane().add(mapCells);
                   grafico.draw(mapCells[i].r);
                   horiz = horiz + Integer.parseInt(mapPixels);
                   if(horiz == Integer.parseInt(mapLargura)*Integer.parseInt(mapPixels))
                        horiz = 0;
                        vert = vert + Integer.parseInt(mapPixels);
              repaint();
         @Override
         protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              System.out.println("entrou");
              Graphics2D g2d = (Graphics2D)g;
              if(mapCells !=null)
                   for(int i=0, horiz = 0 , vert = 0; i < mapCells.length; i++)
                        g2d.draw(mapCells[i].r);
                        horiz = horiz + Integer.parseInt(mapPixels);
                        if(horiz == Integer.parseInt(mapLargura)*Integer.parseInt(mapPixels))
                             horiz = 0;
                             vert = vert + Integer.parseInt(mapPixels);
         @Override
         public Dimension getPreferredScrollableViewportSize() {
              return super.getPreferredSize();
         @Override
         public int getScrollableBlockIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              // TODO Auto-generated method stub
              return 5;
         @Override
         public boolean getScrollableTracksViewportHeight() {
              // TODO Auto-generated method stub
              return false;
         @Override
         public boolean getScrollableTracksViewportWidth() {
              // TODO Auto-generated method stub
              return false;
         @Override
         public int getScrollableUnitIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              // TODO Auto-generated method stub
              return 5;

    Im so sorry Darryl here are the other 3 classes
    package main;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.filechooser.FileNameExtensionFilter;
    public class MenuActions {
         public void newMap(){
              final JTextField pixels = new JTextField(10);
              final JTextField hCells = new JTextField(10);
              final JTextField wCells = new JTextField(10);
              JButton btnOk = new JButton("OK");
              final JFrame frame = new JFrame("Escolher dimens�es do mapa");
              frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
              btnOk.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
              String txtPixels = pixels.getText();
              String hTxtCells = hCells.getText();
              String wTxtCells = wCells.getText();
              frame.dispose();
              MainWindow.returnMainWindow().map.createMap(txtPixels,hTxtCells,wTxtCells);         
              frame.getContentPane().add(new JLabel("N�mero de pixels em cada c�lula:"));
              frame.getContentPane().add(pixels);
              frame.getContentPane().add(new JLabel("Altura do mapa (em c�lulas):"));
              frame.getContentPane().add(hCells);
              frame.getContentPane().add(new JLabel("Largura do mapa (em c�lulas):"));
              frame.getContentPane().add(wCells);
              frame.getContentPane().add(btnOk);
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setSize(300, 165);
              frame.setResizable(false);
             frame.setVisible(true);
         public Map openMap (){
              //Abre somente arquivos XML
              JFileChooser fc = new JFileChooser();
              FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", "xml" );
              fc.addChoosableFileFilter(filter);
              fc.showOpenDialog(MainWindow.returnMainWindow().getFrame());
              //TO DO: manipular o mapa aberto
              return new Map();          
         public void save(){
         public void saveAs(){
              //Abre somente arquivos XML
              JFileChooser fc = new JFileChooser();
              FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", "xml" );
              fc.addChoosableFileFilter(filter);
              fc.showSaveDialog(MainWindow.returnMainWindow().getFrame());
              //TO DO: Salvar o mapa aberto
         public void exit(){
              System.exit(0);          
         public void copy(){
         public void paste(){
    package main;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.KeyStroke;
    public class MenuBar implements ActionListener{
         private JMenuBar menuBar;
         private final Color color = new Color(250,255,245);
         private String []menuNames = {"Arquivo","Editar"};
         private JMenu []menus = new JMenu[menuNames.length];
         private String []arquivoMenuItemNames = {"Novo","Abrir", "Salvar","Salvar Como...","Sair" };
         private KeyStroke []arquivoMenuItemHotkeys = {KeyStroke.getKeyStroke(KeyEvent.VK_N,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_A,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.SHIFT_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_F4,ActionEvent.ALT_MASK)};
         private JMenuItem []arquivoMenuItens = new JMenuItem[arquivoMenuItemNames.length];
         private String []editarMenuItemNames = {"Copiar","Colar"};
         private KeyStroke []editarMenuItemHotKeys = {KeyStroke.getKeyStroke(KeyEvent.VK_C,ActionEvent.CTRL_MASK),
                                                                 KeyStroke.getKeyStroke(KeyEvent.VK_V,ActionEvent.CTRL_MASK)};
         private JMenuItem[]editarMenuItens = new JMenuItem[editarMenuItemNames.length];
         private static MenuBar instance = null;
         public JMenuItem lastAction;
         private MenuBar()
         public static MenuBar createMenuBar()
              if(instance == null)
                   instance = new MenuBar();
                   return instance;                    
              else
                   return instance;
         public JMenuBar create()
              //cria a barra de menu
              menuBar = new JMenuBar();
              //adiciona items a barra de menu
              for(int i=0; i < menuNames.length ; i++)
                   menus[i] = new JMenu(menuNames);
                   menuBar.add(menus[i]);
              //seta a hotkey da barra como F10
              menus[0].setMnemonic(KeyEvent.VK_F10);
              //adiciona items ao menu arquivo
              for(int i=0; i < arquivoMenuItemNames.length ; i++)
                   arquivoMenuItens[i] = new JMenuItem(arquivoMenuItemNames[i]);
                   arquivoMenuItens[i].setAccelerator(arquivoMenuItemHotkeys[i]);
                   menus[0].add(arquivoMenuItens[i]);
                   arquivoMenuItens[i].setBackground(color);
                   arquivoMenuItens[i].addActionListener(this);
              //adiciona items ao menu editar
              for(int i=0; i < editarMenuItemNames.length ; i++)
                   editarMenuItens[i] = new JMenuItem(editarMenuItemNames[i]);
                   editarMenuItens[i].setAccelerator(editarMenuItemHotKeys[i]);
                   menus[1].add(editarMenuItens[i]);
                   editarMenuItens[i].setBackground(color);
                   editarMenuItens[i].addActionListener(this);
              menuBar.setBackground(color);
              return menuBar;                    
         @Override
         public void actionPerformed(ActionEvent e) {
              lastAction = (JMenuItem) e.getSource();
              MenuActions action = new MenuActions();
              if(lastAction.getText().equals("Novo"))
                   action.newMap();
              else if(lastAction.getText().equals("Abrir"))
                   action.openMap();
              else if(lastAction.getText().equals("Salvar"))
                   action.save();               
              else if(lastAction.getText().equals("Salvar Como..."))
                   action.saveAs();               
              else if(lastAction.getText().equals("Sair"))
                   action.exit();               
              else if(lastAction.getText().equals("Copiar"))
                   action.copy();               
              else if(lastAction.getText().equals("Colar"))
                   action.paste();               
    package main;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JComponent;
    public class Cell extends JComponent{
         public float presSub = 0;
         public double errPressInfer = 0.02;
         public double errPressSup = 0.02;
         public float profundidade = 1;
         public Rectangle2D r ;
         public Cell(double x, double y, double pixel)
              r = new Rectangle2D.Double(x,y,pixel,pixel);          
    Edited by: xnunes on May 3, 2008 6:26 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Help!! How to put more than one JComponent on one JFrame

    Hi!
    I'm having a big problem. I'm trying to create an animation that is composed of various images. In one JComponent I have an animation of a sprite moving left and right on the screen(Which works right now). On another JComponent I have a still image that I want to put somewhere on the screen. For some reason I can only see what I add last to the JFrame. Can somebody help me? Thanks
    P.S I don't want to have all the images on the same JComponent. I want to have different classes for different images or animations. You can get the sprites I use from here http://www.flickr.com/photos/59719950@N00/
    import java.awt.Color;
    import javax.swing.JFrame;
    public class ScreenSaverViewer
         public static void main(String[] args)
         Character characterGame = new Character();
         basketballHoop hoopz = new basketballHoop();
         //Clock clock = new Clock();
         JFrame app = new JFrame("Screensaver");
            app.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            app.getContentPane().add(hoopz);
            //app.getContentPane().add(clock);
            app.getContentPane().add(characterGame);
            app.setSize (450,450);
            app.setBackground (Color.black);
            app.setLocation (300,200);
            app.setVisible (true);
            characterGame.run();
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    import java.util.ArrayList;
    public class Character extends JComponent
        BufferedImage backbuffer;
        int sliderSpeed = 1;
        int sliderX = 1;
        int sliderY = 1;
        int direction = 1;
        Image myImg = Toolkit.getDefaultToolkit().getImage ("/home/climatewarrior/Sprites_gabriel/muneco_0.png");
        private Image fetchImage(int x)
             ArrayList<Image> images = new ArrayList<Image>();
             for (int i = 0; i < 4; i++)
                  images.add(i, Toolkit.getDefaultToolkit().getImage ("/home/climatewarrior/Sprites_gabriel/muneco_" + i + ".png"));
             return images.get(x);
        private void displayGUI()
            int appWidth = getWidth();
            int appHeight = getHeight();
            backbuffer = (BufferedImage) createImage (appWidth, appHeight);
            Graphics2D g2 = backbuffer.createGraphics();
            g2.setRenderingHint (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.drawImage (myImg, sliderX, sliderY, getWidth() / 2 * direction, getHeight() / 2, this);
            g2.dispose();
            repaint();
        public void paintComponent (Graphics g)
            super.paintComponent(g);
            if (backbuffer == null)
                 displayGUI();
            g.drawImage(backbuffer, 0, 0, this);
       public void run ()
            while(true)
                   sliderX = -(getWidth() - getWidth()/2);
                   sliderY = getHeight()/3;
                   int x = 0;
                   int increment = 1;
                   do
                   sliderX += increment;
                   if (sliderX % 30 == 0)
                             myImg = fetchImage(x);
                             direction = -1;
                             x++;
                             if (x == 4)
                             x = 0;
                   displayGUI();
                   } while (sliderX <= getWidth() + (getWidth() - getWidth()/2));
                   do
                   sliderX -= increment;
                   if (sliderX % 30 == 0)
                        myImg = fetchImage(x);
                        direction = 1;
                        x++;
                        if (x == 4)
                             x = 0;
                   displayGUI();
                   } while (sliderX >= -(getWidth() - getWidth()/2));
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class Clock extends JComponent
        BufferedImage backbuffer;
        Image myImg = Toolkit.getDefaultToolkit().getImage("/home/climatewarrior/Sprites_gabriel/score_board.png");
        public void paintComponent (Graphics g)
             g.drawImage(myImg, 250, 100, getWidth()/2, getHeight()/3, null);
             super.paintComponent (g);
             repaint();
    }

    Here's a file I had hanging around. It's about as simple as they come, hopefully not too simple!
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    class SimpleAnimationPanel extends JPanel
        private static final int DELAY = 20;
        public static final int X_TRANSLATION = 2;
        public static final int Y_TRANSLATION = 2;
        private static final String DUKE_FILE = "http://java.sun.com/" +
                  "products/plugin/images/duke.wave.med.gif";
        private Point point = new Point(5, 32);
        private BufferedImage duke = null;
        private Timer timer = new Timer(DELAY, new TimerAction());
        public SimpleAnimationPanel()
            try
                // borrow an image from sun.com
                duke = ImageIO.read(new URL(DUKE_FILE));
            catch (MalformedURLException e)
                e.printStackTrace();
            catch (IOException e)
                e.printStackTrace();
            setPreferredSize(new Dimension(600, 400));
            timer.start();
        // do our drawing here in the paintComponent override
        @Override
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            if (duke != null)
                g.drawImage(duke, point.x, point.y, this);
        private class TimerAction implements ActionListener
            public void actionPerformed(ActionEvent e)
                int x = point.x;
                int y = point.y;
                Dimension size = SimpleAnimationPanel.this.getSize();
                if (x > size.width)
                    x = 0;
                else
                    x += X_TRANSLATION;
                if (y > size.height)
                    y = 0;
                else
                    y += Y_TRANSLATION;
                point.setLocation(new Point(x, y)); // update the point
                SimpleAnimationPanel.this.repaint();
        private static void createAndShowUI()
            JFrame frame = new JFrame("SimpleAnimationPanel");
            frame.getContentPane().add(new SimpleAnimationPanel());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }

  • New to java: how to replace an image extending a JComponent?

    Hi,
    I'm new to Java and I have a question about Swing:
    I have a class called ActiveImage (entends JComponent, implements     MouseMotionListener, MouseWheelListener) which takes an Image and displays it. It also receives some mouse events for zooming and moving it around. I display it in a JFrame using:
    content = getContentPane();
    content.setLayout(new BorderLayout());
    image = toolkit.getImage (filename);
    ActiveImage activeImage = new ActiveImage(image);
    content.add(activeImage, BorderLayout.CENTER);
    (This code is in a class extending JFrame.)
    This works fine. However, this JFrame also contains a JToolbar with two buttons. Now when I click one of them, I want to replace the image with another one. I've tried removing it and creating a new ActiveImage to add that to content, but that didn't work very well. remove() resulted in a NullPointerException.
    My question: what would be the best way to go about this?
    Many thanks for any help,
    Diederick de Vries

    B.T.W., this is the trace:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
            at ActiveImage.ActiveImageFrame$1.actionPerformed(ActiveImageFrame.java:60)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:234)
            at java.awt.Component.processMouseEvent(Component.java:5488)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3093)
            at java.awt.Component.processEvent(Component.java:5253)
            at java.awt.Container.processEvent(Container.java:1966)
            at java.awt.Component.dispatchEventImpl(Component.java:3955)
            at java.awt.Container.dispatchEventImpl(Container.java:2024)
            at java.awt.Component.dispatchEvent(Component.java:3803)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
            at java.awt.Container.dispatchEventImpl(Container.java:2010)
            at java.awt.Window.dispatchEventImpl(Window.java:1766)
            at java.awt.Component.dispatchEvent(Component.java:3803)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
            at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:234)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)Just before this, it says "button clicked". The function that calls the setImage() goes:
    theButton.addActionListener (new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
              System.out.println("button clicked");
              activeImage.setImage(image);
    });Reading the trace, I would think that the exception has something to do with this last code, since it stops there (line 60 is the setImage()). If the setImage() function itself was where the fault was, wouldn't the trace end there?
    I'm really at a loss here ... :-(

  • Changing Arrows and Color of a JScrollBar inside of a JScrollPane

    Hi. I can't believe this hasn't been asked and answered before but I can't find it in these forums if it has.
    I am trying to create a JScrollPane in a touchscreen based application - no mouse... The default scrollbar
    in my JScrollPane is too small for large fingers. I have successfully increased the size of the scrollbar
    to a usable size using: UIManager.put("scrollbar.width", 75).
    My next problem is two-fold.
    1) The arrows at top and bottom of the scrollbar are now heavily pixelated (i.e. jagged and blocky) and
    look like we zoomed in too much on a bitmap. How can I change these arrows to a graphic that is
    more related to the current size of my scrollbar?
    2) The color of the scrollbar is shades of 'baby blue'. My color scheme for my application is shades of
    beige or brown. This makes the scrollbar stand out like a sore thumb. How can I change the color
    of the scrollbar?
    Note: This is being coded in NetBeans 6.7.1 but I can't find any property in the visual editor that covers
    my problems.
    Also, I came across the UIManager.put("scrollbar.width", xx) from googling. Is there an official (complete)
    list of the properties available to the UIManager?
    Thanks

    To help out anyone who has been struggling with this as I have, here is the final solution we were able to use. We only needed to work with the vertical scroll bar, but it should be easy to work with now that a better part of the work is done. I do hope this is helpful.
         public ReportDisplayFrame()
              UIManager.put( "ScrollBar.width", 75);
              RDFScrollBarUI rdfScrlBarUI = new RDFScrollBarUI();
              rdfScrlBarUI.setButtonImageIcon( new ImageIcon( "C:/company/images/upArrow.jpg") , rdfScrlBarUI.NORTH);
              rdfScrlBarUI.setButtonImageIcon( new ImageIcon( "C:/company/images/downArrow.jpg") , rdfScrlBarUI.SOUTH);
              tempScrlBar = new JScrollBar();
              tempScrlBar.setBlockIncrement( 100);
              tempScrlBar.setUnitIncrement( 12);
              tempScrlBar.setUI( rdfScrlBarUI);
    // other constructor code //
              rdfScreenRedraw();
         private void rdfScreenRedraw()
              String methodName = "rdfScreenRedraw()";
              logger.log(Level.INFO, methodName + ": Revalidating: mainPanel Thread = ["+Thread.currentThread().getName()+"]");
              jPanelRpt.revalidate();
              jPanelRpt.repaint();
         class RDFScrollBarUI extends BasicScrollBarUI {
              private ImageIcon decImage = null;
              private ImageIcon incImage = null;
              public void setThumbColor(Color thumbColor) {
                   this.thumbColor = thumbColor;
              public void setThumbDarkShadowColor(Color thumbDarkShadowColor) {
                   this.thumbDarkShadowColor = thumbDarkShadowColor;
              public void setThumbHighlightColor(Color thumbHighlightColor) {
                   this.thumbHighlightColor = thumbHighlightColor;
              public void setThumbLightShadowColor(Color thumbLightShadowColor) {
                   this.thumbLightShadowColor = thumbLightShadowColor;
              public void setTrackColor(Color trackColor) {
                   this.trackColor = trackColor;
              public void setTrackHighlightColor(Color trackHighlightColor) {
                   this.trackHighlightColor = trackHighlightColor;
              public void setButtonImageIcon( ImageIcon theIcon, int orientation)
                   switch( orientation)
                        case NORTH:
                             decImage = theIcon;
                             break;
                        case SOUTH:
                             incImage = theIcon;
                             break;
                        case EAST:
              if (scrollbar.getComponentOrientation().isLeftToRight())
                                  decImage = theIcon;
                             else
                                  incImage = theIcon;
                             break;
                        case WEST:
              if (scrollbar.getComponentOrientation().isLeftToRight())
                                  incImage = theIcon;
                             else
                                  decImage = theIcon;
                             break;
              @Override
              protected JButton createDecreaseButton(int orientation) {
                   JButton button = null;
                   if ( decImage != null)
                        button = new JButton( decImage);
                   else
                        button = new BasicArrowButton(orientation);
                   button.setBackground( new Color( 180,180,130));
                   button.setForeground( new Color( 236,233,216));
                   return button;
              @Override
              protected JButton createIncreaseButton(int orientation) {
                   JButton button = null;
                   if ( incImage != null)
                        button = new JButton( incImage);
                   else
                        button = new BasicArrowButton(orientation);
                   button.setBackground( new Color( 180,180,130));
                   button.setForeground( new Color( 236,233,216));
                   return button;
         }

  • Resizing JComponent not displaying in packed frame

    Please help, I'm trying to dynamically resize a dialog when a component expands/collapses, and when I set the component visible it is not firing a component resize event, as I believe I am setting minimum and preferred size properly. The code I am using is posted below. TriangleIcon is a triangle icon, which will point in any of the SwingConstants directions.
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.SwingConstants;
    public class TestPackedFrame extends JDialog {
         public TestPackedFrame() {
              setModal(true);
              Container contentPane = getContentPane();
              contentPane.setLayout(new BorderLayout());
              PreviewPane previewPane = new PreviewPane(new JLabel("Display Hidden"));
              previewPane.addComponentListener(new ComponentAdapter() {
                   public void componentResized(ComponentEvent e) {
                        pack();
              contentPane.add(previewPane,BorderLayout.CENTER);
              JButton closeButton = new JButton("Close");
              closeButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        setVisible(false);
              contentPane.add(closeButton,BorderLayout.PAGE_END);
         public static void main(String[] args) {
              JDialog.setDefaultLookAndFeelDecorated(true);
              Toolkit.getDefaultToolkit().setDynamicLayout(true);
              System.setProperty("sun.awt.noerasebackground", "true");
              TestPackedFrame frame = new TestPackedFrame();
              frame.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
              frame.dispose();
              System.exit(0);
    class PreviewPane extends JComponent implements MouseListener {
         private boolean expanded;
         private JLabel arrowLabel;
         private Component view;
         public PreviewPane(Component view) {
              this(view, false);
         public PreviewPane(Component view, boolean expanded) {
              this.setLayout(new BorderLayout());
              arrowLabel = new JLabel("Preview", new TriangleIcon(true,
                        SwingConstants.EAST, 6), SwingConstants.LEFT);
              arrowLabel.addMouseListener(this);
              this.add(arrowLabel, BorderLayout.NORTH);
              this.view = view;
              setExpanded(expanded);
              this.add(view, BorderLayout.CENTER);
         public void setExpanded(boolean expanded) {
              this.expanded = expanded;
              view.setVisible(expanded);
              if (expanded)
                   view.repaint();
         public boolean isExpanded() {
              return expanded;
         public void paint(Graphics g) {
              super.paint(g);
         public void mouseClicked(MouseEvent e) {
         public void mousePressed(MouseEvent e) {
              Object source = e.getSource();
              if (source == arrowLabel) {
                   TriangleIcon currentIcon = (TriangleIcon) arrowLabel.getIcon();
                   if (currentIcon.getDirection() == SwingConstants.EAST) {
                        arrowLabel.setIcon(new TriangleIcon(true, SwingConstants.SOUTH,
                                  6));
                        setExpanded(true);
                        repaint();
                   } else if (currentIcon.getDirection() == SwingConstants.SOUTH) {
                        arrowLabel.setIcon(new TriangleIcon(true, SwingConstants.EAST,
                                  6));
                        setExpanded(false);
         public Dimension getMinimumSize() {
              Dimension arrowSize = arrowLabel.getMinimumSize();
              Dimension viewSize = isExpanded() ? view.getMinimumSize()
                        : new Dimension(0, 0);
              return new Dimension(Math.max(arrowSize.width, viewSize.width),
                        arrowSize.height + viewSize.height);
         public Dimension getPreferredSize() {
              Dimension arrowSize = arrowLabel.getPreferredSize();
              Dimension viewSize = isExpanded() ? view.getPreferredSize()
                        : new Dimension(0, 0);
              return new Dimension(Math.max(arrowSize.width, viewSize.width),
                        arrowSize.height + viewSize.height);
         public void mouseReleased(MouseEvent e) {
         public void mouseEntered(MouseEvent e) {
         public void mouseExited(MouseEvent e) {
    }Edited by: stringman520 on Jan 27, 2008 1:20 AM

    Here is the code for TriangleIcon. How could I call pack directly when the component is displayed? The PreviewPane doesn't receive the window object, so while I can pack the dialog directly when it is displayed, subsequent changes do nothing.
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Polygon;
    import javax.swing.Icon;
    import javax.swing.SwingConstants;
    public class TriangleIcon implements Icon, SwingConstants {
         public static int DEFAULT_TRIANGLE_SIZE = 3;
         private boolean enabled;
         private int direction;
         private int triangleSize;
         public TriangleIcon() {
              this(false);
         public TriangleIcon(boolean enabled) {
              this(enabled,NORTH);
         public TriangleIcon(boolean enabled, int direction) {
              this(enabled, direction, DEFAULT_TRIANGLE_SIZE);
         public TriangleIcon(boolean enabled, int direction, int triangleSize) {
              this.enabled = enabled;
              this.direction = direction;
              this.triangleSize = triangleSize;
         public void paintIcon(Component c, Graphics g, int x, int y) {
              if (enabled) {
                   g.setColor(Color.BLACK);
              } else {
                   g.setColor(Color.LIGHT_GRAY);
              Polygon triangle = new Polygon();
              switch (direction) {
              case NORTH:
                   triangle.addPoint(x, y + triangleSize);
                   triangle.addPoint(x + triangleSize, y);
                   triangle.addPoint(x + triangleSize * 2, y + triangleSize);
                   triangle.addPoint(x, y + triangleSize);
                   break;
              case EAST:
                   triangle.addPoint(x, y);
                   triangle.addPoint(x + triangleSize, y + triangleSize);
                   triangle.addPoint(x, y + triangleSize * 2);
                   triangle.addPoint(x, y);
                   break;
              case SOUTH:
                   triangle.addPoint(x, y);
                   triangle.addPoint(x + triangleSize * 2, y);
                   triangle.addPoint(x + triangleSize, y + triangleSize);
                   triangle.addPoint(x, y);
                   break;
              case WEST:
                   triangle.addPoint(x + triangleSize, y);
                   triangle.addPoint(x, y + triangleSize);
                   triangle.addPoint(x + triangleSize, y + triangleSize * 2);
                   triangle.addPoint(x+triangleSize,y);
                   break;
              g.fillPolygon(triangle);
         public int getIconWidth() {
              switch (direction) {
              case NORTH:
              case SOUTH:
                   return triangleSize*2;
              case EAST:
              case WEST:
                   return triangleSize;
              return 0;
         public int getIconHeight() {
              switch (direction) {
              case NORTH:
              case SOUTH:
                   return triangleSize;
              case EAST:
              case WEST:
                   return triangleSize*2;
              return 0;
         public int getDirection() {
              return direction;
    }

  • Need help fast :a question about jcomponent and jscrollpane

    I draw a graphic on a jcomponent like this :
    class drawrecttree extends JComponent {
    public void paint( Graphics g) {
    and I add this to jscrollpane:
    drawrecttree www=new drawrecttree();
    www.k_choose=k_valuenow;
    www.node=currentNode;
    www.setAutoscrolls(true);
    jScrollPane2.setViewportView(www);
    but I hope the jscrollpane can autoscroll,that means jscrollpane's size is 400*400,if the Jcomponent's size is 200*300, just add jcomponent;if jcomponent is bigger than 400*400,the jscrollpane can autoscroll,how can I do that?
    Edited by: hcgerard on Jan 8, 2008 2:18 AM
    Edited by: hcgerard on Jan 8, 2008 2:22 AM
    Edited by: hcgerard on Jan 8, 2008 2:52 AM

    Below is a small non-compilable unit (you need to add a few things of course) - but at any rate, here is some code that, if you get it working, you will see that the scrollbars do the right thing.
    public class TestScrollPane  extends JFrame {
      private Container     container;
      private JPanel        panel;
      private JLabel        label;
      private JScrollPane   scroller;
      public TestScrollPane() {
        container = getContentPane();
        panel     = new JPanel();
        panel.setLayout(new BorderLayout());
        /* Get you images here ...                */
        /* I will call them imageOne and imageTwo */
        label     = new JLabel(new ImageIcon(imageOne));
        panel.add(label);
        scroller  = new JScrollPane(panel);
        scroller.setPreferredSize(new Dimension(100, 100));
        container.add(scroller);
        pack();
        /* Rest of JFrame stuff */
      public static void main(String[] argv)  throws InterruptedException {
        TestScrollPane tsp = new TestScrollPane();
        Thread.sleep(5000);
        tsp.label.setIcon(new ImageIcon(tsp.imageTwo));
        Thread.sleep(5000);
        tsp.label.setIcon(new ImageIcon(tsp.imageOne));
    }

  • Scroll bar....isn't in the JScrollBar...why?

    Hey, Ive created a perfect scroll bar, in a swing app, it looks perfect...except in my JScrollBar, there are no bars....why?
    Here's my code...
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Beginning of Code~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    * Summary description for gui
    public class MapEditor extends JFrame
    private JScrollPane jScrollPane1;
    private JScrollPane jScrollPane3;
    private JButton jButton2;
    private JButton jButton3;
    private JButton jButton6;
    private JButton jButton7;
    private JButton jButton8;
    private JButton jButton9;
    private JButton jButton10;
    private JButton jButton11;
    private JButton jButton12;
    private JPanel contentPane;
    // TODO: Add any attribute code to meet your needs here
    public MapEditor()
         super();
         initializeComponent();
         // TODO: Add any constructor code after InitializeComponent call
         this.setVisible(true);
    private void initializeComponent()
         jScrollPane1 = new JScrollPane();
         jScrollPane3 = new JScrollPane();
         jButton2 = new JButton();
         jButton3 = new JButton();
         jButton6 = new JButton();
         jButton7 = new JButton();
         jButton8 = new JButton();
         jButton9 = new JButton();
         jButton10 = new JButton();
         jButton11 = new JButton();
         jButton12 = new JButton();
         contentPane = (JPanel)this.getContentPane();
         // jScrollPane1
         // jScrollPane3
         // jButton2
         jButton2.setText("Rock");
         jButton2.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton2_actionPerformed(e);
         // jButton3
         jButton3.setText("Grass");
         jButton3.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton3_actionPerformed(e);
         // jButton6
         jButton6.setText("Grass2");
         jButton6.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton6_actionPerformed(e);
         // jButton7
         jButton7.setText("Water 1");
         jButton7.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton7_actionPerformed(e);
         // jButton8
         jButton8.setText("Path");
         jButton8.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton8_actionPerformed(e);
         // jButton9
         jButton9.setText("Water 3");
         jButton9.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton9_actionPerformed(e);
         // jButton10
         jButton10.setText("Dirt");
         jButton10.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton10_actionPerformed(e);
         // jButton11
         jButton11.setText("Snow");
         jButton11.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton11_actionPerformed(e);
         // jButton12
         jButton12.setText("Water 2");
         jButton12.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   jButton12_actionPerformed(e);
         // contentPane
         contentPane.setLayout(null);
         addComponent(contentPane, jScrollPane1, 0,0,476,408);
         addComponent(contentPane, jScrollPane3, 476,86,248,290);
         addComponent(contentPane, jButton2, 476,1,83,28);
         addComponent(contentPane, jButton3, 559,1,83,28);
         addComponent(contentPane, jButton6, 643,1,83,28);
         addComponent(contentPane, jButton7, 476,30,83,28);
         addComponent(contentPane, jButton8, 476,58,83,28);
         addComponent(contentPane, jButton9, 643,30,83,28);
         addComponent(contentPane, jButton10, 643,58,83,28);
         addComponent(contentPane, jButton11, 559,58,83,28);
         addComponent(contentPane, jButton12, 560,30,83,28);
         // gui
         this.setTitle("gui - extends JFrame");
         this.setLocation(new Point(0, 0));
         this.setSize(new Dimension(729, 627));
    /** Add Component Without a Layout Manager (Absolute Positioning) */
    private void addComponent(Container container,Component c,int x,int y,int width,int height)
         c.setBounds(x,y,width,height);
         container.add(c);
    // TODO: Add any appropriate code in the following Event Handling Methods
    private void jButton2_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    private void jButton3_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    private void jButton6_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    private void jButton7_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    private void jButton8_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    private void jButton9_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    private void jButton10_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    private void jButton11_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    private void jButton12_actionPerformed(ActionEvent e)
         // TODO: Add any handling code here
    // TODO: Add any method code to meet your needs in the following area
    public static void main(String[] args) {
              new MapEditor();
    }

    Hi,
    please use code tag when posting so much code.
    It eases a lot reading your code.
    Hey, Ive created a perfect scroll bar, in a swing app,
    it looks perfect...except in my JScrollBar, there are
    no bars....why?basically because there is nothing to scroll and even to view !!
    nowhere in your code appears a call to :
    jScrollPane1.setViewportView(Component view);
    Moreover the scroll bar appearance policy, by default is when needed.
    When needed means that if the component prefered size you wish
    to view is greater than the one of the JScrollPane, they will appear
    otherwise they won't.
    So, what would you like to see in you JScrollPane ? the buttons ?
    regards,

  • Java.lang.NullPointerException in JComponent

    hi below error i am getting, could you plz help me.
    java.lang.NullPointerException
         at vobPrimCompare$1.getColumnClass(vobPrimCompare.java:170)
         at javax.swing.JTable.getColumnClass(JTable.java:1752)
         at javax.swing.JTable.getCellRenderer(JTable.java:3700)
         at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:1148)
         at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:1051)
         at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:974)
         at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
         at javax.swing.JComponent.paintComponent(JComponent.java:541)
         at javax.swing.JComponent.paint(JComponent.java:808)
         at javax.swing.JComponent.paintChildren(JComponent.java:647)
         at javax.swing.JComponent.paint(JComponent.java:817)
         at javax.swing.JViewport.paint(JViewport.java:722)
         at javax.swing.JComponent.paintChildren(JComponent.java:647)
         at javax.swing.JComponent.paint(JComponent.java:817)
         at javax.swing.JComponent.paintChildren(JComponent.java:647)
         at javax.swing.JComponent.paint(JComponent.java:817)
         at javax.swing.JComponent.paintChildren(JComponent.java:647)
         at javax.swing.JComponent.paint(JComponent.java:817)
         at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4787)
         at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4740)
         at javax.swing.JComponent._paintImmediately(JComponent.java:4685)
         at javax.swing.JComponent.paintImmediately(JComponent.java:4488)
         at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:410)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:117)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:189)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:478)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)what could be the problem, could u plz help me.
    below code is for(vobPrimCompare.java)
    public vobPrimCompare() {
        tm = new AbstractTableModel() {
          public int getColumnCount() { return headers.length; }
          public int getRowCount() { return( tabHash.size() ); }
          public boolean isCellEditable(int row, int col) {
              if (col==8) return true;
              return false;
          public String getColumnName(int col) { return headers[col]; }
          public Object getValueAt(int row, int col) {
            compareNode cell=(compareNode)tabHash.get(new Integer(row));
            if (cell == null) return "cell";
            if (col==8)
              if (cell.primUpdate) return "UPDATED"; else return "PASS";
            if (col==0) return cell.diffCode;
            if (tabHash==prodTabHash) return(getProdTabRow(cell, col));
            return(getDocTabRow(cell, col));
           public Class getColumnClass(int c) {
              return getValueAt(0, c).getClass();here last line is 170(at vobPrimCompare$1.getColumnClass(vobPrimCompare.java:170))

    The value that's being returned is null, and then you're trying to call getClass on it, which is a nullpointerexception

  • JTable display cell previous/last selected/edited/clicked value/JComponent

    I have a problem with the minesweeper I made,
    The game board is a JTable containing custom gadgets in the cells,
    The first game goes without problem, but I press the JButton starting a new game,
    I randomly refill the JTable with new custom gadgets,
    My problem is that the last cell I clicked in the JTable is still in the clicked state with the previous value and I cannot click or see the new custom gadget that ought to be there ...
    The custom gadgets extends JLabel and use custom AbstractCellEditor and custom TableCellRenderer, but I think it is not related to my custom gadgets,
    I work on OSX,
    Any hint to my problem's origin?
    Any solutions?

    My code included not related classes I eliminated to use only standard java classes,
    here is is the minimal code for my mine sweeper reproducing the problem on the third launch
    any hint? :
    import java.awt.Container;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseEvent;
    import java.util.Random;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableModel;
    public class MyMineSweeper
       private class JTableCellRenderer implements javax.swing.table.TableCellRenderer
          private javax.swing.table.TableCellRenderer defaultRenderer;
          public JTableCellRenderer(javax.swing.table.TableCellRenderer aRenderer)
             defaultRenderer = aRenderer;
          public java.awt.Component getTableCellRendererComponent(javax.swing.JTable aTable, Object anElement, boolean isSelected, boolean hasFocus, int aRow, int aColumn)
             if(anElement instanceof javax.swing.JComponent)
                return (javax.swing.JComponent)anElement;
             return defaultRenderer.getTableCellRendererComponent(aTable, anElement, isSelected, hasFocus, aRow, aColumn);
       private class JTableCellEditor extends javax.swing.AbstractCellEditor implements javax.swing.table.TableCellEditor
          private javax.swing.JComponent component;
          private int theClickCountToStart = 0;
          public java.awt.Component getTableCellEditorComponent(javax.swing.JTable aTable, Object anElement, boolean isSelected, int aRow, int aColumn)
             component = (javax.swing.JComponent) anElement;
             return component;
          public Object getCellEditorValue()
             return component;
          public boolean isCellEditable(java.util.EventObject anEvent)
             if(anEvent instanceof java.awt.event.MouseEvent)
                return ((java.awt.event.MouseEvent)anEvent).getClickCount() >= theClickCountToStart;
             return true;
          public int getClickCountToStart()
             return theClickCountToStart;
          public void setClickCountToStart(int aClickCountToStart)
             theClickCountToStart = aClickCountToStart;
       private class Tile extends javax.swing.JLabel
          public class JTileMouseListener implements java.awt.event.MouseListener
             public void mouseClicked(MouseEvent e)
                if(isRevealed()==false)
                   reveal();
             public void mousePressed(MouseEvent e)
             public void mouseReleased(MouseEvent e)
             public void mouseEntered(MouseEvent e)
             public void mouseExited(MouseEvent e)
            public void reveal(int aY, int anX)
               Tile tile = ((Tile)theMapModel.getValueAt(aY, anX));
               if(tile.isRevealed()==false)
                  tile.reveal();
            public void changed()
               if(theNeighbourCount==0)
                  if(theX>0)
                     if(theY>0)
                        reveal(theY-1, theX-1);
                     reveal(theY, theX-1);
                     if(theY<theMapModel.getRowCount()-1)
                        reveal(theY+1, theX-1);
                  if(theY>0)
                     reveal(theY-1, theX);
                  if(theY<theMapModel.getRowCount()-1)
                     reveal(theY+1, theX);
                  if(theX<theMapModel.getColumnCount()-1)
                     if(theY>0)
                        reveal(theY-1, theX+1);
                     reveal(theY, theX+1);
                     if(theY<theMapModel.getRowCount()-1)
                         reveal(theY+1, theX+1);
                   setBackground(java.awt.Color.WHITE);
                else if(theNeighbourCount==9)
                   setText("*");
                   setBackground(java.awt.Color.RED);
                   System.out.println("no!");
                   theMap.setEnabled(false);
                else
                   setText(String.valueOf(theNeighbourCount));
                   setBackground(java.awt.Color.WHITE);
                setBorder(javax.swing.BorderFactory.createEmptyBorder());
                if(isFinished()==true)
                   System.out.println("victory!");
                   theMap.setEnabled(false);
                theMapModel.fireTableCellUpdated(theY,theX);
          private DefaultTableModel theMapModel;
          private int theX;
          private int theY;
          private short theNeighbourCount;
          protected boolean revealed = false;
          public Tile(int aYIndex, int anXIndex, short aNeighbourCount)
             theMapModel = (DefaultTableModel)theMap.getModel();
             theX = anXIndex;
             theY = aYIndex;
             theNeighbourCount = aNeighbourCount;
             addMouseListener(new JTileMouseListener());
             setOpaque(true);
             setHorizontalAlignment(CENTER);
             setBackground(java.awt.Color.LIGHT_GRAY);
             setBorder(javax.swing.BorderFactory.createRaisedBevelBorder());
             setSize(getHeight(), getHeight());
          public void reveal()
             revealed = true;
             theRevealedTileCount +=1;
             changed();
          public boolean isRevealed()
             return revealed;
       private JFrame theFrame;
       private JTable theMap;
       private int theMapSize = 10;
       private int theTrapCount = 5;
       private int theRevealedTileCount = 0;
       private void startGame()
          Point[] traps = new Point[theTrapCount];
          Random generator = new Random();
          for(int trapIndex = 0; trapIndex<theTrapCount; trapIndex+=1)
             Point newPoint = null;
             boolean alreadyTrapped = true;
             while(alreadyTrapped==true)
                newPoint = new Point(generator.nextInt(theMapSize-1), generator.nextInt(theMapSize-1));
                alreadyTrapped = false;
                for(int existingTrapIndex= 0; existingTrapIndex<trapIndex;existingTrapIndex++)
                   if(newPoint.equals(traps[existingTrapIndex])) alreadyTrapped = true;
             traps[trapIndex] = newPoint;
          TableModel mapModel = theMap.getModel();
          for(int yIndex = 0; yIndex<theMapSize; yIndex+=1)
             for(int xIndex = 0; xIndex<theMapSize; xIndex+=1)
                short neighbours = 0;
                int x = 0;
                int y = 0;
                for(int trapIndex = 0; trapIndex<theTrapCount; trapIndex+=1)
                   x = traps[trapIndex].x - xIndex;
                   y = traps[trapIndex].y - yIndex;
                   if(x==0 && y==0)
                      trapIndex = theTrapCount;
                   else if((x==1 || x==-1) && (y==1 || y==-1))
                      neighbours += 1;
                   else if((x==0) && (y==1 || y==-1))
                      neighbours += 1;
                   else if((x==1 || x==-1) && (y==0))
                      neighbours += 1;
                if(x==0 && y==0)
                   mapModel.setValueAt(new Tile(yIndex, xIndex, (short) 9), yIndex, xIndex);
                else
                   mapModel.setValueAt(new Tile(yIndex, xIndex, neighbours), yIndex, xIndex);
          theRevealedTileCount  = 0;
          theMap.setEnabled(true);
       private boolean isFinished()
          return ((theMapSize*theMapSize)-theRevealedTileCount)==theTrapCount;
       public MyMineSweeper()
          theFrame = new javax.swing.JFrame("mine sweeper");
          JPanel cp = new JPanel();
          theMap = new JTable(new DefaultTableModel(10,10)
             public Class getColumnClass(int column)
                return getValueAt(0, column).getClass();
          theMap.setDefaultRenderer(JComponent.class, new JTableCellRenderer(theMap.getDefaultRenderer(JComponent.class)));
          JTableCellEditor editor = new JTableCellEditor();
          theMap.setDefaultEditor(JComponent.class, editor);
          editor.setClickCountToStart(0);
          theMap.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
          startGame();
          cp.add(theMap);
          Action newGameAction = new AbstractAction("new game")
             public void actionPerformed(ActionEvent e)
                startGame();
          JButton newGameTrigger = new JButton(newGameAction);
          cp.add(newGameTrigger);
          theFrame.getContentPane().add(cp);
          theFrame.pack();
          theFrame.show();
       public JFrame getFrame()
          return theFrame;
      }

  • Jcomponent vs jframe

    hey all, im kinda new in java programming but i like this language alot, i was trying to look online for some GUI code, well i found a lot of sample swing code, some of them extends JComponent while the other extends JFrame...
    what exactly is the difference, please ellaborate and be clear as much as you can...
    thnx in advance

    A JFrame is a top-level window. Usually, your GUI application will have one single JFrame.
    JComponent is the base-class for all widgets, such as JButton, JLabel, JTree, etc. You add your widgets to a container, e.g. a JPanel (which also derives from JComponent btw), which at some point is added, directly or indirectly, to your top-level frame.
    code, some of them extends JComponent while the other
    extends JFrame...It's not very often that you actually need to extend a JComponent, and there is almost never a good reason to extend JFrame.

  • JComponent unreachable by tabbing, but SHIFT-tab works??

    Hey all,
    I have some weird behaviour happening with a JComboBox in the following JPanel code. The JPanel has several JLabels, JTextFields and JComboBoxes. All button one (the last one) of the JTextFields and JComboBoxes is reachable by pressing the TAB button. However, I can get to it if I press SHIFT+TAB and go through my focusable components backwards.
    Either I'm missing something very simple, or maybe this is a bug. I would think it's me, not Java, that is causing this problem.
    Any help is appreciated. Thanks.
    * Created on Jul 20, 2006
    * To change the template for this generated file go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    package GUI;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import inputHandlers.DigitDocument;
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.border.TitledBorder;
    * @author Michael C. Freake
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    public class CurrCovgPanel extends JPanel implements FocusListener{
         private static int WIDTH, HEIGHT;
         private static Color BACKGROUND_COLOR, GREEN_COLOR = Color.GREEN, WHITE_COLOR = Color.WHITE;
         public CurrCovgPanel(Color bgColor, int width, int height){
              super(new FlowLayout(FlowLayout.LEADING,0,1));
              //BACKGROUND_COLOR = bgColor;
    BACKGROUND_COLOR = Color.BLUE;
              WIDTH = width;
              HEIGHT = height;
              init();
              // TODO Create a 'load' method that would put actual buffer values in the components.
              // Otherwise we can default to blank/default values in all fields.
              // TODO May want to create and call validate method here that would indicate any errors
              // to the user on load.
              // OR Have the CovgApp call this validate method AFTER the screen has been loaded.
         public void init(){
              setBackground(BACKGROUND_COLOR);
              setPreferredSize(new Dimension(WIDTH,HEIGHT));
              setBorder(BorderFactory.createTitledBorder(
                                            BorderFactory.createLineBorder(Color.YELLOW),
                                            "CURRENT COVERAGE AND PREMIUMS",
                                            TitledBorder.CENTER, TitledBorder.TOP,
                                            null, Color.YELLOW));
              int labelHeight = 15;
              // The following components should be Globals to whatever class they end up in.
              // If they are globals, we can access their values and modify them in other methods.
              JTextField buildLimit1 = new JTextField(new DigitDocument(4),"0",0);
              buildLimit1.setPreferredSize(new Dimension(35,labelHeight));
              buildLimit1.setHorizontalAlignment(JTextField.RIGHT);
              buildLimit1.setForeground(Color.CYAN);
              buildLimit1.setBackground(BACKGROUND_COLOR);
              buildLimit1.setBorder(null);
              buildLimit1.addFocusListener(this);
              JTextField buildLimit2 = new JTextField(new DigitDocument(4),"0",0);
              buildLimit2.setPreferredSize(new Dimension(35,labelHeight));
              buildLimit2.setHorizontalAlignment(JTextField.RIGHT);
              buildLimit2.setForeground(Color.CYAN);
              buildLimit2.setBackground(BACKGROUND_COLOR);
              buildLimit2.setBorder(null);
              buildLimit2.addFocusListener(this);     
              JComboBox buildDed1 = new JComboBox();
              buildDed1.setPreferredSize(new Dimension(60, labelHeight));
              buildDed1.setForeground(Color.CYAN);
              JComboBox buildDed2 = new JComboBox();
              buildDed2.setPreferredSize(new Dimension(60, labelHeight));
              buildDed2.setForeground(Color.CYAN);
              JComboBox buildForm1 = new JComboBox();
              buildForm1.setPreferredSize(new Dimension(60, labelHeight));
              buildForm1.setForeground(Color.CYAN);
              JComboBox buildForm2 = new JComboBox();
              buildForm2.setPreferredSize(new Dimension(60, labelHeight));
              buildForm2.setForeground(Color.CYAN);
              JLabel buildPrem1 = new JLabel("1234",JLabel.RIGHT);
              buildPrem1.setPreferredSize(new Dimension(30,labelHeight));
              buildPrem1.setForeground(Color.CYAN);
              JLabel buildPrem2 = new JLabel("5678",JLabel.RIGHT);
              buildPrem2.setPreferredSize(new Dimension(30,labelHeight));
              buildPrem2.setForeground(Color.CYAN);
              JTextField contLimit1 = new JTextField(new DigitDocument(4),"0",0);
              contLimit1.setPreferredSize(new Dimension(35,labelHeight));
              contLimit1.setHorizontalAlignment(JTextField.RIGHT);
              contLimit1.setForeground(Color.CYAN);
              contLimit1.setBackground(BACKGROUND_COLOR);
              contLimit1.setBorder(null);
              contLimit1.addFocusListener(this);     
              JTextField contLimit2 = new JTextField(new DigitDocument(4),"0",0);
              contLimit2.setPreferredSize(new Dimension(35,labelHeight));
              contLimit2.setHorizontalAlignment(JTextField.RIGHT);
              contLimit2.setForeground(Color.CYAN);
              contLimit2.setBackground(BACKGROUND_COLOR);
              contLimit2.setBorder(null);
              contLimit2.addFocusListener(this);
              JComboBox contDed1 = new JComboBox();
              contDed1.setPreferredSize(new Dimension(60, labelHeight));
              contDed1.setForeground(Color.CYAN);
              JComboBox contDed2 = new JComboBox();
              contDed2.setPreferredSize(new Dimension(60, labelHeight));
              contDed2.setForeground(Color.CYAN);
              JComboBox contForm1 = new JComboBox();
              contForm1.setPreferredSize(new Dimension(60,labelHeight));
              contForm1.setForeground(Color.CYAN);          
              JComboBox contForm2 = new JComboBox();
              contForm2.setPreferredSize(new Dimension(60,labelHeight));
              contForm2.setForeground(Color.CYAN);
              JLabel contPrem1 = new JLabel("4321",JLabel.RIGHT);
              contPrem1.setPreferredSize(new Dimension(30,labelHeight));
              contPrem1.setForeground(Color.CYAN);
              JLabel contPrem2 = new JLabel("8765",JLabel.RIGHT);
              contPrem2.setPreferredSize(new Dimension(30,labelHeight));
              contPrem2.setForeground(Color.CYAN);
              JComboBox liabLimit = new JComboBox();
              liabLimit.setPreferredSize(new Dimension(60,labelHeight));
              liabLimit.setForeground(Color.CYAN);
              JLabel liabPrem1 = new JLabel("7", JLabel.RIGHT);
              liabPrem1.setPreferredSize(new Dimension(30,labelHeight));
              liabPrem1.setForeground(Color.CYAN);
              JLabel liabPrem2 = new JLabel("7", JLabel.RIGHT);
              liabPrem2.setPreferredSize(new Dimension(30,labelHeight));
              liabPrem2.setForeground(Color.CYAN);
              JComboBox liabForm = new JComboBox();
              liabForm.setPreferredSize(new Dimension(60,labelHeight));
              liabForm.setForeground(Color.CYAN);
    //          ********** THIS IS THE JCOMBOBOX THAT SHOULD TAB INTO THE glassLimit JCOMBOBOX          
              JComboBox medLimit = new JComboBox();
              medLimit.setPreferredSize(new Dimension(60,labelHeight));
              medLimit.setForeground(Color.CYAN);
              JLabel medPrem = new JLabel("12", JLabel.RIGHT);
              medPrem.setPreferredSize(new Dimension(30,labelHeight));
              medPrem.setForeground(Color.CYAN);
    //          ********** THIS IS THE JCOMBOBOX THAT ISN"T ALLOWING FOCUS
              JComboBox glassLimit = new JComboBox();
              glassLimit.setPreferredSize(new Dimension(60,labelHeight));
              glassLimit.setForeground(Color.CYAN);
              JLabel glassPrem = new JLabel("5", JLabel.RIGHT);
              glassPrem.setPreferredSize(new Dimension(30,labelHeight));
              glassPrem.setForeground(Color.CYAN);
              JLabel grcYN = new JLabel("N", JLabel.LEFT);
              grcYN.setPreferredSize(new Dimension(30,labelHeight));
              grcYN.setForeground(WHITE_COLOR);
              JLabel subTotalPrem1 = new JLabel("539", JLabel.RIGHT);
              subTotalPrem1.setPreferredSize(new Dimension(30,labelHeight));
              subTotalPrem1.setForeground(WHITE_COLOR);
              JLabel subTotalPrem2 = new JLabel("554", JLabel.RIGHT);
              subTotalPrem2.setPreferredSize(new Dimension(30,labelHeight));
              subTotalPrem2.setForeground(WHITE_COLOR);
              // Setting up and adding Location 1 & 2 headers
              JLabel loc1 = new JLabel("Location 1", JLabel.RIGHT);
              loc1.setPreferredSize(new Dimension(60,labelHeight));
              loc1.setForeground(Color.YELLOW);
              JLabel loc2 = new JLabel("Location 2", JLabel.RIGHT);
              loc2.setPreferredSize(new Dimension(60,labelHeight));
              loc2.setForeground(Color.YELLOW);
              JLabel prem1 = new JLabel("Premium", JLabel.RIGHT);
              prem1.setPreferredSize(new Dimension(60,labelHeight));
              prem1.setForeground(Color.YELLOW);
              JLabel prem2 = new JLabel("Premium", JLabel.RIGHT);
              prem2.setPreferredSize(new Dimension(60,labelHeight));
              prem2.setForeground(Color.YELLOW);
              add(loc1);
              add(Box.createHorizontalStrut(155));
              add(prem1);
              add(Box.createHorizontalStrut(30));
              add(loc2);
              add(Box.createHorizontalStrut(155));
              add(prem2);
              // Setting up static JLabels for viewing on the screen
              JLabel build = new JLabel("BUILD", JLabel.RIGHT);
              build.setPreferredSize(new Dimension(40,labelHeight));
              build.setForeground(GREEN_COLOR);
              JLabel cont = new JLabel("CONT", JLabel.RIGHT);
              cont.setPreferredSize(new Dimension(40, labelHeight));
              cont.setForeground(GREEN_COLOR);
              JLabel liab = new JLabel("LIAB", JLabel.RIGHT);
              liab.setPreferredSize(new Dimension(40, labelHeight));
              liab.setForeground(GREEN_COLOR);
              JLabel med = new JLabel("MED", JLabel.RIGHT);
              med.setPreferredSize(new Dimension(40, labelHeight));
              med.setForeground(GREEN_COLOR);
              JLabel glass = new JLabel("GLASS", JLabel.RIGHT);
              glass.setPreferredSize(new Dimension(40,labelHeight));
              glass.setForeground(GREEN_COLOR);
              JLabel grc = new JLabel("GRC", JLabel.RIGHT);
              grc.setPreferredSize(new Dimension(40,labelHeight));
              grc.setForeground(GREEN_COLOR);
              JLabel subTotal = new JLabel("SUB TOTAL", JLabel.LEFT);
              subTotal.setPreferredSize(new Dimension(70,labelHeight));
              subTotal.setForeground(GREEN_COLOR);
              JLabel ded1 = new JLabel("ded", JLabel.RIGHT);
              ded1.setPreferredSize(new Dimension(40, labelHeight));
              ded1.setForeground(WHITE_COLOR);
              JLabel ded2 = new JLabel("ded", JLabel.RIGHT);
              ded2.setPreferredSize(new Dimension(40,labelHeight));
              ded2.setForeground(WHITE_COLOR);
              JLabel form1 = new JLabel("form", JLabel.RIGHT);
              form1.setPreferredSize(new Dimension(40, labelHeight));
              form1.setForeground(WHITE_COLOR);
              JLabel form2 = new JLabel("form", JLabel.RIGHT);
              form2.setPreferredSize(new Dimension(40, labelHeight));
              form2.setForeground(WHITE_COLOR);
              JLabel form3 = new JLabel("form", JLabel.RIGHT);
              form3.setPreferredSize(new Dimension(40, labelHeight));
              form3.setForeground(WHITE_COLOR);
              // Load the coverage JPanel to the Window
              // Line 1 - BUILD
              add(build);
              add(Box.createHorizontalStrut(5));
              add(buildLimit1);
              add(Box.createHorizontalStrut(230));
              add(buildLimit2);
              add(Box.createHorizontalStrut(210));
              // Line 2 - BUILD Deductible
              add(ded1);
              add(Box.createHorizontalStrut(5));
              add(buildDed1);
              add(Box.createHorizontalStrut(200));
              add(buildDed2);
              add(Box.createHorizontalStrut(180));
              // Line 3 - BUILD Form
              add(form1);
              add(Box.createHorizontalStrut(5));
              add(buildForm1);
              add(Box.createHorizontalStrut(140));
              add(buildPrem1);
              add(Box.createHorizontalStrut(30));
              add(buildForm2);
              add(Box.createHorizontalStrut(180));
              add(buildPrem2);
              // Line 4 - CONT
              add(cont);
              add(Box.createHorizontalStrut(5));
              add(contLimit1);
              add(Box.createHorizontalStrut(230));
              add(contLimit2);
              add(Box.createHorizontalStrut(210));
              // Line 5 - CONT Deductible
              add(ded2);
              add(Box.createHorizontalStrut(5));
              add(contDed1);
              add(Box.createHorizontalStrut(200));
              add(contDed2);
              add(Box.createHorizontalStrut(180));
              // Line 6 - CONT Form
              add(form2);
              add(Box.createHorizontalStrut(5));
              add(contForm1);
              add(Box.createHorizontalStrut(140));
              add(contPrem1);
              add(Box.createHorizontalStrut(30));
              add(contForm2);
              add(Box.createHorizontalStrut(180));
              add(contPrem2);
              // Line 7 - LIAB
              add(liab);
              add(Box.createHorizontalStrut(5));
              add(liabLimit);
              add(Box.createHorizontalStrut(140));
              add(liabPrem1);
              add(Box.createHorizontalStrut(270));
              add(liabPrem2);
              // Line 8 - LIAB Form
              add(form3);
              add(Box.createHorizontalStrut(5));
              add(liabForm);
              add(Box.createHorizontalStrut(460));
              // Line 9 - MED
              add(med);
              add(Box.createHorizontalStrut(5));
              add(medLimit);
              add(Box.createHorizontalStrut(140));
              add(medPrem);
              add(Box.createHorizontalStrut(270));
              // Line 10 - GLASS
              add(glass);
              add(Box.createHorizontalStrut(5));
              add(glassLimit);
              add(Box.createHorizontalStrut(140));
              add(glassPrem);
              add(Box.createHorizontalStrut(280));
              // Line 11 - GRC
              add(grc);
              add(Box.createHorizontalStrut(5));
              add(grcYN);
              add(Box.createHorizontalStrut(440));
              // Line 12 - SUB TOTAL
              add(subTotal);
              add(Box.createHorizontalStrut(175));
              add(subTotalPrem1);
              add(Box.createHorizontalStrut(270));
              add(subTotalPrem2);
         /* (non-Javadoc)
          * @see java.awt.event.FocusListener#focusGained(java.awt.event.FocusEvent)
         public void focusGained(FocusEvent e) {
              // TODO Could adjust color here to look better.
              JComponent theComp = (JComponent) e.getSource();
              if (theComp instanceof JTextField){
                   theComp.setBackground(Color.WHITE);
              System.out.println("theComp = " + theComp);
         /* (non-Javadoc)
          * @see java.awt.event.FocusListener#focusLost(java.awt.event.FocusEvent)
         public void focusLost(FocusEvent e) {
              // TODO Could perform validation checks and do call to rating here.
              JComponent theComp = (JComponent) e.getSource();
              if (theComp instanceof JTextField){
                   theComp.setBackground(BACKGROUND_COLOR);
              System.out.println("theComp = " + theComp);
    }

    Here some code to help anyone run and view my panel:
    Main:
    package GUI;
    import java.awt.Color;
    import javax.swing.JFrame;
    public class ShowPanel extends JFrame{
         public ShowPanel(){
              super();
              setTitle("MY Example");
              getContentPane().add(new CurrCovgPanel(Color.BLUE, 590,240));
              pack();
              setResizable(false);
              setVisible(true);
         public static void main(String[] args){
              ShowPanel a = new ShowPanel();
    }Another need component:
    package inputHandlers;
    import java.awt.Toolkit;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.PlainDocument;
    public class DigitDocument extends PlainDocument{
         private int maxChars;
         public DigitDocument(int maxChars){
              super();
              this.maxChars = maxChars;
         public void insertString(int offs, String str, AttributeSet a) throws BadLocationException, NumberFormatException{
           try{
              if(this.getLength()+str.length() > maxChars) throw new NumberFormatException();//<----
              int i = Integer.parseInt(str);
              super.insertString(offs, str, a);
           catch(NumberFormatException e){
              // do nothing because a user input was not a digit
              Toolkit.getDefaultToolkit().beep();
    }

Maybe you are looking for

  • Every time I try to sync my iphone to my macbook, itunes freezes.

      I have the latest version of itunes but haven't synced my phone since I bought it.  I just spent an hour and a half with apple care support and all they had me do was uninstall and re install itunes and it has done nothing to help me.  Any ideas?

  • How to use counter using PCI 6259

    Hello, users, I have a PCI 6259 board and use Labview 7.1. I'd like to repetitively count the photon signals at 10ms integration time. I want cumulative counts in every 1 sec (1000ms) (or 1 min (60000ms)) And I want to save counts into txt.file which

  • What's the best app for taking a video on ipad2?

    I am a tennis coach and am looking for an app for my iPad2 to do video analysis. I need to be able to video someone doing a serve and then show it to them in slow motion and be able to pause it. What's the best app for this?

  • The CD for iPhoto 2, iMovie 3 would not load in my Apple iBook Dual USB.

    The CD for iPhoto 2, iMovie 3 would not load in my Apple iBook Dual USB. It was "NOT AUTHORIZED". Can anyone tell me what this means? Thank you

  • Runtime Error LIST_TOO_MANY_LPROS

    Hi, I am getting the following runtime error . Dump:   No further list processing possible.                                                                                What happened?                                               You requested too