JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That problem is really nothing to do with generics. It's the same as

String s = "hello";
Object o;
o = s; // this is OK
s = o; // this isn't, even if it would be ok with this particular data
s = (String) o; // is OK, unless there was something at runtime that put a non-String into o

Maybe you are having a problem with the way the generics don't treat subclasses like the rest of Java. A type <T> doesn't include T's subclasses, for that you need some variant of <? extends T>. Most people have a problem with that.
To quote the Oracle tutorials:

In general, if Foo is a subtype (subclass or subinterface) of Bar, and G is some generic type declaration, it is not the case that G<Foo> is a subtype of G<Bar>. This is probably the hardest thing you need to learn about generics, because it goes against our deeply held intuitions.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Input: you need a List. You give it an ArrayList which is a subclass All ArrayLists are Lists, so it's OK
Output: You need an ArrayList. YOu give it a List, which is a superclass. Not all Lists are ArrayLists (eg some are LinkedLists), so it's not OK

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Looks like you have put some String data into a column whose class is Boolean.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK, that's getting a lot closer. Main problem is that the getColumnClass method needs to be in the table model class, and takes an int as its parameter.
Here's an example that just illustrates the stuff you need (for the requirements that you have posted so far).
First, you need a table model that's just like the DefaultTableModel, except that it returns sensible values for getColumnClass, eg

    class BetterDefaultTableModel extends DefaultTableModel {

        private Class[] columnTypes;

        public BetterDefaultTableModel(Object[][] data, Object[] columnNames,
                Class[] columnTypes) {
            super(data, columnNames);
            this.columnTypes = columnTypes;
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return columnTypes[columnIndex];
        }
    }

This just adds an array of column classes to the default, and implements a constructor just like the one you are currently using, except that you also pass in an array of column classes. That array is then used to give the correct return value for getColumnClass.

And here's an example of using it:

        JTable table = new JTable();
        Object[][] data = {{"hello", true}, {"goodbye", false}};
        String[] columnNames = {"a String", "a Boolean"};
        Class[] columnTypes = {String.class, Boolean.class};
        table.setModel(new BetterDefaultTableModel(
                data, columnNames, columnTypes));

Please spend a few minutes reading and understanding that code, then try using it in your environment. Assuming it does what you need, you can then use what it taught you to write your own program.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I really don't know how to make this any clearer than the Java and training experts who wrote the tutorial. Your code doesn't even start to resemble the tutorial code I linked to. Did you read it? I honestly don't know to make it any clearer than that. Sorry.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK. That code is going off in all kinds of wrong directions. I need you to go back and re-readthe link I gave earlier
This part of the tutorial
You need to create a simple table model, just like the one in that tutrorial, and implement a getColumnClass metjod in it, like the example a bit further down that tutorial (code in bold), that returns the appropriate class (eg String, Integer, Boolean) for each column. Returning Boolean will make that column use check boxes automatically.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Don't know about "correct", but if I were doing this, that's how I would do it (at least as a starting point).
Looks like panel 1 has only one JLabel it it (?) so is redundant.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

peek if you want to see the first item without removing it, yes.
I don't think gthere's any way to see the later items in the correct order without removing (poll) the first element.
NB highest priority == lowest Integer value, counter-intuitively!

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

PriorityQueue inherits its toString() from java.util.AbstractCollection, which doesn't know about sort orders. (println uses toString() on all its arguments).
If you poll() the elements as intended, you get them in the correct order, eg

Integer i;
while ((i = pq.poll())!= null) System.out.print(i + " ");
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK, "exactly the same" was a bit of an exaggeration, but the overall approach is the same.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Also, multithreading isn't just a Java thing. If a language and its libraries don't implement support for multi-threading then they're no use in the real world of software deveopment.
Multi-threading is conceptually difficult, and can be very hard to wrap your head around. Java's support for multi-threading is as easy as it gets, mainly because it has excellent library support for amny of the more common ways you would use mutiple threads in practice (thread pools, swing worker etc etc). You won't find a popular language that does it properly and makes it any easier than Java.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

