JComponent

Hi -
I have a class C that extends JComponent. having an x & y co-ordinate. (setLocation).
Objects of class C will later be added to a JPanel and displayed in a JFrame.
I want to add an icon (gif from disk) to C objects and also join them by a line (C objects hold a list of adjectent objects of the same class).
I'm really stuck on the icon and line drawing bit. I've been told to use the 'void pain (Graphics)' method, but 2 days later i'm none the wiser.
Any help greatly appreciated
J

public class ClassCofJb90 extends JComponent{
  public void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawImage( ..... );
    g.drawLine( ..... );
    // you might want repeat the above draw methods in a loop
}

Similar Messages

  • 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 ... :-(

  • 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));
    }

  • 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();
    }

  • Cannot See Components Added To JComponent

    Hi,
    It seems that components added to direct descendents of JComponent are not visible. Please see the following pseudocode:
    // In the following b is NOT visible:
    class MyComponent extends JComponent{}
    b = JButton("OK")
    p = MyComponent()
    p.add(b)
    f = JFrame()
    f.contentPane.add(p)
    f.show()
    // In the following b IS visible:
    b = JButton("OK")
    p = JPanel()
    p.add(b)
    f = JFrame()
    f.contentPane.add(p)
    f.show()
    How does one make JComponent-added components visible?
    Thanx
    --A                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Components and Containers are a bit different. Try calling paintChildren on your custom component like this:
    public void paintComponent(Graphics g){
       ...//do what you need to
       paintChildren(g);

  • How painting behind a JComponent ?

    Hi all,
    I'm trying to paint stuff like shadows, frames (not borders), etc. behind JComponents.
    So every shape only intersects with the relative JComponent's one.
    Cannot paint these stuff in the container's paintComponent() method since more widgets can have one or more of them, so I guess It should be better do the job in every child's paintComponent() method.
    What follows was the code I tested but doesn't work.
    Any hints ? Thanks in advance.
    Lucio
    import java.awt.*;
    import javax.swing.*;
    public class UpButton extends JButton {
        Dimension dimension = new Dimension(100, 100);
        Point point = new Point(100, 100);
        public UpButton(String text) {
         setSize(dimension);
         setLocation(point);
         setBackground(new Color(255,186,26));
         setText(text);
        public void paintComponent(Graphics g) {
         Component c = (Component) getParent();
         Graphics2D g2 = (Graphics2D)
                                      c.getGraphics().create(0,0,dimension.width,dimension.height);
         g2.translate(-(point.x + 10), -(point.y + 5));
         g2.setPaint(Color.gray);
         g2.fill(new Rectangle(dimension));
         g2.dispose();
         super.paintComponent(g);
        public static void main(String[] args) {
         JFrame jFrame = new JFrame();
         jFrame.getContentPane().setLayout(null);
         jFrame.add(new UpButton("Test"));
         jFrame.setSize(300,300);
         jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jFrame.setVisible(true);
    }

    I'm very grateful to you, weebib
    I was missing the setClip method, now perfectly works.
    It doesn't seems to me too difficult (now ;-)
    Here my modified version :
    import java.awt.*;
    import javax.swing.*;
    public class UpButton extends JButton {
        Dimension dimension = new Dimension(100, 100);
        Point point = new Point(100, 100);
        public UpButton(String text) {
         setSize(dimension);
         setLocation(point);
         setBackground(new Color(255,186,26));
         setText(text);
        public void paintComponent(Graphics g) {
         Graphics2D g2 = (Graphics2D) g.create();
         g2.translate(10, 5);
         g2.setClip(0, 0, 100, 100);
         g2.setPaint(Color.gray);
         g2.fill(new Rectangle(dimension));
         g2.dispose();
         super.paintComponent(g);
        public static void main(String[] args) {
         JFrame jFrame = new JFrame();
         jFrame.getContentPane().setLayout(null);
         jFrame.add(new UpButton("Test"));
         jFrame.setSize(300,300);
         jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jFrame.setVisible(true);
    }

  • SetBackground() useless for JComponent?

    if you extend JComponent and then use setBackground(Color.RED), actually there is no change of the background.
    According to the API doc,
    public void setBackground(Color bg)
    Sets the background color of this component. The background color is used only if the component is opaque, and only by subclasses of JComponent or ComponentUI implementations. Direct subclasses of JComponent must override paintComponent to honor this property.
    It is up to the look and feel to honor this property, some may choose to ignore it.
    even if I set the JComponent to be opaque or override paintComponent() method, it doesn't work.
    codes are as follow:
    class MyComponent extends JComponent
    {   public void paintComponent(Graphics g)
        {    setOpaque(true);
             setBackground(Color.RED);  // no use :(
    }so how to interpretate that method detail of api doc? and how to use setBackgound() method to set the background color of a JComponent.
    BTW, if i extend JPanel instead, then in the paintComponent() method, I have to call super.paintComponent(g) --> why so?
    thx in advance

    so if i want to fill the background with RED (it already has some shapes painted on it)I suggest you read about Swing's painting architecture, as described in the tutorial .
    When paintComponent() is invoked (by the Swing painting framework) it is supposed to paint everything (background +++ "other shapes") in the painting rectangle, except:
    - the components underneath (which may appear if your own component is translucent, but that's a bit involved), including the immediate parent Container and its parent container hierarchy, which have automatically paint themselves in that area when their own paintComponent method, before your paintComponent() method was called in turn
    - the components above, which will automatically paint themselves over what your paintComponent() method is just painting, when their own paintComponent method is called in turn.
    If your JComponent subclass paints two things (say, a background fill, and green squares on top of that), it has to paint both each time your paintComponent is called, on the supllied Graphics rectangle.
    class MyComponent extends JComponent
    {   public MyComponent()
        {    setBackground(Color.RED);
        public void paintComponent(Graphics g)
        {    Graphics2D g2=(Graphics2D)g;
             g2.fill(...); // rectangle of background color
             g2.draw(...); // whatever is supposed to appear on top
    if it is g2.fillRect(0,0,getWidth(),getHeight()), then it will cover other drawings on the component.Maybe, but you will redraw those drawings just after filling the rectangle, so they will appear anyway.
    Now if you're concerned with doing an animation, there are a lot of techniques to optimize painting so as to not repaint everything, but do some practice and research before discussing them, as you seem to begin with Swing.
    Good luck.

  • Extending JComponent  and creating new derived class

    <!--[if gte mso 9]><xml>
    Normal
    0
    false
    false
    false
    EN-US
    X-NONE
    X-NONE
    MicrosoftInternetExplorer4
    </xml><![endif]--><!--[if gte mso 9]><xml>
    </xml><![endif]-->
    <!--[if gte mso 10]>
    <style>
    /* Style Definitions */
    table.MsoNormalTable
    {mso-style-name:"Table Normal";
    mso-tstyle-rowband-size:0;
    mso-tstyle-colband-size:0;
    mso-style-noshow:yes;
    mso-style-priority:99;
    mso-style-qformat:yes;
    mso-style-parent:"";
    mso-padding-alt:0in 5.4pt 0in 5.4pt;
    mso-para-margin-top:0in;
    mso-para-margin-right:0in;
    mso-para-margin-bottom:10.0pt;
    mso-para-margin-left:0in;
    line-height:115%;
    mso-pagination:widow-orphan;
    font-size:11.0pt;
    font-family:"Calibri","sans-serif";
    mso-ascii-font-family:Calibri;
    mso-ascii-theme-font:minor-latin;
    mso-fareast-font-family:"Times New Roman";
    mso-fareast-theme-font:minor-fareast;
    mso-hansi-font-family:Calibri;
    mso-hansi-theme-font:minor-latin;}
    </style>
    <![endif]-->
    Dear Friends,
    I developed new component SwingComponent and I extends it
    from JComponent and also implements
    the interfaces like
    KeyListener and MouseListener .. but when I press ctrl+b and ctrl +n  it wont recognize in the KeyEvent but it works fine if i press  individual keys. Please give me an idea
    public class SwingComponent extends JComponent implements
    KeyListener,
    MouseListener{

    This one working fine for individual character for example if i press 'A' in keyborad it was working but how to activate if i press ctrl + n or ctrl + b in the JComponent or Component. did you got my question?
    private KeyListener keyListener;
         public void addKeyListener(KeyListener listener) {
                  keyListener = AWTEventMulticaster.add(keyListener, listener);
              enableEvents(AWTEvent.KEY_EVENT_MASK);
         public void removeKeyListener(KeyListener listener) {
              keyListener = AWTEventMulticaster.remove(keyListener, listener);
         public void processKeyEvent(KeyEvent evt) {
              if (keyListener != null) {
                   System.err.println("" + evt.getKeyChar() + " " +                                    
                                        evt.getKeyCode());
                   switch (evt.getID()) {
                   case KeyEvent.KEY_PRESSED:
                        keyListener.keyPressed(evt);
                        break;
                   case KeyEvent.KEY_RELEASED:
                        keyListener.keyReleased(evt);
                        break;
                   case KeyEvent.KEY_TYPED:
                        keyListener.keyTyped(evt);
                        break;
              super.processKeyEvent(evt);
           public void keyTyped(KeyEvent e) {
                     System.out.println(e.getKeyChar());
         public void keyPressed(KeyEvent e) {
                System.out.println(e.getKeyCode());
         public void keyReleased(KeyEvent e) {
                 System.out.pirntln(e.getKeyCode());
              }

  • JComponent needs to be painted on creation

    I have a Card class that extends JComponent. The paintComponent method is implemented. Added it to a JPanel. Added the JPanel to the JFrame. The JComponent only shows up when the frame is resized, not when the frame is first shown on screen. The only fix I can think of is to place a method in the constructor of JComponent that paints itself on creation. Has anyone had this problem before?
    public Card(Rank rank, Suit suit, String img) {
            super();
            this.rank = rank;
            this.suit = suit;
            this.image = Toolkit.getDefaultToolkit().createImage(img);
         setPreferredSize(new Dimension(400, 300));
         setVisible(true);
    public void paintComponent(Graphics g) {
    boolean x = g.drawImage(this.image, getX(), getY(), null);
    }

    If I'm not mistaken, the Toolkit#createImage() methods do asynchronous loading of the image, so when your JFrame is being displayed, the image hasn't been fully loaded yet. Use a method of loading the image that blocks until it's complete, such as ImageIO. Here's a working example:
    import java.awt.*;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class ImageJPanelTest extends JFrame {
         public ImageJPanelTest() {
              JPanel contentPane = new Card();
              setContentPane(contentPane);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setTitle("Image JPanel Test");
              pack();
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        new ImageJPanelTest().setVisible(true);
         class Card extends JPanel {
              private Image image;
              public Card() {
                   String img = "anchor.png";
                   // Commented-out line requires the frame to be resized/moved/etc.
                   // before image is shown.  The lines following it show the image
                   // immediately.
                   //image = Toolkit.getDefaultToolkit().createImage(img);
                   try {
                        image = ImageIO.read(new File(img));
                   } catch (IOException ioe) {
                        ioe.printStackTrace();
                        image = null; // Create a default image to prevent NPE later
                   setPreferredSize(new Dimension(400, 300));
              public void paintComponent(Graphics g) {
                   g.drawImage(image, 0,0, null);//getX(), getY(), null);
    }

Maybe you are looking for

  • HDMI Closed Clamshell mode display wake crash with Mavericks.

    Hi! Macbook Pro 2.8 GHz Intel i7, 16GB DDR3 RAM, OS X 10.9.3 So, I am running a macbook pro with an external HD display through the HDMI out on the computer, and the comptuer itself running in closed clamshell mode. Sometimes when the display sleeps

  • Cut & paste doesn't work most of time in finder

    anyone knows why and how to fix it?

  • Career query in NW

    Hi , I am an ABAP developer having an year experience, currently I wanted to update my skill set with netweaver technology.I have no experience in JAVA ,, but did a core java course and wanted to do J2ee having an idea to go with EP. I havent started

  • "Distorted Playback"?

    When I import 1920x1080 video into iMovie, I am notified that "selecting [full video quality] may result in degraded video playback on this computer." When I do import the video at full resolution, I do get degraded video, with weird lines going hori

  • Class to find the components of a field-symbol

    Hi, Can anyone tell any class/function module to get the components of a field-symbol which is like an internal table. Thanks.