Okay it works fine now. I just swapped the offending line...

[CODE]
InputStream is = getClass().getResourceAsStream( path );
[/CODE]

...for this line...

[CODE]
FileInputStream is = new FileInputStream( filePath );
[/CODE]

...and I can get to files outside the jar file and set the encoding fine. Phew.

Thanks James. That's a helpful bit of code!

So it seems that I have to use a File object to get to a text file that's located outside of the Jar file, but then this gives me encoding problems as the files are all UTF-8 encoded and File uses the default system encoding which is Cp1252 in this case. And the only way to get around the encoding problem is to use an InputStream object, but I can't use this to get to files located outside of the Jar file. And then I'm stuck, erg.

Hi all,

I'm trying read in the contents of a series of text files located in a folder in the same directory as a jar file. I've been trying to work out how to do this for a while now, but to no success, so any pointers as to where I'm going wrong would be greatly appreciated.

I'm using two methods, one to get the names of the text files in the folder (called "resources"), and another method to read the contents of these files.

(I'm using InputStreamReader to read the files as I need to specify the UTF-8 encoding because these files contain both Latin and Japanese characters which need to be displayed in a GUI.)

Here's the code with the try/catches omitted:

[CODE]
private void setupTextFiles()
{
String path = "resources/";
File folder = new File( path );
File[] fileList = folder.listFiles();

for( File file : fileList )
{
    String filename = file.getName();

    if( filename.endsWith( ".txt" ) || filename.endsWith( ".TXT" ) )
    {
        readTextFile( filename );
    }
}

}

private void readTextFile( String filename )
{
String path = "resources/" + filename;
InputStream is = getClass().getResourceAsStream( path );
InputStreamReader isr = new InputStreamReader( is, "UTF-8" );
BufferedReader br = new BufferedReader( isr );
String line = br.readLine();

while( line != null )
{
    // process lines of text

    line = br.readLine();
}

br.close();
isr.close();
is.close();

}
[/CODE]

However, I'm getting a "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" which tracks back to line 22 in the above code, so clearly ...

Hi everyone,

I'd like to write a small application to basically read in some text from a file, display it in a GUI (I've done this using a textpane), and then change the font color of certain words if they exist in the text (say from the default color to [COLOR="Red"]red[/COLOR]) ... but I'm not sure how to go about the highlighting part.

Does anyone have any hints / suggestions on a good way to do this?

Thanks!

Thanks for the hints guys!

I've tried a simple approach using a while loop and some boolean flags and I've also had a look at SwingWorker; however the results aren't great yet.

The thing is that I have to wait for 2 threads to finish outside of the Swing event dispatch thread.

I call a class from a GUI-related method (as shown in the above code), and that class initiates a Process (thread 1), which in turn initiates a Receiver class (thread 2) to receive output from the Process.

So, thread 1 has to wait for thread 2 to finish, and the EDT has to wait for thread 1 to finish.

Would SwingWorker still be a good way to tackle this situation?

Thanks!

Hi everyone,

I want to intitialise an object to perform a certain computation and wait for the object to finish, but I'm not sure what the best way is to go about this.

Here's a couple of methods to give you an idea of what I'd like to do:

[CODE]
private void method()
{
if( flag == true )
{
activateEngine();

    if( result == true )
    {
        ...
    }
}

}

private void activateEngine()
{
Engine eng = new Engine();
result = eng.getResult();
}
[/CODE]

I'm not too savvy with threads yet, so any advice here would be most appreciated.

Thanks!

Thanks for the help guys!

Hi everyone,

I'm having trouble inserting icons into a textpane and I'm not sure why. I'd like to set up a textpane and then be able to insert and display images in that textpane during runtime. As a test I've written the code below for a simple GUI with a textpane and a button - when the button is pressed I want the image to appear in the text pane under the text that's already there.

If anyone can point out where I'm going wrong here, or if there is a better way to go about this, I'd be very grateful.

