Toolkit.getDefaultToolkit().getScreenResolution()

Hi I called Toolkit.getDefaultToolkit().getScreenResolution() to get my monitor screen resolution. It returns 96 dpi.
But as i check my monitor hardware specs, I found it was different. My monitor is 15.1 inch MultiSync LCD1530v and the hardware specs is found at http://www.necmitsubishi.com/products/home/product.cfm?productid=145&cfid=2239759&cftoken=98264266
It can can found that the resolution is 0.3 mm dot pitch, which turns out to be 1/0.03 * 2.54=84.8 dpi. I am a bit confused by this. Can someone help me in answering the following question?
1. what is the link between 96dpi in Toolkit and 0.3mm in hardware specs? Can one derive one from another? Thanks!

I have a 19 inch monitor and I too get 96 dpi. Is there something wrong with getScreenResolution()?
import java.awt.*;
public class TestMethods
public TestMethods()
public static void main(String[] args)
TestMethods testMethods1 = new TestMethods();
Toolkit toolkit= Toolkit.getDefaultToolkit();
Dimension screenSize= toolkit.getScreenSize();
int screenResolution= toolkit.getScreenResolution();
System.out.println("Screen size: " +screenSize);
System.out.println("Screen Resolution: " +screenResolution);
ran it 3 times and got
1600 X 1200
96
1280 X 1024
96
640 X 480
96
What's up with that?

