Java read and write picture using MediaTracker - java

recently I wrote a code to get image (using jfileChooser) and then save it as new picture on hard Drive, and that worked. But when I try to use this code on other computers, or system it didn't work. The MediaTracker always contain a error but I can't display readable information about what going wrong, and I dont have idea how to fix this issue (but I don't won't to read again this source).
Thanks a lot for any ideas what can do wrong.
JFileChooser jfc = new JFileChooser();
jfc.setCurrentDirectory(new File("C:\\"));
jfc.showOpenDialog(null);
File sf = jfc.getSelectedFile();
if( sf==null )
return false;
String iconName = sf.getAbsolutePath();
URL imgUrl = null;
try
{
imgUrl = new URL("file:\\"+iconName);
}
catch(MalformedURLException murle){
//plujemy!
System.out.println(murle);
}
imageA = getToolkit().getImage(imgUrl);
MediaTracker mt = new MediaTracker(this);
try
{
mt.addImage(imageA,0);
mt.waitForAll();
}
catch (InterruptedException ie)
{
ie.printStackTrace(new PrintStream(System.out));
return false;
}
if(mt.isErrorAny()){
return false;
}else{
return true;
}

At a guess, absent a complete example, your call to waitForAll() is blocking the event dispatch thread. Note how the MediaTracker API example waits in a background thread. As an alternative, use SwingWorker to load the image(s), as shown here.

Related

JFileChooser setCurrent directory to Homegroup or Network

I want that when my dialog is opened, then directly go to Homegroup. Thanks.
JFileChooser fc = null;
try {
fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setCurrentDirectory(new File(new URI("file:C:\\" + "..\\Homegroup")));
fc.showOpenDialog(parent);
return fc.getSelectedFile().getAbsolutePath();
} catch (Exception e) {
return null;
}
This code is not working as I want. Thank you very much...
The problem is that you provide an invalid URI and thus get a URISyntaxException. Try something more clean and efficient that accesses an existing file, or learn
URI syntax:
fc.setCurrentDirectory(new File(System.getProperty("user.home")));

javafx , how to show progress bar while printing into text area

i am new in "programming thing , try to learn .
my "app" run bat test files , and all result printed in the textarea , it's working good.
but my goal now is to present progress bar that will show the progress while printing into the text area.
how can i do it ? I've read some guides and I tried somethings but it doesn't work for me
this is the method behind the button that run the bats files
public void RunTestScrip() throws IOException {
Process p = Runtime.getRuntime().exec(path);
final InputStream stream = p.getInputStream();
new Thread(new Runnable() {
public void run() {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(stream));
String line = null;
while ((line = reader.readLine()) != null) {
console.appendText("\n" + line);
progressBar.progressProperty().bind(RunTestScrip()); // dont know how to use it right in my code
}
} catch (Exception e) {
// TODO
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// ignore
}
}
}
}
}).start();
I dont think the script is able to update a javafx ProgressBar. The easiest way is to create your own rules about progress (probably based on the output you are currently appending to the console).
Here is a nice tutorial on how to create a working Progressbar in javafx. Hopefully you are able ro figure out a way to update the progress accordingly.
Edit:
I added a small example of what can be found in the tutorial in case the provided link breaks.
// initialization of a progressBar with 'indeterminate progress'
ProgressBar pb = new ProgressBar(-1.0D);
// to set the current state of a progress bar you simply do the following
pb.setProgress(current_progress);
Note that progress is a value between 0.0D and 1.0D (e.g. in percentage).
A value of -1.0D indicate that the progress is indeterminate.

Setting a custom font to a JLabel