For formatted text don't use a JTextArea, use an editor pane or text pane. See
http://docs.oracle.com/javase/tutorial/uiswing/components/editorpane.html

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes, Java 8 is scheduled for March 2014. Developer previews have been available for ages, along with a version of NetBeans that supports it, and the Release Candidate is due next week. The whole lambda thing is going to change the way we write a lot of code - no more anonymous inner classes for event listeners for a start.
You're right about homework - it will take years before teachers upate their syllabus and exercises, and corporations will take ages to update all their user base. That's their problem. I'm going to enjoy the latest and best for my work. ;)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That message implies you are still on Java 1.6. If so an immediate upgrade to 1.7 is a top priority, noit just for the language/API enhancements buta also for security and perfomance fixes. Oracle officially stopped releaseing public updates for 1.6 in March 2013 (see http://www.oracle.com/technetwork/java/eol-135779.html )

Having done that, a clean install of the latest NetBeans 7.4 should fix the profiler problem.

I still find this bizzare. The only Java things I have ever seen taking more than a few seconds were either IO-bound or massively recursive.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I looked at the screen image, and it's more than just a complete beginners exercise. If you have been set this as part of your course, and you "don't know a thing about it" then there's little anyone here can do to help you. You need to go back over your course materials and learn the stuff that your teacher obviously expects you to know by now.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

They are all variables.
Some veriables are "primitives", eg int, float, boolean, char (See Java Language Spec section 4.2 for the complete list, but they alll have names that begin with a lower case letter. All the classes in standard Java have names the begin with an upper-case letter). They just contain a value; and == workslike you would expect.
Others are "reference variables" and they contain a reference ("pointer") to an Object. Thet are not themselves objects, nor do they contain objects, they just have a reference to an object. Their == tests that their references are equal, ie they are both references to the same Object. To see if two different Objects are considered "equal", you have to call their equals method.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

No, not toString for the JList. By default JList calls toString on each object that it displays to get some text to put in the list. You could change toString for your Person class, but that will probably mess up all the other places where it's used.
You could write a small list model that returns the desired String from you underlying list of Persons.
Or you could write a small cell renderer to draw justthe desired text.
Both these are described more in the intro to the JList API doc, but the simplest custom renderer just takes the default one and changes the text. eg

class CustomRenderer extends DefaultListCellRenderer {
    // same as DefaultListCellRenderer but uses custom text
    @Override
    public Component getListCellRendererComponent(
            JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        // start with the default renderer, then replace its text..
        JLabel label = (JLabel) super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
        // cast the value to the appropriate class, and construct a suitable string
        label.setText(((Person) value).getName());
    return label;
    }
}

ps: mKorbel has drawn my attention to the fact that this may not work too well with keyboard selection from the list using the first letter(s) of an entry - see the link in his post below for details and solutions.)

mKorbel commented: agree +10
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Have you tried a "clean and build" on the project?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The output you posted above shows you have 90% solved already. Just look at those split sections - if they begin with <\ they are an end tag, if they begin with < they are a start tag, the rest are values.
(Your parsing may not be 100% if the source HTML has weird line breaks, but maybe you can worry about that later.)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

One place to start is to split the lines using greater than OR less than as the delimiter, and look at what that gives you...
or you could use indexOf to find the greater thans ands less thans and use substring to pick pieces out of the string...

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That is a valid solution, but a bit tacky - convert the file to a String path just to convert it back to a file...
Much cleaner to just use the file directly

 br = new BufferedReader(new FileReader(file)); 
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The question is pretty vague, but seems to be in two parts:
How to display random image? Have an array containing all the file names and pick a value from it using a random integer. You can get an array of all the files with a particular extension in a folder using a method from the File class. If the names are all like a1, a2 etc just concatenate a random int to theletter "a".
How to display the images one at a time? Use a javax.swing.Timer to run a small method at regular intervals. In that method just set the label's ImageIcon to the next random image.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Rather than getting the Image's buffer, and having to deal with all he types (as Paul mentions) you could use the PixelGrabber class to get an array of SRGB ints for any or all of any Image, regardless of its internal format. The API doc for PixelGraber also documents the correct way to extract the individual components from the int values.
If you are happy that your Image will always be a BufferedImage then Paul's getRGB is even easier.

