JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

bguild has already answered your question.
Your writer just writes characters to the output stream. Characters do not have fonts, colors, or anything else, they are just characters.
Depending on where your file is displayed, characters in the file may be interpreted as formatting information according to some standard, eg RTF or HTML. That depends on on how and where the file is being displayed. There is no problem writing RTF or HTML codes to your file, if that's appropriate

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You have made the very common mistake of putting a long-running process on the Swing EDT. That blocks all Swing activity until you return from your ActionPerformed, and so enabling/disabling etc doesn't get implemented in the GUI until after your ActionPerformed is finished. Moving your swing calls onto another thread looks like a solution, but it's a threading bug just waiting to happen. Don't be embarassed, very many beginners make the same mistake.

Study this tutorial to see the correct way to write this kind of code:
http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Why don't you just try that and see for yourself?
(It's nearly right, and when you try it you will see what's wrong and how to fix it)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Rajesh's post is about as wrong as it's possible to be.
ActionListeners are called on the Swing Event Dispatch Thread. Most Swing methods are not thread safe and MUST be called from the EDT and no other thread.
http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html
Rajesh would have you leave the EDT in order to update Swing components from a non EDT thread - exactly the opposite of right.
bguild has it right.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

First step is simply to do exactly what it told you to do:
Recompile with -Xlint:unchecked for details.
That will tell you what the unsafe or uchecked problem is, and exactly where it is. Then you can either update the code or add an annotation to allow the operation.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You are using buffered streams, so you may need to flush() the output streams after you write each line to them. (If the output buffer is not full the data will not be transmitted until another write fills the buffer OR you flush it explicitly.)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

System.nanoTime() returns the time in nanoSeconds. Take its value before you start and after you finish and subtract the two.

csk19 commented: the program takes takes 23ms. +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You can do your basic drawing by extending JPanel with a custom paintComponent that draws the roads according to a model that defines their number oflanes, start & end copordinates etc, and draws the cars according to a car model that defines where the cars are and which way they are heading etc. Thew sophisication of the drawing is up to you - maybe start very simple (eg car = rectangle) and enhance later (eg car = jpeg image) if you have time.
You can use a MouseListener and a MouseMotionListener on that panel to detect clicks and drags that you can interpret as adding or modifing the model.
If I were doing this I would start with the model and just use hard-coded test data and print statements to confirm that the model correctly stores, updates and delivers all the data you need. Only then would I build the GUI, knowing I had a solid base to build from, and a sensible model/view architecture.

Until you have a class design for the model and some GUI sketches it's hard to be more specific.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The server seems to be waiting for input from its local user before it tries to read iput from the remote client. That seems wrong. Line 23 may be the problem.
ps Next time please describe your problem properly - eg what results you expect vs what you got. Saying " it is not working in proper way" isn't good enough.

jalpesh_007 commented: thanks +4
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

This is a typical problem with Scanner. Most of the methods use the delimiter (default white space) to separate tokens, and keep the following delimiter. Except for readLine that discards the following new line character(s). So, for example if you use a nextInt followed by a nextLine with a file that has "123\n a line of text" the nextLine will unexpectedly return "" - the remainder of the line that's left after the nextInt. To fix that you need an extra, dummy, readLine toget past the newLine character.
Unless you need to use Scanner it's often easier in the lon run to use a BufferedReader and its readLine() method, then parse each line yourself using String's split method and parsers like Integer.parseInt

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Part1: see bguild's answer.

Part2: If you start by finding palindromes then you are left with the problem of finding out if each palindrome is the product of of two numbers 100-999 (not so easy).
If you start by multiplying every possible combination of two numbers 100-999. that's only 500,000 multiplications, which will take no time at all. Then just check each one for being a palindrome, and keep the largest. Provided your code to test for palindromes isn't too slow the whole thing will run in well under a second (17mSec on my 3.2GHz core 2)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes, lots of ideas, but your requirement is still far to vague for anyone to give a proper reply. What kind of simulation do you need for the cars? In how much detail (see previous posts)?
(In 1971/2 I worked on an IBM project to simulate the traffic flow in central Glasgow (a city in Scotland) - it took us more than 20 man years programming effort, excluding setting up the actual road definition data, and with just a command-line user interface. How far do you want to go with yours?)

