"class Junk extends Hashtable .. implements MutableTreeNode"  seems flakey

If I add 3 child nodes to one root and then use DefaultTreeModel(root) in a JTree using this very basic implementation of MutableTreeNode, I can see all three children. Just by merely adding "extends Hashtable.." only the last child shows & blank space is shown in place of the other two (the lines are missing for them as well). Can anybody explain this? For now, I no longer am extending Hashtable - after several hours of figuring out what my problem was.
Regards,
Monty
package temp;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;
public class Node  implements MutableTreeNode {
     final Vector<Node> v = new Vector<Node>();
     final String name;
     Node parent;
     Node(String n) {
          name = n;
     public void insert(MutableTreeNode child, int index) {
          // TODO Auto-generated method stub
     public void remove(int index) {
          // TODO Auto-generated method stub
     public void remove(MutableTreeNode node) {
          // TODO Auto-generated method stub
     public void removeFromParent() {
          // TODO Auto-generated method stub
     public void setParent(MutableTreeNode newParent) {
          parent = (Node) newParent;
     public void setUserObject(Object object) {
     public Enumeration children() {
          return v.elements();
     public String toString() {
          return name;
     public boolean getAllowsChildren() {
          return true;
     public TreeNode getChildAt(int childIndex) {
          // TODO Auto-generated method stub
          return v.get(childIndex);
     public int getChildCount() {
          return v.size();
     public int getIndex(TreeNode node) {
          return v.indexOf(node);
     public TreeNode getParent() {
          return parent;
     public boolean isLeaf() {
          return v.isEmpty();
}

Define equals() and hashCode() methods appropriately in your custom tree node class otherwise the methods from Hashtable, which would be empty in your tested code, are used resulting a weird JTree object. See the API documentation for the TreeModel interface for the issue.
When you post a code on a public forum, you should post an SSCCE(http://homepage1.nifty.com/algafield/sscce.html) for making forum friends' helping work lighter.

Similar Messages

  • 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.

  • Use extends and implements or not?

    What is considered a better way of implementing classes? with the use of extends and/or implements or not?
    ex:
    public class TabPanel extends JPanel implements ActionListeneror have it return the needed Type
    ex:
    public class TabPanel implements ActionListener
    public JPanel TabPanel()
    JPanel jp = new JPanel();
    jp.add(new JLabel("Test"));
    return jp;
    }

    To extend or not to extend, that is a question. Defenitely, you must subclass when you need to override some method. You want to subclass to reuse the customized class. You want to implement an interface when you need a class implementing it.
    Regarding your example:
    public class TabPanel implements ActionListener {
         public JPanel TabPanel() {
              JPanel jp = new JPanel();
              jp.add(new JLabel("Test"));
              return jp;
    }Are you sure it will work? IMO, you do not have to specify result type and must not return anything in the constructors. Why to bother with TabPanel class? If you like to hide the scope, use {} braces in the code.
    JPanel panel = new JPanel();
    jp.add(new JLabel("Test"));
    public class NonAnanymousListener implements ActionListener {

  • Creating array of objects of class which extends Thread

    getting NullPointerException
    can i not create thread array this way?
    class sample extends Thread
    { int i,id;
      public sample(int c)
       { id=c;
      public void run()
      { for(i=0;i<6;i++)
         System.out.println("Thread "+id+" "+i);
    public class thread extends Frame implements ActionListener
    {  Button b1;
       sample s[];
       thread()
       { for(int i=0;i<2;i++)
              s=new sample(i);
         setLayout(new FlowLayout());
         b1=new Button("OK");
         add(b1);
         b1.addActionListener(this);
         public void actionPerformed(ActionEvent e)
         {   b1.setEnabled(false);
              for(int i=0;i<2;i++)
              { s[i]=new sample(i);
              s[i].start();
         public static void main(String args[])
         { thread t1=new thread(); 
         t1.setVisible(true);
         t1.setSize(150,150);

    You need:
    sample [] s = new sample[2];However
    1) You should get into the habit that class names start with capital letters, variable and field names with lower case.
    2) It's not a good idea to extend Thread, make a class which implements the Runnable interface and hook a standard Thread object to that.

  • 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.

  • 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

  • Closing a class that extends JPanel

    Hi, i have a class that extends JPanel(lets call it class A). In that class, if the user click the logout button, i want class A to close and display class B that extends JFrame. right now, i am able to call class B, but i cannot close class A.
    I uses remove() to close class A, but it doesnt work... could u tell me what to do??
    I put this code in class A...
    if (e.getSource() == logoutButton)     {
         remove(this);
         new Rest_Login1();
         String [] ar = null;
         Rest_Login1.main(ar);
    } Thx

    so i want to remove the CustomerPanel3 and display the Rest_Login1...
    some of my code look like this.
    thx
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class CustomerPanel3 extends JPanel implements ActionListener
    // some JButton, JLabel n etc
         public void actionPerformed (ActionEvent e)
              if (e.getSource() == logoutButton)     {
                   remove(this);
                   new Rest_Login1();
                   String [] ar = null;
                   Rest_Login1.main(ar);
    public class Rest_Login1 {
         public static void main(String args[])
              JFrame login1 = new JFrame("Login User Interface");
              JFrame.setDefaultLookAndFeelDecorated(true);
              RestaurantLogin userpan = new RestaurantLogin();
              login1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              login1.setSize(600, 250);
              login1.setLocation(230,192);
              login1.getContentPane().add(userpan);
              login1.setVisible(true);
    }

  • Converting a class that extends Frame to run in a thread

    I have written a class to display an image. The class extends Frame.
    Now I want to make this class part of a larger program and run it in a thread.
    The class extends Frame so it can't also extend Tread.
    I would appreciate an help in making this change.
    Thanks
    Bill

    public class MyFrame extends Frame implements Runnable
    public void run() {
    // have to implement
    }Then, in some other class:
    Frame myFrame = new MyFrame();
    Thread t = new Thread(myFrame);
    t.start();Thanks for the suggestion. It makes sense.
    However I have come across another problem. Citing this example the compilere is giving me the error
    cannot resolve symbol
    symbol: variable myFrame
    location: class Test6 (the some other class)
    Any ideas why myFrame cannot be resolved?

  • Difference between extends and implements

    hi
    i am new to java. i need to know the difference between extends class implement class.
    can anybody explain in simple words? i am new too oops concept also?
    what are the conditions to use extends class, implement and interface?
    class b extends a implements c
    i know class a is a super class and class b is a sub class.
    if class b extends class a means how should be the class a, what about the methods?
    and class a implements class c means what should be the conditions?
    i searched in Internet but the explanation is not very to me.can body explain me please?
    thank you

    sarcasteak wrote:
    Your class can implement an interface, which means it must use the methods defined in the interface.No, it doesn't need to use them. It needs to implement them. Or be declared abstract.
    Note that the methods in the interface are empty,No, they're not. They're abstract.
    // empty method
    void foo() {}
    // abstract method
    abstract void foo();(The abstract keyword is optional for interface methods, since they're all abstract.
    and you have to define what they do in your class that implements the interface.Just like they have to for abstract methods in a class you extend, if the child class is not declared abstract.
    There really isn't any difference between "extends" and "implements." There is no situation where you can choose. Any case where one is legal, only that one is legal. They could just as easily be a single keyword.
    Presumably the OP's real question is, "When do I use a class for a supertype vs. using an interface for a supertype?" The answer to that, of course, is:
    Use a class when at least some of the methods have valid default implementations. Use an interface when that is not the case. And of course the two are not mutually exclusive. It's quite common to do both.
    At the end of the day, an interface is really nothing more than a class that has no non-final or non-static member variables and whose instance methods are all abstract, and from which you can multiply inherit.
    Edited by: jverd on Feb 4, 2010 1:56 PM

  • Extends and implements

    "extends" => inheritance?
    and "implements" => interface?
    or the opposite?
    and what is the difference between an
    abstract class and interface?
    Thanks in advance
    Jack

    EXTENDS
    Yes, "extends" means inheritance.
    E.g.:
    public class Chihuahua extends Dog {
    }So, from the moment you use "extends" we can say that Chihuahua IS-A Dog.
    IMPLEMENTS
    We use "implements" keyword when a class must implement one or more interfaces.
    E.g.:
    public class Chihuahua extends Dog implements SmallDog, NiceDog{
    }Interfaces are a way to simulate multiple inheritance in Java language.
    Now we also can say that a Chihuahua IS-A Dog, IS-A SmallDog and IS-A NiceDog. Yes, interfaces also causes IS-A relationships.
    ABSTRACT CLASSES x INTERFACES
    Well, some book authors says that interfaces are a more "pure version" of a abstract class. If you don't know yet, all methods of a interface are abstract, that is: the class that implements an interface MUST (with no exceptions) implements (override) all his methods. Is also important to know that all methods in a interface has a header only (no implementation), for instance:
    public interface SmallDog {
    public abstract void walkFast( );
    public abstract void hiddenBelowTheDesk( );
    }But why all methods of an interface must not be implemented? Simply because they are abstract.
    An abstract class can contain OR NOT abstract methods. In mention of the abstract methods the behavior of a class that inherits from a abstract class is the same. Look this example:
    Dog.java
    public abstract class Dog{
       private String raceName;
       public abstract void bark();
       public abstract void run();
       public String getRaceName(){
          return this.raceName;
    }You can see that we have two abstract methods: bark and run. It means that if a class extends from Dog it MUST override the methods bark and run methods. getRaceName is a method, but it isn't an abstract abstract method.
    Now let's see the Chihuahua class again:
    public class Chihuahua extends Dog{
    private BigEye leftEye;
    private BigEye rightEye;
    private BigEar leftEar;
    private BigEar rightEar;
    public void bark(){
    public void run(){
    INTERFACES INHERITS FROM OTHER INTERFACES
    Yes, it can sound crazy, but it is possible in Java. An interface can inherits from other interfaces. It ins't hard to understand. Based on the two interfaces SmallDog and NiceDog we will see how an interface can inherits from another one:
    public interface CompleteCoolDog extends SmallDog, Nicedog{
    }The interface CompleteCoolDog contains all methods from SmallDog and Nicedog, but is not obbligatory to implement them because an interface can not implement methods, only declare them. And who must implement them? The first concrete class that implements CompleteCoolDog interface.
    You can see very nice informations about interfaces and abstract classes in the books of Kathy Sierra and Bert Bates (Study guides for SCJP).
    I hope I helped you a little. Some doubt please, mail me.
    See you =)

  • Instantiating a class using new with implements or extends

    I have created a class as follows:
    class MyFileFilter extends javax.swing.filechooser.FileFilter implements java.io.FilenameFilter {     
         ...code here...
    }and it all works fine. If I try to use this code directly without importing the class, I would normally use the new keyword, but since this uses extends and implements, it is giving me errors such as:
    [javac] ';' expected
    Is there any way that I can use this with the new keyword, such as:
    MyFileFilter theFilter = new MyFileFilter extends javax.swing.filechooser.FileFilter implements java.io.FilenameFilter {
         ...code here...

    maybe your ';' error is really a coding error. Here is a sample of code where I do something similar in the middle of a method.
        public static void redirectOutput() {
            try {
                // make a print stream that logs the time for each entry.
                class TimeStampPrintStream
                    extends PrintStream {
                    public TimeStampPrintStream(OutputStream out, boolean b) {
                        super(out, b);
                    public void println(String s) {
                        super.println(new Date() + ": " + s);
                System.out.close();
                System.err.close();
                System.setErr(new TimeStampPrintStream(new FileOutputStream(com.perigee.fileio.LogFile.getLogDirectory() + "System.err"), true));
                System.setOut(new TimeStampPrintStream(new FileOutputStream(com.perigee.fileio.LogFile.getLogDirectory() + "System.out"), true));
                System.err.println("System.err File");
                    System.out.println("System.out File");
            } catch (Exception e) {
                System.out.println("Could not redirect System.out/err");
                e.printStackTrace();
        }

  • Cann't extend a inner class where as can Implement a nested Interface

    i cann't extend a inner class in some other outer class . Where as i can implement the nested Interface in some other class. Why????
    for example:-
    class ABC
    class Inner
    /* class body */
    interface TempInterface
    /* interfacebody */
    class OuterClass
    class InnerTwo extends ABC.inner //(line 1)Will give error
    class InnerTwo implements ABC.TempInterface //(line 2)Will run fine
    the line 1 is going to give compilation error i.e not in the scope but the line 2 will run fine .
    Both of the things are in the same class but giving 2 other results.
    I am not getting sufficient reasons for it.
    Can any one help me????
    Reagrds
    Arunabh

    As far as the language is concerned, the classonly
    exists in the context of an instance of theenclosing
    class.This still exhibits a class/object confusion to me.
    It should be 'instance only exists ...' or 'instance
    can only exist'. The class only exists in the
    scope of the enclosing class, but this is another
    issue.I'm not following what you're saying. The second sentence sounds like you're disagreeing with me. The last sentence sounds like you're agreeing with me.
    A non-static nested class is an instance member, just like an instance method or instance variable. As such, as far as the language is concerned, that class only exists in the context of an instance of the enlcosing class.It's not just instances of the nested class--its the class definition itself that only exists within the context of an instance of the enclosing class. That's why you have to do anEclosingIntstance.NestedClass and can't do EnclosingClass.NestedClass.

  • When extending class do constructors get implemented as well

    Say i need to call a list as an object and it was an extension of another list. Would the constructor be the same but with the extended list name??
    For example:
    First class:
    public class ListR
            //variables
         public ListModelR()
              trackCount = 0;
              firstTrack = null;
              lastTrack = null;
         }///rest of code...
    Would the class that extended this hav a constructor of its class name or would i have to reference ListModelR?
    Thanks James

    You cant have a constructor that is different from your classes name.
    class A
         public A()
              int a = 5;
    class B
         public B()
              super(); //executes the super class's default constructor
    }

  • ClassCastexception when casting a Class that extends HttpServletRequestWrap

    I have inherited some code that runs OK in JDK 1.4.2 in a JSP, but give s an exception when the JSP runs unfer 1.5.0. My Class is a as follows:
    public class WrappedRequest extends HttpServletRequestWrapper {
         public WrappedRequest(HttpServletRequest req) {
              super(req);     
         /** Return value string of requested parameter.
         * <ul>
         * <li> If htmlEncode == NO_HTML_ENCODE, return the native request param, un-html encoded
         * <li> If htmlEncode == HTML_ENCODE, return an html encoded copy of the requested parameter
         * <li> If htmlEncode is neither, return the html encoded copy of the requested parameter     
         * </ul>
         * @param     name               name of the request parameter
         * @param     htmlEncode          whether html encoded/un-encoded parameter value should be returned.
         * @return     String of the requested parameter value. If parameter name is null, return null
         public String getParameter(String name, int htmlEncode) {
              if(name != null && (htmlEncode == NO_HTML_ENCODE)) {
                   String str = super.getParameter(name);
                   return str;
              else
                   return getParameter(name);     
         public String getParameter(String name) {
              String str = super.getParameter(name);
              if(str != null)
                   str = Utils.htmlEncode(str); //Another package class
              return str;               
    This class in normally invoked as follows:
         String changeApproval = ((WrappedRequest)request).getParameter("CrApp" , WrappedRequest.NO_HTML_ENCODE);
    I get a ClassCastException exception on this line. Any suggestions?
    Regards,

    Stuart_Millington wrote:
    Further to my original post I have another question. Please bear in mind that I am fairly new to Java and this is code that I have inherited. In the following line of code (which is the line that causes the exception:
    String changeApproval = ((WrappedRequest)request).getParameter("CrApp" , WrappedRequest.NO_HTML_ENCODE);
    Why is the request being cast? The following code SEEMS to run OK:
    WrappedRequest wr = new WrappedRequest(request);
    String CrApproval = wr.getParameter("CrApp" , WrappedRequest.NO_HTML_ENCODE);
    Any ideas?
    Regards,
    Stuart MillingtonOkay, then I understand your problem.
    You can only cast request to WrappedRequest when request IS A WrappedRequest - ie the statement request = new WrappedRequest(request) was called. You are apparently trying to convert a default implementation of HttpServletRequest into a WrappedRequest without first 'Wrapping' the request.
    What does Wrapping a Request mean and do? A request object is generated by the servlet container and it isn't easy to switch in your own implementation. So instead you make a WrappedRequest which takes the original instance of the HttpServletRequest generated from by the container and adds functionality to it. A WrappedRequest would have to extend an HttpServletRequest, and implement all the public API of said parent class. Most of the time the methods would look something like this:
    public String getParameter(String key) { return this.parentRequest.getParameter(key); } That is, it simply delegates most of the work to the HttpServletRequest it is wrapping. But some functions it may want to change behavior for and for those you insert your implementation.
    What you need to do:
    1) Learn how to use Java before you touch Servlets and server side stuff. You are adding too much complication by going straight to the end game. Use a book and the tutorials to get you through.
    2) Take the time to run the JavaEE tutorial.
    3) Start with your own code. Taking code snippets you see around the net and trying to get them to work is tough when you don't understand the concepts. For example, using a WrappedRequest is normally fairly useless if it isn't implemented using a Filter, and they work the best when they don't require a change to the request interface (i.e. when you never actually have to do a cast). Since you don't know Filters, and don't yet understand how the wrapper works I would suggest not using them.
    This is probably a mis-use of the RequestWrapper idea anyway (since, like I said, it requires a change in interface). What you would be better off doing is simply choosing to pass the parameter through a utility function that does the encoding for you. Example like:
    String changeApproval = HTMLEncoder.encode(request.getParameter("CrApp");when you want the parameter encoded and
    String changeApproval = request.getParameter("CrApp");when you don't.
    If you don't want to make your own utility for this purpose (and why would you) you can download a library that does it for you. One example is the [org.apache.commons.lang.StringEscapeUtils#escapeXML|http://commons.apache.org/lang/apidocs/org/apache/commons/lang/StringEscapeUtils.html#escapeXml(java.lang.String)] class#method from the Apache Foundation. The StringEscapeUtils is part of the Apache Commons Lang project, which you can reach [At the Commons/lang website.|http://commons.apache.org/lang/]

  • Using a class or servlet that implements Serializable

    Hello everyone,
    Can someone please help me. I need to make a program that uses a class or servlet that implements Serializable and then use the values of the variables in servlets.
    The first is using it to validate login. then changing the color of the background, header and footer of each servlet.
    the variables in the Serialized file are all Strings for color, username, password, header text and footer text.
    I tried using the applet tag to run the class in the servlet but it is not working.

    It's not working because you seem to be making random guesses what servlets, serialization and files are

Maybe you are looking for