cwarn23 commented: Thanks for the great help! +12
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Maybe its a problem with the byte arithmetic? The RGB byte values are unsigned (0 to +255), but Java bytes are signed (-128 to +127). You may need to do some masking (ANDing with hex FF) to stop the first bit being propogated as a sign bit when you convert byte to int or vice-versa?

Eg. consider this simplified case:

        byte x = (byte) 127;
        byte y = (byte) 127; 
        byte z = (byte) (x + y);
        System.out.println(x+" "+y+" "+z);

I bet you expect to 254 in z. But it's -2.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Sorry, it looks like you may be out of luck. I don't think there are many JavaFX users active in this forum (yet). Still, don't give up too soon - people are still coming back after the New Year.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You set a LayoutManager for each JFrame's content pane or JPanel, it then handles the exact positioning of its contents, based on your specifications. Please see the tutorial I linked in my previous post.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes, and I would place the buttons as a GridLayout inside a JPanel, so the JFrame has a text field and a JPanel, one above the other.

A loop to create the buttons is a good idea. There's no need to have an array of buttons - once created and an action listener added there's no need to reference the buttons any more. (In the action listener you can just getText for the event source to see which button was pressed (there are better ways, but that's the easiest).) You could define a String array with the labels, which makes it easy to add the right label to each button.

labels = {"7","8"..."=","+")
for i = 0 to 15 {
   create new button with its text = labels[i]
   add it to the JPanel
   set its action listener
}
...
wait for user to press one!
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You can set the layout manager for the container to null, then use setBounds to set the size and position of your label in pixels.
However, if you do it's going to look very silly when someone runs your code on a screen with "retina" resolution, or even just on a system with a bigger system font selected.
You can keep you application looking OK across different systems by using a layout manger to position components according to the current font sizes etc.
See http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

pack() fits everything together according to the layout manager(s) and any other constrains you have specified. Until you call it your laying out isn't finished. In particular the setSize for the JFrame will be overridden by the pack, but a setMinimumSize should be honoured.

There's only so much you can do with a simple layout manager like GridLayout - I see you already found the h/v spacing options for the constructor. You can shift the labels right by changing their setHorizontalAlignment to close them up to the entry fields. How important is it in this case to get it "just right" as opposed to "near enough"?

In the end, if you really want total control over spacing etc, while still retaining the resizability and platform independence that a layout manager gives you, you have to go to one of the heavy-duty managers - GridBagLayout or SpringLayout. SpringLayout was designed for use by visual form editors, so GridBagLayout is probably the best option if you are writing the code yourself.

Personally, I find the visual editors useless for anything other than the most simple layouts, and I use GridBagLayout for pretty much everything. The syntax is a bit cumbersome, the learning curve is steep, but IMHO it's worth it in the end if you really want complete control.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The simplest way is to use multiple JPanels to organise the groups of controls.

eg Place 3 JPanels in your JFrame, flowing left to right. In the first one add the two checkboxes, in the second add the x,y labels and fields, in the third add the buttons. In each of those three cases the controls are just placed in a vertical stack (2x2 grid for the middle one) centered vertically in their respective JPanels.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It's a classic double-declaration problem. YOu have created two different "contentPane" variables.

13  protected JPanel contentPane;

this is the contentPane variable that you use in the actionPeformed and which is initially null, and which is never initialised by you

26  JPanel contentPane = new JPanel();

this is the local variable in runProgram which you initialise, and which "masks" the first contentPane variable, and goes out of scope when runProgram returns.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I don't have time now to study your code - I gave up when I saw you trying to add things to a JLabel! But you can't just add overlapping things to an ordinary frame or panel and have any control over which gets painted on top of which.

But in general there are two ways to have a background image:
1. Create a trivial subclass of JPanel that draws its background from your image file, and add all you other components to that.

class PanelWithBackground extends JPanel {
        ...

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(myBackgroundImage, 0, 0, this);
    }
}
  1. Use a JLayeredPane with a JLabel for the background and use the layered panel's Z ordering to ensure the background label is behind everything else
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It depends...
For primitives that are local variables declared inside methods or other blocks, and for method parameters, they are allocated on the stack and released as soon as they go out of scope.
For primitives that are declared as static members of a class, the lifetime is the same as the program's.
For primitives that are instance members of a class, their lifetime is the same as that of the instance in which they were created.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Only in that it "just works" regardless of platform. Why re-invent the wheel?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Where you create them and where you store them are two different things. It may be best for the Game class to have responsibility for creating everything, including Items, but then immediately adding them to the appropriate Inventory.

Coupling is always a bit of a question in respect of the "Master" class that many apps have -in this case your Game class. It typically needs to have access to everything else in the game, so is highy coupled. Whether the coupling from Game to Item is via Inventory or not doesn't look like a big issue here, so personally I'd stick to the structure shown in yor class diagram, at least until I found a reason not to.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That's the object-oriented way of thinking! Sudents study Subjects, not "subject names".

Suppose you want to know how many credits a Student can earm from his current set of Subjects - you loop thru his List of Subjects adding their credit points. If all you have is subject names you have to use those to look up the corresponding Subjects in some kind of Map in order to get the credit points.
(Same for checking whether he has met minumum requirements for spread of Subjects, of has forboidden combinations of Subjects, etc etc.)

It's not "heavy". Either way the Student class just has a list of refernces to other objects, be they Strings or Subjects

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

In that case I would ensure that Student and Subjst follow the rules for JavaBeans, and use XMLEncoder to write the ArrayLists of Students and Subjects to a file in XML format. You can use any extension for the file you like. (I have done this myself, it really is simple.)

To be fair: Others may still prefer to use SQL to store the Students, Subjects, and the Student/Subject pairs. Its certainly do-able, but a lot more code than XMLEncoder. If any SQL enthusiasts out there want to make the case for doing that, now would be a good time...

Maybe you should use a custom TableModel that' simply a wrapper for the data that's in the two ArrayLists - then there's nothing more to store for that.

ps Why do the Student objects store subject names, why not Subject instances?

CoilFyzx commented: I am now at the point where I am creating a 'wrapper'for the data via a custom TableModel. This is all alien to me. Are there any resources available to guide me in the right direction please? +2
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

"What sort of info" was a summary of your question, followed immediatly by an attempt at an answer (classes & methods etc) - I wasn't re-asking it back to you :)

The problem here is that there are many quirky details about how to select and implement the various examples of persistence in your question. Apparently tiny details in the requirements can swing the choice one way or another. Within the time/resource constraints of a volunteer service like this there's only so much time we can spend. To give an answer noticibly better than the one I already gave I would need to understand the whole picture (complete requirements specification, use cases, technical constraints, success citeria, financial/timscale constraints etc etc.), and complete a first-pass design.

That's obviously unrealistic, so I was suggesting that you should take what's useful from the suggestions from this thread and attempt the first-pass class diagram, which would be a good basic for further review and discussion.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

What sort of info? I woul;d start by trying to name all the main classes that will represent the data and all the things you want to do with it (ignore the GUI for now). Write the names, return types and parameters for the main public methods you will need to call. Now, on paper or even just in your head, try to run through a few typical use cases using those classes and methods. Keep refining them until the use cases work smoothly.
Then, and only then, code all that up in Java along with some simple test methods to conform that your code works as expected.

You will inevitably need to add to those classes (eg to support the GUI) and maybe re-write bits when you run into problems. That's OK. The main thing is to develop one piece at a time and keep testing as you go.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

How can you possibly access a remote machine without using its IP address? YOu could use something like JmDNS to locate the remote machine, but you still have to use the IP address from JmDNS to access the machine itself.

ps:
DaniWeb Member Rules (which you agreed to when you signed up) include:
"Do provide evidence of having done some work yourself if posting questions from school or work assignments"
http://www.daniweb.com/community/rules

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

it is processed to create data that does not belong in the database. So I have to save that data locally,

In that case I'd go back to just serialising or XMLing the highest-level Java object (ArrayList or whatever) that holds all that data, but I'd be sure to implement that via an interface so I could change it later.

Can't comment on the last question without a LOT more info. Maybe jsut start with something simple an go from there???

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

There is a problem that, from tine to time, Oracle change the serialisation format for one or more classes - in the Image case I mentioned before it was to close a security loophole. That's why its only really safe for transient storage or data transfer. A file written before the change may not be readable after the change. In practice this is a rare event, and you may never encounter it if you are just using serialisation to hold status info from one run to the next.

If the data came from a database in the first place, then maybe it's not necessary to save another copy - all you need to save is anything changed but not yet comitted to the database, or additional status info that's not part of the actual data (eg window sizes).

Without more understanding of your application it's hard to be specific. My instinct (and that's all it is) leans towards:

  • data should be updated back into the source database
  • credentials and preferences should use the java.util.prefs.Preferences class
  • session info like window configuration should be saved in an XML file

