Getwidth() and getheight()

I am very new to J2ME.
I am writing a midlet that needs to find the width and height of the device screen, i have already got a part of the program that queries whether the device supports colour graphics and how much memory it has but this is done within the display class and the getwidth()and getheight() commands need to be used within the canvas class. Can anyone give me some tips as to how to implement this.
Thanks for any help.
Phil

use this code:
class DummyCanvas extends Canvas {
protected void paint( Graphics g ){
m_screenHeight = getHeight();
m_screenWidth = getWidth();
display.setCurrent( mClass.m_MainForm );
hope that helps.

Similar Messages

  • Problems with getWidth() and getHeight() in class Canvas

    Hi,
    i am developing MIDlets with Sun Studio4 One Update1 (Mobile Edition). Here is a simple example Code for my Problem:
    class MyCanvas extends Canvas
        public void paint(Graphics g)
            //Clear the Display
            g.setColor(0,0,0); //black
            g.fillRect(0,0,getWidth(),getHeight());
    }If i try to execute the Program with the Default Color Phone emulator included with Suns WTK2.0, everything works fine. (Ive tried to print out the results of getWidth() and getHeight() on the console, everything ok, the Displays width and height is displayed.).
    The problem is, that any other emulator from WTK1.0.4_01 (included with Sun Studio4 ME) compiles and preverifies fine, but while running the application, the emulator quits with the following error:
    ALERT: No such method getWidth.()I
    Execution completed successfully
    Anyone has an idea?
    Thanks!!

    Hello,
    I'm having the exact same problem and I'd like to know what changes you made to your code to get it working. My class is not an inner class and is very much like yours and so follows the form:
    class MyCanvas extends Canvas{ 
    int element = getWidth()/10;
    public void paint(Graphics g) {        //Clear the Display  
    g.setColor(0,0,0); //black
    g.fillRect(0,0,getWidth(),getHeight());
    I am also using WTK104. I did not have this problem until I renamed my file. I carried the renaming throughout the rest of the file in a consistent fashion and I don't see any problems with it. Any help appreciated.

  • GetWidth() and getHeight() weird behaviour?

    Okay guys, what am i doing wrong here.
    Group myGroup;
    Label CompassLabel;
    //  doing new for all.
    //add label to the group.
    myGroup.getChildren().add(CompassLabel);
    CompassLabel.setText("360");So i have a label and add it to a group.
    Then i do this:
    System.out.println(CompassLabel.getWidth() + CompassLabel.getHeight());both return the value 0.0
    if i do this:
    Node nodeN = myGroup.getChildren().get(0); //The Label
    if (nodeN instanceof Label)
                            Label label = (Label) nodeN;
                            System.out.println(label.getWidth() + label.getHeight());
    }it gives:
    26.27734375 // Returned Value for width
    32.27734375 // returned Value for heightWhy is that? Thanks, regards.