I'm doing a simple Pong game and wanted to add an 8-Bit font but can not figure how.
This is the method I used for JLabels:
public void drawScore()
{
player1 = "Player 1";
player2 = "Player 2";
JLabel leftScore = new JLabel(player1);
JLabel rightScore = new JLabel(player2);
leftScore.setForeground(Color.white);
rightScore.setForeground(Color.white);
leftScore.setLocation(20, 0);
rightScore.setLocation(730, 0);
leftScore.setSize(100, 40);
rightScore.setSize(100, 40);
add(leftScore);
add(rightScore);
}
I tried solutions which I found on here and other web-sites and they didn't work out well either. There is a .TTF file in a folder called 'assets' -which I created- in Java Project Folder named Pong. It would be perfect if the right code not include try and catch blocks.
private static Font fontAwesome;
static {
try (InputStream in = YOURCLASS.class.getClassLoader().getResourceAsStream("assets/fontawesome-webfont.ttf")) {
fontAwesome = Font.createFont(Font.TRUETYPE_FONT, in);
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
}
Here's an example with fontawesome. Paste that at the top of your class and then simply use
leftScore.setFont(fontAwesome); to set the font.
Unfortunately you're going to need the try/catches. Note that the multicatch block might not work depending on your language level. If it doesn't just split them into two catch blocks.
Please try this:
try {
InputStream is = YourClass.class.getResourceAsStream("path/to/font");
Font font = Font.createFont(Font.TRUETYPE_FONT, is);
Font sizedFont = font.deriveFont(18f);
jLabel.setFont(sizedFont);
} catch (Exception ex) {
System.err.println("Not loaded");}
After you load the font you need to set a size to it!
You will have to use try/catch blocks to do this.

New to Java. Problems reading from file using Context and openFileInput

I've been trying to do this on my own for the past couple hours and am kinda losing it a little.
All I want to do is open a file, read it and display it to the console; that's it.
I'm using eclipse to develop for android 2.3.3.
I have tried using a bunch of different ways with code that I have found here, and on other sites. Here is what I have now and how its all called:
In the OnCreate function:
setContentView(new TestMap(this));
The testMap class:
TestMap(Context context){
super(context);
// might need to be on the panel class
loadTileFile("worldonelayout.txt", context);
in the same class:
private void loadTileFile (String filename, Context context){
FileInputStream input = null;
InputStreamReader reader = null;
char[] inputBuffer = new char[256];
String data = null;
try {
input = context.openFileInput("worldonelayout.txt");
reader = new InputStreamReader(input);
reader.read(inputBuffer);
data = new String(inputBuffer);
System.out.println(data);
Toast.makeText(context, "Text read", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Text not read", Toast.LENGTH_SHORT).show();
} finally {
try {
input.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
This code doesnt work. It always hits the exception.
"/data/data/com.name.somethingiremoved/files/worldonelayout.txt (No such file or directory)".
This happens at the first CATCH. BTW my file is in the root directory: Documents\Eclipse\workspace\project\worldonelayout.txt. I can also see the file in the browser on the left
From what I have seen here and on other sites, it is something to do with the Context class being derived from the Activity? I don't want to have this code in the same class as my activity. Is there a way round this?
If you need anything more from me, let me know.
The open file is looking for a file on the phone's file system, not on the computer's. Its telling you exactly where it expects to find it - on the phone under /data/data/com.name.somethingiremoved/files/worldonelayout.txt

Java - How to access an image packed in an applet jar

I have created an applet jar. That jar contains an images in the following folder
com\common\images\red.bmp
Now, I want to display this image on the Swing Applet.
private static final ImageIcon redIndicator = new ImageIcon("com\\common\\images\\red.bmp");
After that, I have attached the redIndicator to a JPanel but I am not able to see this image.
Any suggestions?
==================================EDITED=========================================
private static final ImageIcon marker = loadImage("com/common/images/scale.jpg");
#SuppressWarnings("unused")
private static ImageIcon loadImage(String imagePath) {
BufferedInputStream imgStream = new BufferedInputStream(TpcHandler.class.getResourceAsStream(imagePath));
int count = 0;
if (imgStream != null) {
byte buf[] = new byte[2400];
try {
count = imgStream.read(buf);
} catch (java.io.IOException ioe) {
return null;
} finally {
if (imgStream != null)
try {
imgStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (count <= 0) {
LOGGER.warning("Empty image file: " + imagePath);
return null;
}
return new ImageIcon(Toolkit.getDefaultToolkit().createImage(buf));
} else {
LOGGER.warning("Couldn't find image file: " + imagePath);
return null;
}
}
I am getting the following exception
java.io.IOException: Stream closed
at line count = imgStream.read(buf);
This should do the trick (if called from a class loaded from that same jar):
new ImageIcon(getClass().getResource("/com/common/images/red.bmp"))
Use YourPanel.class.getResourceAsStream("/com/common/images/red.bmp"), read the stream to a byte[] and construct the ImageIcon based on that. (and don't use bmps - prefer png or jpeg)
Applets and Images that is a frequently asked questions so, as for Java applets and images, I recommend you read one of my previous answers hope it helps a bit :)
Good luck

Categories