Problem drawing tiled image

I have a tiled buffred image. I have implemented caching and tiling myself i.e. the complete image (that can be as big as 100+MB) is tiled into 512x512 tiles and i am keeping them in a cache implemented as hashmap. The cache size is adjusted based on the available memory.
My logic is that when the user scrolls the image i figure out the tiles that needed to be shown to the user and then see if i can find it in the cache, in case of a cache miss i create the tile in memory (using createCompatibleImage()). Once the tile is created i stuff it in my cache. After making sure the required tiles are available i then simply use drawImage(tile,x,y,null) to draw the tiles inside the paintComponent() method. My problem is that the tiles get drawn erratically i.e. if the viewport requires six tiles to be drawn then every so often few of the tiles do not get drawn. I have made sure that the my program does call drawImage() six times once for each tile - but it seems that despite drawImage call the actual drawing has a mind of its own.
I do not suspect my tile creation or cachig code since when someof the tiles are not shown properly all i have to do is to move mouse over the undrawn area and the tiles appear immediately.
My code is spread all over so it is difficult to produce all the relevant code in here, so i will give some code snippet:
// Code for creating a new tile
public createTile()
GraphicsConfiguration gc = Utility.getDefaultConfiguration();
BufferedImage overlayImage = gc.createCompatibleImage(width, height);
int ii = 0;
int jj = 0;
     for (int i= 0; i<width; i++){                
          for (int j=0; j<height; j++){
               int rgb = ....;//the rgb is calculated based on some specific logic.
               overlayImage.setRGB(ii,jj,rgb);
               jj++;
          ii++;
          jj = 0;
// After creating the image I then resize the image to handle zoom in/zoom out
// using nearest neighbor interpolation. I don't suspect the resize code so
// have not reporduce it here.
     return (resizeImage(overlayImage,newWidth,newHeight)).
====================================================
// Extract of some of my paint code is given below.
//I am not calling super.paintComponent() because i am redrawing the
// whole screen with my tiled image.
  public void paintComponent(Graphics g)
       Graphics2D g2d = (Graphics2D)g;
     Tile[]tiles = getChosenTiles();
               for (int i=0; i<tiles.length; i++){
                    g2d.drawImage(tiles.getImage(), tiles[i].x, tiles[i].y, null);

Since nobody replied to the post - i had no option but to dig into the problem myself. Good thing is that I managed to find the solution.
As it turned out my logic was as below:
Step 1: find out the tiles that need to be shown on the viewport.
Step 2: obtain these tiles from the cache
Step 2a: If tiles not found in cache then create the tiles in memory.
Step 3: for (int i=0;i<tiles.length; i++) {             
                g2d.drawImage(tiles.getImage(), null, tiles[i].x, tiles[i].y);
The problem was that for some reason the Java graphics drawing could not keep up with the for loop. What i did was to move the drawing logic inside Step 2. i.e. I would get a tile and then draw it immediately after getting it. In other words the logic was changed to
Step 1: find out the tiles that need to be shown on the viewport
Step 2:
             for (int i=0;i<tiles.length; i++) {
                 BufferedImage image = tiles.getImage();
if (image == null) {
image = createTileImage(tiles[i]);
tiles[i].setImage(image);
g2d.drawImage(tiles[i].getImage(), null, tiles[i].x, tiles[i].y);
This solved my problem.
-km

Similar Messages

  • Problems drawing image

    Im sorry for even askign this but i'm having problems drawing an image, no idea why its not working!!! I know that my Image object actually is the image because i can get it to display on a button, but i need to get it to display in the JPanel through the paintComponent() method, for some reason it wont do it. Thanks for the help.
    Here's my code
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class StatWindow extends JDialog{
        private StatPanel panel;
        public StatWindow(JFrame parent) {
            this(parent, null);
        public StatWindow(JFrame parent, String data){
            super(parent, "Stat", false);
            getContentPane().setLayout(null);
            panel = new StatPanel();
            getContentPane().add(panel);
            panel.setBounds(0, 0, 220, 220);
            setSize(300, 300);
            setVisible(true);
        class StatPanel extends JPanel{
            private Image diagram1;
            private Image diagram2;
            private Image diagram3;
            private Image diagram4;
            private Image diagram5;
            private Image diagram6;
            private Image diagram7;
            private Image diagram8;
            private Image diagram9;
            private Image diagram10;
            private Image diagram11;
            private Image diagram12;
            private Image diagram13;
            private Image diagram14;
            private Image diagram15;
            private Image diagram16;
            private Image diagram17;
            private Image diagram18;
            private Image diagram19;
            private Image diagram20;
            private Image diagram21;
            private Image diagram22;
            private Image diagram23;
            private Image diagram24;
            private Image diagram25;
            private Image diagram26;
            private Image diagram27;
            public StatPanel(){
                super();
                Image diagram1 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_01.jpg"));
                Image diagram2 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_02.jpg"));
                Image diagram3 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_03.gif"));
                Image diagram4 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_04.jpg"));
                Image diagram5 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_05.jpg"));
                Image diagram6 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_06.jpg"));
                Image diagram7 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_07.gif"));
                Image diagram8 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_08.jpg"));
                Image diagram9 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_09.jpg"));
                Image diagram10 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_10.jpg"));
                Image diagram11 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_11.gif"));
                Image diagram12 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_12.jpg"));
                Image diagram13 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_13.jpg"));
                Image diagram14 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_14.gif"));
                Image diagram15 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_15.gif"));
                Image diagram16 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_16.jpg"));
                Image diagram17 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_17.jpg"));
                Image diagram18 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_18.gif"));
                Image diagram19 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_19.jpg"));
                Image diagram20 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_20.jpg"));
                Image diagram21 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_21.jpg"));
                Image diagram22 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_22.gif"));
                Image diagram23 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_23.jpg"));
                Image diagram24 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_24.gif"));
                Image diagram25 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_25.jpg"));
                Image diagram26 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_26.jpg"));
                Image diagram27 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_27.jpg"));
                addMouseMotionListener(new MouseMotionHandler());
                addMouseListener(new MouseHandler());
                JButton b = new JButton(new ImageIcon(diagram1));
                getContentPane().add(b);
                b.setBounds(0, 0, 40, 40);
            class MouseMotionHandler extends MouseMotionAdapter{
                public void mouseMoved(MouseEvent e){
            class MouseHandler extends MouseAdapter{
                public void mousePressed(MouseEvent e){
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D)g.create();
                g2d.drawImage(diagram1, 0, 0, this);
                g2d.dispose();
    }

    you have these declarations
    private Image diagram1;
    private Image diagram2;
    and in your constructor you have these
    Image diagram1 = getToolkit().getImage...
    Image diagram2 = getToolkit().getImage...
    the inclusion of the 'type' Image makes them local to the constructor

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

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

  • Server goes out of memory when annotating TIFF File. Help with Tiled Images

    I am new to JAI and have a problem with the system going out of memory
    Objective:
    1)Load up a TIFF file (each approx 5- 8 MB when compressed with CCITT.6 compression)
    2)Annotate image (consider it as a simple drawString with the Graphics2D object of the RenderedImage)
    3)Send it to the servlet outputStream
    Problem:
    Server goes out of memory when 5 threads try to access it concurrently
    Runtime conditions:
    VM param set to -Xmx1024m
    Observation
    Writing the files takes a lot of time when compared to reading the files
    Some more information
    1)I need to do the annotating at a pre-defined specific positions on the images(ex: in the first quadrant, or may be in the second quadrant).
    2)I know that using the TiledImage class its possible to load up a portion of the image and process it.
    Things I need help with:
    I do not know how to send the whole file back to servlet output stream after annotating a tile of the image.
    If write the tiled image back to a file, or to the outputstream, it gives me only the portion of the tile I read in and watermarked, not the whole image file
    I have attached the code I use when I load up the whole image
    Could somebody please help with the TiledImage solution?
    Thx
    public void annotateFile(File file, String wText, OutputStream out, AnnotationParameter param) throws Throwable {
    ImageReader imgReader = null;
    ImageWriter imgWriter = null;
    TiledImage in_image = null, out_image = null;
    IIOMetadata metadata = null;
    ImageOutputStream ios = null;
    try {
    Iterator readIter = ImageIO.getImageReadersBySuffix("tif");
    imgReader = (ImageReader) readIter.next();
    imgReader.setInput(ImageIO.createImageInputStream(file));
    metadata = imgReader.getImageMetadata(0);
    in_image = new TiledImage(JAI.create("fileload", file.getPath()), true);
    System.out.println("Image Read!");
    Annotater annotater = new Annotater(in_image);
    out_image = annotater.annotate(wText, param);
    Iterator writeIter = ImageIO.getImageWritersBySuffix("tif");
    if (writeIter.hasNext()) {
    imgWriter = (ImageWriter) writeIter.next();
    ios = ImageIO.createImageOutputStream(out);
    imgWriter.setOutput(ios);
    ImageWriteParam iwparam = imgWriter.getDefaultWriteParam();
    if (iwparam instanceof TIFFImageWriteParam) {
    iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    TIFFDirectory dir = (TIFFDirectory) out_image.getProperty("tiff_directory");
    double compressionParam = dir.getFieldAsDouble(BaselineTIFFTagSet.TAG_COMPRESSION);
    setTIFFCompression(iwparam, (int) compressionParam);
    else {
    iwparam.setCompressionMode(ImageWriteParam.MODE_COPY_FROM_METADATA);
    System.out.println("Trying to write Image ....");
    imgWriter.write(null, new IIOImage(out_image, null, metadata), iwparam);
    System.out.println("Image written....");
    finally {
    if (imgWriter != null)
    imgWriter.dispose();
    if (imgReader != null)
    imgReader.dispose();
    if (ios != null) {
    ios.flush();
    ios.close();
    }

    user8684061 wrote:
    U are right, SGA is too large for my server.
    I guess oracle set SGA automaticlly while i choose default installion , but ,why SGA would be so big? Is oracle not smart enough ?Default database configuration is going to reserve 40% of physical memory for SGA for an instance, which you as a user can always change. I don't see anything wrong with that to say Oracle is not smart.
    If i don't disincrease SGA, but increase max-shm-memory, would it work?This needs support from the CPU architecture (32 bit or 64 bit) and the kernel as well. Read more about the huge pages.

  • Problem Displaying an Image in a JScrollPane

    Hi All,
    I've placed a Toolbar at the bottom of a JFrame and above the toolbar I placed a JTabbedPane. In one of the tabs I want to display a full sized image.The size of the image that I want to display using a scroll pane is 595x842 pixels. Now the problem is that when I display the image in the scroll pane the bottom toolbar is overlapped with the scrollpane. I don't want to resize the image as it is spoiling the image quality.I used the below code
    JPanel imagepagepanel=new JPanel()
        protected void paintComponent(Graphics g)
              js=new JScrollPane();
              Point p = js.getViewport().getViewPosition();
              g.drawImage(demoicon.getImage(), p.x, p.y, null);
    mytabbedpane.addTab("View Image",js); //add the scrollpane to the tabI even tried using a label to display the image in the tabbedpane and I've got the same overlapping problem.
    I am able to embed the default browser in my application using JDIC API and the image display is fine in the browser without overlapping the bottom toolbar. But I don't want to use a web browser to display the image.
    It would be of great help if anyone could suggest a solution to the overlapping problem. I want the scroll pane to work similar to a web browser while displaying a large sized image.
    Thanks in advance.

    Override the paintComponent method to just draw the
    image at 0, 0, w, h.
    The rest is not needed, to say the least.Here's an easier way
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import java.awt.*;
    import java.io.File;
    import java.io.IOException;
    public class ImageInTabbedScrollTest extends JFrame {
        public ImageInTabbedScrollTest() {
            buildGUI();
        private void buildGUI() {
            JPanel mainPanel = (JPanel) getContentPane();
            mainPanel.setLayout(new BorderLayout());
            JTabbedPane tabbedPane = new JTabbedPane();
            try {
                Image image = ImageIO.read(new File("images/terrain.jpg"));
                ImageIcon icon = new ImageIcon(image);
                JLabel label = new JLabel(icon);
                JPanel panel = new JPanel(new GridLayout(0,1,5,5));
                panel.add(label);
                JScrollPane jsp = new JScrollPane(panel);
                tabbedPane.addTab("Image",jsp);
                JPanel anotherPanel = new JPanel();
                JLabel label2 = new JLabel("Second Panel");
                anotherPanel.add(label2);
                 label2.setFont(new Font("San Serif",Font.BOLD, 40));
                tabbedPane.add("Label",anotherPanel);
                mainPanel.add(tabbedPane, BorderLayout.CENTER);
                JToolBar tBar = new JToolBar();
                tBar.add(new Button("OK"));
                tBar.add(new Button("Maybe"));
                tBar.add(new Button("No"));
                mainPanel.add(tBar, BorderLayout.SOUTH);
                  } catch (IOException e) {
                e.printStackTrace();
        public static void main(String[] args) {
            Runnable runnable = new Runnable() {
                public void run() {
                    ImageInTabbedScrollTest testFrame = new ImageInTabbedScrollTest();
                    testFrame.setSize(new Dimension(600,600));
                    testFrame.setLocationRelativeTo(null);
                    testFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                    testFrame.setVisible(true);
            SwingUtilities.invokeLater(runnable);
    }

  • Two problems with displaying images in JPanel

    Hi,
    I need to display some small rectangular images inside a JPanel. These images also need to be componenents as they will have listeners associated with them. I have never had any experience with images, so I might totally be down the wrong path. I was thinking of just creating a class which extends JComponent, and using the graphics drawImage method. However, I don't want each image component to have to know exactly where to draw the image associated with itself. Rather, I want the JPanel which holds all of the images to know how to lay them out.
    Is there an easier way to use images?
    Which brings me to my second problem. I want these images to overlap each other, so that only a small portion of each is showing (this way I can fit more on the screen), then when the user clicks on one, I can show more of it.
    Unfortunately, I don't know of any layout managers which will allow me to overlap components. I could use the drawImage method mentioned above, but like I said, I would like to try to not have each image object try and figure out its location.
    any help is greatly appreciated. Thanks!

    Hi
    there is a better way ; it is called a JLabel ;-)
    JLabel myJLabel = new JLabel(new ImageIcon("img/myLogo.gif"));for your second problem, don't use any layout manager like in this code :
    myJPanel.setLayout(null);
    myJPanel.add(myJLabel);
    myJLabel.setBounds(new Rectangle(x, y, width, height);hope it helps
    Nico

  • CS6 creates tiled image when moving from LR4 and HDR Effex Pro

    Just recently I've had a problem with CS6 where it creates a partial (tiled) image when "Edit In" from LR4 and when saving back to CS6 from HDR Effex Pro. THe image may have one or several retangles which may be black, white, or part of the image that's in the wrong place if that makes any sense. All software is running with current updates. I've had the software about 6 months and never incurred this problem until the last week. Help!

    I've run through several scenarios and find that it's always in CS6 that I have the problem. I opened a file in all modules of Nik as well as OnOne's Perfect Photo Suite. When I go back (save) to CS6 there is always a problem. When I save in CS6 and then open up in LR the image is fine. So the file must not be corrupt, it just doesn't present it properly in CS6. The GPU driver appears to be up to date....last update was in 2011 and I've had this computer since late 2012.

  • Draw rotated image to given width and height

    Problem, if an image where width and height aren't equal is rotated and drawn again, the image is not drawn (stretched) to the full width.
    Below is an example to illustrate my problem. The top image is stretched to the full width, the other aint.
    Example picture: http://www.google.nl/intl/nl_nl/images/logo.gif
    What am I doing wrong??
    Greet Retep
    import java.awt.Font;
    import java.awt.Frame;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.geom.AffineTransform;
    import java.awt.image.AffineTransformOp;
    import java.awt.image.BufferedImage;
    import java.awt.image.BufferedImageOp;
    import java.io.BufferedInputStream;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JComponent;
    public class Test2 extends Frame{
         public static void main(String[] args)
              try {
                   new Test2();
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         public Test2() {
              super("Rotate picture");
              add(new RotateTest());
            addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
            setFont(new Font("default", Font.PLAIN, 24));
            setSize(300, 300);
            setVisible(true);
         class RotateTest extends JComponent {
             public void paint(Graphics g) {
                 Graphics2D g2d = (Graphics2D)g;
                 try {
                        BufferedImage image = ImageIO.read(new BufferedInputStream(new FileInputStream("C:/logo.gif")));
                        AffineTransform affineTransForm = new AffineTransform();
                      affineTransForm.rotate(Math.toRadians(270), image.getWidth(), 0); 
                      //flip
                      //affineTransForm.translate(0, image.getHeight());
                      //affineTransForm.scale(1, -1);
                      BufferedImageOp bufferedImageOp = new AffineTransformOp(affineTransForm,
                              AffineTransformOp.TYPE_BICUBIC);
                      BufferedImage image2 = bufferedImageOp.filter(image, null);
    //                  BufferedImage tempImage = new BufferedImage(image.getWidth(),image.getHeight(), image2.getType());
    //                Graphics2D graphics2D = tempImage.createGraphics();
    //                graphics2D.drawImage(image2, 0, 0, null);
    //                graphics2D.dispose();
                      g2d.drawImage(image, 5, 15, 280, 50, null);
                      g2d.drawImage(image2, 5, 70, 280, 50, null);
                      //g2d.drawImage(tempImage, 5, 125, 280, 50, null);
                      //g2d.drawImage(image, affineTransForm, null);
                      g2d.drawRect(5, 15, 280, 50);
                      g2d.drawRect(5, 70, 280, 50);
                   } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                   } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
    }

    Let's see if this helps...
    import java.awt.Font;
    import java.awt.Frame;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.geom.AffineTransform;
    import java.awt.geom.Rectangle2D;
    import java.awt.image.BufferedImage;
    import java.io.BufferedInputStream;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JComponent;
    public class T2Rx extends Frame {
        public static void main(String[] args) {
            try {
                new T2Rx();
            } catch (Exception e) {
               e.printStackTrace();
        public T2Rx() {
            super("Rotate picture");
            add(new RotateTest());
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            setFont(new Font("default", Font.PLAIN, 24));
            setSize(300, 375);
            setLocation(200,200);
            setVisible(true);
        class RotateTest extends JComponent {
            BufferedImage image;
            RotateTest() {
                // You only need to do this one time. Save the image in a
                // a member variable so you can access it whenever you want.
                try {
                    image = ImageIO.read(new BufferedInputStream(
                                         new FileInputStream("logo.gif")));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
            protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D)g;
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                    RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                int w = getWidth();
                int h = getHeight();
                BufferedImage scaled = scaleTo(image, 280, 50);
                int iw = scaled.getWidth();
                int ih = scaled.getHeight();
                double x = (w - iw)/2.0;
                double y = 1;
                g2.drawImage(scaled, (int)x, (int)y, this);
                g2.draw(new Rectangle2D.Double(x, y, iw, ih));
                double theta = Math.PI*3/2;
                x = (w - ih)/2.0;
                y = (ih + iw)/2.0 + 1;
                AffineTransform at = AffineTransform.getTranslateInstance(x, y);
                at.rotate(theta, iw/2.0, ih/2.0);
                g2.drawRenderedImage(scaled, at);
                g2.draw(at.createTransformedShape(new Rectangle2D.Double(0, 0, iw, ih)));
        private BufferedImage scaleTo(BufferedImage src, int w, int h) {
            //System.out.printf("type = %d%n", src.getType());
            // This type gives a better appearance after scaling.
            int type = BufferedImage.TYPE_INT_RGB;
            BufferedImage out = new BufferedImage(w, h, type);
            Graphics2D g2 = out.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            g2.setBackground(getBackground());
                             //java.awt.Color.pink);  // just checking
            g2.clearRect(0, 0, w, h);
            double xScale = (double)w/src.getWidth();
            double yScale = (double)h/src.getHeight();
            double scale = Math.min(xScale, yScale);    // scale to fit
                           //Math.max(xScale, yScale);  // scale to fill
            double x = (w - scale*src.getWidth())/2;
            double y = (h - scale*src.getHeight())/2;
            AffineTransform at = AffineTransform.getTranslateInstance(x, y);
            at.scale(scale, scale);
            g2.drawRenderedImage(src, at);
            g2.dispose();
            return out;
    }

  • I am facing a Problem with reading images from database

    Hi everybody..
    any help will be most appreciated, I am facing problem with reading images from database. I am pasting my code... 
                    string connect = "datasource = localhost; port = 3306; username = root; password = ;"; 
                    MySqlConnection conn = new MySqlConnection(connect); // creating connecting string
                    MySqlCommand sda = new MySqlCommand(@"select * from management.add_products ", conn); //creating query
                    MySqlDataReader reader; 
                    try
                        conn.Open(); // Opening Connection
                        reader = sda.ExecuteReader(); // Executing my Query..
                        while (reader.Read())
                            byte[] imgg = (byte[])(reader["Picture"]);
                            if (imgg == null)
                                pc1.Image = null;
                            else
                                MemoryStream mstream = new MemoryStream(imgg);
                                pc1.Image = System.Drawing.Image.FromStream(mstream);
    It says Parameter not Valid... i am reading all the images from database

    I agree with Viorel. You are getting the error because the format of the data is incorrect probably because the data was modify. It may not be the reading of the database the is incorrect, but the application that wrote the data into the database. You need
    to compare the imgg array data with the data before it was written to the database to see if the data matches.  I usually start by comparing the number of bytes which is easier to check then compare the actual to isolate which function is changing the
    byte count.
    An image is binary data.  The standard VS methods for reading and writing data (usually stream classes) default to ASCII encoding which will corrupt binary data.  The solution usually is to use UTF8 encoding instead of the default ascii encoding. 
    Ascii encoding with stream often aligns the data and adds extra null bytes to the end of the data which can produce these type errors.
    jdweng

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

  • Tiling image within infinitely vertically expandable rounded box

    I would like to place a 1px high image within a round box which will expand inifnitely in a dynamic ecommerce site. I know how to create a div for the header (ie rounded box, roundedbox h1) and place the top part, then the rest in the main div with the bottom of the rounded box positioned at "bottom." However, there are physical limitations to this method; it seems it would be ideal to place a tiled image to complete everything within the top and bottom portions; the problem is that it appears at the top no matter how it's placed. Is there any way to specify a margin for the background image only?
    Incidentally, I hate the look of this new forum. Why everyone wants to jump on the Facebook wagon is beyond me...

    Hi Murray; for example, I crop the top 60px of the rounded box and make it the background for the #body_content h1 div, then use the bottom rounded remains of the box and make it the background image for the #body_content div. The problem is that without sufficient content, the cropped body bg image shows at the top of the div; whereas if there is too much, a blank space will occur between the two. I'd like to think there is a way to insert a third div with a 1 px high tiled image but someho give it a 60px margin at both top and bottom to prevent overlapping...
    #body_content {
    margin-left: 20px;
    background-image: url(../../../Images/maincontent_bg_footer.gif);
    background-repeat: no-repeat;
    background-position: left bottom;
    width: 820px;
    margin-top: 0px;
    margin-right: 0px;
    margin-bottom: 20px;
    padding: 0px;
    #body_content h1 {
    background-image: url(../../../Images/maincontent_bg_heading.gif);
    background-repeat: no-repeat;
    height: 60px;
    margin: 0px;
    padding: 0px;

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

  • Tiled Image - JViewport?

    HELP wimper
    I want to create a large tiled image that you only see a 302x128 section of that can be scrolled to see different sections 'a la' ye old 2D commadore 64 games like paradroid.
    I would be EXTREMELY grateful if any of you wonderous people out there could point me in the best direction. I am quite new to Object Oriented programming and have been directed towards the JViewport class, but other tutorials on the net use g.drawImage... to limited success. (http://userpages.umbc.edu/~enorth1/tilemapper/tile.htm).
    I realise that to you Java gurus this request probally seems extremely dippy, but I have reached desperation point looking for a place to start from.
    Thanks in advance,
    Simon Engledew - a very stuck newbie.

    You can create an extension of the JPanel class and override the paintComponent() method to draw your graphics. If you implement the Scrollable interface, you will be able to interact with a JScrollPane or, if you are adventurous, a standalone JViewport.
    Mitch Goldstein
    Author, Hardcore JFC (Cambridge Univ Press)
    [email protected]

Maybe you are looking for

  • Dreamweaver Lightbox Widget

    Lightbox gallery works in browser, but not online.  Images are displayed, but javascript is not working.  Any suggestions for troubleshooting?  http://www.vanessa-lynn.com/paintings.html

  • How to join two or more separate tracks into one track

    I have a CD of music that I want to import. It is a study tool so all the tracks are parcelled up for easier examination- i.e. Beethoven's Symphony no. 5 in C Minor is not one long track, it is cut into 28 separate tracks ranging in time from 26 seco

  • How do I limit the number of measures per line in Logic Pro score editor

    I would like to control the number of measures per line in Logic Pro X Score  Editor, currently it puts random numbers of measures per line depending on the accumulated lenth of the measures per line, as if looking for "the best fit". Any ideas how t

  • Flash froze and crashed computer

    I was playing a flash-based game when the game completely locked up my computer, and the only possible solution was to do a hard reboot (pressing and holding the power key). I waited and then restarted, but the screen had vertical and horizontal pixe

  • Can the Macbook Pro (Retina, Mid 2012) Hard Drive be Upgraded?

    I have a Macbook Pro Retina Display Mid 2012 that has a 512GB SSD Hard Drive. I am finding that I need more space and having an External Hard Drive is a little inconvenient. I see that there are 1TB SSD and thinking of changing out my Hard Drive. Is