Extend vs import

Hi
Im getting confused about the idea of importing packages into my class and extend class. What I actually doing when I extend a class?
Thanks
D

is that correct using?I don't know what you mean by this question. If it does what you need it to do, then it is one correct solution. Are you asking if it's "the right way" or "the best way"? There rarely is a "right" or "best" way to do something. At minimum, it has to function according to the requirements. Beyond that, you have considerations of performance, maintainability, meeting the instructor's requirements as to which constructs to use or not to use.
One thing I would change is that I'd use a StringBuffer to build up the string from the elements, and then when you're done, call sbuf.toString() to return the String. This is more efficient than repeatedly appending to a String, alhtough unless your list is large, it's unlikely to make a significant difference.
Also, you don't have to cast before calling toString. Object obj = iter.next();
String str = obj.toString(); The correct toString method will be called without the cast.
And in fact, you don't even have to call toString str = str + obj; will end up calling toString for you. That's what the + operator does for String. It's one of the convenient little quirks of the language.
That's just general info though. If you go with the StringBuffer, you can just do sbuf.append(it.next()).append(newline); What's newline? Well, rather than using "\n" you should use System.getProperty("line.separator") to get your end of line character(s).
>
Now my problem is like that, the constructor receive
instances and I put them in the superclass,now how can
I return it to the caller?
Huh?
public class DataItemArray extends LinkedList{
/** The arr is used for cloned string storage. */
LinkedList arr = new LinkedList();
//copy the reciverd list to its superclass array
public DataItemArray(LinkedList diArray) {
for(int i=0;i<diArray.size();i++){
super.add(diArray.get(i));
}The above will work, if you're trying to construct one of your objects by adding all the elements of a LinkedList to it. I think LinkedList has a constructor that takes another List or Collection as an arg, so you can just do this: public DataItemArray(Collection col) {
    super(col);
} which will have the same effect.
By the way, never iterate over a LinkedList using a counter and list.get(i). That's O(n^2). So a list with 3 times as many items will take 9 times as long. Always use an Iterator for iterating over a Collection.
Also, you don't need to call super.add. If you're going to call an add method, just call add(). Instance methods are polymorphic, so regardless of which add() you think you're calling, it will be this.add(). In your case, this.add() is inherited from super.
public LinkedList getArray(){
return super.?????
}Why do you want a method that returns an ArrayList? Your class IS a LinkedList. If you want to return the original list from which your class was constructed (why, I can't imagine) then you probably want composition, rather than inheritance. Don't extend LL. Just implement List and take a List as an arg at construction time.
That's one solution, but it really depends on what you're trying to do. If you really want something that is a LL except that it has a different toString, then keep extending as you do, but get rid of that getArray method, as it serves no purpose.

Similar Messages

  • Is there any Possibility of extending or importing a jcd in JCAPS.

    Hi,
    I am using JCAPS 512. Please let me know is there any possibility to
    reuse a jcd by extending or importing it.
    Please let me know in which location the classes created in edesigner will be stored in system.
    Regards
    Venkatesh.S

    Using JCAPS 5.1.3 on several large projects and JCD's extensibility is my biggest gripe. I'm a Java developer accustomed to code freely. Actually, wanted to extend and reuse OTDs as well, guess SeeBeyond markets it like a "Visual Basic" tool for integration. They should have learned from Delphi how to do it better.
    Anyway, the JCD are J2EE Stateless Session Beans under the covers, the code you write with eDesigner (NetBeans 3) goes through a "codegen" process. That is, you are not writing the Session Bean directly, consequently, the classic limitations with interpreted code.
    However, the next JCAPS version with NetBeans Open ESB will make developers happy by allowing normal Java development.

  • Can we initiate a class without extending or importing that class or packag

    Can we invoke a class
    class dog
    public static void main(String args[])
    Animal a = new Aniamal();
    like this without extending or importing the package belongs to animal.

    Can we invoke a class
    class dog
    public static void main(String args[])
    Animal a = new Aniamal();
    like this without extending or importing the package
    belongs to animal.give it the package location
    class dog
      public static void main(String args[])
        org.mypackage.Animal a = new org.mypackage.Animal();
    }

  • PS Extended Video Import Problem

    I cannot find any other reference to this problem in the FAQs or FORUMS.
    I cannot import any video files into PS Extended (10.0.1) without a Photoshop crash. The crash is caused by quicktime.qts file. I have tried to re-install quicktime several times with no success. Every other Quicktime function seems to work well.
    I have a newer Intel Quad PC with 2gb memory, 260GB of disk space and a nVidia Geforce 8800GTS video card.
    ANY HELP OUT THERE?!?!?