    Hey Thanks.
    I can see the label on my Scene, so it's there.
    And between my first output and the second is like no other code.
    And it's pretty much the same object, isn't it?
    Can you give me some functions to check if there is something wrong?
    Can give you more code tho.
    public ViewPort()
            Compass              = new Circle();
            LineGroup           = new Group();
            LineGroup.getChildren().add(Compass);
            getChildren().add(LineGroup);
            for(int i = 15; i < 375;)
                CompassLine = new Line();
                CompassLabel = new Label(Integer.toString(i));
                LineGroup.getChildren().add(CompassLine);
                LineGroup.getChildren().add(CompassLabel);
                xStart = Compass.getCenterX() + ((Compass.getRadius() - 30) * Math.sin( i * ((2 * Math.PI) / 360)) );
                xStart2 = Compass.getCenterX() + ((Compass.getRadius() - 15) * Math.sin( i * ((2 * Math.PI) / 360)) );
                CompassLine.setStartX(xStart2);
                yStart = Compass.getCenterY() - ((Compass.getRadius() - 30) * Math.cos( i * ((2 * Math.PI) / 360)) );
                yStart2 = Compass.getCenterY() - ((Compass.getRadius() - 15) * Math.cos( i * ((2 * Math.PI) / 360)) );
                CompassLine.setStartY(yStart2);
                xEnd = Compass.getCenterX() + (Compass.getRadius() * Math.sin(i * ((2 * Math.PI) / 360)) );
                CompassLine.setEndX(xEnd);
                yEnd = Compass.getCenterY() - (Compass.getRadius() * Math.cos(i * ((2 * Math.PI) / 360)) );
                CompassLine.setEndY(yEnd);
                CompassLabel.setLayoutX(xStart - (CompassLabel.getWidth() / 2));
                CompassLabel.setLayoutY(yStart - (CompassLabel.getHeight() / 2));
    * Below it gives 0.0
                Node myNode = CompassLabel;
                Label myLabel = (Label) myNode;
                System.out.println(myLabel.getWidth() + myLabel.getHeight());
                i = i + 15;
            (TrainingsAnimation.getInstance().radarStage.widthProperty()).addListener(new ChangeListener()
                @Override
                public void changed(ObservableValue arg0, Object arg1, Object arg2)
                     newStageWdith.set(getWidth());
                     Compass.setCenterX(newStageWdith.getValue() / 2);
                     Compass.setRadius(TrainingsAnimation.getInstance().radarStage.getWidth() / 2 );
            (TrainingsAnimation.getInstance().radarStage.widthProperty()).addListener(new ChangeListener()
                @Override
                public void changed(ObservableValue arg0, Object arg1, Object arg2)
                    newStageHeight.set(getHeight());
                    Compass.setCenterY(newStageHeight.getValue() / 2);
                    for(int i = 0; i < LineGroup.getChildren().size(); i++)
                        Node nodeN = LineGroup.getChildren().get(i);
                        if (nodeN instanceof Line)
                            // Set new points for Line(actLine);
                            actLine++;
                            alpha = actLine * 15;
                            Line line = (Line)nodeN;
                            xStart = Compass.getCenterX() + ((Compass.getRadius() - 30) * Math.sin( alpha * ((2 * Math.PI) / 360)) );
                            xStart2 = Compass.getCenterX() + ((Compass.getRadius() - 15) * Math.sin( alpha * ((2 * Math.PI) / 360)) );
                            line.setStartX(xStart2);
                            yStart = Compass.getCenterY() - ((Compass.getRadius() - 30) * Math.cos( alpha * ((2 * Math.PI) / 360)) );
                            yStart2 = Compass.getCenterY() - ((Compass.getRadius() - 15) * Math.cos( alpha * ((2 * Math.PI) / 360)) );;
                            line.setStartY(yStart2);
                            xEnd = Compass.getCenterX() + (Compass.getRadius() * Math.sin(alpha * ((2 * Math.PI) / 360)));
                            line.setEndX(xEnd);
                            yEnd = Compass.getCenterY() - (Compass.getRadius() * Math.cos(alpha * ((2 * Math.PI) / 360)) );
                            line.setEndY(yEnd);
                        else if (nodeN instanceof Label)
                            Label label = (Label)nodeN;
                            label.setLayoutX(xStart - (label.getWidth() / 2) ) ;
                            label.setLayoutY(yStart - (label.getHeight() / 2) );
    * here are the correct height and width
                            System.out.println(label.getWidth() + label.getHeight());
                    Compass.setRadius(TrainingsAnimation.getInstance().radarStage.getHeight() / 2 );
        }Think this is to confusing and unclear to read, but maybe you see the mistake. i wrote a comment on the two ouputs.

  • Java.awt.Image getWidth() and getHeight() not working!

    Right- this is want I want to do.
    I have a background image which is added as a background image to a third party API class which extends Java.awt.Container. Such container is then added to the Content Pane of MyClass (which extends JFrame)
    I want to read the width and height of the image and resize MyClass accordingly.
    Problem is calling theImage.getWidth(MyClass.this) or theImage.getWidth(theThirdPartyAPIContainer) always return -1 and -1 denoting that no information is available.
    What do I need to do to obtain the height and width?

    Post here, cos don't know your email.
    Anyway
    - Can't use setPreferredSize because the Conatiner which is added to the ContentPane is a Awt Component not a Swing JComponent!
    - Also, the background is added AFTER the this.pack()and this.show().
    -I figured out that I could access Insets.top, Insets.left, Insets.right, Insets.bottom.
    I have basically the following
    |JMenuBar |
    L____________________________________________|
    | |
    | |
    | |
    | Third Party Class extending java.awt.Container |
    | containing an image of known size |
    | |
    L____________________________________________|
    I am fine for the width I do
    Insets frameInsets = this.getInsets();
    width = image.getWidth() + frameInsets.left + frameInsets.right;
    Height is the problem
    After some Trial an error it LOOKS on Solaris as if the following is right-
    height = image.getHeight()+frameInsets.top+ myJMenuBar.getSize()+getHeight+ myJMenuBar.getInsets().top + myJMenuBar.getInsets().bottom
    I cannot comprehend whether this is just a coincidence or not as I don't know why frameInsets.bottom should in any case be excluded.
    Here are the dimensions-
    frameInsets.left = 6
    frameInsets.right= 6
    frameInsets.top =28
    frameInsets.bottom = 6
    JMenuBar height = 23
    JMenuBar's Insets.top = 1
    JMenuBar's Insets.bottom = 1
    What should be the 'correct' calculations and does the Insets for the JMenuBar and the JFrame overlaps?

  • Image object getWidth() and getHeight() returning -1

    Hello all,
    I'm currently unit testing a pretty simple utility that calculates a new image position, given a handful of parameters (including image width and height).
    The problem I'm running into is this:
    The image width/height don't always load immediately. My only clue so far from searching the web is this:
    http://download-llnw.oracle.com/javase/6/docs/api/java/awt/Image.html#getWidth%28java.awt.image.ImageObserver%29
    which states Determines the width of the image. If the width is not yet known, this method returns -1 and the specified ImageObserver object is notified later. In my JUnit test harness, I have the following code to load my images, using Toolkit:
    public static final String TEST_IMG_1_PATH = "images/apple_logo.png";
    public static final String TEST_IMG_2_PATH = "images/dude.png";
    private Image testImage1, testImage2;
    @Before
    public void setUp() throws Exception {
         testImage1 = Toolkit.getDefaultToolkit().getImage(TEST_IMG_1_PATH);
         testImage2 = Toolkit.getDefaultToolkit().getImage(TEST_IMG_2_PATH);
         // check the image size to see if they are fully loaded:
         System.out.println(testImage1.getWidth(null));
         System.out.println(testImage1.getHeight(null));
         System.out.println(testImage2.getWidth(null));
         System.out.println(testImage2.getHeight(null));
    }Because the utility method I'm testing heavily depends on the image size, my tests intermittently fail. When I run this, I typically get -1 for all of the image dimension checks (see the above println()s).
    -1
    -1
    -1
    -1Even with these "-1" results, my test still passes... which means at some point before the test assert() statement executes, the images do become fully loaded.
    My question is: What can I do to make sure my image is loaded fully before I do anything with it? Is there any elegant way to handle this? Am I doing something wrong?
    Thanks for your time.
    -Thok

    [http://forums.sun.com/thread.jspa?threadID=5446922]
    db

  • Bottom and right with getwidth or getheight

    I need to get the size of a button in a applet I am building the problem is that when I use Button.getHeight() IE 5.0 throws a java exception. Are there any other ways I can do this? Other then getheight and getwidth.

    getSize().width, getSize().heigth

  • Why table getWidth and setWidth is not working when resize column the table

    hi all,
    i want to know why the setWidth is not working in the following code,
    try to uncomment the code in columnMarginChanged method and run it wont resize the table.
    i cont set width(using setWidth) of the other table column using getWidth of the main table column.
    and i want to resize the right side columns only (you can check when you resize the any column the left and right side columns also resizing)
    any suggestions could be helpful.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.SwingUtilities;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.TableColumnModelEvent;
    import javax.swing.event.TableColumnModelListener;
    import javax.swing.table.TableColumnModel;
    public class SynTableResize extends JFrame implements TableColumnModelListener, ActionListener
        JTable  table1       = new JTable(5, 5);
        JTable  table2       = new JTable(5, 5);
        JTable  table3       = new JTable(5, 5);
        JButton btn          = new JButton("refresh");
        JPanel  pnlcontainer = new JPanel();
        public SynTableResize()
            setLayout(new BorderLayout());
            pnlcontainer.setLayout(new BoxLayout(pnlcontainer, BoxLayout.Y_AXIS));
            pnlcontainer.add(table1.getTableHeader());
            pnlcontainer.add(Box.createVerticalStrut(5));
            pnlcontainer.add(table2);
            pnlcontainer.add(Box.createVerticalStrut(5));
            pnlcontainer.add(table3);
            table2.setTableHeader(null);
            table3.setTableHeader(null);
            table1.getColumnModel().addColumnModelListener(this);
            table3.setColumnModel(table1.getColumnModel());
            table2.setColumnModel(table1.getColumnModel());
            table2.getColumnModel().addColumnModelListener(table1);
            table3.getColumnModel().addColumnModelListener(table1);
            btn.addActionListener(this);
            getContentPane().add(pnlcontainer, BorderLayout.CENTER);
            getContentPane().add(btn, BorderLayout.SOUTH);
            setSize(new Dimension(400, 400));
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        public static void main(String[] args)
            new SynTableResize();
        public void columnAdded(TableColumnModelEvent e)
        public void columnMarginChanged(ChangeEvent e)
            TableColumnModel tcm = table1.getColumnModel();
            int columns = tcm.getColumnCount();
            for (int i = 0; i < columns; i++)
                table2.getColumnModel().getColumn(i).setPreferredWidth(tcm.getColumn(i).getWidth());
                table3.getColumnModel().getColumn(i).setPreferredWidth(tcm.getColumn(i).getWidth());
                // the following commented code wont work.
    //            table2.getColumnModel().getColumn(i).setPreferredWidth(tcm.getColumn(i).getPreferredWidth());
    //            table3.getColumnModel().getColumn(i).setPreferredWidth(tcm.getColumn(i).getPreferredWidth());
    //            table2.getColumnModel().getColumn(i).setWidth(tcm.getColumn(i).getWidth());
    //            table3.getColumnModel().getColumn(i).setWidth(tcm.getColumn(i).getWidth());
            SwingUtilities.invokeLater(new Runnable()
                public void run()
                    table2.revalidate();
                    table3.revalidate();
        public void columnMoved(TableColumnModelEvent e)
        public void columnRemoved(TableColumnModelEvent e)
        public void columnSelectionChanged(ListSelectionEvent e)
        public void actionPerformed(ActionEvent e)
            JTable table = new JTable(5, 5);
            table.setColumnModel(table1.getColumnModel());
            table.getColumnModel().addColumnModelListener(table1);
            pnlcontainer.add(Box.createVerticalStrut(5));
            pnlcontainer.add(table);
            pnlcontainer.validate();
            pnlcontainer.repaint();
    }thanks
    dayananda b v

    hi,
    thanks for your replay,
    yes i know that, you can check the following code it works fine.
    actually what i want is, when i resize table column it shold not automaticaly reszie when table resized and i dont want horizontal scroll bar, meaning that all table columns should resize with in the table size(say width 300)
    if i make table autoresize off than horizontal scroll bar will appear and the other columns moved and i want scroll to view other columns.
    please suggest me some way doing it, i tried with doLayout() no help,
    doLayout() method only can be used when table resizes. first off all i want to restrict table resizing with in the limited size
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.event.ChangeEvent;
    import javax.swing.table.TableColumnModel;
    public class TempSycnTable extends JFrame
        JTable  table1       = new JTable(5, 5);
        MyTable table2       = new MyTable(5, 5);
        MyTable table3       = new MyTable(5, 5);
        JPanel  pnlcontainer = new JPanel();
        public TempSycnTable()
            JScrollPane src2 = new JScrollPane(table2);
            JScrollPane src3 = new JScrollPane(table3);
    //        table1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    //        table2.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    //        table3.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    //        src2.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    //        src3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            table2.setTableHeader(null);
            table3.setTableHeader(null);
            table3.setColumnModel(table1.getColumnModel());
            table2.setColumnModel(table1.getColumnModel());
            table2.getColumnModel().addColumnModelListener(table1);
            table3.getColumnModel().addColumnModelListener(table1);
            table2.setTableHeader(null);
            table3.setTableHeader(null);
            setLayout(new BorderLayout());
            pnlcontainer.setLayout(new BoxLayout(pnlcontainer, BoxLayout.Y_AXIS));
            pnlcontainer.add(table1.getTableHeader());
            pnlcontainer.add(Box.createVerticalStrut(5));
            pnlcontainer.add(src2);
            pnlcontainer.add(Box.createVerticalStrut(5));
            pnlcontainer.add(src3);
            getContentPane().add(pnlcontainer, BorderLayout.CENTER);
            setSize(new Dimension(300, 300));
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        public static void main(String[] args)
            new TempSycnTable();
        class MyTable extends JTable
            public MyTable()
                super();
            public MyTable(int numRows, int numColumns)
                super(numRows, numColumns);
            public void columnMarginChanged(ChangeEvent event)
                final TableColumnModel eventModel = table1.getColumnModel();
                final TableColumnModel thisModel = getColumnModel();
                final int columnCount = eventModel.getColumnCount();
                for (int i = 0; i < columnCount; i++)
                    thisModel.getColumn(i).setWidth(eventModel.getColumn(i).getWidth());
                repaint();
    }thanks
    daya

  • Image.getWidth(ImageObserver obs) returns -1

    hello everyone i have used following code to load an image
    URL location=Sprite.class.getClassLoader().getResource(path);
        img=Toolkit.getDefaultToolkit().getImage(location);and this code to draw an image:
    g2d.drawImage(img, x, y, this);now i need to know the width and height of image for detecting collision.
    getWidth() and getHeight() returns -1.
    System.out.println(img.getWidth(this));my images are getting displayed in the frame.but when i try to access width and height of an image then it returns -1 which means width and height of image is not known yet.
    help !!
    thanks.

    sorry.
    This problem is in my game code.Since the code is very long so i am giving a small code reflecting my problem
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.net.URL;
    import javax.swing.*;
    import java.awt.Graphics;
    public class Sprite extends JPanel
    private JFrame frame;
    private Image img;
    public Sprite()
    frame=new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500,400);
    frame.getContentPane().add(this);
    frame.setVisible(true);
    URL location=Sprite.class.getClassLoader().getResource("small.jpg");
    img=Toolkit.getDefaultToolkit().getImage(location);
    this.repaint();
    System.out.println(img.getWidth(null));
    public void paintComponent(Graphics g)
    g.drawImage(img,150,150,this);
    public static void main(String[] args)
    new Sprite();
    }So i want the width and height of an image.But when i try to get it, it just returns -1 which means width and height is not known yet, according to java doc.
    if i use img=new ImageIcon("small.jpg").getImage() to load an image and if i access the width and height of an image using img.getWidth(ImageObserver obs) then i get correct value of width and height.
    i want to use above code that i provided to load an image.So pls help me out.Why it is returning -1 ?.
    Edited by: JGarage on Dec 6, 2008 7:59 AM
    Edited by: JGarage on Dec 6, 2008 8:00 AM