... but without knowing the full requirements this is just a provisional opinion.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Serialization allowes you to write/read arbitrary objects to a binary file, in a Java-specific binary format that may be subject to change (not just an empty threat - I had a live system fail when the serialisation of Image objects changed somewhere in the later releases of 1.6).
A very similar alternative is to use the XMLEncoder/Decoder classes to write the objects to a .xml file in standard XML format. It's much the same as serialising, excepy that you have a readable standard XML format file, not an obscure proprietary binary file.

Re GUI objects - you can't serialise open WIndows etc because they are tied in to native OS components - you would have to create a little class to hold the types of the open windows with their x,y coordinates and sizes, from which you could easily reconstruct the user's visual layout.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

In defence of cool_zephy's suggestion...
Storing a Serializable object - no matter how complex its internal structure and content - is a single call to writeObject. Restoring it ditto.
Storing/restoring data with multiple occurences of complex data by mapping it into relational tables can be very complex and code intensive.
I'm not saying that using a database mnager is a bad idea, just that writing a currentState object to an ObjectOutputStream could be vastly simpler.
Personally I would
1. Start with making my state object a valid javabean, then use java.beans.XMLEncoder to write it as an XML file
2. Encapsulate the whole save/restore behind a simple interface so I could change ithe implemenattaion later.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You can read the image into an Image object, then use the PixelGrabber class to examine the individual pixels and get their colors, but after that it gets difficult - how exactly would you define "background color" and "foreground color" for some arbitrary image?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK. Just FYI here's the simpler algorithm - I didn't encapsulate it in a method because it's only one line...

        System.out.print("Enter three points for a triangle: ");
        Scanner in = new Scanner(System.in);
        Point a = new Point(in.nextInt(),in.nextInt()); // eg 10 10
        Point b = new Point(in.nextInt(),in.nextInt()); // eg 10 110
        Point c = new Point(in.nextInt(),in.nextInt()); // eg 110 10
        int area = Math.abs(((a.x - c.x)*(b.y - a.y) - (a.x-b.x)*(c.y-a.y))/2);
        System.out.println(area);  // should be 100 * 100 /2 with above data
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That's one way to do it.

A more experienced programmer would probably separate the user interface from the calculation.
The initialisations on line 7-9 are redundant because those values are never used.
There's a much simpler formula for the area of a triangle defined by three Points a,b,c:
0.5*((a.x - c.x) * (b.y - a.y) - (a.x-b.x) * (c.y-a.y))

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I research, learn, try, and ask for help. That's what helped me increase my ability to code in Java.

Yes, absolutely right.
But how does this fit with your posting a complete undocumented uncommented solution that the OP can just copy/paste without any understanding? I hope in your future posts you will prefer to help and guide the OP so they can laern how to solve the problem for themself

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If it's a csv file then you need commas to separate the values, not spaces. For importing to Excel you can also separate the values with tab characters \t

ps don't ever do this

catch(Exception e) {
   System.out.println("There was an error.");
}

The Exception contains a huge amout of info about exactly what the eror was, but you are discarding all of it. Use e.printStackTrace(); to see all the info about the error.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

JLabels etc accept simple HTML code to control formatting, headings, font color etc, eg

  aLabel.setText("<HTML><H1> Hello</H1>" +
                 "<FONT COLOR="RED"><CENTER>World" +
                 "<FONT SIZE=-2 COLOR="GREEN"> and friends");