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.

Similar Messages

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

  • How do you have two classes drawing to the same JPanel? Graphics g problem

    Hi all,
    This is probably a five second answer but im really stuck on it!
    How do i have two classes both writing to the same JPanel?
    I have one class that extends JPanel and using Graphics g, draws to the panel ie g.drawString(..);
    But i would like another class to draw to the same panel, so that the two different classes can both draw what they like to the JPanel.
    How do i do this?
    I have tried sending the Graphics g object from the one class to the other but only the original class draws still. I was thinking perhaps if it carn't be done could i have a JPanel on top of the other one that is transparent so there would be a tracing paper effect?
    Many thanks

    I have tried sending the Graphics g object from the
    one class to the other but only the original class
    draws still. I was thinking perhaps if it carn't beThis is the right idea. One problem you may be running into is that JPanel fills in its background with the background color by default. If you switch and use JComponent instead of JPanel you may get better results. Another idea is to use a "painter": a class that has a paint(Graphics g) but is not a component and just paints on a component. I've done this before in implementing Tetris where the dropping piece is a class which can paint itself but is not a component.

  • About draw GIF in "paintComponent(Graphics)" Method ???

    I extends a new class A from JPanel and overwrite the method of "paintComponent(Graphics)", the code is like below:
    public void paintComponent(Graphics g)
      super.paintComponent(g);
      // imgObj is a GIF file.
      g.drawImage(imgObj, 100, 100, this);
    }it's OK, the GIF can be show like a movie.
    but if the code in an other class B, and invoke in A.paintComponent method, it can not show like a movie, it only show a static frame. Code like below:
    public void paintComponent(Graphics g)
      super.paintComponent(g);
      bClassObj.drawGIF(g);
    public class B
      public void drawGIF(Graphics g)
        g.drawImage(imgObj, 100, 100, this);
    } WHY !!!!???

    I try it OK...
    the last parameter of method drawImage() in B must be point to instance of A.

  • JEditorPane (or subclasses) and a class that extends JPanel

    hello to all,
    i'm realizing an application with Swing.
    i have realized a class that extends JPanel(called "PanelLayer") and, other to draw a ruler as Office 2003, it must contain an other subclass of JPanel (called "PanelLayer") that, in turn, will contain a JEditorPane.
    the problem is strange: i should continue in moviment the mouse to look well the JEditorPane (or subclasses)
    the URL is a image of the result that i get...
    URL : http://phantom89.helloweb.eu/img/img.jpg
    codes:
    public class Layer extends JPanel implements ComponentListener{
        private static final long serialVersionUID = 1L;
        private Rectangle2D.Double areaCentrale = new Rectangle2D.Double(100,100,850,1285);
        private double larghFoglio = 21.0*50;
        private double altFoglio = 29.7*50;
        private double zoom = 1.0;
        private JScrollPane sp = new JScrollPane(this);
        private Rectangle2D.Double posFoglio = new Rectangle2D.Double();
        private int lastX,lastY;
        private PanelLayer pl;
        private Point mouse = null;
        private JEditorPane text;
        public Layer(PanelLayer pl){
            this.setLayout(null);
            this.pl = pl;
            this.setPreferredSize(new Dimension((int)(40+larghFoglio*zoom), (int)(100+altFoglio*zoom)));
            areaCentrale = new Rectangle2D.Double(100*zoom,100*zoom,850*zoom,1285*zoom);
                sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
            sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            //try{
                text = new JEditorPane();
                text.setBounds(50,50,200,200);
                this.add(text);
            //}catch(IOException e){}
            lastX = sp.getHorizontalScrollBar().getValue();
            lastY = sp.getVerticalScrollBar().getValue();
            this.addComponentListener(this);
            this.addMouseListener(this);
            this.addMouseMotionListener(this);
        public void paintComponent(Graphics g){
            if(posFoglio.height + posFoglio.width == 0){
                this.posFoglio = new Rectangle2D.Double((this.getWidth()-larghFoglio*zoom)/2,50,larghFoglio*zoom,altFoglio*zoom);       
            Graphics2D g2d = (Graphics2D)g;
            g2d.setPaint(Color.lightGray);
            g2d.fillRect(0,0,this.getWidth(),this.getHeight());
            g2d.translate((this.getWidth()-larghFoglio*zoom)/2,50);
            g2d.setPaint(Color.black);
            g2d.draw(new Rectangle2D.Double(0,0,larghFoglio*zoom,altFoglio*zoom));
            g2d.setPaint(Color.white);
            g2d.fill(new Rectangle2D.Double(1,1,larghFoglio*zoom-1,altFoglio*zoom-1));
            g2d.setPaint(Color.blue);
            g2d.draw(areaCentrale);
        public JScrollPane getJScrollPane(){
            return sp;
        public Rectangle2D.Double getDimFoglio(){       
            return this.posFoglio;
        public double getCmWidth(){
            return larghFoglio*zoom/50+((larghFoglio*zoom/50)%1 <= getIncr() ? 0 : getIncr());
        public double getCmHeight(){
            return altFoglio*zoom/50+((altFoglio*zoom/50)%1 <= getIncr() ? 0 : getIncr());
        public Point getPointMouse(){
            return mouse;
        public void refresh(){
            lastX = sp.getHorizontalScrollBar().getValue();
            posFoglio.x = (this.getWidth()-larghFoglio*zoom)/2-lastX;
        public double getIncr(){
            return zoom/2;
        public void mouseClicked(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {}
        public void mousePressed(MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
        public void mouseDragged(MouseEvent e) {}
        public void mouseMoved(MouseEvent e) {
            mouse = e.getPoint();
            mouse.x -= sp.getHorizontalScrollBar().getValue();
            mouse.y -= sp.getVerticalScrollBar().getValue();
            pl.repaint();
        public void componentHidden(ComponentEvent e) {}
        public void componentMoved(ComponentEvent e) {
            lastX = sp.getHorizontalScrollBar().getValue();
            posFoglio.x = (this.getWidth()-larghFoglio*zoom)/2-lastX;
            lastY = sp.getVerticalScrollBar().getValue();
            posFoglio.y = 50-lastY;
            pl.repaint();
        public void componentResized(ComponentEvent e) {
            this.repaint();
            pl.repaint();
        public void componentShown(ComponentEvent e) {}
    public class PanelLayer extends JPanel implements MouseWheelListener,MouseInputListener{
        private static final long serialVersionUID = 1L;
        private Layer layer;
        private JScrollPane sp = null;
        private boolean visualizzaMouse = false;
        public PanelLayer(){
            this.setLayout(null);
            layer = new Layer(this);
            layer.addMouseListener(this);
            layer.addMouseMotionListener(this);
        public void paintComponent(Graphics g){
            if(layer.getDimFoglio().getWidth()+layer.getDimFoglio().getHeight() == 0){
                layer.setSize(50,50);
            if(sp == null){
                sp = layer.getJScrollPane();
                sp.addMouseWheelListener(this);
                sp.setBounds(30,30,this.getWidth()-30,this.getHeight()-30);
                this.add(sp);
            }else{
                layer.refresh();
            sp.setBounds(30,30,this.getWidth()-30,this.getHeight()-30);
            Graphics2D g2d = (Graphics2D)g;
            g2d.setPaint(new Color(153,255,153));
            g2d.fill(new Rectangle2D.Double(0,0,this.getWidth(),30));
            g2d.fill(new Rectangle2D.Double(0,0,30,this.getHeight()));
            g2d.setPaint(Color.black);
            g2d.drawLine(0,0,this.getWidth(),0);
            g2d.drawLine(0,30,this.getWidth(),30);
            g2d.drawLine(0,0,0,this.getHeight());
            g2d.drawLine(30,0,30,this.getHeight());
            for(double i=0,j=0;i<=layer.getCmWidth();i+=layer.getIncr(),j++){
                if(j%2==0){
                    g2d.drawLine((int)(layer.getDimFoglio().x+31+i*50), 15,(int)(layer.getDimFoglio().x+31+i*50), 30);
                    g2d.drawString(String.valueOf((int)(j/2)), (float)(layer.getDimFoglio().x+31+i*50), 13);               
                }else{
                    g2d.drawLine((int)(layer.getDimFoglio().x+31+i*50), 22,(int)(layer.getDimFoglio().x+31+i*50), 30);
            for(double i=0,j=0;i<=layer.getCmHeight();i+=layer.getIncr(),j++){
                if(j%2==0){
                    g2d.drawLine(15, (int)(layer.getDimFoglio().y+31+i*50),30,(int)(layer.getDimFoglio().y+31+i*50));
                    g2d.drawString(String.valueOf((int)(j/2)),5,(float)(layer.getDimFoglio().y+31+i*50));
                }else{
                    g2d.drawLine(22, (int)(layer.getDimFoglio().y+31+i*50),30,(int)(layer.getDimFoglio().y+31+i*50));
            if((layer.getPointMouse() != null)&&(visualizzaMouse)){
                g2d.drawLine(layer.getPointMouse().x+30,0,layer.getPointMouse().x+30,30);
                g2d.drawLine(0,layer.getPointMouse().y+30,30,layer.getPointMouse().y+30);
            g2d.setPaint(new Color(153,255,153));
            g2d.fillRect(1,1,29,29);
            int largh = layer.getJScrollPane().getVerticalScrollBar().getWidth();
            g2d.fillRect(this.getWidth()-largh, 1, largh, 29);
            g2d.fillRect(1, this.getHeight()-largh, 29, largh);
        public void mouseWheelMoved(MouseWheelEvent e) {
            JScrollBar vsb = layer.getJScrollPane().getVerticalScrollBar();
            vsb.setValue(vsb.getValue()+20*e.getWheelRotation());
        public void refresh(){
            if((layer != null)&&(sp != null)){
                layer.setSize(this.getWidth()-30,this.getHeight()-30);
                sp.setViewportView(layer);
                this.repaint();
        public void mouseClicked(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {
            visualizzaMouse = true;
            repaint();
        public void mouseExited(MouseEvent e) {
            visualizzaMouse = false;
            repaint();
        public void mousePressed(MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
        public void mouseDragged(MouseEvent e) {}
        public void mouseMoved(MouseEvent e) {}
    }(my english isn't very good)

    Don't really understand what the posted code does and I can't execute the code so I don't have much to offer.
    But I did notice that you don't invoke super.paintComponent(...) which means you may have garbage being painted on the panels.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html

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

  • 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 set the size of a class that extends JDialog

    Hi,
    I was trying to set the size of my dialog window to be 600 by 600, but couldn't change it. Here is my code:
    public class alii extends JDialog {
    /** Creates new form alii */
    public alii(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    private void initComponents() {
    Container contentPane = getContentPane();
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    closeDialog(evt);
    pack();
    public static void main(String args[]) {
    JFrame frame = new JFrame();
    alii a = new alii(new javax.swing.JFrame(), true);
    frame.setSize(600,500);
    frame.setLocation(200,200);
    frame.setVisible(true);}}
    Please help me with this and explain to me what is the problem and what needs to be changed.
    Cheers

    Hi,
    The code you sent me doesn't work, and the code I posted wasn't a complete, but there is the complete one. You can see now what the code does.
    * alii.java
    * Created on 15 November 2003, 13:31
    * @author Ali
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.util.*;
    import java.io.*;
    import java.applet.*;
    import java.net.*;
    public class sun extends JDialog {
    int x[] = new int[4];
    int y[] = new int[4];
    int w[] = new int[4];
    int h[] = new int[4];
    int Y_ax = 310;
    double DrawGraf[][] = new double[4][4];
    String line[] = new String[9];
    double Perc[] = new double[4];
    double Sum=0;
    GUICanvas can;
    double graphvalue[] = new double [5];
    /** Creates new form alii */
    public sun(Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    //setVisible(true);
    //setSize(600,500);
    //setLocation(200,200);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    //Container contentPane = getContentPane();
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    closeDialog(evt);
    //contentPane.setSize(700,700);
    //pack();
    public void drawthegraph(String s)
    /* try {
    URL url = new URL(
    "http://localhost:111/test/servlet/Compare?value="+s);
    BufferedReader in = new BufferedReader(
    new InputStreamReader(url.openStream()));
    for (int c = 0; c<9; c++)
    line[c] = in.readLine();
    in.close();
    }catch (Exception e){
    e.printStackTrace();
    graphvalue[0] = 200;
    graphvalue[1] = 200;
    graphvalue[2] = 100;
    graphvalue[3] = 300;
    graphvalue[4] = 20;
    //graphvalue[4] = can.d2i(graphvalue[4]);
    //System.out.println(line[8]);
    Sum = graphvalue[0]+graphvalue[1]+graphvalue[2]+graphvalue[3];
    Perc[0] = graphvalue[0]/Sum*200;
    Perc[1] = graphvalue[1]/Sum*200;
    Perc[2] = graphvalue[2]/Sum*200;
    Perc[3] = graphvalue[3]/Sum*200;
    System.out.println(Perc[0]);
    DrawGraf[0][0] = 130;
    DrawGraf[0][1] = Y_ax - Perc[0];
    DrawGraf[0][2] = 60;
    DrawGraf[0][3] = Perc[0];
    DrawGraf[1][0] = DrawGraf[0][0]+60;
    DrawGraf[1][1] = Y_ax - Perc[1];
    DrawGraf[1][2] = 60;
    DrawGraf[1][3] = Perc[1];
    DrawGraf[2][0] = DrawGraf[1][0]+60;
    DrawGraf[2][1] = Y_ax - Perc[2];
    DrawGraf[2][2] = 60;
    DrawGraf[2][3] = Perc[2];
    DrawGraf[3][0] = DrawGraf[2][0]+60;
    DrawGraf[3][1] = 310 - Perc[3];
    DrawGraf[3][2] = 60;
    DrawGraf[3][3] = Perc[3];
    for(int d=0;d<4;d++)
    x[d]=d2i(DrawGraf[d][0]);
    y[d]=d2i(DrawGraf[d][1]);
    w[d]=d2i(DrawGraf[d][2]);
    h[d]=d2i(DrawGraf[d][3]);
    repaint();
    static int d2i(double d) {return (int) Math.round(d);}
    public void paint (Graphics g)
    g.setColor(Color.red);
    for(int d=0;d<4;d++)
    g.fill3DRect(x[d],y[d],w[d],h[d],true);
    g.setColor(Color.blue);
    g.drawLine(130,130,130,310);
    g.drawLine(130,310,370,310);
    g.setColor(Color.black);
    g.drawString("WELCOME TO Ali",150,100);
    g.drawString("Region: Lambeth",430,150);
    g.drawString("Manger: ",430,170);
    g.drawString("Location: ",430,190);
    g.drawString("Number of Staff: "+graphvalue[4],430,210);
    g.drawString("Week1",135,345);
    g.drawString("Week2",195,345);
    g.drawString("Week3",255,345);
    g.drawString("Week4",315,345);
    g.drawString(" "+"20 -",100,295);
    g.drawString(" "+"40 -",100,255);
    g.drawString(" "+"60 -",100,215);
    g.drawString(" "+"80 -",100,175);
    g.drawString("100 -",100,135);
    g.setColor(Color.yellow);
    g.drawLine(130,290,370,290);
    g.drawLine(130,250,370,250);
    g.drawLine(130,210,370,210);
    g.drawLine(130,170,370,170);
    g.drawLine(130,130,370,130);
    /** Closes the dialog */
    private void closeDialog(java.awt.event.WindowEvent evt) {
    setVisible(false);
    dispose();
    * @param args the command line arguments
    public static void main(String args[]) {
    JFrame frame = new JFrame();
    sun sn = new sun(frame, true);
    frame.setSize(600,500);
    frame.getContentPane().add(sn);
    frame.setLocation(200,200);
    frame.setVisible(true);
    You were right that I am know to this, but getting there slowly and thanks for your help.
    Cheers

  • Pass a value to a class that extends AbstractTableModel

    Hi
    I have a problem with a table model that I cannot find a way of overcoming.
    I have created a class called MyTableModel that extends AbstractTableModel.
    MyTableModel creates and uses another class that I have defined in order to retrieve records from a database, MyTableModel fills the table with these records.
    However, I wish to alter my class in order to provide an int parameter that will act as a �where� value in the classes sql query.
    The problem is this, I cannot work out how to pass a value into MyTableModel. I have tried creating a simple constructor in order to pass the value but it doesn�t work.
    My code is shown below:
    import BusinessObjects.JobItemClass;
    import DBCommunication.*;
    import java.util.ArrayList;
    import javax.swing.table.AbstractTableModel;
    public class MyJobItemTableModel extends AbstractTableModel
      public MyJobItemTableModel(int j)
          jobNo = j;
      int jobNo;
      JobAllItems jobItems = new JobAllItems(jobNo);
      ArrayList items = jobItems.getItems();
      String columnName[] = { "Item Number", "Item Description", "Cost per item", "Quantity" };
      int c = items.size();
      Class columnType[] = { Integer.class, String.class, Double.class, Integer.class };
      Object table[][] =  new Object[c][4];
      public void fillTable()
          if(c > 0)
            for (int i = 0; i < c; i = i + 1)
              this.setValueAt(((JobItemClass) items.get(i)).getItemNumber(), i, 0);
              this.setValueAt(((JobItemClass) items.get(i)).getDescription(), i, 1);
              this.setValueAt(((JobItemClass) items.get(i)).getCostPerItem(), i, 2);
              this.setValueAt(((JobItemClass) items.get(i)).getQuantity(), i, 3);
      public void setJobNo(int s)
          jobNo = s;
      public int getColumnCount()
          if(c > 0)
            return table[0].length;
          else
              return 0;
      public int getRowCount()
        return table.length;
      public Object getValueAt(int r, int c)
        return table[r][c];
      public String getColumnName(int column)
        return columnName[column];
      public Class getColumnClass(int c)
        return columnType[c];
      public boolean isCellEditable(int r, int c)
        return false;
      public void setValueAt(Object aValue, int r, int c)
          table[r][c] = aValue;
    }Any advice will be appreciated.
    Many Thanks
    GB

    your JobAllItems is created before constructor code is run (since it is initialized in class member declaration)
    use something like
    public MyJobItemTableModel(int j)
          jobNo = j;
          items = (new JobAllItems(jobNo)).getItems();
          c = items.size();
          table =   new Object[c][4];
      int jobNo;
      ArrayList items;
      String columnName[] = { "Item Number", "Item Description", "Cost per item", "Quantity" };
      int c;
      Class columnType[] = { Integer.class, String.class, Double.class, Integer.class };
      Object table[][] ;instead of
    public MyJobItemTableModel(int j)
          jobNo = j;
      int jobNo;
      JobAllItems jobItems = new JobAllItems(jobNo);
      ArrayList items = jobItems.getItems();
      String columnName[] = { "Item Number", "Item Description", "Cost per item", "Quantity" };
      int c = items.size();
      Class columnType[] = { Integer.class, String.class, Double.class, Integer.class };
      Object table[][] =  new Object[c][4];

  • Can I invoke a class that extends JAppl from another class extends JAppl

    Can I invoke a class that extends JApplet from another class that extends JApplet. I need to invoke an applet then select an action which opens another applet. Thanks in advance.

    Nobody is able to solve this problem, i cant even
    think this things. i have hope so plz try and get
    result and help.Did you understand what Sharad has said???
    Yep, you can forward to specific error page from servlet when even error occured in JSP. In order to achieve you have to open jsp file from servlet say example by using reqdisp.forward.
    handle exception in the part where you are forwarding. And forward to the specific error page inside catch block.

  • Portlets development: When to use the class that extends PortletBridge...

    When I create some Portlet (.jspx based) JDeveloper generate some resources. One of those is a class (with the name that I´ve configured) that extends PortletBridge...
    Ok. So, I want to know if I use JSF standards should I put my actions into this class or should I create another Managed bean to handle that? What to do with this generated class?
    Thank you.

    So you want to create a portlet that uses JSF instead of JSP?
    You can JDev do that for you. When you create a new portlet there is a step where you can specify the default page for the portlet mode (view, edit).
    On the right hand side you can select ADF JSF (or something like that).
    JDev will then create a class that extends the PortletBridge class and you don't have to do anything more. Just edit the jspx like it's a normal page.

  • Can any one change this Applet into a class that extends Jpanel.....

    Hi,
    I need this applet as a class that extends JPanel, I will be very very thankful to you if any one kindly change this Applet code into a class that extends JApplet.
    I will be very thankful to you if some one can reserve few minutes & do this favor early.
    Thanks a lot for any help.
         My Pong Code
    import java.applet.*;
    import java.awt.*;
    import java.io.*;
    import java.awt.event.*;
    public class Class1 extends Applet implements Runnable
    {     private final int APPLET_WIDTH = 900;
         private final int APPLET_HEIGHT = 600;
         private int px = 15;
         private final int py = 560;
         private final int ph = 10;
         private final int pw = 75;
         private int old_px = px;
         private int bx = 450;
         private int by = 15;
         private final int bh = 20;
         private final int bw = 20;
         private int move_x = 2;
         private int move_y = 2;
         private boolean done = false;
         Thread t;
         private final int delay = 25;
         public void init()
         {     setBackground(Color.black);
              setSize(APPLET_WIDTH, APPLET_HEIGHT);
              requestFocus();
              addKeyListener(new DirectionKeyListener());
             (t = new Thread(this)).start();
         public void run()      {
        try      {     while((t == Thread.currentThread()) && (done == false))           {     
                   if ((bx < 15) || (bx > APPLET_WIDTH-30))                     move_x = -move_x;                                if ((by < 15) ||                    ((by > APPLET_HEIGHT-60)&&                     ((px<=bx)&&(bx<=px+pw))))
                        move_y = -move_y;
                   if (by > APPLET_HEIGHT)
                        done = true;
                                   bx = bx + move_x;
                   by = by + move_y;                                                repaint();
                   t.sleep(delay);
         catch(Exception e)      {}
         }//end run
         /*public void move_paddle(int amount)
              old_px = px;
              //if (amount > 0)
                //if (px <= APPLET_WIDTH-15)
                   px = px + amount;
              //else if (amount < 0)
               // if (px >= 15)
                   px = px + amount;
         public void paint(Graphics page)
              //     page.setColor(Color.black);
              //     page.drawRect(old_px, py, pw, ph);
                   page.setColor(Color.blue);
                   page.drawRect(px, py, pw, ph);
                   page.setColor(Color.white);
                   page.drawOval(bx, by, bw, bh);
                   if ((done == true) && (by > APPLET_HEIGHT))
                        page.drawString("LOSER!!!", APPLET_WIDTH/2, APPLET_HEIGHT/2);
                   else if (done == true)
                        page.drawString("Game Over, Man!", APPLET_WIDTH/2-10, APPLET_HEIGHT/2);
         private class DirectionKeyListener implements KeyListener               
              public void keyPressed (KeyEvent event)
                   switch (event.getKeyCode())
                   case KeyEvent.VK_LEFT:
                        old_px = px;
                        if (px >=15)
                             px -=10;
                        break;
                   case KeyEvent.VK_RIGHT:
                        old_px = px;
                        if (px+pw <= APPLET_WIDTH-15)
                             px += 10;
                        break;
                   case KeyEvent.VK_Q:
                        done = true;
                   default:
                   }  //end switch
                   repaint();
              }//end keyPressed
              public void keyTyped (KeyEvent event)
              public void keyReleased (KeyEvent event)
         }  //end class 
    }

    thank you sir for your advice.
    Its not like that I without any attempt, just past code here & asked for its conversion. I spent about 5 hours on it, can say spoil whole day but to no avail. You then just guide me, give some hint so that I do it. I will most probably wanted to do it by myself but asked for help when was just disappointed.
    I try to put all init() in default constructor of identical copy of this applet that extends JPanel. Problem.....ball tend to fell but pad not moving. Also out out was not getting ant color input. That was like my best effort.....other tried that I found by search like just do nothing only extend panel OR frame in spite of applet, start applet from within main of another class.... these are few I remember what I tried.
    I will be very very thankful to you if you can help/guide me how can I do it. Behavior of the Applet is like a normal PONG game with on pad controlled by arrow keys, & one ball colliding with walls of boundary & falling down.
    Thanks a lot again for your attention & time.

  • How do i open a web page with VeriSign Class 3 Extended Validation SSL SGC SS CA certfificate i can't open web pages with this, how do i open a web page with VeriSign Class 3 Extended Validation SSL SGC CA certfificate i can't open web pages with this

    how do i open a web page with VeriSign Class 3 Extended Validation SSL SGC SS CA ?

    Hi
    I am not suprised no one answered your questions, there are simply to many of them. Can I suggest you read the faq on 'how to get help quickly at - http://forums.adobe.com/thread/470404.
    Especially the section Don't which says -
    DON'T
    Don't post a series of questions in  a single post. Splitting them into separate threads increases your  chances of a quick answer.
    PZ
    www.pziecina.com

  • ?Is it possible to create a javafx class without extending Application class ? If yes, how

    Is it possible to create a javafx class without extending Application class ? If yes, how ?

      There is no  such thing as a javafx  class.  It is a regular  java class.  The Aapplication class is  the entry
    point  for JavaFX application.  You have to extend the Application class to create Javafx  application .

  • LoadClass    (error loading a class which extends other class  at run-time)

    Hey!
    I'm using the Reflection API
    I load a class called 'SubClass' which exists in a directory called 'subdir' at run-time from my program
    CustomClassLoader loader = new CustomClassLoader();
    Class classRef = loader.loadClass("SubClass");
    class CustomClassLoader extends ClassLoader. I have defined 'findClass(String className)' method in CustomClassLoader.
    This is what 'findClass(String className)' returns:
    defineClass (className,byteArray,0,byteArray.length);
    'byteArray' is of type byte[] and has the contents of subdir/SubClass.
    the problem:
    The program runs fine if SubClass does not extend any class.
    If however, SubClass extends another class, the program throws a NoClassDefFoundError. How is it conceptually different?
    Help appreciated in Advance..
    Thanks!

    Because i'm a newbie to the Reflection thing, i'm notI don't see reflection anywhere. All I see is class loading.
    sure what role does the superclass play when i'm
    trying to load the derived class and how to get away
    with the errorWell... hint: all the superclass's stuff is not copied into the subclass.
    I am quite sure it fails to load the superclass because of classpath issues.

Maybe you are looking for

  • Videos no longer play in itunes 12

    Upon downloading the new itunes 12, videos in my library no longer play on my computer.  The second screen come up and looks like it wants to start but stays black.  The video play button ison bu the time toggle doesn't move. Any ideas?

  • Home sharing apple tv toshiba laptop

    I have problems to set up apple tv and my Toshiba laptop for home sharing last night I watch a movie and everthing works but not now

  • Transporting Tablespaces

    All Experts I am running oracle 10.2.0.1 on 64bit Microsoft server 2003. I want change database server and trying to transport tableces from one database server to another. I have to first create users on new database or not what about users's privil

  • I downloaded Lion but can't disable the automatic login, how do I change this?

    When I downloaded Lion, I am always prompted to login. I was wondering how I can disable this.  I've tried to go to system preferences, to un-check the ability to disable automatic login but it is grayed out.  Is there a way to get around this? thank

  • Packing Slip as part of A/R Invoice

    A client has requested that for orders that are processed directly as A/R Invoices without Sales Order, Delivery etc, that the second page of the AR Invoice be a packing slip.   I've tried to do this several different ways with no luck.  In all of th