Does "draw a road" mean just a couple of lines on the screen, or a full photo-realistic aerial view with the trees moving in the wind and people walking past, or what?

If you are in the third year of a CompSci degree then you should have a good idea of how to specify requirements for a program.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

bguild and I are both worried about lines 3-6 in that code. Every time you call addItem you overwrite all five items in the array, thus deleting whatever you added before.

items.length is always better than hard-coding the array size, but in this case you probably should not be doing either. Your array shoud be "big enough" - maybe 100 elements for now, and initially all those elements will be null. As you add new items you will replace those nulls with real items, starting at items[0], then items[1] etc, and keep a counter of how many you have added. Your counter tells you which is the next available element for adding a new item.
Then when you look through the array you use the counter to tell you how many elements to loop through. You don't want to use the complete array size, because then you will be accessing all those null entries that you haven't used yet.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

retrieveItem looks OK, except you have hard-coded 4 as the number of items. You really need a variable that tells you how many items there currently are in the array.
You may want to add some code to check if you went all through the array without finding the id you are looking for - in which ase you could issue an "id not found" error message to the user.

addItem is a bit more of a question... you are adding 1 item, so why add 4 entries to the array? And what is xtr?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Hi cmps
I haven't seen any relevant code from techxaidz, so I have no idea whether his array is private or not. I know you suggested that, but...
More seriously, he's struggling with which item to get. Showing him how to get an item from its index number really doesn't help. For this to make any sense he needs to retrieve items by ID or title or somesuch, which is the direction I was trying to point him in. Although you can think of this like an ArrayList, I believe it would be more relevant to think of it like a Map<String><Library> where the key is ID or Title.
Having said all that, I'm sure we both agree that this is one of the worst designed and specified exercises ever, and OP deserves all the help he can get.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Is it possible to do this without having a database? (newbie)

Yes, just follow the 3 steps I described. That's all just ordinary Java.

Right now, your "database" is just the array of items. Maybe later you will be asked to create a "real" database to store all that info, but for now it sounds like you are just being asked to hold it in memeory in an array.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Here's one way to interpret what that method should do...
1. prompt the user for some identifying info (eg item ID)
2. write a loop that accesses each item in the items array in turn, and tests each one to see if they have the ID you are looking for.
3. Once you have found the item in the array you can retrive all its other info and display it.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Just a quick heads-up, especially for anyone using Java in their web browser.
There's a "widely exploited" vulnerability in Java that could allow bypassing normal security when a Java applet is run silently upon visiting a web site. (ie It's a bad one). Users are being widely advised to disable Java in their browsers until this is fixed.
The good news is that Oracle just released update 11 for Java 7 that they say fixes this problem.
You should consider installing update 11 as quickly as possible.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The person who wrote this problem description obviously doesn't understand object oriented design, so that makes it harder for you. Judging from the variables, the class they call Library clearly does not represent a library, it represents one LibraryHolding - which is an abstract class (instance variables ID, Date of Acquisition, Description, number of copies, title) with non-abstract sub-classes Book, Magazine, and Multimedia ( singular nouns, not plural - each instance represents one book etc) that have extra instance variables. There is no class corresponding to a Library - that's just an array of LibraryHoldings.
The addItem and retriveItem methods would sensibly be instance methods of a class that represents a Library, but your teacher has confused that with LibraryItem.
In short - you need a Library class whose instances represents a whole library, and which has instance methods for addItem etc, and an array of LibraryHoldings. And a LibraryHolding class that represents a single item in the library, with variables like ID, title etc.

You really need to make a start on this now. If/when you get stuck post what you have done so far for further help.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Have you read the Oracle tutorial on JTables?
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If the command line interface has all the needed functionality, then you can use the Java ProcessBuilder class to drive octave's command line interface "behind the scenes" and retrieve all its output for display in your GUI.
You'll find tutorials and samples on the web.
ps: don't be distracted by references to Runtime.exec - this is an old class that was replaced by ProcessBuilder a few years ago.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Two quick points:
1. Date.getHours etc have been deprecated since Java 1.1 (in 1997!) You should use GregorianCalendar instead
2. For updating a GUI you should use a javax.swing.Timer to run your updates on the swing thread, not a java.util.Timer which runs in its own thread.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

