Drawing an  Image in a ScrollPane

In a Frame application I have to draw an image inside a ScrollPane.
Can you give me an example showing how this can be done ?
Thank you.

Sounds like you are using AWT. Go up to Swing (tutorial at http://java.sun.com/docs/books/tutorial/uiswing/ ) and paint on a custom JPanel which is the scroll pane's view port (you'll find the tutorial in the same place as the Swing one).
Stephen

Similar Messages

  • How to draw an image at the center of a JscrollPane

    I have an image that I want to be centered in my JScrollPane. When I zoom-in, I want the image to fill the entire jscrollpane. When I zoom out it returns to the original scale. My problem is, when I open the image, it appears at the upper left corner of the JScrollPane. I want it centered. Also, when I zoom-in, it gets larger than the scrollpane. That is it goes beyond the boundaries of the JScrollpane. The function I am using to draw the image is:
    Image img = imp.getImage();
                   if (img!=null)
                        g.drawImage(img,0,0, (int)(srcRect.width*magnification), (int)(srcRect.height*magnification),
                        srcRect.x, srcRect.y, srcRect.x+srcRect.width, srcRect.y+srcRect.height, null);If I change the initial x,y values from (0,0) to any other value, it grays the upper left corner. So forinstance, if I did the following, the upper left corner of the scrollpane would become gray.
    g.drawImage(img,100,200, (int)(srcRect.width*magnification), (int)(srcRect.height*magnification),
                        srcRect.x, srcRect.y, srcRect.x+srcRect.width, srcRect.y+srcRect.height,null);How can I center my image in the scrollpane?

    When I zoom-in, I want the image to fill the entire jscrollpane. When I zoom out it returns to the original scaleSo why are you using a scroll pane? A scroll pane is used when its contents can potentially be larger than the scrollpane.
    Although it wasn't originally designed for this purpose you can probably use my [Background Panel|http://www.camick.com/java/blog.html?name=background-panel]. It supports displaying an image at its actual size as well as scaled to fit the panel. So you should just be able to toggle the style as required.

  • How to use the Rectangle class to draw an image and center it in a JPanel

    I sent an earlier post on how to center an image in a JPanel using the Rectangle class. I was asked to send an executable code which will show the malfunction. The code below is an executable code and a small part of a very big project. To simplifiy things, it is just a JFrame and a JPanel with an open dialog. Once executed the JFrame and the FileDialog will open. You can then navigate to a .gif or a .jpg picture and open it. What I want is for the picture to be centered in the middle of the JPanel and not the upper left corner. It is also important to stress that, I am usinig the Rectangle class to draw the Image. The region of interest is where the rectangle is created. In the constructor of the CenterRect class, I initialize the Rectangle class. Then I use paintComponent in the CenterRect class to draw the Image. The other classes are just support classes. The MyImage class is an extended image class which also has a draw() method. Any assistance in getting the Rectangle to show at the center of the JPanel without affecting the size and shape of the image will be greatly appreciated.
    I have divided the code into three parts. They are all supposed to be on one file in order to execute.
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class CenterRect extends JPanel {
        public static Rectangle srcRect;
        Insets insets = null;
        Image image;
        MyImage imp;
        private double magnification;
        private int dstWidth, dstHeight;
        public CenterRect(MyImage imp){
            insets = getInsets();
            this.imp = imp;
            int width = imp.getWidth();
            int height = imp.getHeight();
            ImagePanel.init();
            srcRect = new Rectangle(0,0, width, height);
            srcRect.setLocation(0,0);
            setDrawingSize(width, height);
            magnification = 1.0;
        public void setDrawingSize(int width, int height) {
            dstWidth = width;
            dstHeight = height;
            setSize(dstWidth, dstHeight);
        public void paintComponent(Graphics g) {
            Image img = imp.getImage();
         try {
                if (img!=null)
                    g.drawImage(img,0,0, (int)(srcRect.width*magnification), (int)(srcRect.height*magnification),
              srcRect.x, srcRect.y, srcRect.x+srcRect.width, srcRect.y+srcRect.height, null);
            catch(OutOfMemoryError e) {e.printStackTrace();}
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Opener().openImage();
    class Opener{
        private String dir;
        private String name;
        private static String defaultDirectory;
        JFrame parent;
        public Opener() {
            initComponents();
         public void initComponents(){
            parent = new JFrame();
            parent.setContentPane(ImagePanel.panel);
            parent.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            parent.setExtendedState(JFrame.MAXIMIZED_BOTH);
            parent.setVisible(true);
        public void openDialog(String title, String path){
            if (path==null || path.equals("")) {
                FileDialog fd = new FileDialog(parent, title);
                defaultDirectory = "dir.image";
                if (defaultDirectory!=null)
                    fd.setDirectory(defaultDirectory);
                fd.setVisible(true);
                name = fd.getFile();
                if (name!=null) {
                    dir = fd.getDirectory();
                    defaultDirectory = dir;
                fd.dispose();
                if (parent==null)
                    return;
            } else {
                int i = path.lastIndexOf('/');
                if (i==-1)
                    i = path.lastIndexOf('\\');
                if (i>0) {
                    dir = path.substring(0, i+1);
                    name = path.substring(i+1);
                } else {
                    dir = "";
                    name = path;
        public MyImage openImage(String directory, String name) {
            MyImage imp = openJpegOrGif(dir, name);
            return imp;
        public void openImage() {
            openDialog("Open...", "");
            String directory = dir;
            String name = this.name;
            if (name==null)
                return;
            MyImage imp = openImage(directory, name);
            if (imp!=null) imp.show();
        MyImage openJpegOrGif(String dir, String name) {
                MyImage imp = null;
                Image img = Toolkit.getDefaultToolkit().getImage(dir+name);
                if (img!=null) {
                    imp = new MyImage(name, img);
                    FileInfo fi = new FileInfo();
                    fi.fileFormat = fi.GIF_OR_JPG;
                    fi.fileName = name;
                    fi.directory = dir;
                    imp.setFileInfo(fi);
                return imp;
    }

    This is the second part. It is a continuation of the first part. They are all supposed to be on one file.
    class MyImage implements ImageObserver{
        private int imageUpdateY, imageUpdateW,width,height;
        private boolean imageLoaded;
        private static int currentID = -1;
        private int ID;
        private static Component comp;
        protected ImageProcessor ip;
        private String title;
        protected Image img;
        private static int xbase = -1;
        private static int ybase,xloc,yloc;
        private static int count = 0;
        private static final int XINC = 8;
        private static final int YINC = 12;
        private int originalScale = 1;
        private FileInfo fileInfo;
        ImagePanel win;
        /** Constructs an ImagePlus from an AWT Image. The first argument
         * will be used as the title of the window that displays the image. */
        public MyImage(String title, Image img) {
            this.title = title;
             ID = --currentID;
            if (img!=null)
                setImage(img);
        public boolean imageUpdate(Image img, int flags, int x, int y, int w, int h) {
             imageUpdateY = y;
             imageUpdateW = w;
             imageLoaded = (flags & (ALLBITS|FRAMEBITS|ABORT)) != 0;
         return !imageLoaded;
        public int getWidth() {
             return width;
        public int getHeight() {
             return height;
        /** Replaces the ImageProcessor, if any, with the one specified.
         * Set 'title' to null to leave the image title unchanged. */
        public void setProcessor(String title, ImageProcessor ip) {
            if (title!=null) this.title = title;
            this.ip = ip;
            img = ip.createImage();
            boolean newSize = width!=ip.getWidth() || height!=ip.getHeight();
         width = ip.getWidth();
         height = ip.getHeight();
         if (win!=null && newSize) {
                win = new ImagePanel(this);
        public void draw(){
            CenterRect ic = null;
            win = new ImagePanel(this);
            if (win!=null){
                win.addIC(this);
                win.getCanvas().repaint();
                ic = win .getCanvas();
                win.panel.add(ic);
                int width = win.imp.getWidth();
                int height = win.imp.getHeight();
                Point ijLoc = new Point(10,32);
                if (xbase==-1) {
                    xbase = 5;
                    ybase = ijLoc.y;
                    xloc = xbase;
                    yloc = ybase;
                if ((xloc+width)>ijLoc.x && yloc<(ybase+20))
                    yloc = ybase+20;
                    int x = xloc;
                    int y = yloc;
                    xloc += XINC;
                    yloc += YINC;
                    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
                    count++;
                    if (count%6==0) {
                        xloc = xbase;
                        yloc = ybase;
                    int scale = 1;
                    while (xbase+XINC*4+width/scale>screen.width || ybase+YINC*4+height/scale>screen.height)
                        if (scale>1) {
                   originalScale = scale;
                   ic.setDrawingSize(width/scale, height/scale);
        /** Returns the current AWT image. */
        public Image getImage() {
            if (img==null && ip!=null)
                img = ip.createImage();
            return img;
        /** Replaces the AWT image, if any, with the one specified. */
        public void setImage(Image img) {
            waitForImage(img);
            this.img = img;
            JPanel panel = ImagePanel.panel;
            width = img.getWidth(panel);
            height = img.getHeight(panel);
            ip = null;
        /** Opens a window to display this image and clears the status bar. */
        public void show() {
            show("");
        /** Opens a window to display this image and displays
         * 'statusMessage' in the status bar. */
        public void show(String statusMessage) {
            if (img==null && ip!=null){
                img = ip.createImage();
            if ((img!=null) && (width>=0) && (height>=0)) {
                win = new ImagePanel(this);
                draw();
        private void waitForImage(Image img) {
        if (comp==null) {
            comp = ImagePanel.panel;
            if (comp==null)
                comp = new JPanel();
        imageLoaded = false;
        if (!comp.prepareImage(img, this)) {
            double progress;
            while (!imageLoaded) {
                if (imageUpdateW>1) {
                    progress = (double)imageUpdateY/imageUpdateW;
                    if (!(progress<1.0)) {
                        progress = 1.0 - (progress-1.0);
                        if (progress<0.0) progress = 0.9;
    public void setFileInfo(FileInfo fi) {
        fi.pixels = null;
        fileInfo = fi;
    }

  • Learning iPhone SDK - Trying to draw an image

    Although I have programmed for Mac in the last years, I have never used Mac-specific technologies as Cocoa (I have programmed more in OpenGL, SDL, and the like).
    Now I am getting started with the iPhone SDK. I'd like to do some OpenGL|ES stuff, but since it is not supported in the Simulator, and you need to join the Developer Program to test stuff on directly on the device (and admission of new members is closed right now), I am focused on other stuff right now, like using Core Graphics for drawing images on the iPhone.
    My application is based on the Cocoa Touch Application template. I left the default code except for a few changes.
    In file "UntitledAppDelegate.m", I have changed the method applicationDidFinishLaunching to:
    - (void)applicationDidFinishLaunching:(UIApplication *)application {
    window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    contentView = [[[MyView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
    [window addSubview:contentView];
    [window makeKeyAndVisible];
    Then, in the MyView interface file (MyView.h), I have added the attribute "UIImageView* image;" to the class, which is declared as a property, and synthesized.
    In the class implementation (MyView.m), I have changed the method initWithFrame to:
    - (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
    self.backgroundColor = [UIColor darkGrayColor];
    image = [self loadImageView:@"box01.png"];
    [self addSubview:image];
    return self;
    loadImageView is a private method I have implemented as:
    - (UIImageView *)loadImageView:(NSString *) imageName {
    UIImage *img = [UIImage imageNamed:imageName];
    UIImageView *theView = [[UIImageView alloc] initWithImage:img];
    return theView;
    Since I have loaded the UIImage, and initialized a UIImageView with it, and the image view is added as a subview of the main view attached to the window, I thought it should be everything needed to draw an image on the screen. But nothing is visible. The screen is simply black when I run this on the Simulator. It doesn't even set the background to dark gray.
    So I need some help with this, I sure that anyone with experience in Mac programming will know how to help me.
    Thank you in advance.
    Message was edited by: Jedive

    I removed the XIB file from the project, but that didn't help. It was a problem with my inexperience with Objective-C. When accessing class properties in a method of the same class, i was not putting "self." before the property (in C++ that's redundant). For example, in the line "window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];". After adding it, it works correctly.

  • What's the RIGHT way to draw an image in the upper left corner?

    I have an NSView in a ScrollView and I'm trying to draw an image in it. The problem is that I want the upper left corner of the image locked to the upper left corner of the frame, instead of the lower left corner, which is what the View wants me to do. I will need to be able to zoom in and out, and rotate.
    currently, I have a kludge of a system where I calculate how much I have to translate my image based on the size of the image and the size of the window. In order to do this, I needed to create an extra view outside the scrollview, so that I could get the size of the window, not including decorations. Then I can calculate the size of the view based on the size of the image and the size of the window, and based on THAT, I can figure out where to translate the image to.
    My only other thought was to use the isFlipped: method, but that ends up reversing my image L-R which is bad.
    Is there another way I should be doing this?
    thanks.

    Ah, the problem is that the content view includes the control panel, and while I'm sure I can get access to the control panel, and find out it's size, and then calculate everything off that, it becomes messy, and my way is easier, and no more messy.
    And I never said this was HARD. I have already DONE it. It's just ugly, and I'm wondering if there is a better way to do it. Translating between coordinate systems is normal, but changing lower left to upper left origin is an artifact of the Mac's history with PDF and PS.
    If the way I'm doing it is the accepted normal way, then fine, just tell me that.

  • How do I draw an image on a JPanel?

    To be honest I have no idea even where to start. I tried hacking through the tutorials but it just didn't help me (normally they do, I don't what's up).
    Anyway, so what I'm trying to do is build a game. The Graphics2D is great for simple shapes but drawing characters is getting kind of ridiculous (tedious + difficult + looks bad). So, I need to figure out how to display an image on a JPanel.
    To that end I have several questions.
    1 - What image type do I use? Like jpeg, bmp, gif, etc.
    2 - How do I make parts of it transparent?
    3 - How do I make it appear on the screen, given some coordinates on the JPanel?

    To draw an image directly to a JPanel given certain coordinates, you have to create a custom JPanel and override its paintComponent() method. Like this:
    class PaintPanel extends JPanel{
    public void paintComponent(Graphics g){
    super.paintComponent(g);
    //painting code goes here}
    }Java can load in and draw GIF and JPEG images. If you decide to use GIF files, any good image editor like Adobe Photoshop should be able to make them transparent for you before the fact. If you want to set transparency within your java program you will have to create a BufferedImage and make certain colors within it transparent, but I would like to know how to do that as much as you do.

  • How can I draw an image in the browser using mouse

    I have to draw an image in the browser and have to store a file in the server and I don't know how can I do it. Is there anybody who konw it.

    Components other than applets cannot be downloaded into client machines
    unleess There is a Java Web Start kind of Mechanism present on client and the server also supports
    this .Hence your application is between Applet ---Xdownloadable ApplicationXX ---- traditinal Application

  • Help!How can i draw an image that do not need to be displayed?

    I want to draw an image and save it as an jpeg file.
    first I have to draw all the elements in an image object.I write a class inherit from Class Component,I want to use the method CreateImage,but I get null everytime.And i cannot use the method getGraphics of this object.Thus i can not draw the image.
    when i use an applet,it runs ok.I use panel and frame,and it fails.
    How can i draw an image without using applet,because my programme will be used on the server.
    Thank you.

    you could try this to create the hidden image
    try
              GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
              GraphicsDevice gs = ge.getDefaultScreenDevice();
              GraphicsConfiguration gc = gs.getDefaultConfiguration();
              offImage = gc.createCompatibleImage(100, 100);
              offG = offImage.getGraphics();
          catch(Exception e)
              System.out.println(e.getMessage());
          }

  • Draw circles,images in flex

    How can we draw circles,images in flex? (ex as in
    ms-paint)

    http://livedocs.adobe.com/flex/3/html/help.html?content=Drawing_Vector_Graphics_1.html

  • How do I draw an image through a rectangle?

    I have worked with c# in the past, and i remember being able to draw an image but drawing it within the bounds of the rectangle. I would do this so collision detection was easy. Any suggestions?
    btw since im so very new to the language, i am even having trouble with g.drawImage stuff :(
    any help would be amazing -_-                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    hollow wrote:
    hmm ya i was messing around with that already, i guess im just retarded. i will keep looking thanks! ><No, you are not retarded. You are just incredibly impatient. Take a step back and ease yourself into the language. Take the time to read some articles while you're at it. I would also take a look at JavaFX2, it is a more modern approach to client application development and is less clunky than Java2D with a very active community. It might be that you are more comfortable with it.

  • Drawing static images in flash 8

    Hello Community !
    Does anyone here know what the steps and tools that are used
    to draw static images in Flash 8? Once drawn I would like to import
    them into Dreamweaver 8 nad Illustrator 8. Not to be used as a flah
    movies of Jif or gif.
    Any books you may know about and ofr videos would be great,
    preferably "books" on the subject.
    Thanks
    ATj The Flow

    Thanx Albee!
    albee wrote:
    > you need to define i explicitly:
    >
    >
    >
    > _root.createEmptyMovieClip("fundo",1);
    > fundo.loadMovie("image3.jpg");
    > var fotosArray:Array = ["image1.jpg", "image3.jpg",
    "image7.jpg"];
    > var i:Number = 0;
    > function fotosRotativas() {
    > i == 2 ? i = 0 : i++;
    > loadMovie(fotosArray
    , fundo);
    > }
    > setInterval(fotosRotativas,5000);
    >

  • Load and draw an image

    frist ... sorry for my english.
    i'm loading an image with this code
              try {
                   String imgStr1 = "img/Os1.jpg";
                   String imgStr2 = "img/Os2.jpg";
                   img1 = ImageIO.read(new File(imgStr1));
                   img2 = ImageIO.read(new File(imgStr2));
              catch (IOException e) {
                   JOptionPane.showMessageDialog(null, "No se pudo cargar las imagenes: " + e, "ALERT!!", JOptionPane.ERROR_MESSAGE);
    but i don't know how to draw the image
    please help me
    thanks

    Use ImageIcon on a JLabel.

  • How to draw an Image on a JPanel?

    Hi all,
    Can any one give code for drawing an image on a JPanel?
    thanks,
    amar

    That's for the JLabel right? ... For a JPanel on a JFrame, you could do something like this:
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    import java.net.URL;
    public class TestImagePaint  extends JFrame {
      private BjPanel bjp;
      public TestImagePaint( String imageName )   throws IllegalArgumentException {
        if ( imageName == null  ||  !( new File( imageName ).isFile() ) ) {
          throw new IllegalArgumentException( "\nIn TestImagePaint constuctor"
                                             +"\t IllegalArgumentException:" );
        bjp = new BjPanel( imageName );
        getContentPane().add( bjp );
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setBounds( 100, 100, 400, 300 );
        setVisible( true );
      public static void main( String[] argv ) {
        new TestImagePaint( argv[0] );
      public class BjPanel  extends JPanel {
        private URL   url;
        private Image image;
        public BjPanel( String imageName ) {
          try {
            url   = BjPanel.class.getResource( imageName );
            image = Toolkit.getDefaultToolkit().getImage( url );
            repaint();
          catch( Exception e ) {
            System.out.println( "Can't get Image: "+imageName+"\n\t"+e );
            System.exit( -1 );
        public void paint(Graphics g) {
          g.drawImage( image, 0, 0, this );
    }

  • How to draw an image on transparent JPanel?

    I want to draw an image on the transparent JPanel. How to do it?
    I do like this:
    ( In constructor )
    setOpaque(false);
    String imageName = "coral.jpg";
    iimage_Bg = Toolkit.getDefaultToolkit().getImage(imageName);
    ( In paintComponent( Graphics g ) )
    Graphics2D g2D = (Graphics2D) g;
    g2D.drawImage( iimage_Bg, 0, 0, getWidth() , getHeight() , Color.white, null );
    But it doesn't work. Please help me!
    Thank you very much.
    coral9527

    Check the values that are returned from getWidth() and getHeight(). If they either are zero, then paintComponent(Graphics g) never gets called by the components paint(Graphics g) method. I cannot see the how this component has been added or displayed so can give no advice on how you can guarantee getting a valid size. If you have simply added it to a JFrame and called pack(), the size will be zero, as the panel does not contain any components (you would not have this problem if you were adding a JLabel with an ImageIcon for example). Try not packing the frame, and giving it a valid size.

  • Blackjack drawing multiple images problem

    Hi. Im making a blackjack game and im having some trouble drawing the images.
    The drawing is fine. But the problem is when to draw new cards. I dont know how to draw a new card without the old one dissapearing. I understand why it dissapears as the code is now, but i dont know how to fix it. Somehow i have to make each card beeing able to paint itself on the board? The filenames of the images to be drawn is fetched by the getCard() in the card class. Since blackjack doesnt use that many cards in play at the same time its possible to simply make more image variables and some if statements deciding which to paint, but that sollution isnt very nice, and i want to make more advanced cardgames after this, so if someone could help me with this it would truly be great.
    Thanks.
    Image displaying board after first new card is dealed, and third one
    http://www.wannerskog.com/newcards.jpg
    Card Class
    public class Card {
         private int value;
         private String color;
         public Card(String incolor,int invalue) {
              value = invalue;
              color = incolor;
         public String getCard() {
              return value+color;
         public int getValue() {
              return value;
    Deck
    import java.util.*;
    //Creates a deck of cards
    public class Deck {
         Card card;
         private Set deck = new HashSet();
         List deck2;
         public void createDeck() {
              for(int i=2; i<=14; i++) {
                   card = new Card("s",i);
                   deck.add(card);
              for(int i=2; i<=14; i++) {
                   card = new Card("h",i);
                   deck.add(card);
              for(int i=2; i<=14; i++) {
                   card = new Card("c",i);
                   deck.add(card);
              for(int i=2; i<=14; i++) {
                   card = new Card("d",i);
                   deck.add(card);
              deck2 = new Vector(deck);
         public void shuffleDeck() {
              Collections.shuffle(deck2);
         public List getDeck() {
              return deck2;
    Dealer Class
    import java.util.*;
    public class Deal {
         Deck deck = new Deck();
         private String card1;
         private String card2;
         public Deal() {
              deck.createDeck();
              deck.shuffleDeck();
         public void dealCards(int j) {
              deck.shuffleDeck();
              List d = (List)deck.getDeck();
              Card card;
              Iterator it = d.iterator();
              String card1 = "";
              String card2 = "";
              for(int i=1; i<=j; i++) {
                   card = (Card)it.next();
                   if(i==1) card1 = card.getCard();
                   if(i==2) card2 = card.getCard();
              this.card1 = card1;
              this.card2 = card2;
         public String getCard1() {
              return card1;
         public String getCard2() {
              return card2;
    Jpanel displaying the buttons
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Controll extends JPanel {
         JButton deal = new JButton("Deal");
         JButton newcard = new JButton("New card");
         JButton stay = new JButton("Stay");
         JButton exit = new JButton("Exit");
         public Controll(View view) {
         final Deal d = new Deal();
         final View v = view;
              class ChoiceListener implements ActionListener
                   int i=0;
                   public void actionPerformed(ActionEvent event) {
                        if("deal".equals(event.getActionCommand()))
                             d.dealCards(2);
                             stay.setEnabled(true);
                             newcard.setEnabled(true);
                             deal.setEnabled(false);
                             v.dealCards(d.getCard1(),d.getCard2());
                             v.resetNew();
                             v.repaint();
                             i=0;
                        if("exit".equals(event.getActionCommand()))
                             System.exit(0);
                        if("newcard".equals(event.getActionCommand()))
                             if(i != 3) {
                                  d.dealCards(1);
                                  v.newCard(d.getCard1(),20);
                                  v.repaint();
                                  i++;
                             if(i == 3) {
                                  newcard.setEnabled(false);
                                  stay.setEnabled(false);
                                  deal.setEnabled(true);
                        if("stay".equals(event.getActionCommand()))
                             deal.setEnabled(true);
                             stay.setEnabled(false);
                             newcard.setEnabled(false);
              Color c = new Color(0, 0, 100);
              setPreferredSize(new Dimension(400, 40));
              setBackground(c);
              ActionListener listener = new ChoiceListener();
              deal.setActionCommand("deal");
              exit.setActionCommand("exit");
              newcard.setActionCommand("newcard");
              stay.setActionCommand("stay");
              exit.addActionListener(listener);
              deal.addActionListener(listener);
              newcard.addActionListener(listener);
              stay.addActionListener(listener);
              add(deal);
              add(newcard);
              add(stay);
              add(exit);
              stay.setEnabled(false);
              newcard.setEnabled(false);
    JPanel displaying the board with cards
    import java.awt.*;
    import javax.swing.*;
    import java.awt.image.*;
    import java.awt.event.*;
    public class View extends JPanel {
         String dealcard1;
         String dealcard2;
         String newcard;
         int i;
         private Image cardimage1 = null;
         private Image cardimage2 = null;
         private Image cardimage3 = null;
         public View() {
              Color c = new Color(0, 100, 0);
              setPreferredSize(new Dimension(400, 300));
              setBackground(c);
         public void dealCards(String incard1, String incard2) {
              dealcard1 = incard1;
              dealcard2 = incard2;
         public void newCard(String incard3,int j){
              newcard = incard3;
              i = i+j;
         public void resetNew() {
              i=0;
              newcard = "";
         public void paint(Graphics g) {
              super.paint(g);
              Toolkit kit = Toolkit.getDefaultToolkit();
              cardimage1 = kit.getImage("CardImages/"+dealcard1+".gif");
              cardimage2 = kit.getImage("CardImages/"+dealcard2+".gif");
              cardimage3 = kit.getImage("CardImages/"+newcard+".gif");
              g.drawImage(cardimage1,80,200,this);
              g.drawImage(cardimage2,100,200,this);
              g.drawImage(cardimage3,180+i,200,this);
    Main
    import javax.swing.*;
    import java.awt.*;
    public class Main
         public static void main(String[] args)
                   JFrame frame = new JFrame("card");
                   View v = new View();
                   Controll c = new Controll(v);
                   frame.getContentPane().add(v, BorderLayout.NORTH);
                   frame.getContentPane().add(c, BorderLayout.SOUTH);
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frame.pack();
                   frame.show();
    }

    Actually, your app looks okay. Since you asked for some ideas I made some changes, including changing the name of some classes, variables and the image folder. I put all the files in one because I'm lazy. Score is the only class without changes. And nice images.
    Some suggestions:
    1 � try to keep the responsibilities of the View/CardTable class limited to rendering images. You only need to load an image once; continual loading makes for slow performance. If you are using j2se 1.4+ you can use the ImageIo read methods and could then load the images in the Deck class, eliminating the need to pass the images to Deck from View/CardTable (which is an ImageObserver needed for the MediaTracker).
    2 � let the classes do more of the work, eg, Deal/Dealer can add the new cards to the View/CardTable. This will simplify the event code. The ChoiceListener class could be an inner named/nested class and will be easier to follow/maintain if removed from the class constructor.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    public class CardGame
        public static void main(String[] args)
            JFrame frame = new JFrame("card");
            CardTable table = new CardTable();
            Controller control = new Controller(table);
            frame.getContentPane().add(table, BorderLayout.NORTH);
            frame.getContentPane().add(control, BorderLayout.SOUTH);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
    class CardTable extends JPanel {
        Image[] images;
        Image cardBack;
        private String score;
        List player, house;
        public CardTable() {
            loadImages();
            score = "0";
            player = new ArrayList();
            house = new ArrayList();
            Color c = new Color(0, 100, 0);
            setPreferredSize(new Dimension(400, 300));
            setBackground(c);
        public void setScore(int score) {
            this.score = String.valueOf(score);
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            int x = 80, y = 50;
            Card card;
            for(int j = 0; j < house.size(); j++) {
                card = (Card)house.get(j);
                if(j == 0)
                    g.drawImage(cardBack, x, y, this);
                else
                    g.drawImage(card.getImage(), x, y, this);
                x += 20;
            x = 80; y = 200;
            for(int j = 0; j < player.size(); j++)
                card = (Card)player.get(j);
                g.drawImage(card.getImage(), x, y, this);
                x += 20;
            g.setColor(Color.white);
            g.drawString("Score: " + score, 345, 15);
        public void reset() {
            player.clear();
            house.clear();
            repaint();
        public void addCard(Card card)
            player.add(card);
            repaint();
        public void addDealerCard(Card card)
            house.add(card);
            repaint();
        private void loadImages() {
            String[] suits = { "c", "h", "s", "d" };
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            MediaTracker tracker = new MediaTracker(this);
            cardBack = toolkit.getImage("cards/00w.gif");
            tracker.addImage(cardBack, 0);
            images = new Image[suits.length * 13];
            int index = 0;
            for(int j = 0; j < suits.length; j++)
                for(int k = 2; k < 15; k++)
                    String fileName = "cards/" + k + suits[j] + ".gif";
                    images[index] = toolkit.getImage(fileName);
                    tracker.addImage(images[index], 0);
                    index++;
            try
                tracker.waitForAll();
            catch(InterruptedException ie)
                System.out.println("Image loading in CardTable interrupted: " +
                                    ie.getMessage());
    class Controller extends JPanel {
        CardTable table;
        Dealer d;
        JButton deal, newcard, stay, exit;
        public Controller(CardTable ct) {
            table = ct;
            d = new Dealer(table, table.images);
            Color c = new Color(0, 0, 100);
            setPreferredSize(new Dimension(400, 40));
            setBackground(c);
            deal = new JButton("Deal");
            newcard = new JButton("New card");
            stay = new JButton("Stay");
            exit = new JButton("Exit");
            deal.setActionCommand("deal");
            exit.setActionCommand("exit");
            newcard.setActionCommand("newcard");
            stay.setActionCommand("stay");
            ActionListener listener = new ChoiceListener();
            exit.addActionListener(listener);
            deal.addActionListener(listener);
            newcard.addActionListener(listener);
            stay.addActionListener(listener);
            add(deal);
            add(newcard);
            add(stay);
            add(exit);
            stay.setEnabled(false);
            newcard.setEnabled(false);
        private class ChoiceListener implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                String ac = event.getActionCommand();
                if(ac.equals("deal")) {
                    d.prepareDeck();
                    table.reset();
                    d.dealCards(2);
                    d.dealDealerCards(2);
                    stay.setEnabled(true);
                    newcard.setEnabled(true);
                    deal.setEnabled(false);
                    Score s = d.getScore();
                    table.setScore(s.getScore());
                if(ac.equals("exit"))
                    System.exit(0);
                if(ac.equals("newcard"))
                    d.dealCards(1);
                    Score s = d.getScore();
                    table.setScore(s.getScore());
                    if(s.getScore() > 21) {
                        stay.setEnabled(false);
                        newcard.setEnabled(false);
                        deal.setEnabled(true);
                        s.resetScore();
                if(ac.equals("stay"))
                    deal.setEnabled(true);
                    stay.setEnabled(false);
                    newcard.setEnabled(false);
                    Score s = d.getScore();
                    table.setScore(s.getScore());
    class Dealer {
        CardTable table;
        Deck deck;
        Iterator it;
        private int score;
        private int dealerScore;
        Score s;
        public Dealer(CardTable ct, Image[] images) {
            table = ct;
            deck = new Deck(images);
            score = 0;
            dealerScore = 0;
            s = new Score();
        public void dealCards(int j) {
            Card card;
            for(int i = 0; i < j; i++) {
                card = (Card)it.next();
                table.addCard(card);
                if(card.getValue() > 10)
                    score += 10;
                else
                    score += card.getValue();
            s.setScore(score);
            score = 0;
        public void dealDealerCards(int j) {
            Card card;
            for(int i = 0; i < j; i++) {
                card = (Card)it.next();
                table.addDealerCard(card);
                if(card.getValue() > 10)
                    dealerScore += 10;
                else
                    dealerScore += card.getValue();
            s.setDealerScore(dealerScore);
            dealerScore = 0;
        public void prepareDeck() {
            deck.shuffle();
            it = deck.getCards().iterator();
        public Score getScore() {
            return s;
    class Score {
        private int score;
        public void setScore(int s) {
            score = score + s;
        public void resetScore() {
            score = 0;
        public int getScore() {
            return score;
        private int dealerScore;
        public void setDealerScore(int s) {
            dealerScore = dealerScore + s;
            System.out.println("DEALER: " + dealerScore);
        public void resetDealerScore() {
            dealerScore = 0;
        public int getDealerScore() {
            return dealerScore;
    class Deck {
        List cards;
        public Deck(Image[] images) {
            cards = new ArrayList();
            createDeck(images);
        private void createDeck(Image[] images) {
            for(int j = 0; j < images.length; j++)
                int value = j % 13 + 2;
                cards.add(new Card(images[j], value));
        public void shuffle() {
            for(int j = 0; j < 4; j++)
                Collections.shuffle(cards);
        public List getCards() {
            return cards;
    class Card {
        private Image image;
        private int value;
        public Card(Image image, int value) {
            this.image = image;
            this.value = value;
        public Image getImage() {
            return image;
        public int getValue() {
            return value;
    }

Maybe you are looking for