Drawing a Graphics object on a Graphics object

Is there anyway to draw a Graphics object on another Graphics object? I'm trying to show 2 screens, side by side, on a Canvas and I'm trying to cheat a little :-P Basically, I want to take half of one screen and half of another and put them on top of each other to form one screen.
OR is there a way to turn a Graphics object into an Image object?

I'm not sure if this is what you're after, but you can
- create an offscreen image using "createImage(int width, int height)" method of a Component , then
- obtain the graphics context of the offscreen image using "getGraphics()",
- you can then draw onto the offscreen image using the graphics context.
hope that helps. =)

Similar Messages

  • Drawing 2D graphics with no frame or no panel ?

    Hi,
    I would like to know if it is possible to draw 2D graphics directly over the OS(windows2002) ? like drawing a rectangle over the desktop without any JPanel or JFrame.
    cheers,
    sletourne

    It is possible, I've done it ;-)
    import java.awt.*;
    import java.awt.event.*;
    public class JustSomething implements WindowListener
         public static void main(String args[])
              new JustSomething();
         public JustSomething()
              Frame winf = new Frame();
              winf.setLocation(2000,2000);
              winf.add(new java.awt.Label("If you see this you have a mighty big screen"));
              Window win = new Window(winf);          
              win.setSize(width,height);
              winf.addWindowListener(this);
         public void windowOpened(WindowEvent windowevent){}
         public void windowClosing(WindowEvent windowevent){}
         public void windowClosed(WindowEvent windowevent){}
         public void windowIconified(WindowEvent windowevent){}
         public void windowDeiconified(WindowEvent windowevent){}
         public void windowActivated(WindowEvent windowevent){}
         public void windowDeactivated(WindowEvent windowevent){}

  • Can somebody help me out? I need a Corel Draw (.cdr) graphic converted to Illustrator

    I'm trying to get a logo from brandsoftheworld.com but the one I want is in .CDR. I don't have Corel Draw (who does anymore) but I see that Illustrator 6 can open it. Unfortunately, I'm still on CS5.5. Can somebody help me out?

    Send it to me. I'll save it as an EPS file for you.
    Bob AT theindesignguy DOT com
    TwitchOSX <mailto:[email protected]>
    Thursday, January 24, 2013 7:11 PM
    >
          Can somebody help me out? I need a Corel Draw (.cdr) graphic
          converted to Illustrator
    created by TwitchOSX <http://forums.adobe.com/people/TwitchOSX> in
    /InDesign/ - View the full discussion
    <http://forums.adobe.com/message/5020999#5020999

  • TableCellRenderer, drawing to the object

    i have hit a bit of a snag and need a recommendation......
    i'm building an application that will allow the user to drag office cubicles onto a layout and move them around, etc. the list of available cubicles (sizes and such) are stored in a JTable and displayed on the left side as a single column.
    The issue i have run into is in my cell renderer.
    The user is able to create custom cubicle sizes/shapes in a seperate editor, these cubicles are then added to the table, i would like to be able to render scaled down versions of the cubicles inside the cells in the JTable as pictoral icons for each cube. inside my cell renderer class when i override the getTableCellRendererComponent method i am able to set the text, or apply an Icon but i can not get a Graphics hook to do any kind of drawing, which is what i need to do to create the scaled image of the cubicle. so i guess my question is, is it possible to draw to the TableCellRenderer object before returning it? since it is possible to write text or an icon and set the background color i am lead to believe that a Graphics context exists for the object although calls to getGraphics return null.
    thanks for any insight.
    -xian
    another solution is to store a scaled icon object in each Cubicle object but again i need to create the Icon dynamically, is there an easy facility to draw to an Icon object?

    thx for the response, i did give this a try, however since i am returning "this" it would only work for one cell, to use the paint method i would have to create a seperate instance of my cell renderer for every cubicle size and because the user can add additional cubicle sizes/shape at any time it is impossible for me to create the paint methods at run time....
    i'm starting to think that pre-drawing the cubicle thumbnail to an ImageIcon and applying that to the JLabel may accually be the easiest way to go.
    thanks!
    -xian

  • How to make lines I draw as an objects??

    Hi friends:
    I met a problem here, I find a similiar code below, but cannot solve it.
    How to make lines I draw as objects in this application??
    ie the lines I draw will be selectable as other JLabels, can be highlighted, can be deleted etc, just like any other components or object,
    How to do this??
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.Vector;
    import java.lang.reflect.Array;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Drawines
         public static void main(String[] args)
            JFrame f = new JFrame("Draw Lines");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new ConnectionPanel());
            f.setSize(400,300);
            f.setLocation(200,200);
            f.setVisible(true);
    class Drawines extends JPanel
        JLabel                                       label1, label2, label3, label4;
        JLabel[]                       labels;
        JLabel                                       selectedLabel;
        protected              JButton btn            = new JButton("DrawLines");
        protected              JButton btn1           = new JButton("Clear");
        protected              JButton btn2           = new JButton("No Draw");
        protected                      boolean isActivated = false;
        protected           int      stoppoint     = 0;          
        int cx, cy;
        Vector order                     = new Vector();
        Vector order1                     = new Vector();
        Object[] arr                    = null;
        public ConnectionPanel()
            setLayout(null);
            addLabels();
            label1.setBounds( 25,  50, 125, 25);
            label2.setBounds(225,  50, 125, 25);
            label3.setBounds( 25, 175, 125, 25);
            label4.setBounds(225, 175, 125, 25);
            btn.setBounds(10, 5, 100, 25);
            btn1.setBounds(100, 5, 100, 25);
            btn2.setBounds(200, 5, 100, 25);
                add(btn);
             add(btn1);
             add(btn2);
            determineCenterOfComponents();
            ComponentMover mover = new ComponentMover();
             ActionListener lst = new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                     ComponentMover mover = new ComponentMover();
                           addMouseListener(mover);
                           addMouseMotionListener(mover);
                           isActivated = false;
            ActionListener lst1 = new ActionListener() {
                       public void actionPerformed(ActionEvent e) {
                           isActivated=true;
              btn.addActionListener(lst);
              btn1.addActionListener(lst1);
        public void paintComponent(final Graphics g)
             super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
             Point[] p;
                System.out.println("order.size()"+ order.size());
                System.out.println("order1.size()"+ order1.size());
                     if (!isActivated && order1.size()==0) {
                         for(int i = 0 ; i < order.size()-1; i++) {
                                JLabel l1 = (JLabel)order.elementAt(i);
                               JLabel l2 = (JLabel)order.elementAt(i+1);
                               order1.add(order.elementAt(i));
                               order1.add(order.elementAt(i+1));
                               System.out.println();
                               p = getCenterPoints(l1, l2);
                               g2.setColor(Color.black);
                                            g2.draw(new Line2D.Double(p[0], p[1]));            
                     }else if(!isActivated && order1.size()>0){
                             order=order1;
                         for(int i1 = 0 ; i1 < order.size()-1; i1++) {
                               JLabel l1 = (JLabel)order.elementAt(i1);
                               JLabel l2 = (JLabel)order.elementAt(i1+1);
                               System.out.println();
                               p = getCenterPoints(l1, l2);
                               g2.setColor(Color.red);
                                g2.draw(new Line2D.Double(p[0], p[1]));    
                                System.out.println(" order1.size() = " + order.size());
                     }else {
                          order1 = order;
                         for(int i1 = 0 ; i1 < order1.size()-1; i1++) {
                                    JLabel l1 = (JLabel)order1.elementAt(i1);
                                    JLabel l2 = (JLabel)order1.elementAt(i1+1);
                                    p = getCenterPoints(l1, l2);
                                    g2.setColor(Color.blue);
                                    if (order.elementAt(i1) !=null){
                                         g2.draw(new Line2D.Double(p[0], p[1]));    
        private Point[] getCenterPoints(Component c1, Component c2)
            Point
                p1 = new Point(),
                p2 = new Point();
            Rectangle
                r1 = c1.getBounds(),
                r2 = c2.getBounds();
                 p1.x = r1.x + r1.width/2;
                 p1.y = r1.y + r1.height/2;
                 p2.x = r2.x + r2.width/2;
                 p2.y = r2.y + r2.height/2;
            return new Point[] {p1, p2};
        private void determineCenterOfComponents()
            int
                xMin = Integer.MAX_VALUE,
                yMin = Integer.MAX_VALUE,
                xMax = 0,
                yMax = 0;
            for(int i = 0; i < labels.length; i++)
                Rectangle r = labels.getBounds();
    if(r.x < xMin)
    xMin = r.x;
    if(r.y < yMin)
    yMin = r.y;
    if(r.x + r.width > xMax)
    xMax = r.x + r.width;
    if(r.y + r.height > yMax)
    yMax = r.y + r.height;
    cx = xMin + (xMax - xMin)/2;
    cy = yMin + (yMax - yMin)/2;
    private class ComponentMover extends MouseInputAdapter
    Point offsetP = new Point();
    boolean dragging;
    public void mousePressed(MouseEvent e)
    Point p = e.getPoint();
    for(int i = 0; i < labels.length; i++)
    Rectangle r = labels[i].getBounds();
    if(r.contains(p) && !isActivated )
    selectedLabel = labels[i];
    order.addElement(labels[i]);
    offsetP.x = p.x - r.x;
    offsetP.y = p.y - r.y;
    dragging = true;
    repaint(); //added
    break;
    public void mouseReleased(MouseEvent e)
    dragging = false;
    public void mouseDragged(MouseEvent e)
    if(dragging)
    Rectangle r = selectedLabel.getBounds();
    r.x = e.getX() - offsetP.x;
    r.y = e.getY() - offsetP.y;
    selectedLabel.setBounds(r.x, r.y, r.width, r.height);
    //determineCenterOfComponents();
    repaint();
    private void addLabels()
    label1 = new JLabel("Label 1");
    label2 = new JLabel("Label 2");
    label3 = new JLabel("Label 3");
    label4 = new JLabel("Label 4");
    labels = new JLabel[] {
    label1, label2, label3, label4
    for(int i = 0; i < labels.length; i++)
    labels[i].setHorizontalAlignment(SwingConstants.CENTER);
    labels[i].setBorder(BorderFactory.createEtchedBorder());
    add(labels[i]);
    Thanks in advance.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    2 choice, bundle your app in a jar, or get a native compiler.
    executable jar
    http://java.sun.com/j2se/1.3/docs/guide/jar/jarGuide.html
    http://developer.java.sun.com/developer/qow/archive/21/index.html
    native
    http://gcc.gnu.org/java/
    http://www-106.ibm.com/developerworks/library/j-native.html
    http://icafe.sourceforge.net/
    http://www.towerj.com/
    http://www.xlsoft.com/en/products/development/jet/jetpro.html

  • Inability to draw simple graphics in Java properly (threads and JFrame)

    I am trying to use a thread to continually draw randomly positioned and randomly sized squares in the middle of a JFrame window. I have got 'something' working with the following code, however when run, the actual window doesn't come up properly. If I resize the window it does, and I get the result I wanted, but when the window is first opened it does not fully draw itself on screen. Can anybody help here? I am a bit of a novice when it comes to Java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class TestDraw extends JFrame implements Runnable {
    //DECLARE VARIABLES
         private JLabel lblText;
         private JButton btnBegin;
         private JPanel contentPane;
         private int CoordX, CoordY,SizeX, SizeY, Colour;     // Co'ords for drawing the squares
         Random random = new Random();                              // Random numbers (for square dimensions and colours)
         int n_1 = 450, n_2 = 130, n_3 = 100, n_4 = 4;          // The different ranges of randoms I require
         Thread squares = new Thread(this);                         // Implements a new thread
    //END OF DECLARE VARIABLES
    // CALLS INITIAL PROCEDURE, SETS VISIBLE ETC
         public TestDraw() {
              super();
              initializeComponent();
              this.setVisible(true);
    // INITIALISATION PROCEDURE CALL
         private void initializeComponent() {
              lblText = new JLabel();
              btnBegin = new JButton();
              contentPane = (JPanel)this.getContentPane();
              // lblText
              lblText.setText("This should draw squares on screen...");
              // btnBegin
              btnBegin.setText("Start");
              btnBegin.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        btnBegin_actionPerformed(e);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, lblText, 10,300,364,18);
              addComponent(contentPane, btnBegin, 144,10,101,28);
              // TestDraw
              this.setTitle("TestDraw Program for CM0246");
              this.setLocation(new Point(0, 0));
              this.setSize(new Dimension(390, 350));
    // POSITION COMPONENTS ON SCREEN
         private void addComponent(Container container,Component c,int x,int y,int width,int height)     {
              c.setBounds(x,y,width,height);
              container.add(c);
    // EVENT HANDLING PROCEDURES
         private void btnBegin_actionPerformed(ActionEvent e) {
              System.out.println("\nAction Event from btnBegin called...");
              squares.start(); //STARTS THE SQUARES DRAWING THREAD (Draws random squares on screen)
    // THE MAIN METHOD (STARTS THE PROGRAM)
         public static void main(String[] args) {
              TestDraw bobdole = new TestDraw();
    // THE SQUARE DRAWINGS THREAD (SHOULD DRAW RANDOM SIZED AND COLOURED SQUARES IN RANDOM PLACES)
         public void run() {
              System.out.println("Thread running if this prints");
                   while(true) {
                        int int_1 = random.nextInt(n_1);     // chooses random int for X co'ord
                        int int_2 = random.nextInt(n_2)+70;     // chooses random int for Y co'ord
                        int int_3 = random.nextInt(n_3)+10;     // chooses random int for X dimension
                        int int_4 = random.nextInt(n_3)+10;     // chooses random int for Y dimension
                        CoordX = int_1;
                        CoordY = int_2;
                        SizeX  = int_3;
                        SizeY  = int_4;
                        repaint();
                        try {
                             squares.sleep(500);
                        catch (InterruptedException e) {
                             System.out.println(e);
    // THE PAINT METHOD ATTATCHED TO THE SQUARES THREAD
         public void paint( Graphics g ) {
              System.out.print("Colour" + Colour);
              g.setColor(Color.blue);
              g.fillRect(CoordX, CoordY, SizeX, SizeY);
    // END OF PROGRAM

    I don't see any problem when I run the program but.. In general you shouldn't paint directly on a frame by overloading the paint method. You should rather create a custom component on which you draw.
    But if you do overload paint, make sure you call super.paint before doing anything else.
    More information in this tutorial: http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html

  • Drawing with graphics

    If I draw a rounded rectangle from top to bottom, the corners are nicely rounded. If I draw the rectangle from bottom to top the entire shape is rounded instead of just the corners. How can I draw from bottom to top and still round just the corners?
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"   creationComplete="init()">
        <mx:Script>
            <![CDATA[
                private function init():void{
                    canvas.graphics.beginFill(0xffff00);
                    canvas.graphics.drawRoundRect(300,300,50,200, 20, 20);
                    canvas.graphics.drawRoundRect(600,500,50,-200, 20, 20);
            ]]>
        </mx:Script>
    <mx:Canvas id="canvas"    />
    </mx:Application>

    If I draw a rounded rectangle from top to bottom, the corners are nicely rounded. If I draw the rectangle from bottom to top the entire shape is rounded instead of just the corners. How can I draw from bottom to top and still round just the corners?
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"   creationComplete="init()">
        <mx:Script>
            <![CDATA[
                private function init():void{
                    canvas.graphics.beginFill(0xffff00);
                    canvas.graphics.drawRoundRect(300,300,50,200, 20, 20);
                    canvas.graphics.drawRoundRect(600,500,50,-200, 20, 20);
            ]]>
        </mx:Script>
    <mx:Canvas id="canvas"    />
    </mx:Application>

  • Appleworks6 (drawing - text & graphics) to be converted - how?

    I have a lot of mathematics worksheets, produced on Appleworks6 (on the drawing package with text and graphics) over the years. The new OS will not support Rosetta, I understand, and so I need to transfer (translate?) all the worksheets into a more modern format, available to both Mac and PC users. How do I do this and what applications are now available which will be suitable? If I try Word:mac (11.6.3) it tells me the Appleworks6 drawing document is not the right file type.

    If it were an AW6 text document with inserted graphics, then Pages would probably open it.
    However, as a drawing document with text added that may not work. It is possible that Keynote might be able to open it.
    Edit - - nope - just tried it with Keyboate, won't do it.
    Just played with AW6 a bit. If these documents are static docs, meaning ones which do not need to be changed or otherwise addressed except viewed, there's other choices. One I tried just now in AW6, ws to do a Save As and change the format to JPEG.
    This resulted in a document that should be openable by most anyone. In OS X, it opens in Preview automatically, but should be able to be opened in any app that can open JPEG files.
    In Pages it got a bit trickier - Pages would not open it directly, not even via Open in File menu. But, when I treated it as a regular JPEG it worked: I opened a blank text doc in Pages, then drag-and-dropped the JPEG file into it. That worked - gave me a Pages doc with an inserted image of the original AW6 graphics file.

  • Drawing 2d graphics

    Sorry, does anybody know the most convenient way to draw graphics? f.e to draw graphic just on two vectors of points X and Y. Rrd4J is not enough good because rrd works with time.

    To whom it may be interest.
    This is a small example to draw a chart having "values on X" and "values on Y" :-) using JFreeChart
    import java.awt.Font;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import junit.framework.TestCase;
    import org.jfree.chart.ChartFactory;
    import org.jfree.chart.JFreeChart;
    import org.jfree.chart.axis.NumberAxis;
    import org.jfree.chart.plot.PlotOrientation;
    import org.jfree.chart.plot.XYPlot;
    import org.jfree.chart.title.TextTitle;
    import org.jfree.data.xy.XYDataset;
    import org.jfree.data.xy.XYSeries;
    import org.jfree.data.xy.XYSeriesCollection;
    public class SimpleChartTest extends TestCase {
         private XYSeriesCollection createDataset() {
              XYSeriesCollection result = new XYSeriesCollection();
              XYSeries s3 = new XYSeries("P", true, false);
              s3.add(0, 2.355450986);
              s3.add(0.5, 2.799548641);
              s3.add(1.5, 3.614688072);
              s3.add(11.5, 8.283364855);
              s3.add(12.5, 8.534275028);
              s3.add(13.5, 8.762648582);
              s3.add(14.5, 8.971407287);
              s3.add(15.5, 9.163180317);
              s3.add(16.5, 9.340328068);
              s3.add(17.5, 9.504964014);
              s3.add(19.5, 9.804039109);
              s3.add(20.5, 9.941644878);
              result.addSeries(s3);
              return result;
         private JFreeChart createChart(XYDataset dataset) {
              JFreeChart chart = ChartFactory.createXYLineChart(null,
                        "Value on X", "Value on Y", dataset, PlotOrientation.VERTICAL, true,
                        true, false);
              TextTitle t1 = new TextTitle("Title1", new Font(
                        "SansSerif", Font.BOLD, 14));
              TextTitle t2 = new TextTitle(
                        "Title2",
                        new Font("SansSerif", Font.PLAIN, 11));
              chart.addSubtitle(t1);
              chart.addSubtitle(t2);
              XYPlot plot = chart.getXYPlot();
              NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
              domainAxis.setUpperMargin(0.12);
              domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
              NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
              rangeAxis.setAutoRangeIncludesZero(false);
              return chart;
         public void test() throws IOException {
              XYSeriesCollection dataset = createDataset();
              JFreeChart chart = createChart(dataset);
              BufferedImage image = chart.createBufferedImage(360, 500);
              File file = new File("test-data/charts/newimage.png");
    ImageIO.write(image, "png", file);
    }

  • Drawing 2D Graphics in the center of a JPanel

    Hi,
    Below is my GUI. The basic idea is, I want this to create a neat UI on any machine with any monitor resolution settings. Because I dont really know what will be the resolution of the target machine, I do not perform a setPreferred size on any component. I have several problems here.
    1. My DiagramPanel.paintComponent method relies on the Panel's preferred size to draw a rectangle in the center of the panel. When a panel is layed out using BorderLayout, it expands it to fit the space. So is there some method I can use to know, what space the component panel is occupying (its dimension) ?
    2. Also, when the frame is maximized or resized, the DiagramPanel's dimension changes. So I want to be able to redraw the diagram in the new center position. How can I do this ?
    4. I am using the Frame size to be the screen dimension and set it to be maximized. So when I try to restore the window, it takes up the whole screen even the space including the windows taskbar. Is there someway to get the screen dimension leaving out the space for the taskbar ?
    3. I dont set the DividerLocation of the contentPane because, I want it to be set automatically based on the contents of the leftPanel. But when i print out the dividerLocation after creating the UI, it prints -1. How can I get the current divider location then ?
    import java.awt.BorderLayout;
    import java.awt.Button;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.LayoutManager;
    import java.awt.Toolkit;
    import java.awt.Graphics;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextArea;
    @SuppressWarnings("serial")
    public class MainFrame extends JFrame {
    public MainFrame() {
    createAndShowGUI();
    private void createAndShowGUI() {
    initMainFrame();
    initMenus();
    initPanels();
    initContentPane();
    setVisible(true);
    System.out.println("Divider location "+ contentPane.getDividerLocation());
    private void initMainFrame() {
    setTitle("Main Frame");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setState(JFrame.NORMAL);
    //GETS SCREEN SIZE
    Dimension screen_Dimension = Toolkit.getDefaultToolkit().getScreenSize();
    setSize(screen_Dimension.width, screen_Dimension.height);
    setExtendedState(MAXIMIZED_BOTH);
    private void initContentPane() {
    getContentPane().add(contentPane);
    contentPane.setEnabled(false); / *prevent the divider location from being moved* /
    contentPane.setLeftComponent(leftpanel);
    contentPane.setRightComponent(rightpanel);
    contentPane.setOpaque(true);
    private void initMenus() {
    exitMenu.setActionCommand(EXIT_COMMAND);
    file.add(exitMenu);
    menub.add(file);
    setJMenuBar(menub);
    private void initPanels() {
    initLeftPanel();
    initRightPanel();
    private void initLeftPanel() {
    leftpanel.setLayout(new FlowLayout(FlowLayout.CENTER));
    leftpanel.add(new Button("Click"));
    private void initRightPanel() {
    LayoutManager border = new BorderLayout();
    rightTab.setLayout(border);
    scrollingDiagram = new JScrollPane(diagramPanel);
    diagramDescriptionPanel.setLayout(new BorderLayout());
    diagramDescriptionPanel.add(diagDescTextArea, BorderLayout.CENTER);
    rightTab.add(scrollingDiagram, BorderLayout.CENTER);
    rightTab.add(diagramDescriptionPanel, BorderLayout.SOUTH);
    rightpanel.addTab("Right Tab", rightTab);
    public static void main(String args[]) {
    try {
    new MainFrame();
    } catch (Exception e) {
    e.printStackTrace();
    System.exit(0);
    private JSplitPane contentPane = new JSplitPane();
    private JMenuBar menub = new JMenuBar();
    private JMenu file = new JMenu("File");
    private JMenuItem exitMenu = new JMenuItem("Exit");
    private JPanel leftpanel = new JPanel();
    private JTabbedPane rightpanel = new JTabbedPane();
    private JPanel rightTab = new JPanel();
    private JScrollPane scrollingDiagram;
    private DiagramPanel diagramPanel = new DiagramPanel();
    private JPanel diagramDescriptionPanel = new JPanel();
    private JTextArea diagDescTextArea = new JTextArea(18, 45);
    public static final String EXIT_COMMAND = "Exit";
    @SuppressWarnings("serial")
    class DiagramPanel extends JPanel{
    public static int RECT_WIDTH = 100;
    public static int RECT_HEIGHT = 75;
    public void paintComponent(Graphics g) {
    super.paintComponents(g);
    Coordinates centerOfPanel = getCenterCoordinates();
    g.drawRoundRect(centerOfPanel.x, centerOfPanel.y, RECT_WIDTH, RECT_HEIGHT, 10, 10);
    public Coordinates getCenterCoordinates() {
    Dimension panelDimension = getPreferredSize();
    int x = (panelDimension.width - RECT_WIDTH) / 2;
    int y = (panelDimension.width - RECT_HEIGHT) / 2;
    return new Coordinates(x,y);
    class Coordinates {
    int x;
    int y;
    Coordinates(int x, int y) {
    this.x = x;
    this.y = y;

    Hi,
    The getSize worked perfectly for me. But what I tried doing now is that, instead of just the simple centering of the rectangle, i did this
    1. When the dimension of the rectangle is smaller than the Panel.getSize(), do centering as usual
    2. else when the rectangle is bigger, say because its width was longer than Panel.getSize().getWidth(), I center the rectangle only on its Height, and set the preferred size of the Panel to (rectangle.getWidth(), panel.getSize().getHeight()). And I call revalidate, so that the scrollbars appear.
    Problem im running into now is that, once I do a setPreferredSize, everytime I use a getSize later on, i always get the same size. But what I want to see is that, when the rectangle can fit in the panel, i want it centered without any scrollbars, but when it cannot fit on the width, i want it to appear centered on height, but have a horizontal scroll bar.
    I'd be really grateful, if you could help me with this.
    Here is the code
    public void paintComponent(Graphics g) {
              super.paintComponents(g);
              Coordinates centerOfPanel = getCenterCoordinates();
              g.drawRoundRect(centerOfPanel.x, centerOfPanel.y, RECT_WIDTH, RECT_HEIGHT, 10, 10);
              //preferredSize might have changed, call revalidate
              revalidate();
    public static final int PANEL_MARGIN = 50;
    public Coordinates getCenterCoordinates() {
              setPreferredSize(null);
              Dimension panelDimension = getSize();
              Dimension myPreferredSize = new Dimension();
              if (panelDimension.width > RECT_WIDTH)
                   myPreferredSize.width = panelDimension.width;
              else
                   myPreferredSize.width = RECT_WIDTH + 2 * PANEL_MARGIN; // MARGIN on left end and right end
              if (panelDimension.height > RECT_HEIGHT)
                   myPreferredSize.height = panelDimension.height;
              else
                   myPreferredSize.height = RECT_HEIGHT + 2 * PANEL_MARGIN; // MARGIN on top and bottom
              System.out.println("Panel size is " + getSize());
              setPreferredSize(myPreferredSize);
              System.out.println("Preferred size is " + myPreferredSize);
              //center of the panel.
              int x = (myPreferredSize.width - RECT_WIDTH) / 2;
              int y = (myPreferredSize.height - RECT_HEIGHT) / 2;
              return new Coordinates(x,y);
         }

  • How to use a Graphics Object in a JSP?

    Hello, I do not know if this is a good or a silly question. Can anyone tell me if we can use a Graphics object in a JSP. For example to draw a line or other graphics, i am planning to use the JSP. Any help is much appreciated.
    Regards,
    Navin Pathuru.

    Hi Rob or Jennifer, could you pour some light here.
    I have not done a lot of research for this, but what i want to do is below the polygon i would like to display another image object like a chart... is it possible? If so how to do it? Any help is much appreciated.
    here is the code:
    <%
    // Create image
    int width=200, height=200;
    BufferedImage image = new BufferedImage(width,
    height, BufferedImage.TYPE_INT_RGB);
    // Get drawing context
    Graphics g = image.getGraphics();
    // Fill background
    g.setColor(Color.white);
    g.fillRect(0, 0, width, height);
    // Create random polygon
    Polygon poly = new Polygon();
    Random random = new Random();
    for (int i=0; i < 5; i++) {
    poly.addPoint(random.nextInt(width),
    random.nextInt(height));
    // Fill polygon
    g.setColor(Color.cyan);
    g.fillPolygon(poly);
    // Dispose context
    g.dispose();
    // Send back image
    ServletOutputStream sos = response.getOutputStream();
    JPEGImageEncoder encoder =
    JPEGCodec.createJPEGEncoder(sos);
    encoder.encode(image);
    %>
    Regards,
    Navin Pathuru

  • Drawing on a visual object

    Hi everyone,
    Is it possible to draw on visual objects in java 3d.
    e.g. Could the user draw a shape on a sphere?
    thanks

    I'm not sure if this is what you're after, but you can
    - create an offscreen image using "createImage(int width, int height)" method of a Component , then
    - obtain the graphics context of the offscreen image using "getGraphics()",
    - you can then draw onto the offscreen image using the graphics context.
    hope that helps. =)

  • How can i draw a outline around an object in a picture

    I am trying to draw around an object in a picture to show the different values and defined edges.  Can anyone help?

    Use one of the selection tools -- lasso, rectangle marquee or elliptical marquee, for example.
    Photoshop Help | Making selections
    Nancy O.

  • Drawing object on the intersections point of 2 lines.

    hi guys, im very new in actionscrip , please give me some guidance.
    i'm doing this project , about 2 lines intersecting each other(the 2 lines are not always on the same position) . i try to find the intersections point using collision detection method but how do i place an object on the intersections point?
    if(line1.hitTestObject(line2)) //  so this is how we find the intersection point but we do not know how to draw/place an object on the  intersection point.

    then it's easier to calculate the intersection algebraically:
    function intersectionF(x1:Number,y1:Number,x2:Number,y2:Number,x3:Number,y3:Number,x4:Number,y4:Number):Array {
         if (x1==x2) {
              if (x3==x4) {
                   if (x1==x3) {
                        return ["line1"];
                   } else {
                        return [null];
              } else {
                   // line 1 vert, line 2 not
                   var m2:Number = (y3-y4)/(x3-x4);
                   var b2:Number = y3-m2*x3;
                   return [x1,m2*x1+b2];
         } else {
              // line 1 not vert
              if(x3==x4){
                   // line 2 vert
                   var m1:Number = (y1-y2)/(x1-x2);
                   var b1:Number = y1-m1*x1;
                   return [x3,m1*x3+b1];
              } else {
                   // line 2 not vert
                   m1 = (y1-y2)/(x1-x2);
                   b1 = y1-m1*x1;
                   m2 = (y3-y4)/(x3-x4);
                   b2 = y3-m2*x3;
                   var x:Number = (b2-b1)/(m1-m2);
                   return [x,m1*x+b1];

  • Why doesn't Object Drawing mode stay on?

    Even when I draw shapes using Object Drawing and leave it
    turned on, some shapes will randomly act as though I'm using Merge
    mode. For example, if I marquee-select several shapes on a layer
    and apply a shape tween, some of the objects will become split
    where I dragged the marquee box and the parts will do their own,
    separate tweens.
    Am I doing something wrong or is this just another
    quirk?

    Not sure i understand - by having them all unique shapes you
    are making it exponentially harder -
    all you have to do is convert 1 sqaure shape to a symbol -
    then edit that symbol and make your alpha
    animation (fade the square out).
    Next - drag as many instances (or copy and paste) of this
    symbol necessary to fill up the image - to
    place them all on different layers (you wont need to anyway)
    select tham all - right click over them
    and select Distribute to Layers (takes a couple seconds).
    Then simply duplicate this scene (using
    the Scene panel) for each new image. Really simple :)
    Chris Georgenes / mudbubble.com / keyframer.com / Adobe
    Community Expert
    tunghoy wrote:
    > OK, then maybe you can suggest a different method of
    what I'm doing. I have
    > several dozen scenes, each with a photo on the bottom
    layer that covers the
    > whole stage. Layered on top of the photo is a grid of
    (almost) squares, divided
    > among 10 layers. Think of a 9 x 6 table that covers the
    stage. Each of the 10
    > layers has a random handful of squares that change
    opacity together.
    >
    > As each scene progresses, the squares change opacity,
    revealing more or less
    > of the photo underneath. So tweened over 100 frames, the
    squares in group 1
    > will change from 10% to 25% opacity, the squares in
    group 2 will change from
    > 50% to 42% opacity and so on. In the next scene, the
    squares in the groups will
    > change again. It creates a sort of twinkling effect.
    >
    > Right now, the squares are all shapes, not symbols. I
    didn't want to put each
    > square in a separate layer, because it would take me
    forever to create 54
    > tweens in each of dozens of scenes. And I still have
    dozens more scenes to
    > create.
    >
    > Can you think of a way to do this that makes more sense?
    >

Maybe you are looking for

  • Different Music on different devices

    I have both an iPad and an iPhone as well as a very large music collection.   Each of my Apple devices has different storage capacities.   I have already told iTunes that should only download selected songs to my Apple device.   Because of different

  • Image rendered in HTML region on same page

    I am using the Oracle OBE tutorial below to insert and manage a photo associate with an employee record. Howerver, clinking on the download link renders the image in a separte browser window. Is there any way to render the photo from the report and/o

  • This AirPort base station was unable to extend the wireless network.

    I have an AirPort Extreme in the lounge connected to BT infinity. I also have an airport express in the kitchen connected to a stereo system. I have had this set up for around 12 months. The airport express will not extend the wireless network. I res

  • Search on Items

    I have created a form in this: I want to make the logic to query the db through the forms -> If customer is not in the db then I need to add . if in then update or delete: In this i have customer_name ,cus_id and etc. customer name and cus_id -> i am

  • New stock removal strategy

    Folks, This is the scenario, We have 2-3 pallets in a single storage bin.The bin is like a deep rack in the warehouse. So the logic would be to use the Last in first out strategy to pull out the pallet which is outside/first one reachable to the user