"but to no avail", while very poetic, tells us nothing. What was wrong with it? Did you set a mono-spaced font eg Courier?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Hello all.
I'm currrently working on a GUI that needs to support dragging some application-specific objects from a selection area onto a work area (JPanel). It's currently working in a "click where to place the object, then click the Add button" mode, but that's not good enough.
The obvious approach is to use D&D (Java 6 or later) with a custom DataFlavor for the objects, but I'm struggling to find and decent documentation or examples of how to fit the whole thing together. The Oracle tutorials do a decent job of listing all the classs and methods involved, but not how to fit it all into an application. There are many code samples on the web, but many are pre-Java6, and the remainder use Swing's built-in support for some specific data flavors.
If you have any experience of doing this, or know of any useful info source, I'd love to hear from you.
Thanks
James
ps: This is not homework ;)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Your question is far too vague. setVisible(true) is the way to make an invisible component visible, but what has that got to do with singletons?
If you ask a much more specific question, with enough background for us to understand what yur problem really is, then I'm sure someone will help you.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

^ excellent advice from Tux. Plus: sort out your indentation - it's very hard to see where blocks begin and end and, even worse, its too easy to think that the indentation accurately reflects the block structure of the code when in reality it doesn't.
Finally, use lots of temporary print statements to track the values of key variables and the calls to key methods so you can see where your logic is going wrong.

Re-post your code with formatting fixed and all the exceptions caught and logged. I very much doubt that anyone here is going to spend time trying to debug code that has empty catch blocks.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Re implementing bguild's excellent suggestion:
Simply create a little class Line, with vars for oldX, oldY etc. Give it a constructor that takes all the values it needs. Declare it as "implements Serializable" so it can be sent over an object stream. "history" can then be an ArrayList of LineData, which can be sent over a socket as a single object.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Maybe its because your layout manager isn't updating to include the new JLabel until you force it by re-sizing the window. Try calling revalidate() (and maybe also repaint()) after adding the JLabel

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

We don't support people who are unwilling to put in some effort.
Look at the SimpleDateFormat doc in the Java API documentation online.
(The method you need is called format, and it's inherited from the DateFormat class).

Just look it up, it's really easy, but nobody here is going to do your homeowrk for you

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Use the SimpleDateFormat class to convert your Date object into a String that's formatted exactly how you want to see it, and use that String in the text field.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It would be simpler to convert the position references directly to array indexes -
eg
pos.charAt(0) - 'a' returns 0 if pos starts with 'a', 1 for 'b', 2 for 'c'
and
pos.charAt(1) - '1'similarly for the numeric part.
Now you have the i,j values to index the array of text fields directly

tux4life commented: Exactly what I was thinking ;-) +13
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Problem is probably that because you are drawing the panel Java has no idea how big it should be. It's probably showing a preferred size of 0x0. It works in the center position because that gets all the available space after the other components have been positioned.Try setting a preferred size and/or minimum size for your paint panel.
Normally people extend JPanel rather than JComponent for this use - that may make a difference as well(?)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK guys, that's enough repeating each other's posts. Tux4life made it perfectly clear the first time. Please don't just re-post the same answer without adding any new information.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You can use Bitwise unary NOT operator

Check the Java Language Spec... there no such thing as a "Bitwise unary NOT operator". There is bitwise complement operator, just like the previous poster already said.

ps You can also exclusive OR with a value of all 1 bits.

tux4life commented: There's no such thing as "bitwize" :P +13
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

new Thread(....).start(); to start a new thread. .run() just executes your run method on the existing thread.
Line 17; NEVER comment out the stackTrace or you will never know about your errors.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You can't mix object I/O and imageIO in a single file like that. ImageIO writes a single image in the desired format (jpg, png etc). The API doc also says " If there is already a File present, its contents are discarded.", so it's stricly one image per file. ObjectStreams support multiple objects in one file, but they have their own special format to do that. Unfortunately BufferedImages are not Serialisable, so you can't write then to an Object stream.
One possible solution is to convert you Image objects to ImageIcon (and v.v after reading them). ImageIcons can be written to /read from Object streams with writeObject and readObject, and you can have as many as you want, mixed with any other objects, in a single file.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Parse: take some data in the form of a string and convert it into an integer or whatever. Java provides standard ,methods for doing that, eg Integer.parseInt(String s) takes a string and interprets it as an integer, and returns that value as an int. It's what nextInt is doing behind the scenes.
Personally I prefer to read all my input with nextLine, then use parseInt, and other methods like it, to interpret the data. That avoids problems like the one you have with nextInt and nextLine. It also works well if you stop using a Scanner and enhance your app with a GUI dialog that prompts for input.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If you move the code lines 12-17 into Skate's constructor then you can simply call new Skate(); in your button's ActionListener

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