Thanks!

[CODE]
package inserticon;

import javax.swing.ImageIcon;

public class Display extends javax.swing.JFrame
{

// Variables 

private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextPane jTextPane1;

// Constructor

public Display()
{
    initComponents();
}

// Method to intialise the GUI

private void initComponents() 
{
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextPane1 = new javax.swing.JTextPane();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jTextPane1.setFont(new java.awt.Font("Tahoma", 0, 16)); 
    jTextPane1.setText("Some fairly boring text.");
    jScrollPane1.setViewportView(jTextPane1);

    jButton1.setFont(new java.awt.Font("Tahoma", 0, 16)); 
    jButton1.setText("Insert icon");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,  layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 446, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE))
            .addContainerGap())
    );

    pack();
}

// Method it insert an icon into the textpane when the button is pressed.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) 
{
    jTextPane1.insertIcon( new ImageIcon( "icon.png" ) );
}

}

[/CODE]

Thanks everyone for your advice.

@ Norm1 and SOS : Yep, I got the full path using getAbsolutePath() and it turned out it was wrong.

@ Mike : Thanks for the tip about using an Image object instead of a BufferedImage.

Hi everyone,

I'm having a little problem I'm sure someone can help me with. I'm trying to read in 10 png images and save them in an ArrayList as BufferedImage objects (I think this is the right way to go about it but if not plaease say so).

Here is my code so far:

[CODE]
package imageloader;

import java.io.;
import javax.imageio.
;
import java.awt.image.*;
import java.util.ArrayList;

public class Interface
{

/* Fields */

private ArrayList<String> fileList = new ArrayList<String>();
private ArrayList<BufferedImage> imageList = new ArrayList<BufferedImage>();

/* Constructor */

public Interface()
{
    buildFileList();
    loadImages();
}

/**
 * Method to populate the fileList array.
 */

private void buildFileList()
{
    fileList.add( "./images/image1.png" );
    fileList.add( "./images/image2.png" );
    fileList.add( "./images/image3.png" );
    fileList.add( "./images/image4.png" );
    fileList.add( "./images/image5.png" );
    fileList.add( "./images/image6.png" );
    fileList.add( "./images/image7.png" );
    fileList.add( "./images/image8.png" );
    fileList.add( "./images/image9.png" );
    fileList.add( "./images/image10.png" );
}

/**
 * Method to load images from file and store internally.
 */

private void loadImages()
{
    BufferedImage temp = null;

    try
    {
        for( String item : fileList )
        {
            temp = ImageIO.read( new File( item ) );
            imageList.add( temp );
        }
    }

    catch( IOException e )
    {
        System.err.println( e.getMessage() );
    }
}

}
[/CODE]

I'm trying to read all files in and store them all in an ArrayList as BufferedImage objects, but I'm getting a "Can't read input file!" error message and I'm not sure what I'm doing wrong here. The paths are all okay. Any suggestions?

Thanks!

Thanks for the suggestion SOS!

okay. Thanks for the clue though. Much appreciated.

Interesting. I tried your suggestion NormR1, but the print statement is only printed for the 1st array, not for the 2nd or 3rd. I didn't notice that before.

Here's the test output just to clarify:

[CODE]
DataBuilder test start
retrieveKanji()
characters.size()=100 vs eS=100
DataBuilder test end
[/CODE]

So for some reason the 2nd and 3rd tests are failed yet never executed, is that right?

Hi everyone,

I'm having a problem with a JUnit test I've written. I think there should be a simple solution but I can't work out what's wrong. I'm new to using JUnit so any advice would be a big help.

Here's the test class below. At the moment I'm just testing that 3 arraylists are of the correct size (100 elements). The 1st test passes but the 2nd and 3rd fail, with the results saying that they have 200 and 300 elements respectively. So it seems the results of [I]arraylist[/I].size() are accumulating, which is strange because they're in different tet methods.