  • Class casting, creating an image and decompiling...

    Hi, I've got a couple of questions:
    1)
    How can I fully decompile classes, so with the implementation of the methods? Is it always possible to fully decompile a class file? When is it and when not?
    2)
    I aks this questions before, but I still haven't got it working, so sorry, but I ask it again :) :
    I want to create my own class, for example cMyClass which extends the java.awt.Image class, which has abstract methods. How do these methods(for example getGraphics etc) have to be implemented?
    3)
    I can't cast a Image to cMyClass... why not?
    Someone told me he did the following:
    Canvas c = new Canvas()
    cMyClass oImage = (cMyClass) c.createImage (100, 100);
    and that this worked... I tried to do this too, and it seemed to work, but it actually didn't!!
    I found out that c.createImage returns a null reference!!! That's why Java was able to cast it to my own cMyClass (not a problem to cast a null to something else), but when I created a Image (by doing a lot of unnessacary difficult stuff), and then tried to cast this Image to cMyClass it throw a ClassCastException or something like that...
    How can I cast the java.awt.Image class to my class anyway?
    3)
    Why can't you create a image like i've done above or even like below:
    Canvas c = new Canvas()
    Image oImage = c.createImage (100, 100);
    Why does this return a null reference?
    Isn't there a better way to create an image?
    4)
    The getWidth and getHeight need a I thought observer...? Why is this? I just want the width and height and don't have an observer or something like that. Is there a way around this?
    I tried getWidth(null) but this returns -1
    Please help! :)

    Hi, I've got a couple of questions:
    1)
    How can I fully decompile classes, so with the
    implementation of the methods? Is it always possible
    to fully decompile a class file? When is it and when
    not?You can always get a dump of the bytecode with 'javap -c'. If you don't want to figure things out yourself, try searching google for a class file decompiler, possibly a de-obfuscator.
    De-compilation is completely possible if the original author wanted that, by including debugging information. Depending on the degree of such information and the amount of code obfuscation, the decompiled code may lack variable names, line numbers, field and method names, class names, and even code structure. Names and line numbers are usually not re-creatable automatically, since the information is simply lost, but you can replace them with your own strings when analyzing an unknown class file (using the correct tools). Re-creating the original code structure may work in some cases, but to me the general case looks rather close to the halt problem (i.e. not solvable).
    Use a de-obfuscator, hope you've got good luck, and analyze the bytecode manually if that doesn't work.
    2)
    I aks this questions before, but I still haven't got
    it working, so sorry, but I ask it again :) :
    I want to create my own class, for example cMyClass
    which extends the java.awt.Image class, which has
    abstract methods. How do these methods(for example
    getGraphics etc) have to be implemented?I don't really understand the problem. 'abstract' means on the language level that your subclass must provide an implementation, i.e. a method body. What that method is expected to do is explained in the javadocs for Image. But in fact you're free to do anything. You could play a sound in the getWidth() method (replace with any method name if you want). Just consider the fact that a lot of code calls getWidth in the hope of getting the width of the image, not playing a sound. So much about the language level.
    On a higher level, a subclass of Image should implement a certain way to describe an image. AFAIK this means that your code must know the size of the image and know how to produce the pixels of the image. I can't tell you in general how you must do this, because it depends on your special case. This boils down to the question, why do you want to write a subclass of 'Image'? What new way of describing and image have you come up with?
    3)
    I can't cast a Image to cMyClass... why not?Simple, and that's certainly not an ALT. Because that specific Image is not a cMyClass. It's probably a BufferedImage or similar that was produced by AWT.
    Please read the specs carefully what casting is about.
    Someone told me he did the following:
    Canvas c = new Canvas()
    cMyClass oImage = (cMyClass) c.createImage (100,
    100);
    and that this worked... I tried to do this too, and it
    seemed to work, but it actually didn't!!
    I found out that c.createImage returns a null
    reference!!! That's why Java was able to cast it to my
    own cMyClass (not a problem to cast a null to
    something else), but when I created a Image (by doing
    a lot of unnessacary difficult stuff), and then tried
    to cast this Image to cMyClass it throw a
    ClassCastException or something like that...
    How can I cast the java.awt.Image class to my class
    anyway?You can't, and if you understood casting then you'd understand that it wouldn't make sense.
    3, 4(don't know)
    Maybe stupid question, but for example the BufferedImage, is this
    completly written in Java?
    How is the link made between the OS+hardware and the Java code? I
    mean, displaying images etc. is very platform dependend not?Look for JNI (Java Native Interface). It's a way to link native (e.g. C) code with Java code.

  • Component resize, paint and AffineTransform

    Hello,
    I am resizing a JInternalFrame that contains a JPanel.
    When I call:
    MyJPanel.repaint();The paint function gets the dimensions of the JPanel
    using getWidth() and getHeight(), once, at the start of the
    paint function. The function then proceeds to plot some lines and
    points on a graph. Everything appears to work fine for lines and points (ie: drawOval).
    The function then goes on to draw some text for the axes of the graph. The Y axis
    text plots fine. The X axis text is rotated using AffineTransform and plots intermittently
    with the correct and incorrect position.
    Calling repaint() for the JPanel, without resizing,
    everything renders in the proper place
    via the overridden paint() procedure for that panel.
    When I resize the JInternalFrame, thus causing the
    JPanel to also automatically resize and repaint, the JPanel
    paints all lines and points in the correct locations
    with respect to the bounds of the JPanel. The
    Y axis text, drawn using drawText() plots in the correct place.
    The X axis text then plots in the wrong place after AffineTransform
    positioning in a location that would indicate it is transforming based on the
    coordinate system of the JInternalFrame rather than the JPanel (??).
    To create the text transform I am calling the following function:
    public void drawRotatedText(Graphics g, String text, int xoff, int yoff, double angle_degrees){
                        Graphics2D g2d=(Graphics2D)g;
                        AffineTransform old_at=((Graphics2D)g).getTransform();
                        AffineTransform at = new AffineTransform(old_at);
                        at.setToTranslation(xoff, yoff);
                        at.rotate((angle_degrees/360.0)*Math.PI*2.0);
                        g2d.setTransform(at);
                        g2d.drawString(text, 0, 0);
                        g2d.setTransform(old_at);
                    }The parameter Graphics g is the Graphics passed from public void MyJPanel.paint(Graphics g) .
    Why would AffineTransform get confused regarding which component the Graphics is coming from?
    More importantly, how can I avoid the problem?
    Thanks,
    P

    >
    To create the text transform I am calling the following function:
    public void drawRotatedText(Graphics g, String text, int xoff, int yoff, double angle_degrees){
    Graphics2D g2d=(Graphics2D)g;
    AffineTransform old_at=((Graphics2D)g).getTransform();
    AffineTransform at = new AffineTransform(old_at);
    at.setToTranslation(xoff, yoff);
    at.rotate((angle_degrees/360.0)*Math.PI*2.0);
    g2d.setTransform(at);
    g2d.drawString(text, 0, 0);
    g2d.setTransform(old_at);
    The problem is with the use of at.setToTranslation(xoff, yoff); instead of at.translate(xoff, yoff).
    After changing that the problem cleared up.
    P

  • Remembering the size and location of a frame

    I would like my application to remember the location and size of the frame when closted and restarted.
    First I thought that I simply could store the settings in a file on close, and on startup restore those values.
    But then what if the user maximizes the frame? The those settings would either be the same as when started or the maximum size, so theres no way to remember the latest size in Frame.NORMAL state.
    So I was wondering how you guys solve this? Is there a listener I could use to catch some window rezise event with?
    Best regards
    S�ren

    There are a couple listeners you could use on your JFrame:
    1. ComponentListener's componentResized event will be invoked after the JFrame's size is changed.
    You could examine the state to see if it's NORMAL (not iconified or maximized) and store the latest
    normalized size, to be saved at application shutdown.
    2. WindowStateListener: this is called after the state changes, and I've noticed that calling the JFrame's
    getWidth and getHeight methods here sometimes returns the new dimension, sometimes the old!
    Option 1 seems an all-around better choice.
    Also, if you're saving state in a file -- check out java.util.prefs -- it rocks and it's easier than file i/o!

  • "this" and .width

    I have two questions. I'm trying to figure out animations, and in most examples I see, I find that "this" and .width and .height are normally used. For example:
    public void init()
         int imageWidth = this.size().width;     // get width
         int imageHeight = this.size().height;     // get height
    What is "this" referring to? I was under the impression that "this" was normally used to specify hidden instance variables. How is the program instantiating imageWidth, using the "this" keyword if imageWidth has no value yet?
    My second question is where are the .width and .height coming from? And why should I use them as opposed to getWidth and getHeight, which are listed as inherited methods under JApplet, and also under Dimension. Thx.

    "this" refers to the same object where it is used. Take a look at the following example:public class A
         private int i;
         public A(int i)
              this.i = i;
         public set()
              int i = 5;
              this.i = i;
    }In the constructor, how can you tell if you are referencing the constructor
    parameter i or the instance variable i? Using the this operator.
    Whenever you have a local variable or a local parameter, you must use the this
    operator to reference the instance variable.
    size() must be a method which returns an object, lets say SizeObject, with two public fields: width and heigth, like this:public class SizeObject
         public int width;
         public int heigth;
         public SizeObject(public int width,int heigth)
              this.width = width;
              this.heigth = heigth;
    }Maybe the getWidth() and getHeigth() methods do the same thing as described by you in the init() method.

  • Using ImageIcon load an image

    Hi I'm having a lot of trouble getting the below code to work. Its copied out of my textbook and its supposed to load an image using the getImage method in the ImageIcon class. The strange thing is I have gotten this to work before, but after I installed Windows 2000 the image doesn't seem to load right anymore.
    getWidth and getHeight - on the image afterwards returns -1.
    Could this be windows 2000's problem? I'm pretty sure it isn't .. but when you run out of ideas, it feels good to put the blame on something other than yourself.
    import java.awt.*;
    import javax.swing.*;
    import java.net.*;
    public class DisplayImage extends JApplet
    public void init()
    ImageIcon icon = null;
    try
    icon = new ImageIcon(new URL(getCodeBase(), "Images/backTile.bmp"));
    catch(MalformedURLException e)
    System.out.println("Failed to create URL:\n"+e);
    return;
    int imageWidth = icon.getIconWidth();
    int imageHeight = icon.getIconHeight();
    resize(imageWidth, imageHeight);
    ImagePanel imagePanel = new ImagePanel(icon.getImage());
    getContentPane().add(imagePanel);
    class ImagePanel extends JPanel
    public ImagePanel(Image image)
    this.image = image;
    public void paint(Graphics g)
    g.drawImage(image,0,0,this);
    Image image;
    Again thx a lot. I know its a lot of code to read. Any help at all would be much appreciated.

    ".bmp" ? Windows bitmap isn't a supported file type, you should save your image as .gif, .png, or as .jpg.

  • Image seems not loading in servlet running in tomcat 4 ... (win xp)

    This servlet basically takes a images file do some scaling then send out as outputstream.
    BUT the image dun since to load ... i keep getting a -1 for the width n height of the image .... seems that image cant load in tomcat....
    Is it something wrong wif my code or is there a bug in tomcat....
    Can someone help thanks
    This is the servlet code:
    import javax.servlet.http.*;
    import javax.servlet.*;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.image.*;
    public class ImageOperater extends HttpServlet
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException
    { System.out.println("Start of post");
    OutputStream out = null;
    try{
    out = res.getOutputStream();
    catch(Exception e)
    e.printStackTrace();
    System.out.println("Start of imageprocessing");
    //image processing
    Image img = Toolkit.getDefaultToolkit().getImage("images/peppers.png");
    ImageFilter imf = new CropImageFilter(0,0,200,200);
    ImageProducer ip = new FilteredImageSource(img.getSource(),imf);
    img = Toolkit.getDefaultToolkit().createImage(ip);
    img =img.getScaledInstance(500,-1,Image.SCALE_AREA_AVERAGING);
    //image processing finish
    //check if the image is fully loaded
    System.out.println("Start of image loading");
    MediaTracker mediaTracker = new MediaTracker(new Container());
    mediaTracker.addImage(img, 0);
    try{
    mediaTracker.waitForID(0);
    System.out.println(mediaTracker.checkAll());
    System.out.println("thread sleep");
    Thread.sleep(1000);
    catch(Exception e)
    e.printStackTrace();
    try{
    mediaTracker.waitForID(0);
    System.out.println(mediaTracker.checkAll());
    System.out.println("thread sleep");
    Thread.sleep(1000);
    catch(Exception e)
    e.printStackTrace();
    //image fully loaded
    System.out.println("Start of buffered image ");
    System.out.println("width"+img.getWidth(null)+" Height "+img.getHeight(null));
    //preparing the buffered image to be send
    BufferedImage bimg = new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_INT_RGB);
    Graphics gr = bimg.getGraphics();
    gr.drawImage(img, 0, 0, null);
    gr.dispose();
    //finished preparing
    //ig = Toolkit.getDefaultToolkit().createImage(bimg.getSource());
    System.out.println("Start of sending");
    //send out to client
    try{
    ImageIO.write((RenderedImage)bimg,"png",new File("c:\\test.png"));
    ImageIO.write((RenderedImage)bimg,"png",out);
    catch(Exception e)
    e.printStackTrace();
    try{
    out.flush();
    out.close();
    catch(Exception e)
    e.printStackTrace();
    System.out.println("post ended");
    but if the same code is put into an applet it works ... thw getWidth() and getHeight() returns the correct value:
    Image img = Toolkit.getDefaultToolkit().getImage("images/peppers.png");
    ImageFilter imf = new CropImageFilter(0,0,200,200);
    ImageProducer ip = new FilteredImageSource(img.getSource(),imf);
    img = Toolkit.getDefaultToolkit().createImage(ip);
    img =img.getScaledInstance(500,-1,Image.SCALE_AREA_AVERAGING);
    //image processing finish
    //check if the image is fully loaded
    System.out.println("Start of image loading");
    MediaTracker mediaTracker = new MediaTracker(new Container());
    mediaTracker.addImage(img, 0);
    try{
    mediaTracker.waitForID(0);
    System.out.println(mediaTracker.checkAll());
    System.out.println("thread sleep");
    Thread.sleep(1000);
    catch(Exception e)
    e.printStackTrace();
    try{
    mediaTracker.waitForID(0);
    System.out.println(mediaTracker.checkAll());
    System.out.println("thread sleep");
    Thread.sleep(1000);
    catch(Exception e)
    e.printStackTrace();
    //image fully loaded
    System.out.println("Start of buffered image ");
    System.out.println("width"+img.getWidth(null)+" Height "+img.getHeight(null));
    //preparing the buffered image to be send
    BufferedImage bimg = new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_INT_RGB);
    Graphics gr = bimg.getGraphics();
    gr.drawImage(img, 0, 0, null);
    gr.dispose();
    //finished preparing
    //ig = Toolkit.getDefaultToolkit().createImage(bimg.getSource());
    System.out.println("Start of sending");
    //send out to client
    try{
    ImageIO.write((RenderedImage)bimg,"png",new File("c:\\test.png"));

    hi ganttan
    first you have to make sure your server is running xwindow. in most cases a linux/apache server does not run it by default. then there is a much simpler approach of scaling images with a servlet:
    Iterator readers = ImageIO.getImageReadersByFormatName("gif");
    ImageReader reader = (ImageReader)readers.next();
    ImageInputStream iis = ImageIO.createImageInputStream(new File(path));
    reader.setInput(iis, true);
    ImageReadParam param = reader.getDefaultReadParam();
    param.setSourceRenderSize(new Dimension(width, height));
    BufferedImage thumbnail = reader.read(0, param);
    ImageIO.write(thumbnail, "gif", response.getOutputStream());
    however this does not work for jpeg images. use setSourceSampling() instead of setSourceRenderSize() in this case but unfortunately it's limited and you can not scale to any size.

  • Point me in the right direction: want to resize image & store in mysql db

    I finally accomplished one of my tasks! Which was trying to upload a jpeg image into my mysql database, and then display it in a jsp page via a servlet. I extend my thanks to the java forums greatly:)
    Now my next task I find is going to be trickier to accomplish, because I do not have enough experience working with images.
    I would like to make my first task above more efficient.
    When the user selects a jpeg file to send, I want to check the size of the image and resize it as well, before finally storing it in my Mysql database.
    I do not want to lose the resolution, nor do I want it to look distorted after it is resized. I want to keep the same proportions as the original image (I hope that proportion is the proper term). After the image is stored successfully, it will be read out of the database and displayed within a jsp page via a servlet.
    After poking around in the forums, I realized I need to get down the basics with regards to getting the properties of an image and trying to resize it. It doesn't look like it will be an easy task.
    Does anyone know of any sites that provide a good, easy to understand tutorial? Or are there any books you would recommend I read? What Java classes should I be looking into to accomplish my task?
    There are so many far more experienced programmers out there among the forums, that when I look at their code, I'm lost. I just want to understand this process better, by taking it one step at a time.
    Any help is appreciated, as always:)
    Thank You,
    Love2Java

    Load image with ImageIO
    Call getWidth() and getHeight()
    Create a BufferedImage with width and height scaled accordingly
    Get the image's Graphics2D object
    Call drawImage(), passing an AffineTransform to scale accordingly
    Output the image via ImageIO
    That should be it - you just need to read the APIs for the classes I've mentioned, and tack on whatever input/output streams you need at either end (see the java.io package).
    The only thing is:
    I do not want to lose the resolution
    Not totally sure what you mean: if you're scaling the image down to a thumbnail then by definition you're losing resolution. If you mean you want to keep the DPI resolution metadata in the image then you'll have to Google for it, the information is there but it hasn't remained in my head :o)
    But then I can't imagine why you'd need DPI metadata in a thumbnail anyway, so you can probably ignore it.

Maybe you are looking for

  • How to insert a math symbol in a pages document

    I have a nonstandard math symbol to insert inot a pages document. Please explain how to do it.

  • Unicode line-drawing characters - possible Java bug?

    Hi all, I am trying to draw a box using line drawing characters in UTF-8. I make the UTF-8 box file in Microsoft Word where it looks aligned. However, when I run my Java program to display the box in a JTextArea, it is all out of alignment like below

  • Sharing to Flickr - where are my titles?

    When I had iPhoto '09 I used to export my photos to the desktop then upload them to Flickr as I didn't like the way the flickr albums were added to the side of iPhoto under "Web". With iPhoto '11 I decided I dodn't mind having "Flickr" once at the si

  • Intermedia drawback with UTF-8

    Hi , There seems to be a limitation in Intermedia . It cannot index characters that are 2 bytes. For example , Iam indexing an xml which has encoding set as UTF-8 .The indexer is unable to recognise the characters like i g ,etc Any ideas Regards, Sye

  • Are WSRP 2.0's shared-render-parameter supported in 10.1.3.2?

    Hello, Is that part of WSRP 2.0 already implemented in WebCenter 10.1.3.2? If so, how should I define the xsd in portlet.xml? I'm trying with http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd but it gives me the following error: org.xml.sax.SAXP