In this case the answer is trivial. Version 1 works, and version 2 doesn't. Your compiler will tell you the same thing. You can't cast from a String to an int. Check out the Java Language Spec section on casting to see the rules on what you can or cannot convert by a cast.

jalpesh_007 commented: thanks.. +4
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I'm not sure why you see put as a problem, but if you want a mutable integer value there's no need to write a class. You could use an AtomicInteger, or just use a HashMap<String, int[]> with a 1-element int array as the value and keep incrementing its zero'th element

tux4life commented: Nice suggestions, forgot about these ;) +13
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

In pseudo code it looks like:

for i = 0 to 2
   for j = 0 to 2
      array[i][j] = the next character

You have a number of ways to do "the next character", eg have a counter that tracks which is the next character, and increment it each time you use it

plaintext.charAt(counter ++ );
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Matt
Two things you may have misunderstood...
1. This is not a "we do your homework" servce. Somebody may help you learn how to round your results, but nobody will just do it for you.
2. This is the Java forum. Java and JavaScript are not the same thing at all.

So: Please post a request for assistance in learning how to round values, and post it in the Web Development / JavaScript forum

Good luck
J

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Rule 1: never do anything other than painting in your paint/paintComponent method. You have no direct control over how often that will be called, so you lose control of the animation speed. Here's a runnable demo program thatshows how to separate animation model logic from screen painting...

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.TimerTask;
import javax.swing.*;

public class Animation1 extends JPanel {
   // Basic architecture demo for multi-sprite animation

   public static void main(String[] args) {
      // create and display the animation in a JFrame
      final JFrame frame = new JFrame("Animation 1 (close window to exit)");
      Animation1 animationPanel = new Animation1(600, 400);
      frame.add(animationPanel);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }

   private ArrayList<SimpleSprite> sprites = new ArrayList<SimpleSprite>();

   final static int TIMER_MSEC = 30; // mSec per clock tick

   Animation1(int width, int height) {
      setPreferredSize(new Dimension(width, height));
      sprites.add(new SimpleSprite(Color.blue, 0, 35, 2, 1));
      sprites.add(new SimpleSprite(Color.red, 0, 250, 2, -1));
      startTimer();
   }

   void startTimer() {
      // use java.util Timer rather than javax.swing Timer
      // to avoid running intensive simulation code on the swing thread
      java.util.Timer timer = new java.util.Timer();
      TimerTask timerTask = new TimerTask() {
         @Override
         public void run() {
            updateSimulation();
         }
      };
      timer.scheduleAtFixedRate(timerTask, 0, TIMER_MSEC);
   }

   public void updateSimulation() {
      // called by Timer every TIMER_MSEC milliseconds
      for (SimpleSprite s : sprites) {
         s.update(); // update position of the sprite
      }
      repaint(); // request Swing to schedule re-paint of screen
   }

   @Override
   public void paintComponent(Graphics g) {
      // screen refresh - called by Swing as needed
      Graphics2D g2d = (Graphics2D) g;
      paintBackground(g2d);
      for …
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Easiest way is to read the image file ito an ImageIcon, then simply use that in a JLabel

http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It's called an anonymous inner class, it defines a new subclass of Handler and creates an instance of it. Google Java anonymous inner class for tutorials etc.

hamidvosugh commented: Very helpful. Thank you. +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Perhasps use Regex instances to define each of the variants/replacements you are looking for?
You could place all the current Regex's in an ArrayList and loop thru them regardless of how nany there are.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

There are a few ways to do this, but the easiest is probably the contains method:

String s = "Hello from DaniWeb";
if (s.contains("from")) ...
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yet another post from crash bash that ignores the DaniWeb Member Rules, specifically

"Do provide evidence of having done some work yourself if posting questions from school or work assignments"
http://www.daniweb.com/community/rules

Start following the rules, or I'll start deleting your offending posts.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I think you mean "ascending" - lowest values first