Ps. I have put println calls in the actual methods being tested and I know they have the right number of elements (all have 100 each).

[CODE]
public class DataBuilderTest
{

DataBuilder db = new DataBuilder();
private int expectedSize = 100;

public DataBuilderTest()
{
}

@BeforeClass
public static void setUpClass() throws Exception
{
    System.out.println("** DataBuilder test start");
}

@AfterClass
public static void tearDownClass() throws Exception
{
    System.out.println("** DataBuilder test end");
}

@Before
public void setUp()
{
}

@After
public void tearDown()
{
}

@Test
public void testGetCharacters()
{
    ArrayList<String> characters = DataBuilder.getCharacters();
    assertEquals(expectedSize, characters.size());
}

@Test
public void testGetMeanings()
{
    ArrayList<String> meanings = DataBank.getMeanings();
    assertEquals(expectedSize, meanings.size());
}

@Test
public void testGetReadings()
{
    ArrayList<String> readings = DataBank.getReadings();
    assertEquals(expectedSize, readings.size());
}

}
[/CODE]

Any ideas what's up with the above test code?

Hi everyone,

I have a program that displays Chinese and Japanese characters. I've written the program inside Netbeans and it works fine. But when I use the program as an executable jar file, as built in the dist folder by Netbeans, the Chinese and Japanese characters are displayed as nonsense.

In the IDE the font is set to Meiryo as follows, which I think should be fine ...

[CODE]
candidateComboBox.setFont(new java.awt.Font("Meiryo", 0, 36));
[/CODE]

... and I've tried replacing this with a physical truetype font such as ...

[CODE]
File file = new File( "osaka.unicode.ttf" );

try
{
Font font = Font.createFont( Font.TRUETYPE_FONT, file );
font = font.deriveFont( Font.PLAIN, 14f );
outputField.setFont( font );
}

catch( Exception error )
{
// exception handled here
}
[/CODE]

... but this doesn't work either.

Also, the Japanese/Chinese text that is I want to display in the program GUI is read in from a file saved in UTF-8, and the project encoding setting in Netbeans is UTF-8.

Does anyone have any ideas why something like this would fail to work outside of Netbeans?

Yep, I'm hoping to display them in the application, so I'll do some more reading about properties files. Thanks for the advice, much appreciated!

Hi all,

I'm having a compilation problem relating to some Chinese and Japanese characters that I have hardcoded into a hash table. When I compile this code inside an IDE like Eclipse or Netbeans I get no warnings, but when I do it outside of the IDE I get the following warning:

"unmappable character for encoding CP1252"

(From what I understand the default encoding for java is CP1252.)

What should I do about this? Would it be best just to compile with a UTF8 encoding tag as in ...

[CODE]
javac -encoding UTF-8 *.java
[/CODE]

... or should I be using native2ascii in some way?

Any advice about the best approach here would be great. Thanks!

Thanks James. I took your advice and used InputStream rather than FileReader to get the data out of a text file and its working fine now.

[CODE]
InputStream is = getClass().getResourceAsStream( "file.txt" );
InputStreamReader isr = new InputStreamReader( is );
BufferedReader br = new BufferedReader( isr );
String line = br.readLine();

while( line != null )
{
arrayList.add( line );
line = br.readLine();
}

br.close();
isr.close();
is.close();
[/CODE]

Hi everyone,

I'm having some trouble creating an executable jar file that accesses data txt files when running.

I've written a program using Netbeans that reads in both images and data and uses this data while the program is running. But when I try to run the program using the jar file that is automatically created in the dist folder, the images show up just fine, but it hasn't been able to read in the data.

Here's how the directory looks in Netbeans:

[CODE]
ProgramName
SourcePackages
PackageName
VariousJAVAfiles
PackageName.resources.data
VariousTXTfiles
PackageName.resources.images
VariousJPGfiles
[/CODE]

I'm guessing that I have to do something with the libraries, and I've also heard something about using URL objects, but I'm still confused about what to do.