Similar Messages

  • Java.lang.NoClassDefFoundError Toolkit.getDefaultToolkit

    hi all
    i got this error in a servlet.
    i wrote it on my computer with no errors but, when i moved and executed it on a linux machine it doesn't work:
    java.lang.NoClassDefFoundError at java.awt.Toolkit.getDefaultToolkit(Toolkit.java:703)
    at counter.count.createCounter(count.java:245)
    the code is
    images=Toolkit.getDefaultToolkit().getImage(imageSrc);
    i think that the jdk version is the same on both the computers (1.4.0 or higher), and the code is the same!
    why have i this problem
    thanx
    sandro

    hi rajesh
    you don't know how i'm happy to see your answers!
    i'm so desperate with this problem!
    as you asked to me, this is the full stack trace that tomcat prints when i call my servlet:
    javax.servlet.ServletException: Servlet execution threw an exception
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:260)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2415)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:432)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:386)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:534)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:530)
         at java.lang.Thread.run(Thread.java:536)
    root cause
    java.lang.NoClassDefFoundError
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Class.java:130)
         at java.awt.Toolkit$2.run(Toolkit.java:712)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.awt.Toolkit.getDefaultToolkit(Toolkit.java:703)
         at counter.count.createCounter(count.java:231)
         at counter.count.processRequest(count.java:176)
         at counter.count.doGet(count.java:187)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:260)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2415)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:432)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:386)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:534)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:530)
         at java.lang.Thread.run(Thread.java:536)
    i don't know if there is some environment variable set up in a different way from my system (w2k) to the real server system (linux), also because i installed the jdk (1.4.0 on windows) without setting anything
    if can help i'll post you soon the version of tomcat/jdk used by linux
    thanx a lot
    sandro

  • Toolkit.getDefaultToolkit() in Java service never returns on Windows

    I'm stumped by this problem. It appears to be specific to a single machine as I can reproduce it reliably there but not on other machines. I'm hoping someone has some thoughts on what could be going on.
    Here's the scenario:
    I have Tomcat 5 running as a service on a new installed Windows 2000 Server with up to date service packs and j2sdk1.4.2_06. The service is configure to run headless.
    I have a webapp that performs simple image transformations using AWT and Java2D. Any invocation of Toolkit.getDefaultToolkit() never returns. The thread just sits there consuming no CPU and does not throw an exception. I've narrowed it further to a call to new sun.awt.windows.WToolkit() in getToolKit(). sun.awt.windows.WToolkit is the value of the system property awt.toolkit.
    I can reproduce this exact behavior in a different scenario: the server is running sshd on cygwin. If I ssh to the server and run the following class, it also hangs at new sun.awt.windows.WToolkit().
    public class ToolkitTester
      public static void main(String[] args)
        System.out.println("awt.toolkit = " + System.getProperty("awt.toolkit"));
        System.out.print("Invoking: new sun.awt.windows.WToolkit()... ");
        new sun.awt.windows.WToolkit();
        System.out.println("done.");
    }Running this same class from a shell on the server works just fine.
    I have tried j2sdk1.4.2_03 and jdk1.5 with the same results. I've replicated this second scenario (logging in over ssh) on another Windows 2000 server and do not see this behavior.
    Any thoughts?
    Alon

    Okay. Here's the fix...
    The 'no video card' comment was actually pretty close. The issue appears to be with DirectDraw support. We found this by watching regmon as the testing code ran. Installing a new video driver may have addressed this but so does disabling using DirectDraw as described here:
    http://java.sun.com/products/java-media/2D/forDevelopers/java2dfaq.html#dither
    java -Dsun.java2d.noddraw=true
    Wow. Weird one.
    Alon

  • Substitute of java.awt.ToolKit.getDefaultToolKit.beep()

    Hello everybody. I am designing a Swing Application and there I am using java.awt.ToolKit.getDefaultToolKit.beep() method to generate sound in various operations. I want to know is it possible to generate own sound as a substitute of this method? I think it is possible. How can I do this? Thank you.

    Thank you for giving reply.
    As I wish to play .mp3 file I had downloaded an API from Javalobby . I tried it, here is my code :
    package player;
    import java.io.File;
    import java.io.IOException;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.SourceDataLine;
    * @author Tanmoy
    * @Super Scientific Calculator
    * @version 1.2010
    public class Player {
         private File audioFile;
         public Player(String path) {
              this.audioFile = new File(path);
         public void play() {
              AudioInputStream din = null;
              try {
                   AudioInputStream in = AudioSystem.getAudioInputStream(audioFile);
                   AudioFormat baseFormat = in.getFormat();
                   AudioFormat decodedFormat = new AudioFormat(
                        AudioFormat.Encoding.PCM_SIGNED,
                        baseFormat.getSampleRate(), 16, baseFormat.getChannels(),
                        baseFormat.getChannels() * 2, baseFormat.getSampleRate(),
                        false);
                   din = AudioSystem.getAudioInputStream(decodedFormat, in);
                   DataLine.Info info = new DataLine.Info(SourceDataLine.class, decodedFormat);
                   SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
                   if (line != null) {
                        line.open(decodedFormat);
                        byte[] data = new byte[4096];
                        line.start();
                        int nBytesRead;
                        while ((nBytesRead = din.read(data, 0, data.length)) != -1) {
                             line.write(data, 0, nBytesRead);
                        line.drain();
                        line.stop();
                        line.close();
                        din.close();
              } catch (Exception e) {
              } finally {
                   if (din != null) {
                        try {
                             din.close();
                        } catch (IOException e) {
    }And the calling, piece of code is :
    try {
                                  Parser parser = new Parser(parsingString, displayPanel.getCurrentBase(),
                                       displayPanel.getCurrentBase(), displayPanel.getTrigoMode(),
                                       displayPanel.getScale());
                                  String output = parser.solve();
                                  displayPanel.outputTextField.setText(output);
                                  displayPanel.outputTextField.setCaretPosition(displayPanel.outputTextField.getText().length());
                                  displayPanel.charLabel.setText((Integer.toString(output.length())));
                                  if (message == null) {
                                       message = "No Exception";
                             } catch (InvalidSyntaxException invalidSyntaxException) {
                                  message = invalidSyntaxException.getMessage();
                                  JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE);
                                  new Player("/resources/what_the_hell.mp3").play();
                                  displayPanel.outputTextField.setText("0");
                                  displayPanel.charLabel.setText("0");
                             }But I can not able to here the sound.
    What to do now?
    Thank you.

  • How to use Toolkit.getDefaultToolkit().getImage in JPanel in Java Swing

    Hi Sir,
    I want to know how to use Toolkit.getDefaultToolkit.getImage()
    in JPanel (ie) the class that extends the JPanel.There is no problem to include the Toolkit.getDefaultToolkit.getImage()in JFrame.It is displaying it without any problem.But in JPanel it is showing a problem of cannot resolve symbol.Here i can't use JFrame instead of
    JPanel.So how to solve the problem.Pls.do send the code of how to do this.It is Urgent.
    Thanx,
    M.Ananthu

    you use Toolkit.getDefaultToolkit.getImage() in a JPanel exactly the same way you do in a JFrame.
    You are getting a compile message "cannot resolve symbol". You have made a programming error and since you have not included code there is no way to guess what you did wrong.

  • Toolkit.getDefaultToolkit().getScreenSize() Thread Never Ends

    Consider two "Hello World" programs. On the second program add the
    following call:
    Toolkit.getDefaultToolkit().getScreenSize();
    The first program after executing all of the statements in its "main"
    method will exit. The second program after executing all of its
    statements will not. For the second program System.exit(0) must be
    called. Why is this?
    Jason

    Well a Java chat room visit provided me with the information that:
    A call to Toolkit starts an event thread that doesn't die, so that
    System.exit (0) must be called.
    I still don't know if this is a bug and/or if there is a way to kill
    that thread after I am done using the Toolkit...
    Jason

  • Toolkit.getDefaultToolkit().beep() does not beep!

    Hi,everyone:
    I met a problem when I used Toolkit.getDefaultToolkit().beep() .
    When running, no beep can be heard!
    My Environment is as follows:
    Hardware: Dell dimension 2400
    OS : Windows 2003 Enterprise Edition
    JDK : J2SDK1.4.2
    Code :
    Toolkit.getDefaultToolkit().beep();
    (In java application)
    Does My enviornment not support this operation? Can anyone tell me?
    Thank you.

    Yes, its a bit buggy. Does this work for you?
    ** Will you please tell me where to find evidence that this is a bit buggy?
    Thank you.
    System.out.print ( "\007" );In my java application, System.out.print ( "\007" ) works.
    ** But when I write it in my applet, no beep can be heard!
    import java.applet.*;
    import java.awt.*;
    public class MyBeepApplet extends Applet
        int cx = 50;
        int cy = 50;
        String msg="";
        public boolean mouseDown(Event e, int x, int y)
            msg = " Beep?";
            cx = x;
            cy = y;   
            for(int i=0; i<260;i++){
                System.out.print("\007");
                System.out.flush();
            repaint();      
            return true;
        public void paint(Graphics g)
            g.drawString(msg, cx,cy);
    }

  • Always return "Image Object" in Toolkit.getDefaultToolkit().getImage();

    A : Image source = Toolkit.getDefaultToolkit().getImage("C:/aa.jpg");
    B : Image source = Toolkit.getDefaultToolkit().getImage("");
    generally, B may be null. but it is not null.
    so I look at "javax.swing.ImageIcon" class :
    <Part of ImageIcon source>
    public ImageIcon(String filename, String description) {
         image = Toolkit.getDefaultToolkit().getImage(filename);
    if (image == null) { //This code is invaild.
    return; //never return.
         this.filename = filename;
    this.description = description;
         loadImage(image);
    Do you thinking it?
    Bug?

    getimage may not return null in the current implementation but they wanted maybe get sure that no nullpointerexception occures.
    it's not a bug - it's a feature :-)

  • Toolkit.getDefaultToolkit and Dimension = getScreenSize() is too big

    So I normally use
    Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension dim = tk.getScreenSize();but in my application it was a little bit bigger than it should be, which in my case "1920x1600" isn't that big a deal.
    However I made something for my mom, and when she used it on her tiny Dell 10" laptop it was REALLY cut off.
    My Scene's size was set to dim.getWidth() and Height, so it should fill correctly right?
    Should I NOT be using AWT's Toolkit? Is there something in FX I am missing?
    Thanks all!!
    ~KZ

    So the rectangle is just to get the bounds of my screen right?Yes.
    It has nothing to do with actually creating it right?Right. Rectangle2D is similar to java.awt.Dimension.
    Note that there is also javafx.scene.shape.Rectangle which is a shape.
    Do I use the rectangle's Height/Width to set up my Scene's info? You can use it to set scene size. Let’s say you want to create a scene with a screen size:
    javafx.stage.Screen screen = Screen.getPrimary();
    javafx.geometry.Rectangle2D rectangle2D  = screen.getVisualBounds();
    Scene scene = new Scene(root, rectangle2D.getWidth(), rectangle2D.getHeight());

  • ADF Faces & BC: Does Toolkit.getDefaultToolkit() work?

    I have the following lines of code within a manage bean.
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Dimension dimension = toolkit.getScreenSize();
    Locally it works, but no luck once deployed.
    Does this not work because:
    1. I'm trying to run server side code native to the OS.
    2. Security restrictions native to client machine which prevents accessing OS information.
    3. None of the above?
    Many thanks,
    Wes

    Wes,
    Because that code is running on the application server and not on your client PC - it's getting the screen size of the server. Depending upon the java version, if you are running a headless server (one without a video card), you'd get an error.
    There's no way in general for code running on the server to reach out to your browser-running-pc and determine the screen size. This is nothing to do with ADF at all.
    Best,
    John

  • How to prevent the Toolkit.getDefaultToolkit().beep() in JTextField

    Hi,
    I use the JTextField in my application.
    when the user type value in the field e.g. "123456"
    if you press the backspace 5 times the value will be "1" , pressing it again results with ""
    now.....
    pressing it again results a system beep.
    I want to prevent this beep how can I do it??
    thanks

    textField.getDocument().addDocuemntListener(docListener);
    Then implement the removeUpdate(DocumentEvent evt)
    Hope this helps
    Sai Pullabhotla

  • Print HTML file inside JEditorPane

    Hi Guys,
    I'm trying to print the contents of a JEditorPane - actually, a html file that I read and display in that component from the underlying file system. I've had the class that manages the JEditorPane implement Printable - the following is my print() implementation:
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
              throws PrinterException {
              if (pageIndex > 0) {
                   return (NO_SUCH_PAGE);
              } else {
                   Graphics2D g2d = (Graphics2D) graphics;
                   g2d.translate(
                        pageFormat.getImageableX(),
                        pageFormat.getImageableY());
                   ivTextArea.paint(g2d);
                   return (PAGE_EXISTS);
    }I've got another method that gets called when a print button is clicked:
    class .... {
      PrintJob pj;
      PageFormat pf;
    private void printMe() {
               if (pj == null) {
                   pj = PrinterJob.getPrinterJob();
                   pf = pj.defaultPage();
                   pf.setOrientation(PageFormat.PORTRAIT);
              pf = pj.pageDialog(pf);
              pj.setPrintable(this, pf);
              try {
                   pj.print();
              } catch (PrinterException e) {
                   throw new RuntimeException(e);
    }Clearly I'm doing smth wrong, since only a single page gets printed and moreover the formatting is awful [text gets cut instead of moving on the next line]. Can someone help?
    Thanks much!

              if (pageIndex > 0) {
                   return (NO_SUCH_PAGE);This is why you only get a single page.
    page gets printed and moreover the formatting is
    awful [text gets cut instead of moving on the next
    line]. Can someone help?Yeah. Your best bet is either to put the editorpane in a scrollpane and just print what's visible, OR, you can take the print graphics object, convert it into a graphics2D object, and call scale on that by comparing component.getWidth/height to PageFormat.getImageableWidth/Height
    I'm attaching my StandardPrint class. It uses the pageable interface to carry the number of pages + page format as well. I'm not sure if I did the scaling here or not, but I've done it before so I know it works :-) Also, I've got methods for previewing the print, which can save a lot of paper.
    Please feel free to have and use this class, but please do not change the package or portray this as your own work
    =============================
    package tjacobs.print;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.print.*;
    import javax.print.PrintException;
    public class StandardPrint implements Printable, Pageable {
        Component c;
        SpecialPrint sp;
        PageFormat mFormat;
        public StandardPrint(Component c) {
            this.c = c;
            if (c instanceof SpecialPrint) {
                sp = (SpecialPrint)c;
        public StandardPrint(SpecialPrint sp) {
            this.sp = sp;
        public void start() throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            if (mFormat == null) {
                mFormat = job.defaultPage();
            job.setPageable(this);
            if (job.printDialog()) {
                job.print();
        public void setPageFormat (PageFormat pf) {
            mFormat = pf;
        public void printStandardComponent (Pageable p) throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPageable(p);
            job.print();
        private Dimension getJobSize() {
            if (sp != null) {
                return sp.getPrintSize();
            else {
                return c.getSize();
        public static Image preview (int width, int height, Printable sp, PageFormat pf, int pageNo) {
            BufferedImage im = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            return preview (im, sp, pf, pageNo);
        public static Image preview (Image im, Printable sp, PageFormat pf, int pageNo) {
            Graphics2D g = (Graphics2D) im.getGraphics();
    //        PageFormat pf = sp.getPageFormat(pageNo);
    //        int width = im.getWidth(null);
    //        int height = im.getHeight(null);
    //        g.setColor(Color.WHITE);
    //        g.fillRect(0, 0, width, height);
    //        double hratio = height / pf.getHeight();
    //        double wratio = width / pf.getWidth();
    //        g.scale(hratio, wratio);
            try {
                   sp.print(g, pf, pageNo);
              catch(PrinterException pe) {
                   pe.printStackTrace();
            g.dispose();
            return im;
        public int print(Graphics gr, PageFormat format, int pageNo) {
            mFormat = format;
            Graphics2D g = (Graphics2D) gr;
            g.translate((int)format.getImageableX(), (int)format.getImageableY());
            Dimension size = getJobSize();
            if (pageNo > getNumberOfPages()) {
                return Printable.NO_SUCH_PAGE;
            int horizontal = getNumHorizontalPages();
            int vertical = getNumVerticalPages();
            int horizontalOffset = (int) ((pageNo % horizontal) * format.getImageableWidth());
            int verticalOffset = (int) ((pageNo / vertical) * format.getImageableHeight());
            double ratio = getScreenRatio();
            g.scale(1 / ratio, 1 / ratio);
            g.translate(-horizontal, -vertical);
            if (sp != null) {
                sp.printerPaint(g);
            else {
                c.paint(g);
            g.translate(horizontal, vertical);
            g.scale(ratio, ratio);
            g.translate((int)-format.getImageableX(), (int)-format.getImageableY());
            return Printable.PAGE_EXISTS;
        public int getNumHorizontalPages() {
            Dimension size = getJobSize();
            int imWidth = (int)mFormat.getImageableWidth();
            int pWidth = 1 + (int)(size.width / getScreenRatio() / imWidth) - (imWidth == size.width ? 1 : 0);
            return pWidth;
        private double getScreenRatio () {
            double res = Toolkit.getDefaultToolkit().getScreenResolution();
            double ratio = res / 72.0;
            return ratio;
        public int getNumVerticalPages() {
            Dimension size = getJobSize();
            int imHeight = (int)mFormat.getImageableHeight();
            int pHeight = (int) (1 + (size.height / getScreenRatio() / imHeight)) - (imHeight == size.height ? 1 : 0);
            return pHeight;
        public int getNumberOfPages() {
            return getNumHorizontalPages() * getNumVerticalPages();
        public Printable getPrintable(int i) {
            return this;
        public PageFormat getPageFormat(int page) {
            if (mFormat == null) {
                PrinterJob job = PrinterJob.getPrinterJob();
                mFormat = job.defaultPage();
            return mFormat;
    }>
    Thanks much!

  • Is it possible to print a JPanel from the application?

    Hello,
    Just a quick question: Is it possible to print a JPanel from your application? I have plotted a graph and I would like user to be able to print this with a click of a button (or similar)
    Thanks very much for your help, its appreciated as always.
    Harold Clements

    It is absolutely possible
    Check out my StandardPrint class. Basically all you need to do is
    (this is pseudocode. I don't remember the exact names of methods for all this stuff. Look it up if there's a problem)
    PrinterJob pd = PrinterJob.createNewJob();
    StandardPrint sp = new StandardPrint(yourComponent);
    pd.setPageable(sp);
    //if you want this
    //pd.pageDialog();
    pd.doPrint();You are welcome to have use and modify this class but please don't change the package or take credit for it as your own code.
    StandardPrint.java
    ===============
    package tjacobs.print;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.print.*;
    import javax.print.PrintException;
    public class StandardPrint implements Printable, Pageable {
        Component c;
        SpecialPrint sp;
        PageFormat mFormat;
         boolean mScale = false;
         boolean mMaintainRatio = true;
        public StandardPrint(Component c) {
            this.c = c;
            if (c instanceof SpecialPrint) {
                sp = (SpecialPrint)c;
        public StandardPrint(SpecialPrint sp) {
            this.sp = sp;
         public boolean isPrintScaled () {
              return mScale;
         public void setPrintScaled(boolean b) {
              mScale = b;
         public boolean getMaintainsAspect() {
              return mMaintainRatio;
         public void setMaintainsAspect(boolean b) {
              mMaintainRatio = b;
        public void start() throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            if (mFormat == null) {
                mFormat = job.defaultPage();
            job.setPageable(this);
            if (job.printDialog()) {
                job.print();
        public void setPageFormat (PageFormat pf) {
            mFormat = pf;
        public void printStandardComponent (Pageable p) throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPageable(p);
            job.print();
        private Dimension getJobSize() {
            if (sp != null) {
                return sp.getPrintSize();
            else {
                return c.getSize();
        public static Image preview (int width, int height, Printable sp, PageFormat pf, int pageNo) {
            BufferedImage im = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            return preview (im, sp, pf, pageNo);
        public static Image preview (Image im, Printable sp, PageFormat pf, int pageNo) {
            Graphics2D g = (Graphics2D) im.getGraphics();
            int width = im.getWidth(null);
            int height = im.getHeight(null);
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, width, height);
            double hratio = height / pf.getHeight();
            double wratio = width / pf.getWidth();
            //g.scale(hratio, wratio);
            try {
                   sp.print(g, pf, pageNo);
              catch(PrinterException pe) {
                   pe.printStackTrace();
            g.dispose();
            return im;
        public int print(Graphics gr, PageFormat format, int pageNo) {
            mFormat = format;
            if (pageNo > getNumberOfPages()) {
                return Printable.NO_SUCH_PAGE;
            Graphics2D g = (Graphics2D) gr;
              g.drawRect(0, 0, (int)format.getWidth(), (int)format.getHeight());
            g.translate((int)format.getImageableX(), (int)format.getImageableY());
            Dimension size = getJobSize();
              if (!isPrintScaled()) {
                 int horizontal = getNumHorizontalPages();
                 int vertical = getNumVerticalPages();
                 int horizontalOffset = (int) ((pageNo % horizontal) * format.getImageableWidth());
                 int verticalOffset = (int) ((pageNo / vertical) * format.getImageableHeight());
                 double ratio = getScreenRatio();
                 g.scale(1 / ratio, 1 / ratio);
                 g.translate(-horizontalOffset, -verticalOffset);
                 if (sp != null) {
                     sp.printerPaint(g);
                 else {
                     c.paint(g);
                 g.translate(horizontal, vertical);
                 g.scale(ratio, ratio);
              else {
                 double ratio = getScreenRatio();
                 g.scale(1 / ratio, 1 / ratio);
                   double xScale = 1.0;
                   double yScale = 1.0;
                   double wid;
                   double ht;
                   if (sp != null) {
                        wid = sp.getPrintSize().width;
                        ht = sp.getPrintSize().height;
                   else {
                        wid = c.getWidth();
                        ht = c.getHeight();
                   xScale = format.getImageableWidth() / wid;
                   yScale = format.getImageableHeight() / ht;
                   if (getMaintainsAspect()) {
                        xScale = yScale = Math.min(xScale, yScale);
                   g.scale(xScale, yScale);
                   if (sp != null) {
                        sp.printerPaint(g);
                   else {
                        c.paint(g);
                   g.scale(1 / xScale, 1 / yScale);
                   g.scale(ratio, ratio);
             g.translate((int)-format.getImageableX(), (int)-format.getImageableY());     
            return Printable.PAGE_EXISTS;
        public int getNumHorizontalPages() {
            Dimension size = getJobSize();
            int imWidth = (int)mFormat.getImageableWidth();
            int pWidth = 1 + (int)(size.width / getScreenRatio() / imWidth) - (imWidth == size.width ? 1 : 0);
            return pWidth;
        private double getScreenRatio () {
            double res = Toolkit.getDefaultToolkit().getScreenResolution();
            double ratio = res / 72.0;
            return ratio;
        public int getNumVerticalPages() {
            Dimension size = getJobSize();
            int imHeight = (int)mFormat.getImageableHeight();
            int pHeight = (int) (1 + (size.height / getScreenRatio() / imHeight)) - (imHeight == size.height ? 1 : 0);
            return pHeight;
        public int getNumberOfPages() {
              if (isPrintScaled()) return 1;
            return getNumHorizontalPages() * getNumVerticalPages();
        public Printable getPrintable(int i) {
            return this;
        public PageFormat getPageFormat(int page) {
            if (mFormat == null) {
                PrinterJob job = PrinterJob.getPrinterJob();
                mFormat = job.defaultPage();
            return mFormat;
    }

  • Code example of the day: StandardPrint

    It's been a few years since I posted StandardPrint, so I figured I post it again
    You are welcome to use and modify this class, but please don't change the package or erase the attribution, especially if you are in school
    package tjacobs.print;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.awt.print.*;
    import java.io.File;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import tjacobs.ui.menus.FileMenu;
    import tjacobs.ui.util.WindowUtilities;
    * This implements the Printable and Pageable java.awt.print interfaces
    * Allows you to very easily and quickly generate a printout from a component or a SpecialPrint.
    * @author Tom Jacobs
    public class StandardPrint implements Printable, Pageable {
         //standard print variables
         Component c;
        SpecialPrint sp;
        PageFormat mFormat;
         boolean mScale = false;
         boolean mMaintainRatio = true;
         //page number print
        public static final int LEFT = 0;
        public static final int RIGHT = 1;
        public static final int CENTER = 4;
        public static final int TOP = 2;
        public static final int BOTTOM = 3;
        private boolean mPrintPageNumber = false;
        private Font mPageNumberFont;
        private int hAlign = CENTER;
        private int vAlign = BOTTOM;
        //title vars     
        private String mTitle;
        private Font mTitleFont;
        public StandardPrint(Component c) {
            this.c = c;
            if (c instanceof SpecialPrint) {
                sp = (SpecialPrint)c;
        public StandardPrint(SpecialPrint sp) {
            this.sp = sp;
        public void setNumberFont(Font f) {
            mPageNumberFont = f;
        public Font getNumberFont () {
            return mPageNumberFont;
        public int getPageNumberHAlignment () {
            return hAlign;
        public int getPageNumberVAlignment() {
            return vAlign;
        public void setPageNumberHAlignment(int num) {
            hAlign = num;
        public void setPageNumberVAlignment(int num) {
            vAlign = num;
        public void setPrintPageNumber(boolean b) {
             mPrintPageNumber = b;
        public boolean getPrintPageNumber() {
             return mPrintPageNumber;
        protected void printPageNumber(Graphics g, PageFormat format, int pageNo) {
             if (!getPrintPageNumber()) return;
             Shape clip = g.getClip();
            g.setClip(null);
            if (mPageNumberFont != null) {
                g.setFont(mPageNumberFont);
            FontMetrics fm = g.getFontMetrics();
            int height = fm.getHeight();
            String pageStr = "" + (pageNo + 1);
            int width = fm.stringWidth(pageStr);
            int xspot = (int) (format.getWidth() - width) / 2;
            if (getPageNumberHAlignment() == LEFT) {
                xspot = (int) format.getImageableX();
            } else if (getPageNumberHAlignment() == RIGHT) {
                xspot = (int) (format.getWidth() - format.getImageableX() - format.getImageableWidth());
            int yspot = (int) (format.getImageableY() + format.getImageableHeight() + 2 * height);
            if (getPageNumberVAlignment() == TOP) {
                yspot = (int) format.getImageableY() / 2 - height;
                //yspot = (int) (format.getImageableY() + format.getImageableHeight() + 2 * height);
            g.drawString(pageStr, xspot, yspot);
            g.setClip(clip);
        public String getTitle() {
            return mTitle;
        public Font getTitleFont () {
            return mTitleFont;
        public void setTitleFont(Font f) {
            mTitleFont = f;
        public void setTitle(String s) {
            mTitle = s;
        protected void printTitle(Graphics g, PageFormat format) {
            if (mTitle == null) return;
             Shape clip = g.getClip();
            g.setClip(null);
            if (mTitleFont != null) {
                g.setFont(mTitleFont);
            FontMetrics fm = g.getFontMetrics();
            int height = fm.getHeight();
            int width = fm.stringWidth(mTitle);
            int xspot = (int) (format.getWidth() - width) / 2;
            int yspot = (int) format.getImageableY() / 2 + height;
            g.drawString(mTitle, xspot, yspot);
            g.setClip(clip);
         public boolean isPrintScaled () {
              return mScale;
         public void setPrintScaled(boolean b) {
              mScale = b;
         public boolean getMaintainsAspect() {
              return mMaintainRatio;
         public void setMaintainsAspect(boolean b) {
              mMaintainRatio = b;
        public void start() throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            if (mFormat == null) {
                mFormat = job.defaultPage();
            job.setPageable(this);
            if (job.printDialog()) {
                job.print();
        public void setPageFormat (PageFormat pf) {
            mFormat = pf;
        public static void printStandardComponent (Pageable p) throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPageable(p);
            job.print();
        private Dimension getJobSize() {
            if (sp != null) {
                return sp.getPrintSize();
            else {
                return c.getSize();
        public static Image preview (int width, int height, Printable sp, PageFormat pf, int pageNo) {
            BufferedImage im = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            return preview (im, sp, pf, pageNo);
        public static Image preview (Image im, Printable sp, PageFormat pf, int pageNo) {
             return preview(im, sp, pf, pageNo, true);
        public static Image preview (Image im, Printable sp, PageFormat pf, int pageNo, boolean doClipping) {
            Graphics2D g = (Graphics2D) im.getGraphics();
            int width = im.getWidth(null);
            int height = im.getHeight(null);
            double hratio = height / pf.getHeight();
            double wratio = width / pf.getWidth();
            if (doClipping) {
                 Rectangle rect = new Rectangle();
                 rect.x = (int) (pf.getImageableX() * (wratio));
                 rect.y = (int) (pf.getImageableY() * (hratio));
                 rect.width = (int) (pf.getImageableWidth() * (wratio));
                 rect.height = (int) (pf.getImageableHeight() * (hratio));
                 g.setColor(Color.GRAY);
                 g.fillRect(0, 0, width, height);
                 g.setClip(rect);
            g.scale(wratio, hratio);
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, (int) (width * 1 / wratio), (int) (height * 1 / hratio));
            //g.fillRect(0, 0, (int) (width * wratio), (int) (height * hratio));
            try {
                   sp.print(g, pf, pageNo);
              catch(PrinterException pe) {
                   pe.printStackTrace();
            g.dispose();
            return im;
        public int print(Graphics gr, PageFormat format, int pageNo) {
            mFormat = format;
            if (pageNo > getNumberOfPages()) {
                return Printable.NO_SUCH_PAGE;
            Graphics2D g = (Graphics2D) gr;
              //wha?? don't know what this was doing in the code
            //g.drawRect(0, 0, (int)format.getWidth(), (int)format.getHeight());
            if (getTitle() != null) {
                   printTitle(g, format);
              if (getPrintPageNumber()) {
                   printPageNumber(g, format, pageNo);
            g.translate((int)format.getImageableX(), (int)format.getImageableY());
            //Dimension size = getJobSize();
              if (!isPrintScaled()) {
                 int horizontal = getNumHorizontalPages();
                 //don't need this I don't think
                 //int vertical = getNumVerticalPages();
                 int horizontalOffset = (int) ((pageNo % horizontal) * format.getImageableWidth());
                 int verticalOffset = (int) ((pageNo / horizontal) * format.getImageableHeight());
                 double ratio = getScreenRatio();
                 g.scale(1 / ratio, 1 / ratio);
                 g.translate(-horizontalOffset, -verticalOffset);
                 if (sp != null) {
                     sp.printerPaint(g);
                 else {
                     c.paint(g);
                 g.translate(horizontalOffset, verticalOffset);
                 g.scale(ratio, ratio);
              else {
                 double ratio = getScreenRatio();
                 g.scale(1 / ratio, 1 / ratio);
                   double xScale = 1.0;
                   double yScale = 1.0;
                   double wid;
                   double ht;
                   if (sp != null) {
                        wid = sp.getPrintSize().width;
                        ht = sp.getPrintSize().height;
                   else {
                        wid = c.getWidth();
                        ht = c.getHeight();
                   xScale = format.getImageableWidth() / wid;
                   yScale = format.getImageableHeight() / ht;
                   if (getMaintainsAspect()) {
                        xScale = yScale = Math.min(xScale, yScale);
                   g.scale(xScale, yScale);
                   if (sp != null) {
                        sp.printerPaint(g);
                   else {
                        c.paint(g);
                   g.scale(1 / xScale, 1 / yScale);
                   g.scale(ratio, ratio);
             g.translate((int)-format.getImageableX(), (int)-format.getImageableY());     
            return Printable.PAGE_EXISTS;
        public int getNumHorizontalPages() {
            Dimension size = getJobSize();
            if (mFormat == null) mFormat = getPageFormat(0);
            int imWidth = (int)mFormat.getImageableWidth();
            int pWidth = 1 + (int)(size.width / getScreenRatio() / imWidth) - (imWidth / getScreenRatio() == size.width ? 1 : 0);
            return pWidth;
        private double getScreenRatio () {
            double res = Toolkit.getDefaultToolkit().getScreenResolution();
            double ratio = res / 72.0;
            return ratio;
        public int getNumVerticalPages() {
            Dimension size = getJobSize();
            int imHeight = (int)mFormat.getImageableHeight();
            int pHeight = (int) (1 + (size.height / getScreenRatio() / imHeight)) - (imHeight == size.height ? 1 : 0);
            return pHeight;
        public int getNumberOfPages() {
              if (isPrintScaled()) return 1;
            return getNumHorizontalPages() * getNumVerticalPages();
        public Printable getPrintable(int i) {
            return this;
        public PageFormat getPageFormat(int page) {
            if (mFormat == null) {
                PrinterJob job = PrinterJob.getPrinterJob();
                mFormat = job.defaultPage();
            return mFormat;
        public static void main(String args[]) {
             //final GradientPane gp = new GradientPane(400,400);
             //JFrame jf = new JFrame("Standard Print Test");
             //jf.add(gp);
             JFrame jf = new JFrame("StandardPrint Test");
             final JTextArea area = new JTextArea();
             area.append("hello\n");
             for (int i = 0; i < 50; i++) {
                  area.append("\n");
             area.append("world\n");
             JScrollPane sp = new JScrollPane(area);
             jf.add(sp);
             JMenuBar bar = new JMenuBar();
             FileMenu fm = new FileMenu() {
                   private static final long serialVersionUID = 1L;
                   public void load(File f) {}
                  public void save(File f) {}
                  public Pageable getPageable() {
                       //return new StandardPrint(gp);
                       return new StandardPrint(area);
             JMenu printMenu = new JMenu("Print");
             JMenuItem print = new JMenuItem("Print");
             printMenu.add(print);
             ActionListener al = new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
                       StandardPrint sp = new StandardPrint(area);
                       sp.setTitle("Hello World");
                       sp.setPrintPageNumber(true);
                       sp.setPageNumberVAlignment(BOTTOM);
                       sp.setPageNumberHAlignment(CENTER);
                       System.out.println(sp.getNumberOfPages());
                       Image im1 = preview(300,300, sp, sp.getPageFormat(0), 0);
                       Image im2 = preview(300,300, sp, sp.getPageFormat(1), 1);
                       JLabel l = new JLabel(new ImageIcon(im1));
                       WindowUtilities.visualize(l, false);
                       l = new JLabel(new ImageIcon(im2));
                       WindowUtilities.visualize(l, false);
             print.addActionListener(al);
             jf.setJMenuBar(bar);
             bar.add(fm);
             bar.add(printMenu);
             jf.setBounds(100,100,400,400);
             jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             jf.setVisible(true);
         * Interface for using StandardPrint with something other than a Component or something
         * that needs special printing
        public static interface SpecialPrint {
            public Dimension getPrintSize();
            public void printerPaint(Graphics g);
    }

    And SpecialPrint
    * Interface for using StandardPrint with something other than a Component or something
    * that needs special printing
    * @author tjacobs
    public interface SpecialPrint {
    public Dimension getPrintSize();
    public void printerPaint(Graphics g);
    }

  • How do i get the system resolution?

    ya ^^
    How do i get the system resolution?
    thx nate

    java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    java.awt.Toolkit.getDefaultToolkit().getScreenResolution();

Maybe you are looking for

  • Virtual Character in Bex Query / Filter by Attribute

    Hi , We have a query where we need to resrict the query result by a character at run time. I think this is done by using virtuual characters with user exit RSR00002...Here is our requirement. We have the PCA query with Cost element heirarchy (Revenue

  • Q10 + Exchange 2007 SP3 - random calendar entries not synching

    Hi, We have an executive user with a BB Q10 with software v10.1.0.314.  The devices connects via WiFi or 3G to our Exchange 2007 SP3 server and mail/contacts/etc all appear to be flowing normally.  However, the user has reported that some calendar ap

  • Recording sound with Siemens API

    Hello, there is only com.siemens.mp.media package instead of javax.microedition.media on my Siemens C55. It containes most of classes from MMAPI but class RecordControl is missing:( Is there some other approach how to record sound in java on this tel

  • Database character set migration rules

    We have an application which migrates various entities from one database to the other. These databases could have different character sets. The migration process is automated. What character set rules should we follow while migration? Can we use the

  • Kindle App not working with yosemite

    Hi All. After I downloaded the new Yosemite. I had a notice that said my free kindle app downloaded from amazon is not supported by Yosemite. I Have lots of books stored in this app and I need to know is this down to Apple to fix or should I complain