Using paintComponent(Graphics g)

Hi,I need to know how to put a square to the screen using the paintComponent(Graphics g). The square must be put into the shapesArrayList. I know how to get a square to the screen but ive been asked to put it into the shapesArrayList.
Tried a few things but im stumped!
Any help would be great!
Peter
public void paintComponent(Graphics g){
super.paintComponents(g);
Shape nextShape;
Iterator shapesIterator = shapesArrayList.iterator();
while(shapesIterator.hasNext())
nextShape = (Shape) shapesIterator.next();
nextShape.draw(g);
are to the panel in this class

Never mind, it was just something I was doing wrong.

Similar Messages

  • Drawing without paintComponent(Graphics g)

    Hi to all,
    I use paintComponent(Graphics g) to draw particular rectangles on the screen, then i add some event to these rectangles. So far so good.I handle the mouse click from -->
    public void mouseClicked(MouseEvent e){
    // handling goes here
    But an important part of my handling is to also draw something on the screen.
    How can i do that from the mouseClicked method? Can i draw without using paintComponent(...)?
    I mean that, once the paintComponent(...) method finishes, how can i still draw something on the screen?
    Thanks,
    John.

    You can use
    Graphics gg = component.getGraphics();
    gg.draw ....
    but it will be cleared in the paintComponent method
    Look at this sample, the red rectangle will show up when the mouse
    is presses, and gone when the mouse will be released.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    public class Shapes extends JFrame
         DPanel pan = new DPanel();
    public Shapes()
         addWindowListener(new WindowAdapter()
              public void windowClosing(WindowEvent ev)
                   dispose();
                   System.exit(0);
         setBounds(10,10,400,350); 
         setContentPane(pan);
         setVisible(true);
    public class DPanel extends JPanel implements MouseListener
         Vector shapes = new Vector();
         Shape  cs;
    public DPanel()
         addMouseListener(this);
         shapes.add(new Rectangle(20,20,100,40));
         shapes.add(new Rectangle(40,80,130,60));
         shapes.add(new Line2D.Double(20,150,200,180));
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         Graphics2D g2 = (Graphics2D)g;
         for (int j=0; j < shapes.size(); j++)
              g2.draw((Shape)shapes.get(j));
         g.setColor(Color.red);
         if (cs != null) g2.draw(cs);
    public void mouseClicked(MouseEvent m) {}
    public void mouseEntered(MouseEvent m) {}
    public void mouseExited(MouseEvent m)  {}
    public void mouseReleased(MouseEvent m)
         repaint();
    public void mousePressed(MouseEvent m)
         for (int j=0; j < shapes.size(); j++)
              Shape s = (Shape)shapes.get(j);
              Rectangle r = new Rectangle(m.getX()-1,m.getY()-1,2,2);
              if (s.intersects(r))
                   cs = s;
                   Graphics g = getGraphics();
                   g.setColor(Color.red);
                   g.fillRect(r.x-5,r.y-5,10,10);
    public static void main (String[] args) 
          new Shapes();
    }

  • How to use Paintcomponent using parameters/variable

    Hi, I am new to Java.have looked in many topics of this forum, references and could not find the answer. thanks for helping.
    I am trying to test a simple procedure to draw a line from (0,0) to (x,x), where x is an integer entered by the user using a showInputDialog.
    I am using a JPanel and the paintComponent as suggested by some tutorial (so that, the frame can be moved, resized etc..and the line still remains there).
    I have tried for hours how to get the x variable into the g.drawline method. Can anyone help.
    Additionally, my frame has its top-left corner centered on the screen, resulting in the frame being shown in the bottom-right quadrant of the PC screen. How do I center it?
    thanks for the help
    package graphictest;
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Draw extends JFrame {
         public Draw(){                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
            String inputString = JOptionPane.showInputDialogu(null,"enter input")l
            int input;
            input = Integer.parseInt(inputString);
            add(new NewPanel());
         public class NewPanel extends JPanel {
               protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawLine(0, 0,input, input);
        public static void main(String[] args) {  
            Draw frame = new Draw();
            frame.setTitle("Title");
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(800,800);
            frame.setVisible(true);
    }

    You need to make the variable input a class variable, not a variable local to any one method:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    public class Draw extends JFrame
        private int input = 0; //*** you need input to be a class variable
        public Draw()
            String inputString = JOptionPane.showInputDialog(null, "enter input");
            //int input;  //*** and not a variable local to this method!
            input = Integer.parseInt(inputString);
            add(new NewPanel());
        public class NewPanel extends JPanel
            protected void paintComponent(Graphics g)
                super.paintComponent(g);
                g.drawLine(0, 0, input, input);
        public static void main(String[] args)
            Draw frame = new Draw();
            frame.setTitle("Title");
            //frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //frame.setSize(800, 800);
            frame.setPreferredSize(new Dimension(800, 800));
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }

  • Problems with basic Java JPanel animation using paintcomponent

    okay so I am trying to animate a sprite moving across a background using a for loop within the paintComponent method of a JPanel extension
    public void paintComponent(Graphics g){
    Image simpleBG = new ImageIcon("Images/Backgrounds/Simple path.jpg").getImage();
    Image mMan = new ImageIcon("Images/Sprites/hMan.gif").getImage();
    if (!backgroundIsDrawn){
    g.drawImage(simpleBG, 0, 0, this);
    g.drawImage(mMan, xi, y, this);
    backgroundIsDrawn=true;
    else
    for (int i=xi; i<500; i++){
    g.drawImage(simpleBG, 0, 0, this);
    g.drawImage(mMan, i, y, this);
    try{
    Thread.sleep(10);
    } catch(Exception ex){System.out.println("damn");}
    The problem is that no matter what I set my thread to, it will not show the animation, it will just jump to the last location, even if the thread sleep is set high enough that it takes several minutes to calculate,, it still does not paint the intemediary steps.
    any solution, including using a different method of animation all together would be greatly appreciated. I am learning java on my own so i need all the help I can get.

    fysicsandpholds1014 wrote:
    even when I placed the thread sleep outside of the actual paintComponent in a for loop that called repaint(), it still did not work? Nope. Doing this will likely put the Event Dispatch Thread or EDT to sleep. Since this is the main thread that is responsible for Swing's painting and user interaction, you'll put your app to sleep with this. Again, use a Swing Timer
    and is there any easy animation method that doesnt require painting and repainting every time becasue it is very hard to change what I want to animate with a single paintComponent method? I don't get this.
    I find the internet tutorials either way too complicated or not nearly in depth enough. Maybe its just that I am new to programming but there doesn't seem to be a happy medium between dumbed down Swing tutorials and very complicated and sophisticated animation algorithmns.I can only advise that you practice, practice, practice. The more you use the tutorials, the easier they'll be to use.
    Here's another small demo or animation. It is not optimized (repaint is called on the whole JPanel), but demonstrates some points:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    @SuppressWarnings("serial")
    public class AnimationDemo2 extends JPanel {
      // use a publicly available sprite for this example
      private static final String SPRITE_PATH = "http://upload.wikimedia.org/" +
                "wikipedia/commons/2/2e/FreeCol_flyingDutchman.png";
      private static final int SIDE = 600;
      private static final Dimension APP_SIZE = new Dimension(SIDE, SIDE);
      // timer delay: equivalent to the Thread.sleep time
      private static final int TIMER_DELAY = 20;
      // how far to move in x dimension with each loop of timer
      public static final int DELTA_X = 1;
      // holds our sprite image
      private BufferedImage img = null;
      // the images x & y locations
      private int imageX = 0;
      private int imageY = SIDE/2;
      public AnimationDemo2() {
        setPreferredSize(APP_SIZE);
        try {
          // first get our image
          URL url = new URL(SPRITE_PATH);
          img = ImageIO.read(url);
          imageY -= 3*img.getHeight()/4;
        } catch (Exception e) { // shame on me for combining exceptions :(
          e.printStackTrace();
          System.exit(1); // exit if fails
        // create and start the Swing Timer
        new Timer(TIMER_DELAY, new TimerListener()).start();
      // all paintComponent does is paint -- nothing else
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.blue);
        int w = getWidth();
        int h = getHeight();
        g.fillRect(0, h/2, w, h);
        if (img != null) {
          g.drawImage(img, imageX, imageY, this);
      private class TimerListener implements ActionListener {
        // is called every TIMER_DELAY ms
        public void actionPerformed(ActionEvent e) {
          imageX += DELTA_X;
          if (imageX > getWidth()) {
            imageX = 0;
          // ask JVM to paint this JPanel
          AnimationDemo2.this.repaint();
      // code to place our JPanel into a JFrame and show it
      private static void createAndShowUI() {
        JFrame frame = new JFrame("Animation Demo");
        frame.getContentPane().add(new AnimationDemo2());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      // call Swing code in a thread-safe manner
      public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowUI();
    }

  • Class A extends B- where is paintComponent(Graphics) supposed to paint?

    Hi,
    i have the following problem: I thought ControlPanel.paintComponent(Graphics) was supposed to paint the GraphArea (since ConrolPanel.paintComponent(Graphics) overrides GraphAreaExtension.paintComponent(Graphics) ), but lines AND vertices appear on the ControlPanel. Any ideas?
    import ...
    public class GraphAreaExtension extends JPanel
        public int clickCounter;  //how many clicks have been performed, ie
                                    //how many vertices have been painted
        public int clickedX;
        public int clickedY;
        public Point[] darray;
        public GraphAreaExtension()
            setBorder(BorderFactory.createTitledBorder("Graph Area"));
            setPreferredSize(new Dimension(640, 450)); 
            setMaximumSize(new Dimension(640, 450));
            clickCounter=0;
            darray=new Point[8];
            clickedX=-50;
            clickedY=-50;      
            initializeDarray();
            addMouseListener(new MouseAdapter()
               public void mouseClicked (MouseEvent e)
                    clickCounter++;
                    if (clickCounter<=8)
                        clickedY=e.getY();               
                        clickedX=e.getX();
                        darray[clickCounter-1]=new Point(clickedX, clickedY);
                        System.out.print("Click counter "+clickCounter+" ");                   
                        System.out.println("Mouse clicked X: "+clickedX+" Y:"+clickedY);
                        repaint();
                        validate();
        }//GraphAreaExtension constructor
        public void paintComponent(Graphics g)
            System.out.println("paint vertex...");
            g.drawOval(clickedX,clickedY, 25,25);
            g.drawString(getVertexName(clickCounter),clickedX+11, clickedY+15);
            printDarray();
        private static String getVertexName(int num)
            num=num+96;
            char c=(char)num;
            String s=String.valueOf(c);
            return s.toUpperCase();
        private void initializeDarray()
            for (int i=0; i<darray.length; i++)
                darray=new Point(0,0);
    public void printDarray()
    for (int i=0; i<darray.length;i++)
    System.out.print(darray[i].getX()+"\t");
    System.out.println();
    for (int i=0; i<darray.length;i++)
    System.out.print(darray[i].getY()+"\t");
    System.out.println();
    import ...
    /*  This is the Control Panel. 3 kinds of visual objects exist here:
    *  -the JCheckBoxes, which indicate the incoming connections: in1-in8
    *  -the JCheckBoxes, which indicate the outcoming connections: out1-out8
    *  -the "Enter" button, which when pressed updates the in/out-coming
    *   connections -graphically designs the edges, between the vertices.
    *  The data taken from the in/out-coming JCheckBoxes are stored inside
    *  2 boolean arrays respectively: inCon and outCon.
    public class ControlPanel extends GraphAreaExtension implements ItemListener
        JPanel controlPanel;
        JButton jb;
        boolean[] inCon;
        boolean[] outCon;
        JCheckBox in1, in2, in3, in4, in5, in6, in7, in8;
        JCheckBox out1, out2, out3, out4, out5, out6, out7, out8;
        public ControlPanel()
            inCon= new boolean[8];
            outCon= new boolean[8];
            initializeBooleanTable(inCon);
            initializeBooleanTable(outCon);             
            setPreferredSize(new Dimension(800,150));
            setBackground(Color.LIGHT_GRAY);                  
            setBorder(BorderFactory.createTitledBorder("Connections"));
            setPreferredSize(new Dimension(120, 150));                   
            setMaximumSize(new Dimension(120, 150));
            JLabel in= new JLabel("Incoming connections");
            add(in);
            in1=new JCheckBox("A");
            in1.addItemListener(this);
            add(in1);
            in4=new JCheckBox("D");
            in4.addItemListener(this);
            add(in4);
            in8=new JCheckBox("H");
            in8.addItemListener(this);
            add(in8);
            JLabel out= new JLabel("Outcoming connections");
            add(out);          
            out1=new JCheckBox("A");
            add(out1);      
            out1.addItemListener(this);
            out3=new JCheckBox("C");           
            add(out3);  
            out3.addItemListener(this);
            out8=new JCheckBox("H");           
            add(out8);      
            out8.addItemListener(this);
            initializeCheckbox();
           /*  pressing the Enter button, the data concerning the connections,
            *  which the user has entered are transformed into edges between the
            * vertices.
            *  Incoming edges: Green and Outcoming: Red
            jb= new JButton("Enter");
            add(jb);
            jb.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    printConnectionArrays();
                    repaint();
                    validate();
        }//ControlPanel constructor
        public void paintComponent(Graphics g)
            System.out.println("paint edge...");
            for (int i=0; i<darray.length; i++)
                if (inCon==true)
    System.out.println("Entered incoming edges condition for node num "+ (i+1));
    g.drawLine(clickedX,clickedY,(int)darray[i].getX(), (int)darray[i].getY());
    System.out.println("baseX "+clickedX+" baseY "+clickedY+" destX "+(int)darray[i].getX()+" destY "+(int)darray[i].getY());
    g.setColor(Color.GREEN);
    if (outCon[i]==true)
    System.out.println("Entered outcoming edges condition for node num "+ (i+1));
    g.drawLine(clickedX, clickedY,(int)darray[i].getX(), (int)darray[i].getY());
    System.out.println("baseX "+clickedX+" baseY "+clickedY+" destX "+(int)darray[i].getX()+" destY "+(int)darray[i].getY());
    g.setColor(Color.RED);
    }//END for
    initializeCheckbox();
    initializeBooleanTable(inCon);
    initializeBooleanTable(outCon);
    /******************************Helper***Functions***************************/
    /* unchecks Checkboxes for next use
    public void initializeCheckbox()
    in1.setSelected(false); out1.setSelected(false);
    in8.setSelected(false); out8.setSelected(false);
    public void itemStateChanged(ItemEvent e)
    System.out.println("Entered ItemStateChanged()...");
    Object source = e.getItemSelectable();
    if (source.equals(in1)) inCon[0]=true;
    else if (source.equals(in2)) inCon[1]=true;
    else if (source.equals(in8)) inCon[7]=true;
    if (source.equals(out1)) outCon[0]=true;
    else if (source.equals(out2)) outCon[1]=true;
    else if (source.equals(out8)) outCon[7]=true;
    public void printConnectionArrays()
    System.out.print("Incoming ");
    for (int i=0; i<darray.length; i++)
    System.out.print(inCon[i]+" ");
    System.out.print("Outcoming ");
    for (int i=0; i<darray.length; i++)
    System.out.print(outCon[i]+" ");
    System.out.println();
    public static void initializeBooleanTable(boolean[] t)
    for (int i=0; i<t.length-1; i++)
    t[i]=false;

    I've not a clue which is faster, but from an OO point of view--the object should know how to draw itself.

  • Calling paintComponent(Graphics g) in another class

    Dear Friends,
    I have a class (Class Pee) where I implemented the paintComponent(Graphics g) and another class (Class Bee) where I generate some datas. My intention is to call the paintComponent(Graphics g) method in class Pee at class Bee to make use of the generated data to draw some figures.
    I imported java.awt .Graphics, java.awt.Graphics2D, Polygon and geom and declared Graphics2D g2d = (Graphics2D) g; as well, but still when I call paintComponent (Graphics g) it fails to recognize the g. What is actually wrong.
    See code:
    Class Pee
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Polygon;
    import javax.swing.JPanel;
    public class Pee extends JPanel{
    private int offset;
    public void paintComponent(Graphics g, int b[], int c[]){
    super.paintComponent(g);
    Graphics2D g2D = (Graphics2D) g;
    this.setBackground(Color.white);
    Class Bee
        import java.io.*;
        import java.util.*;
        import java.awt.Graphics;
        import java.awt.Graphics2D;
        import java.awt.geom.*;
        import java.awt.Polygon;
       import Graphic.Pee; //importing Pee Class
    public class Bee{
    int x[];
    int y[];
    // other variable declaration
    public Bee{
    x = new int [5];
    y = new int [5];
    Pee dr = new Pee();
    Graphics2D g2d = (Graphics2D) g;
    //code to generate data
    dr.paintComponent(g,x,y);
    }It always say that "g" cannot be resolved. Please how do I get over this.
    Thanks,
    Jona_T

    Swing calls the paintComponent method when we ask a component to draw itself. We do this by
    calling its repaint method. So the general approach is to change the data in the component
    that does the graphics for us and then ask the component to repaint itself. Swing does the
    rest. One benefit of this way of doing things is that the graphic component keeps the data
    and can render all or any part of it at any time. Trying to get a reference to the
    components graphics context from within another class and using it to draw graphics in the
    graphics component prevents this and the foreign class event code can never know when the
    graphics component needs to be re&#8211;rendered.
    So the idea is to keep the graphics/rendering component independent from the event code. The
    event code controls the state (member variables) in the graphics component and tells it when
    to re&#8211;render itself.
    There are a lot of (creative) ways of putting these things together. Here's an example.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.Random;
    import javax.swing.*;
    public class CallingGraphics implements ActionListener {
        GraphicComponentClass graphicComponent;
        DataGenerationClass   dataGenerator = new DataGenerationClass();
        public void actionPerformed(ActionEvent e) {
            Point2D.Double[] data = dataGenerator.getData();
            graphicComponent.setData(data);
        private JPanel getGraphicComponent() {
            graphicComponent = new GraphicComponentClass();
            return graphicComponent;
        private JPanel getLast() {
            JButton button = new JButton("send data to graphics");
            button.addActionListener(this);
            JPanel panel = new JPanel();
            panel.add(button);
            return panel;
        public static void main(String[] args) {
            CallingGraphics test = new CallingGraphics();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test.getGraphicComponent());
            f.getContentPane().add(test.getLast(), "Last");
            f.setSize(400,300);
            f.setLocation(200,200);
            f.setVisible(true);
    class GraphicComponentClass extends JPanel {
        Ellipse2D.Double[] circles = new Ellipse2D.Double[0];
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            for(int j = 0; j < circles.length; j++) {
                g2.draw(circles[j]);
        public void setData(Point2D.Double[] p) {
            double w = getWidth();
            double h = getHeight();
            double dia = 75.0;
            circles = new Ellipse2D.Double[p.length];
            for(int j = 0; j < circles.length; j++) {
                double x = p[j].x*(w - dia);
                double y = p[j].y*(h - dia);
                circles[j] = new Ellipse2D.Double(x,y,dia,dia);
            repaint();
    class DataGenerationClass {
        Random seed = new Random();
        public Point2D.Double[] getData() {
            int n = seed.nextInt(25);
            Point2D.Double[] locs = new Point2D.Double[n];
            for(int j = 0; j < n; j++) {
                double x = seed.nextDouble();
                double y = seed.nextDouble();
                locs[j] = new Point2D.Double(x, y);
            return locs;
    }

  • Paint JTextPane on top of table using paintComponent?

    I have a JTable inside a JScrollPane which draws up a grid. In my application the table serves as a background. The best analogy is that this would be much like you might imagine a game board as a background for the game pieces on top.
    The application isn't a game, but to continue using my example, the components or game pieces are represented by JTextPane objects. These components will reside in different locations on top of the table. They can't be rendered within the table because they often span columns and rows. Additionally, even though they always start at the top of a row grid line, they don't necessarily end at the bottom of one.
    So I was wondering if there is a way to manually paint them. I envisioned that I would override the JTable or the JScrollPane paintComponent method but I am not sure how. Here is what I was thinking:
    protected void paintComponent(Graphics g)
    super.paintComponent(g);
    for (JTextPane myComponent : components)
    SwingUtilities.paintComponent(this.getGraphics(), appointmentComponent, this ,
    (int)startingLocation.getX(), (int)startingLocation.getY(),width, height);
    Of course this doesn't work. But is there a way I can draw a JTextPane or any component in an arbitrary location on top of a container of some sort?
    thanks

    Thanks, such a simple solution, I don't know why I didn't start with this, for some reason I decided a layered pane wouldn't work.
    So I added the JLayeredPane as the viewportview of the JScrollPane. Then I added the table to the layered pane and the objects go on the next layer and work great.

  • Using paintComponent with standard UI components

    I want to override the paintComponent to customize a JProgressBar to hava an associated label.
    How can I do this using the paintComponent method? I don't want to use a JPanel keeping a JLabel and a JProgressBar but rather extending JProgressBar: LabeledProgressBar extends JProgressBar. LabeledProgressBar should have a JLabel inside (or just a String field) to hold the label to be displayed. I thought about using a code like:
    protected void paintComponent(Graphics g)
    super.paintComponent(g);
    g.drawString(myLabel, xpos, ypos);
    Does this work? Can you provide me with some code? (I think it's not that difficult but I don't know how to do it.) I tried it with this code but nothing happens in my GUI. I can see, however, by using System.out.println(); that this code is passed at runtime.
    Thank you,
    Dirk
    [email protected]

    Of course, the user should be able to place the string wherever he wants in the end (north, south, east, west).Which is why the easiest solution is to just create a JPanel with a BorderLayout. Add the progress bar to the center and the JLabel to the North, South, East, West depending on the user requirement.
    Otherwise you need to rewrite the ProgressBar UI. You would need to change the calculations for the prefererred size, change the painting logic etc. Well above my level of expertise. Basically you would need to extend the BasicProgressBarUI.

  • Painting using paintComponent();

    hi guys, here i'm trying to paint over the JFrame which is using null layout.
    i have used paintComponent(). . . nothing is being displayed. i feel like i'm not adding the panel object to the JFrame properly.
    any idea why its not showing the message i'm trying to draw?????????????????????????
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class LoginScreen extends JFrame
         JLabel userId;
         JTextField userIdT;
         JButton userIdHelp;
         *WelcomeLogin welcome;*
         public LoginScreen()
              super("User Login Screen");
              Container surface = getContentPane();
              setSize(1024,750);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setLocationRelativeTo(null);
              surface.setLayout(null);
              *welcome = new WelcomeLogin();*
    *          surface.add(welcome);*
              userId = new JLabel("User ID       :",JLabel.LEFT);
              userId.setBounds(20,50,80,20);     surface.add(userId);
              userIdT = new JTextField(40);
              userIdT.setBounds(120,50,150,20);  surface.add(userIdT);
              userIdHelp = new JButton("?");    
              userIdHelp.setBounds(290,50,50,20);surface.add(userIdHelp);
              public static void main(String[] args)
              LoginScreen login = new LoginScreen();
              login.setVisible(true);
    class WelcomeLogin extends JPanel
         public void paintComponent(Graphics g)
              super.paintComponents(g);
              g.drawString("hey hi, how are you doing!",60,100);
    }

    Null layout has it's place, and if you've never used it and don't know how it works you really ought not to be giving out advice to others.Okay, you got me there. But..
    You don't always want a LayoutManager.Could you tell me why to use it when there is GroupLayout? And a bunch of other once as well. Cant the GroupLayout do the same thing, but better?
    EDIT: For some reason I find my self to want to know about the null layout, and hence Im reading this (also on the layout manager tutorial :S). Those reasons are as good as any for me to shut my trap. I shall try and be more educated on the matters I reply onto next time.
    Edited by: prigas on Apr 22, 2009 12:43 PM

  • PaintComponent(Graphics g) problem

    hi, guys:
    Can someone tell me why my code is not work in paintComponent(Graphics g)
    below are my code:
    protected void paintComponent(Graphics g)
         g.drawLine(0, 0, 100, 100); //this line work
    this.getGraphics().drawLine(0,0,100,100); //this is not work
    I know I should use auto passed "Graphics g", however, I don't understand why this.getGraphics() can't do the same work. It should return the same Graphics object which I expected.
    Thanks for help.

    I just posted my code below (Applet), hope helpful.
    package mypackage;
    import java.applet.Applet;
    import java.awt.*;
    import javax.swing.*;
    class CatchTheCreaturePanel extends JPanel
         private Creature[] creature;
         public CatchTheCreaturePanel()
              this.setPreferredSize(new Dimension(400,300));          
         public void paintComponent(Graphics g)
              g.drawLine(50, 70, 100, 100); //work
              this.getGraphics().drawLine(0, 0, 100, 100); //not work
    public class Jmyass extends JApplet {
         private CatchTheCreaturePanel the_panel;
         public Jmyass() {
              super();
         public void init() {
              the_panel=new CatchTheCreaturePanel();
         public void start() {
              this.getContentPane().add(the_panel);          
    }

  • Can I use a graphics tablet such as Wacom with Keynote?

    I would like to be able to use my Graphics tablet with Keynote to write on my slides while teaching. I am able to use the pen tablet with Powerpoint, I just select pen for pointer and pen color. How do I do this in Keynote?
    Thanks for your help,
    Jackk

    I don't think you can do that within Keynote itself. Is there anything useful in the Inkwell preferences? I have never used a tablet with a Mac before, but I think that Inkwell would have some kind of annotation feature.

  • Can I use 2 graphic card for optimisation in adobe?

    Hi, I am using Adobe CS6, Premiere pro, After effect, Photoshop, InDesign.
    Current set up is Dell XPS 8700, GTX 650 Ti, 128gb Plex SSD, 2TB 72krpm HDD, 16DDR3 non-ECC ram.
    I am looking to build a LGA 1366 dual xeon processor workstation.
    Plextor M5 Pro as main hardisk for application cache
    2x Intel Xeon X5570
    16ddr3 10600Registered/ECC ram
    SAS 10k rpm HDDs support 6gbps but I only using 3gbps controller (media drives)
    Graphic cards:
    1x Nvidia Geforce GTX 650 Ti
    1x Nvidia Quadro FX 1800
    Need advice on the possibility of using both graphic cards in my upcoming set up.
    eg, ulitilising the Cudas on my GTX while still enabling the use of quadro fx 1800. (not sure if Quadro fx1800 can enhance the flow..)
    If able, pls share some light on how to go about enabling both graphic to use in adobe
    My work is mainly, photo and video editing.

    Hi Stormancer,
    You cannot use two different graphics cards in SLI which is the main benefit of having two cards.
    As far as I am aware the FX1800 is optimised for CAD use when you state mainly editing photo and video so I can't see that card being particularly beneficial to you.
    If you can afford it why not just buy a better spec single card either the Quadro or GTX? 
    I currently run a Windows 7 64-bit system with an i7 3700k, three SSD 6/Gbps, RAID 6/Gbps and 2300 Mhz memory with a recently upgraded GTX 680 and find it more than capable of both photo and HD video editing plus some After Effects work.  I would class myself as a serious Hobbyist (with 30 years PC experience) and suspect that yes you need the latest kit if you are editing professionally because of the deadlines and high quality required but once you reach a certain level, the gains are very negligible.
    While I was looking to upgrade my card, people on here suggested the Quadro K5000 mainly because I have a 10-bit NEC PA301W (25th anniversary present off hubbie) but this card was out of my budget so I settled on the GXT680 and find it more than capable for my needs.  It is much faster than the old Radeon 5770 I had.  However, while researching I came across this site which explains the way Mercury GPU is utilised, you may find it helpful:
    http://blogs.adobe.com/genesisproject/2011/10/diving-into-nvidia-gpus-and-what-they-mean-f or-premiere-pro.html

  • 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

  • Mapping Split using the Graphical Mapping Tool

    Hello,
    I am a little confused right now... so I turn to you for help!
    I found this excellent blog:
    /people/claus.wallacher/blog/2006/06/29/message-splitting-using-the-graphical-mapping-tool
    It details how to do a message split using the Graphical Mapping Tool. WHich is exactly what I want!
    But then I found this on help.sap.com:
    http://help.sap.com/saphelp_nw04/helpdata/en/42/ed364cf8593eebe10000000a1553f7/frameset.htm
    Which states that:
    Messages cannot be sent by using different Adapter Engines in a mapping-based message split. This affects configuration thus: All receiver agreements that have a receiver interface from the mapping entered in the key must only be assigned communication channels with the following adapter types: 
    -          RFC Adapter
    -          SAP Business Connector Adapter
    -          File/FTP Adapter
    -          JDBC Adapter
    -          JMS Adapter
    -          SOAP adapter
    -          Marketplace adapter
    -          Mail Adapter
    -          RNIF adapter
    -          CIDX Adapter
    I have a simple mappling split where I want to take a file containing multiple materials and send them one by one to a PROXY into SRM. To send to proxy I want to use the HTTP adapter which is not listed above. BUT if I read it correctly it will work, as long as I dont try to do the interface determination based on the mapping.
    Is this correct, that it will work I mean? I think so but not sure about the wording in the sentence above, and wanted to check before I go destroy my mapping.
    Thanks!
    Nam

    Hi,
    If your scenario is simple and straight fwd like from one source to one target then you can split message without BPM. As Priyanka said in the message mapping go to Message Tab and set the target message occurance to unbounded. Then in the Interface Mapping in the target interface section you will find the occurance in the last column, change occurance to unbounded.
    While doing configuration you have to go for Enhanced Interface Determination thats it.
    Provided you are above sp14, incase of any lowere SP'a you will not even able to activate your mapping program as it will expect ABSTRACT interface to do multimapping.
    Thanks,
    Prakash
    Thanks,
    Prakash

  • Drawing with paintComponent(Graphics g) problem?

    hey, i just recently learnt from a response to previous posts not to put logic type stuff like if statements in the paintComponent method, but how do i get around the issue of drawing something different based on a boolean expression?
    i want to be able to do something like,
    paintComponent(Graphics g) {
          if(drawCircle == true) {
              g.drawCircle(....)
         }else{
              g.drawRectangle(......)
    }Yes, i know i shouldn't do that as i said i've been told NEVER to do this, but how do i work around this issue?
    thanks

    hey, i just recently learnt from a response to previous posts not to put logic type stuff like if statements in the paintComponent method, but how do i get around the issue of drawing something different based on a boolean expression?If you refer to that [my reply in your former thread|http://forums.sun.com/thread.jspa?messageID=10929900#10929900] , note that I warned you against putting business logic (+if (player.hasCollectedAllDiamonds()&&timer.hasNotTimedOut()&&allEnnemies.areDead()) { game.setState(FINISHED);}+) into your paintComponent(...) method, I didn't ask you to ban logic altogether (+if (player.hasCollectedAllDiamonds()) { Graphics.setColor(Color.GREEN); }+)
    EDIT: Oh, how pretentious I was; obviously you merely refer to [this Encephalopathic's post|http://forums.sun.com/thread.jspa?messageID=10929668#10929668], who warns against program logic in paint code; same misunderstanding though, he certainly only meant that the paintXXx's job is not to determine whether the game is over, only to render the game state (whichever it is, it has been determined somewhere else, not in painting code).

Maybe you are looking for

  • Black bars on iMac? (Late 2006)

    Hi, I've been getting weird black bars on my iMac. They seem to appear when there are alot of applications loaded. Some times they're on the side of windows. Sometimes on text. Sometimes my mouse turns green. Sometimes my dock is discolored completel

  • How to use substr in external table defnition.

    Hi All, Im using oracle 11g. I have an external table which is reading data from a file. For one of the column, i need to get only the first 250 characters. My external table defnition looks like this create table tbl_substr ( col1 varchar2(20), col2

  • How do I apply a specific character style to specific text?

    Long-time Photoshop and Illustrator user. New to Indesign. Fortunately, this isn't an issue of how to go about creating fractions. I've already chosen a route for that. I'm simply applying a Character Style that checks the opentype "fractions" box. H

  • Graph weekly scrap summary with zero value.

    Post Author: Phoebe CA Forum: Charts and Graphs Hello, I have a report that summarize weekly quantity by week. Example: ww1 total= 2 ww2 total= 4 ww3 total= 0 ww4 total= 1 However, crystal reports only graph the work week that contains a value, there

  • Suppress cumulated key figures for actual data

    Hello all, I have build a query which display monthly actual and forecast order income for an ficsal year. The fiscal year starts in July and end in June The forecast data were loaded in BW over an flat file for the whole fiscal year. The actual data