Any advice on what I'm missing here would be great, thanks!

Hi all,

I'm working on a project in Java that involves developing a GUI that can, among other things, receive user input from the keyboard, receive and store handwritten input (characters/words) done with a mouse, and display png images.

Eventually the program will be used on a linux environment, but I am wondering if it is possible/wise/advisable to develop it in a Windows environment.

I've experience problems doing this in C in the past, but I've heard a lot about the portability of Java and so any advice here would be greatly appreciated!

Thanks.

Thanks sergb!

Using the CardLayout class sorted it out quite nicely.

Hi everyone,

I'm trying to build a GUI for a project I'm working on, and I'm having trouble working out how to move between different displays within the same GUI.

I have a simple GUI with a menu bar and two buttons in the content pane. If the user clicks button A, I'd like for the user to move to a different content pane or GUI (not sure which is better) with the same menu bar, much like how a user moves between webpages in a browser.

So far I've managed to have it so that when the user clicks button A, a whole new GUI is displayed, but this isn't exactly what I want.

Any ideas on how to go about this? I'm sure it's pretty basic but I haven't managed to find anything on this so far. Thanks in advance!

Thank you very much!

Hi everyone,

I've written a small program to convert combinations of English characters into their corresponding Chinese and Japanese equivalents, and it's working on my computer at home, so so far so good.

However, I'd also like it to work on computers which don't have Chinese or Japanese fonts installed, but I'm not sure how to go about doing this, or even if it's possible.

Is there a way to have the necessary Chinese/Japanese fonts contained within the Java program?

Any advice on how to start going about this would be a huge help!

Thanks for your help guys!

[QUOTE=jiraiya;1183478]Hi everyone,

I have a single string - let's call it string A.
I have an ArrayList of objects.
Each object contains three strings.

I want to iterate through the ArrayList of objects and check if any of the strings contained within the objects are the same as string A. Furthermore, I only want to compare the third string in each object with string A.

Basically, I am having problems with the syntax for a string contained in an object, and any help would be great.

Here's the part of code I'm having trouble with:

[CODE=java]while( iterator.hasNext() )
{
if( iterator.string3.equals( stringA ) )
{

}

}[/CODE]

If anyone could help me with this approach, or give me any ideas for a different approach, that would be a big help.

Thanks![/QUOTE]

Should I just break this down into 2 steps?

I.e. have an outer loop going through the objects and an inner loop going through the strings?

Hi everyone,

I have a single string - let's call it string A.
I have an ArrayList of objects.
Each object contains three strings.

I want to iterate through the ArrayList of objects and check if any of the strings contained within the objects are the same as string A. Furthermore, I only want to compare the third string in each object with string A.

Basically, I am having problems with the syntax for a string contained in an object, and any help would be great.

Here's the part of code I'm having trouble with:

[CODE=java]while( iterator.hasNext() )
{
if( iterator.string3.equals( stringA ) )
{

}

}[/CODE]

If anyone could help me with this approach, or give me any ideas for a different approach, that would be a big help.

Thanks!

[QUOTE=chaospie;1170930]If your program uses the command line, then I believe it will be the shell/consoles job to catch the enter or any other key press and not the actual java program.

There may be a way to do it from the console ( probably using java.lang.Runtime ), but it can easily be done using a GUI.

One way is with a DocumentListener object:
[url]http://java.sun.com/docs/books/tutorial/uiswing/events/documentlistener.html[/url][/QUOTE]

Thanks chaospie!

Ideally I'd like to use a GUI, so that sounds like the perfect suggestion. I'm still quite new to Java and haven't tried implementing a GUI yet, but here goes.

Thanks again!

Hi all,

Does anyone know of a way to scan a character from the command line without the enter key having to be pressed?

For example, the user would type 'a', which is then picked up and scanned by the program and stored, etc.

The only way of scanning input that I know of is by using Scanner, but this requires the enter key to be pressed.

Thanks in advance.