    John,
    Glad that you got it worked out. I was really interested in going to PS CS3 Extended, as I'm doing so much more graphics for video now. Unfortunately, though I've had PS as a standalone for decades (and AI and PM and on, and on), because I had gone the upgrade path to CS2 Production Studio, my individual app. path was cut off. I could only upgrade the full CS3 Production Studio (or whatever the flavor of the month name is) and I only wanted to upgrade PS. Premiere CS3 offered me little and seems frought with problems, so I'll just wait for CS4 to come out and get whichever bundle I'll need.
    Other than your above problem, how do you like it, so far? Do you interface with Premiere Pro and AfterEffects?
    Unfortunately, I do not know of any resources for this particular program. Maybe by CS4, there will be some good books, and tuts out.
    Hunt

  • SCAT t-code catt for extending materials - import file?

    want to extend materials to a new plant but not with the MASS transaction.
    apparently SCAT can do this more efficiently.  i'm not sure how the import file should be formatted.  i.e. want to make thousands of finished goods that will have ~ 7 default screens from MM01.
    please send detailed documents to me if you can
    [email protected]
    thanks

    Hi,
    I have send u a soft copy of how to use SCAT..
    Reward Points,
    Thanks,
    KSR.

  • Page extends vs page import

    What is the difference between
              <%@ page extends="com.beasys.commerce.portal.admin.PortalJspBase"%>
              and
              <%@ page import="com.beasys.commerce.portal.admin.PortalJspBase"%>
              

    "Kenneth Lee" <[email protected]> wrote in message news:<3bebfe13$[email protected]>...
              > What is the difference between
              > <%@ page extends="com.beasys.commerce.portal.admin.PortalJspBase"%>
              > and
              > <%@ page import="com.beasys.commerce.portal.admin.PortalJspBase"%>
              On the terminology extends vs import:- First, your jsp is basically a
              servlet. Whether your servlet is a kind of another class (extends) or
              use (import) another class is up your requirement.
              In your case, in theory, it shouldn't make a difference. Why? Because
              PortalJspBase is like a utility "Singleton" class (seemed like most of
              the functions and variables are static)! Deriving this class would
              possibly save some coding effort. However, since you are making a
              portlet (aren't you?), making it to be a "kind-of" weblogic portlet
              means that you must derive (or in the Java world, extend) from the
              above.
              Only my 2 cents worth.
              Regards
              drit
              

  • Please maintain PAN and LST details Error while extending the Vendor in Purchasing Organisation

    Dear Gurus,
    I have created a import vendor 200100 in finance using FK01 and mentioned LST, CST and PAN No details as "Nil", but when i am extending the Import vendor 200100 to purchasing organization level using T code XKO1, while saving i an getting error as: "Please maintain PAN and LST details"  even i checked in J1ID also... Excise data is maintained for this vendor. Please help me to resolve this issue. Many thanks.
    Regards,
    Siddu M

    Hi,
    You have to maintain PAN and LST number in Vendor master. This can be done in two ways :
    1. Go to transaction code J1ID. Select Vendor Excise details and click on Edit
    Click on
    Next Screen
    OR
    2. Go to Vendor Master
    Click on
    Next Screen
    Click on Sales Tax / Service tax tab
    Click on Withholding Tax tab
    In case CIN tab is not visible please revert as it comes on the basis of configuration which will be guided to you.
    We have said OR because in case it is updated in J1ID it reflects in CIN details or vice versa.
    Hope, this solves your issue else revert.
    Regards,
    Tejas

  • Which function to use for labeling 3D objects? (Acrobat 3D or Acrobat 9 Pro Extended)

    I want to label parts of a 3D model (e.g. "Rough finish", "Glossy" etc.). I want the labels to be present even when the model is rotated, zoomed and turned etc. I tried using the comment feature (text box with a line) in Acrobat 3D (v. 8) but the problem is that the labels disappear as soon as the model is turned or zoomed. They reappear only when the saved "view" is "on".
    Any suggestions on how this can be done, preferably using Adobe Acrobat 8 (or toolkit)? If its absolutely impossible in this version of Adobe I will try to use trial version of Adobe 9 Pro Extended.
    Please advise.
    Thank you.

    Hello,
    You can create 3D comments linked to the geometry within Acrobat Pro Extended 9
    - Import your 3D model
    - Activate 3D then right click and select Tools/Add 3D comment
    - Pick an element on your 3D Part (insert your text) then press ok
    Hope it helps
    Best Regards
    William Gallego

  • Export 3D PDF out of Photoshop Extended

    Hello everybody,
    I'm just looking for an solution to export or save a photoshop 3D object in a PDF file.
    I tried to use Acrobat Pro Extended for importing *.obj and *.u3d files exported from photoshop but unfortunatelly not all parts are imported. For example bump map is missing, reflection map is missing, ect. I think the only layer which is imported is the color layer.
    Or in a short and easy way: I cannot creat a PDF which looks exactly the same than the psd.
    Is there a way or what do I need to do to get the psd 1:1 imported in a 3d PDF?
    Thank you very much
    Regards Dominic

    This ma be the problem
    Acrobat Pro can create 3D PDFs but only from U3D ECMA 1 files
    Since there is a choice you may have select ECMA3 instead of one?

  • 3D PSD file import : how to change 3D anchor point in AE ? Challenge..!

    Hello everyone,
    I've successfully imported a 3D file from Photoshop Extended CS4 into AE CS4. In AE, I can sucessfully animate rotation of the 3D object.
    Here's the problem : I cannot change the 3D object's anchor point. I've tried changing the anchor point's coordinates on the controller layer of the 3D object layer, the numers change, but the anchor point remains at its initial position, as if it was locked.
    I also thought changing the anchor point in PS Extended before importing the file into AE, but PS Extended does not seem to have an anchor point changing tool.
    So I even reasoned back one step : changing the anchor point in my 3D software since the beginning. Well, not possible because PS Extended seems to create an average position for the anchor point when impoting a 3D file from a third party software. So useless changing the coordinates in the 3D software.
    Photoshop Extended 3D is the only possible workflow to import 3D objects into AE that I know of.
    So, is is possible to change the 3D anchor point directly in After Effects ? What blocks that point from being changed ?
    This is quite a challenging problem, good luck for finding a solution ! I'm very sure that this technique is commonly needed and used when working in 3D, and that it will be of great help for many designers that want 3D in After Effects !
    Thanks again !
    Note : please do not confuse simple After Effects standard 3D layer, with the 3D PSD file import layer, these are two totally different types

    Any further forward with this anyone?
    This is driving me insane as well...
    I'm trying to create a simple comp within AE and have my clients logo fly on behind their text while rotating in 3D space.
    The idea is for it to rotate on the X axis, but rotate within the logo itself (straight through the axis within the logo itself)
    But when I try to rotate it, the AP is about 2.5 "logo depths" away from the logo, so when the rotation of any axis starts it looks ridiculous.
    Are Adobe really trying to tell us that moving the AP is not possible within AE for imported Live Photoshop PSD files?
    Hopefully a solution comes along soon as I cannot for the life of me figure out a workaround to the problem......
    Cheers,
    Paul.

  • Import net.rim.blackberry.api.phone.phonelogs.*;

    I have developed a midlet with WTK22 and I have successfully used the Blackberry rapc tool to compile it for the Blackberry where it runs very well. I would now like to import the Blackberry RIM classes in net.rim.blackberry.api.phone.phonelogs.*; to access the phone logs on the Blackberry.
    I can successfully compile a class that extends thread; imports net.rim.blackberry.api.phone.phonelogs.*; and then uses these classes. I can preverify the class by including the net_rim_api.jar in the classpath. I then jar this class with my other midlet classes in a jar library. However, when I try to compile the main midlet class with WTK22 using this phone log class, I get the following error:
    Building "afs"
    Error preverifying class afslib.afsphone
    VERIFIER ERROR afslib/afsphone.run()V:
    Cannot find class net/rim/blackberry/api/phone/phonelogs/CallLog
    Build failed
    From what I have read, it should be possible to use any Blackberry class in net_rim_api.jar as long as it is not part of the UI. Would someone please let me know what I am doing wrong.

    Thank you Hithayath for your response.
    Below is the full code from the class where I am using the classes from RIM:
    package afslib;
    import java.util.*;
    import java.lang.*;
    import net.rim.blackberry.api.invoke.Invoke;
    import net.rim.blackberry.api.invoke.PhoneArguments;
    import net.rim.blackberry.api.phone.phonelogs.*;
    import afslib.*;
    public class afsphone extends Thread
    String pnum;
    public afsphone(String pnum)
    this.pnum = pnum;
    public void run()
         PhoneLogs _logs;
              PhoneArguments call = new PhoneArguments(PhoneArguments.ARG_CALL,pnum);
              Invoke.invokeApplication(Invoke.APP_TYPE_PHONE, call);
              _logs = PhoneLogs.getInstance();
         PhoneCallLog pclog = (PhoneCallLog)_logs.callAt(0,PhoneLogs.FOLDER_NORMAL_CALLS);
              pclog.setNotes("string");
    The afsphone class is compiled, preverified and put into afslib which is imported in the main afs midlet class. When I build afs in the WTK I get the following error:
    Building "afs"
    Error preverifying class afslib.afsphone
    VERIFIER ERROR afslib/afsphone.run()V:
    Cannot find class net/rim/blackberry/api/phone/phonelogs/CallLog
    Build failed
    David

  • DefaultTableModel or extend AbstractTableModel

    I find the DefaultTableModel very easy to use with lots of functionality. As data is stored in a Vector of Vectors any data can be suppported. You don't have to worry about firing any events when cell data is changed, this is handled by the model. There is great support for dynamic tables through the addRow, addColumn methods. When processing needs to be done on a table as a result of a change in cell contents it is easy to use a TableModelListener.
    In many question on this forum I find that people create there own table model by extending AbstractTableModel. Not only is this extra work, but you loose much of the functionality of the DefaultTableModel. One poster even said they believe that the DefaultTableModel should never be used in a production system suggesting that storing the data as a Vector of Vectors is inefficient and that too much casting is done when you need to do any processing.
    Anyway, lets take a simple table with columns containing: quantity, price and cost. When the quantity or price is changed the cost should be calculated.
    How would you implement this in production?
    Is the DefaultTableModel sufficient for your needs or would you create your own TableModel.
    Can you make a general statement about when you would use the DefaultTableModel vs. creating your own TableModel?
    Following are two implementations of this table.
    Any comments on either approach or suggestions on a third approach.
    Using the DefaultTableModel:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class TableProcessing extends JFrame implements TableModelListener
        JTable table;
        public TableProcessing()
            String[] columnNames = {"Item", "Quantity", "Price", "Cost"};
            Object[][] data =
                {"Bread", new Integer(1), new Double(1.11), new Double(1.11)},
                {"Milk", new Integer(1), new Double(2.22), new Double(2.22)},
                {"Tea", new Integer(1), new Double(3.33), new Double(3.33)},
                {"Cofee", new Integer(1), new Double(4.44), new Double(4.44)}
            DefaultTableModel model = new DefaultTableModel(data, columnNames);
            model.addTableModelListener( this );
            table = new JTable( model )
                //  Returning the Class of each column will allow different
                //  renderers to be used based on Class
                public Class getColumnClass(int column)
                    return getValueAt(0, column).getClass();
                //  The Cost is not editable
                public boolean isCellEditable(int row, int column)
                    if (column == 3)
                        return false;
                    else
                        return true;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
         *  The cost is recalculated whenever the quantity or price is changed
        public void tableChanged(TableModelEvent e)
            if (e.getType() == TableModelEvent.UPDATE)
                int row = e.getFirstRow();
                int column = e.getColumn();
                if (column == 1 || column == 2)
                    int    quantity = ((Integer)table.getValueAt(row, 1)).intValue();
                    double price = ((Double)table.getValueAt(row, 2)).doubleValue();
                    Double value = new Double(quantity * price);
                    table.setValueAt(value, row, 3);
        public static void main(String[] args)
            TableProcessing frame = new TableProcessing();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }Extending AbstractTableModel:
    import java.awt.*;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class TableProcessing2 extends JFrame
        JTable table;
        public TableProcessing2()
            ArrayList columnNames = new ArrayList(4);
            columnNames.add("Item");
            columnNames.add("Quantity");
            columnNames.add("Price");
            columnNames.add("Cost");
            ArrayList data = new ArrayList();
            data.add( new Item("Bread", 1, 1.11) );
            data.add( new Item("Milk", 1, 2.22) );
            data.add( new Item("Tea", 1, 3.33) );
            data.add( new Item("Cofee", 1, 4.44) );
            TableModel model = new ItemTableModel(data, columnNames);
            table = new JTable( model );
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
        class Item
            String name;
            int quantity;
            double price;
            double cost;
            public Item(String name, int quantity, double price)
                this.name = name;
                this.quantity = quantity;
                this.price = price;
                cost = quantity * price;
        class ItemTableModel extends AbstractTableModel
            List data;
            List columnNames;
            public ItemTableModel(List data, List columnNames)
                this.data = data;
                this.columnNames = columnNames;
            public String getColumnName(int col) { return columnNames.get(col).toString(); }
            public int getRowCount() { return data.size(); }
            public int getColumnCount() { return columnNames.size(); }
            public Class getColumnClass(int column) { return getValueAt(0, column).getClass(); }
            public boolean isCellEditable(int row, int column)
                if (column == 3)
                    return false;
                else
                    return true;
            public Object getValueAt(int row, int column)
                Item item = (Item)data.get( row );
                switch ( column )
                    case 0: return item.name;
                    case 1: return new Integer(item.quantity);
                    case 2: return new Double(item.price);
                    case 3: return new Double(item.cost);
                return null;
            public void setValueAt(Object value, int row, int column)
                Item item = (Item)data.get( row );
                switch ( column )
                    case 0:
                        item.name = (String)value;
                        break;
                    case 1:
                        item.quantity = ((Integer)value).intValue();
                        break;
                    case 2:
                        item.price = ((Double)value).doubleValue();
                        break;
                    case 3:
                        item.cost = ((Double)value).doubleValue();
                        break;
                fireTableCellUpdated(row, column);
                //  Update dependent cells
                if (column == 1 || column == 2)
                    Double cost = new Double(item.quantity * item.price);
                    table.setValueAt(cost, row, 3);
        public static void main(String[] args)
            TableProcessing2 frame = new TableProcessing2();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }

    mzarra, I think I have enough information to make an informed decision, thanks.
    virivan,
    I took a look at your link. Cool. It looks like you've played with tables more than me. Like mzarra said above, you are probably creating your TableModel in the event thread which doesn't give the GUI a chance to repaint itself. When the table was loading I clicked on a different window and when I clicked back on you application I got a 'black' rectangle on the screen.
    Reply 3 of this thread shows a simple example of moving the logic from the event thread to a separate thread:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=435487
    Also, for fun I created a simple TableModel to store sparse data. It loads instantly. Here's the code I used:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableSparse extends JFrame
        private final static String[] LETTERS =
            "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
            "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
        public TableSparse(int row, int column)
            TableModel model = new LargeTableModel(row, column);
            JTable table = new JTable(model);
            table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
    //        JTable lineTable = new LineNumberTable( table );
    //        scrollPane.setRowHeaderView( lineTable );
        class LargeTableModel extends AbstractTableModel
            HashMap data = new HashMap();
            int rows;
            int columns;
            public LargeTableModel(int rows, int columns)
                this.rows = rows;
                this.columns = columns;
            public String getColumnName(int column)
                if (column < 26)
                    return LETTERS[column];
                int first = (column / 26) - 1;
                int second = (column % 26);
                return LETTERS[first] + LETTERS[second];
            public int getRowCount() { return rows; }
            public int getColumnCount() { return columns; }
            public boolean isCellEditable(int row, int column) { return true; }
            public Object getValueAt(int row, int column)
                //  Check for row
                Integer key = new Integer(row);
                Object o = data.get(key);
                if (o == null) return null;
                //  Now check for column
                HashMap rows = (HashMap)o;
                key = new Integer(column);
                return rows.get(key);
            public void setValueAt(Object value, int row, int column)
                //  Remove cell data
                if (value.toString().equals(""))
                    removeCellData(row, column);
                    return;
                //  Save cell data
                Integer key = new Integer(row);
                HashMap rows = (HashMap)data.get(key);
                if (rows == null)
                    rows = new HashMap();
                    data.put(key, rows);
                key = new Integer(column);
                rows.put(key, value);
            private void removeCellData(int row, int column)
                Integer rowKey = new Integer(row);
                HashMap rows = (HashMap)data.get(rowKey);
                Integer columnKey = new Integer(column);
                rows.remove(columnKey);
                if (rows.isEmpty())
                    data.remove(rowKey);
        public static void main(String[] args)
            TableSparse frame = new TableSparse(64000, 256);
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
    }

  • OAF: Expert Mode disabled when trying to extend a seeded VO!

    Hello All,
    I am trying to extend one of the seeded VO in IRC and when I get to the Query screen, the Query statement is Read-only and the "Expert Mode" checkbox is disabled! So, I am not able to change the query to extend.
    Imported all the necessary server.xml from middle tier (linux) into my PC.
    Created a project.
    Created a New OA Business Component package.
    Select the newly created OA Business Component package , right click and create New View Object and point to the seeed VO to extend.
    Click Next for EO (left as default) and Next till the Query screen
    On the Query screen, both the "Generated Query statement" is read-only and the check box "Expert Mode" is disabled (Read-only!)*** So am unable to check the "Expert Mode" to change the Query !!!
    Am I missing something here??? Please help!
    Thanks for any help.
    FR

    Hi FR ,
    Even I got the same problem to edit the Query . I solved it by first adding a Entity Object to the VO then the Query becomes editable and later you can remove the Entity Object . And in my case the Query remained editable even after removing the EO .
    Thanks,
    Srikanth

  • Saving contents of jinternal frame

    Hi, I seem to have a problem saving files from jinternal frames. I created two files, the main GUI which holds the jdesktop pane and the other file (Documento) extends jinternalframe. I want to be able to save the current (active) jinternal frame but I have no idea how to do it. can anyone help me?
    import javax.swing.JInternalFrame;
    import javax.swing.JDesktopPane;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JMenuBar;
    import javax.swing.JFrame;
    import javax.swing.KeyStroke;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.Graphics.*;
    import javax.swing.JOptionPane;
    import java.io.*;
    import java.util.*;
    *This is the main GUI of the program.
    public class mainGUI extends JFrame
                                   implements ActionListener,
                                    KeyListener{
        JDesktopPane desktop;
        Documento frame;
         private Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
         private JPanel toolbar, editarea, resultarea, blankPanel;
         private JMenu file, edit, project;
         private JMenuItem f_open, f_new, f_save, f_saveas, f_exit, e_select, e_copy, e_paste, p_compile;
         private JTextArea resultfield, editfield,editArea, tstr;
         private JButton bcompile;
         private JFileChooser fc = new JFileChooser();
         private String filepath;
         private ImageIcon bugicon;
         private static int docNum = 0;
         private boolean b_openfile;
         File filename;
        public mainGUI() {
            super("DGJ Program Scanner");
            setSize(800,600);
              setLocation((screen.width-800)/2, (screen.height-600)/2);
            /*Creates the workspace*/
            desktop = new JDesktopPane();
            setContentPane(desktop);
            setJMenuBar(createMenuBar());
            /*Make dragging a little faster*/
            desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
          *This function creates the menu bar
        protected JMenuBar createMenuBar() {
             /*Initializes/instantiates the menu bar and its items*/
              file = new JMenu("File");
              edit = new JMenu("Edit");
              project = new JMenu("Project");
              f_new = new JMenuItem("Create new file");
              f_open = new JMenuItem("Open file...");
              f_save = new JMenuItem("Save current file");
              f_saveas = new JMenuItem("Save As...");
              f_exit = new JMenuItem("Exit program");
              e_select = new JMenuItem("Select All");
              e_copy = new JMenuItem("Copy selected");
              e_paste = new JMenuItem("Paste selected");
              p_compile = new JMenuItem("Scan current file for errors");
              /*Adds listeners to the menu items*/
              f_open.setActionCommand("f_open");
              f_open.addActionListener(this);
              f_save.setActionCommand("f_save");
              f_save.addActionListener(this);
              f_saveas.addActionListener(this);
              f_saveas.setActionCommand("f_saveas");
              f_new.setActionCommand("f_new");
              f_new.addActionListener(this);
              f_exit.setActionCommand("f_exit");
              f_exit.addActionListener(this);
              e_select.setActionCommand("e_select");
              e_select.addActionListener(this);
              e_paste.setActionCommand("e_paste");
              e_paste.addActionListener(this);     
              e_copy.setActionCommand("e_copy");
              e_copy.addActionListener(this);               
              /*Creates the icon of the bug*/
              bugicon = new ImageIcon("images/ladybug.gif");
              /*Creates the menu bar*/
              JMenuBar menu = new JMenuBar();
              menu.add(file);
                   file.add(f_new);
                   file.add(f_open);
                   file.add(f_save);
                   file.add(f_saveas);
                   file.add(f_exit);
              menu.add(edit);
                   edit.add(e_select);
                   edit.add(e_copy);
                   edit.add(e_paste);
              menu.add(project);
                   project.add(p_compile);
              /*Disables the save current file menu...(when program starts, no file is open yet)*/
              f_save.setEnabled(false);
              f_saveas.setEnabled(false);
            return menu;
        //React to menu selections.
        public void actionPerformed(ActionEvent e) {
            if ("f_new".equals(e.getActionCommand()))
            { //new
                createFrame(null);
                f_saveas.setEnabled(true);
            else if("f_open".equals(e.getActionCommand()))
            {//open documento
                   fc.setFileFilter(new SpanFilter());
                  int retval = fc.showOpenDialog(mainGUI.this);
                   tstr = new JTextArea();
                   /*This checks if the user has chosen a file*/
                if (retval == JFileChooser.APPROVE_OPTION) {
                    filename = fc.getSelectedFile();
                        filepath = filename.getPath();            
                        openFile(filename, new Point(30,30));       
            else if("f_save".equals(e.getActionCommand()))
                 try {
                      BufferedWriter out = new BufferedWriter(new FileWriter(filepath));
                      String str;
                      str = editArea.getText();
                      editArea.setText("");  
                      int length = str.length();
                      out.write(str, 0, length);
                      out.close();
                       } catch (Exception ex) {}
                       JInternalFrame fr = new JInternalFrame();
                       fr = desktop.getSelectedFrame();
                       Point p = fr.getLocation();
                        fr.dispose();    
                       openFile(filename, p);
            else if("f_saveas".equals(e.getActionCommand()))
                 fc.setFileFilter(new SpanFilter());
                  int retval = fc.showSaveDialog(mainGUI.this);
                if (retval == JFileChooser.APPROVE_OPTION) {
                    filename = fc.getSelectedFile();
                        filepath = filename.getPath();
                        if(!(filepath.contains(".dgj")))
                             filepath+=".dgj";
                      try {
                           BufferedWriter out = new BufferedWriter(new FileWriter(filepath));
                                String str;
                           str = editArea.getText();
                           int length = str.length();
                           out.write(str, 0, length);
                           out.close();
                       } catch (Exception ex) {}
                       Point p = frame.getLocation();
                        frame.dispose();
                   //     editArea.setText("");     
                       openFile(filename, p);
            else if("e_select".equals(e.getActionCommand()))
                 editArea.selectAll();
            else if("e_copy".equals(e.getActionCommand()))
                   editArea.copy();
            else if("e_paste".equals(e.getActionCommand()))
                 editArea.paste();
            else if("f_exit".equals(e.getActionCommand()))
            { //quit
                quit();
        public void openFile(File filename, Point p)
                        /*Reads the file*/
                        try {
                           BufferedReader in = new BufferedReader(new FileReader(filepath));
                             String str;
                             /*empties the textarea*/
                             tstr.setText("");
                             str = in.readLine();
                             /*Copy each line of the file into the temporary textarea*/
                           do{  
                          tstr.append(str);
                          str = in.readLine();
                          /* the "\n" is for the line to appear in the next line in the textarea,
                           * the "\r" is for windows system, wherein "\r" is required for the text
                           * to appear in beginning of the first line*/
                          if(str!=null)
                               tstr.append("\r\n");
                           }while (str != null);
                             /*Opens the new frame*/
                           createFrame(filename, filename.getName(), tstr.getText(), p);
                           in.close();
                       } catch (Exception ex){}
                      b_openfile = true;
                      f_save.setEnabled(true); 
                      f_saveas.setEnabled(true);   
         *Create a new internal frame.
        protected void createFrame(File f) {
             frame = new Documento(f);
         /*     frame = new JInternalFrame("Document "+(++docNum),
                  true, //resizable
                  true, //closable
                  true, //maximizable
                  true);
            docNum++;
              frame.setSize(600,400);
              frame.setLocation(20*(docNum%10), 20*(docNum%10));       
             editArea = new JTextArea();
              JScrollPane scroll = new JScrollPane(editArea);     
              editArea.addKeyListener(this);
              editArea.append("");
              frame.add(scroll);
            frame.setVisible(true); //necessary as of 1.3
            desktop.add(frame);
            try {
                frame.setSelected(true);
            } catch (java.beans.PropertyVetoException e) {}
          *Overwrite an existing internal frame for an open file
        protected void createFrame(File f, String title, String text, Point P) {
             frame = new Documento(title, f, P);
              frame.setSize(600,400);
              frame.setLocation(P); 
             editArea = new JTextArea();
              JScrollPane scroll = new JScrollPane(editArea);     
              editArea.setText("");
              editArea.addKeyListener(this);
              editArea.append(text);
              frame.add(scroll);
            frame.setVisible(true); //necessary as of 1.3
            desktop.add(frame);
            try {
                frame.setSelected(true);
            } catch (java.beans.PropertyVetoException e) {}
        //Quit the application.
        protected void quit() {
            System.exit(0);
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Make sure we have nice window decorations.
            //JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            mainGUI frame = new mainGUI();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Display the window.
            frame.setVisible(true);
        public void keyTyped(KeyEvent k){}
        public void keyPressed(KeyEvent k)
             if(k.getKeyCode()==10)
                  editArea.append("\r");           
        public void keyReleased(KeyEvent k){}
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }here's the one that extends jinternalframe
    import javax.swing.JInternalFrame;
    import javax.swing.plaf.InternalFrameUI;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    import java.util.*;
    /* Used by mainGUI.java */
    public class Documento extends JInternalFrame {
        static final int xOffset = 30, yOffset = 30;
         static JTextArea editArea;
         static int docNum = 0;
         static File file;
          *The constructer for a new documento
        public Documento(File file) {
            super("Document "+(++docNum),
                  true, //resizable
                  true, //closable
                  true, //maximizable
                  true);//iconifiable
            docNum++;
              this.file = file;
              setSize(600,400);
              setLocation(xOffset*(docNum%10), yOffset*(docNum%10));
    //        setUI(new InternalFrameUI());
         *The constructor for an existing documento
        public Documento(String title, File file, Point p) {
            super(title,
                  true, //resizable
                  true, //closable
                  true, //maximizable
                  true);//iconifiable
              this.file = file;             
              setSize(600,400);          
              setLocation(p);
    //        setUI(new InternalFrameUI());
        public int getNum()
             return docNum;
        public File getPath()
             return file;
    }I know it's pretty lengthy...it's probably all messed up since I'm lost :p
    Thanks if you could help me!

    I would be glad to help, but first I need a clarification. If I understand properly, you have two Java classes that you have created: the "main GUI" (which is most likely a JFrame extension in which the constructor adds a JDesktopPane to the content pane) and "Documento" (which you say is a JInternalFrame extension).
    My question is this: what do you mean by "save the current JInternalFrame"? Do you want to record its position, location, and identity? Do you want to save its contents?
    Thanks. Good luck. ;)

  • How move code from one class to other?

    I have a .fla file.
    There i have some keyframes with labels.
    On .fla file in property in Class field i adde MyMatching class.
    Also i have main code:
    package
         import flash.display.MovieClip;
         import flash.events.MouseEvent;
         import flash.text.TextField;
         public class MyMatching extends MovieClip
              var play_btn:MyButton = new MyButton();
              var kyky:MyTimer;
              public function MyMatching():void
                   welcomeScreen();
              public function welcomeScreen():void
                   stop();
                   trace("working");
                   play_btn.x = 210;
                   play_btn.y = 300;
                   addChild(play_btn);
                   play_btn.addEventListener(MouseEvent.CLICK, goToLevel_1);
              public function goToLevel_1(event:MouseEvent)
                   trace("level 1");
                   play_btn.visible = false;
                   gotoAndStop('Level1Screen');               
                   if (kyky==undefined) {
                        kyky = new MyTimer();
    And i have other class:
    package
         import flash.display.MovieClip;
         import flash.display.Stage;
         import flash.utils.getTimer;
         import flash.text.TextField;
         public class MyTimer extends Stage
              import flash.utils.getTimer;
              var gameStartTime:uint;
              var gameTime:uint;
              var gameTimeField:TextField;
              function mainFunction():void
                   gameTimeField = new TextField();
                   addChild(gameTimeField);
                   gameStartTime=getTimer();
                   gameTime=0;
                   addEventListener(Event.ENTER_FRAME,showTime);
              function showTime(event:Event)
                   gameTime=getTimer()-gameStartTime;
                   gameTimeField.text="You plaing: "+clockTime(gameTime);
              function clockTime(ms:int)
                   var seconds:int=Math.floor(ms/1000);
                   var minutes:int=Math.floor(seconds/60);
                   seconds-=minutes*60;
                   var timeString:String=minutes+":"+String(seconds+100).substr(1,2);
                   return timeString;
    Ho i can play code from class MyTimer in goToLevel_1 function(this function stand in my main class MyMatching) ?
    Thank you.

    First of all your MyTimer class is written wrong and sloppy.
    Why does it extend Stage? The most compact class to extend under the circumstances is Sprite.
    Also, it is very important to get into habit of datatype declarations. Not only it is good practice, in your case good compiler will throw error because although you return String, function doesn't return anything.
    In addition, it is important to declare namespaces like private public and protected inside classes. Not function clickTime():String but private function clockTime():String or public function clickTime():String.
    As for how to show your time elsewhere - you just need to create instnace of it and add it to disaply list:
    var myTimer:MyTimer = new MyTimer();
    addChild(myTimer);
    With that said, your class should look like this:
    package 
         import flash.display.Sprite;
         import flash.events.Event;
         import flash.display.MovieClip;
         import flash.utils.getTimer;
         import flash.text.TextField;
         public class MyTimer extends Sprite
              private var gameStartTime:uint;
              private var gameTime:uint;
              private var gameTimeField:TextField;
              public function MyTimer()
                   gameTimeField = new TextField();
                   addChild(gameTimeField);
                   gameStartTime = getTimer();
                   gameTime = 0;
                   addEventListener(Event.ENTER_FRAME,showTime);
              private function showTime(event:Event):void
                   gameTime = getTimer() - gameStartTime;
                   gameTimeField.text = "You playing: " + clockTime(gameTime);
              private function clockTime(ms:int):String
                   var seconds:int = Math.floor(ms / 1000);
                   var minutes:int = Math.floor(seconds / 60);
                   var timeString:String = minutes + ":" + String(seconds + 100).substr(1, 2);
                   return timeString;

Maybe you are looking for

  • Cisco Connect does not run with Mac OSX Mountain Lion (10.8.2)

    When I first installed Cisco Connect that came with my E1500 router, I was running Mac OSX Snow Leopard (10.7) and it worked fine.  I upgraded my OSX to Mountain Lion and now when I start Cisco Connect, I get: Unsupported operating system The router

  • How to put pictures on an external hard drive from iphoto on a macbook

    Yeah there are pictures on my macbook pro iphoto that i want to put on my external hard drive, but im not sure how to do it, all help is appreciated thanks.

  • Special characters in search

    Hi all, Using Oracle UCM 11g. In the UCM console, when doing a content search using the left-side panel (not the quick search) and entering a content title containing a hyphen (e.g. content-01), no results are being returned even though a content wit

  • Minimum Screen Resolution for Premiere Pro CS3

    I want to be able to run the package on my laptop when out and about, but the screen resolution is only 1024 x 768. Can anyone tell me whether it will run under said resolution, but with a crowded screen or will it simply not work. I have not yet bou

  • Extra condition added in the query

    Hi All, I have created a report but its not showing all the results.When I checked the query I saw the extra filter (where ( D1.c7 = 1 )) .I have not added any such filter.Can someone please tell me how this filter has got added and how we can avoid