I have done my research, no useful results found.
Here is the deal, I'm writing a 'new' clipboard that works like a stack instead of a 'area'. And I'm brave or stupid enoght to do that in Java. So far in my tests to see if this is possible I have managed to create this stack behavior. The only problem I'm getting is that sometimes, mainly when I paste the top of the stack (pop operation), it doesn't pop or for some other reason it pastes twice.
Example:
If i copy this three words: Carlos, Lucas, Eastwood
The stack clipboard behaves like this at paste: Eastwood, Eastwood, Lucas, Carlos
I'm using JNativeHooks for reading the system keypresses and determining when the user is pasting.
I think what is happening is that the system is pasting before my code... Well, here is the code anyway (It is a test, that explains why it is badly commented):
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.Transferable;
import java.util.Stack;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.NativeInputEvent;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
public class Test3 implements NativeKeyListener {
Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
Stack<Transferable> clipStack = new Stack<>();
public static void main(String[] args) {
try {
GlobalScreen.registerNativeHook();
} catch (NativeHookException ex) {
System.err
.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
System.exit(1);
}
Test2 t2 = new Test2();
// Construct the example object and initialze native hook.
GlobalScreen.getInstance().addNativeKeyListener(t2);
}
#Override
public void nativeKeyPressed(NativeKeyEvent ev) {
// Copy
if (ev.getKeyCode() == NativeKeyEvent.VK_C
&& NativeInputEvent.getModifiersText(ev.getModifiers()).equals(
"Ctrl")) {
// Clip the pop
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
clipStack.push(sysClip.getContents(null));
System.out.println("Ctrl+C : Stack(" + clipStack.size() + ")");
}
// Paste
if (ev.getKeyCode() == NativeKeyEvent.VK_V
&& NativeInputEvent.getModifiersText(ev.getModifiers()).equals(
"Ctrl")) {
// Clip the pop
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (clipStack.size() > 1) {
sysClip.setContents(clipStack.pop(), null);
} else
sysClip.setContents(clipStack.peek(), null);
System.out.println("Ctrl+V : Stack(" + clipStack.size() + ")");
}
}
#Override
public void nativeKeyReleased(NativeKeyEvent e) {
}
#Override
public void nativeKeyTyped(NativeKeyEvent e) {
}
}
I would think the same as you suggested.
Have a copy and paste key combination something different from ctrl+c and ctrl+v and you can even bypass using the system clipboard. Simply push the selected text and pop the text directly to your text pointer in your application provided of course that you are using this stack behavior for only a particular application.
The system retains it's own copy of latest clip and it gets a duplicate from your sysClip.setContents(clipStack.pop(), null) on paste operation.
I don't have much idea on disabling the system behavior. You can do research on that. But you can always make sure that it's the only problem by changing the key combination.
Related
I am currently messing around with facial recognition and try to capture photos form my webcam. I am adapting this tutorial to automatically name and save the taken picture. Note that this Code is called from the main() the funtion it self is implemented in another class. Up and until I stop the thread with interrupt() it works. Afterwards the picture is frozen in the GUI and the system doesn't seem to return into the class where I operate over my GUI.
To make myself clear: I want to capture a picture from my webcam and replace the former stream from my webcam with said earlier captured picture. Up and until I capture the picture and interrupt the thread the code works. Aftwards it is stuck.
I experiemented with pulling the Thread into the ActionListener of the CaptureButton but that failed because the main GUI element was not accessible which is courious given that it is defined as public.
It does however throw in the course of compilation some warnings - tho I must admit that I have no clue what they mean:
[ WARN:0] global C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\videoio\src\cap_msmf.cpp (376) `anonymous-namespace'::SourceReaderCB::OnReadSample videoio(MSMF): OnReadSample() is called with error status: -1072873821
[ WARN:0] global C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\videoio\src\cap_msmf.cpp (388) `anonymous-namespace'::SourceReaderCB::OnReadSample videoio(MSMF): async ReadSample() call is failed with error status: -1072873821
[ WARN:1] global C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\videoio\src\cap_msmf.cpp (1021) CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -1072873821
Exception in thread "Thread-0" CvException [org.opencv.core.CvException: cv::Exception: OpenCV(4.5.2) C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\imgcodecs\src\loadsave.cpp:896: error: (-215:Assertion failed) !image.empty() in function 'cv::imencode'
]
at org.opencv.imgcodecs.Imgcodecs.imencode_1(Native Method)
at org.opencv.imgcodecs.Imgcodecs.imencode(Imgcodecs.java:510)
at GUI.FaceRecognition.startCamera(FaceRecognition.java:129)
at main$1$1.run(main.java:19)
at java.base/java.lang.Thread.run(Thread.java:834)
[ WARN:2] global C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
Thread vorbei
I have written my code rather amateurish of that I am sure and I reckon I could use something like callable() but am unsure who to use that. I also do not know how to replicate my problem outside of chucking my entire project around the internet but I can however provide the code of my modifications:
for the funtion itself
public boolean startCamera(){
capture= new VideoCapture(0);
image=new Mat();
byte[] imageData;
ImageIcon icon;
String name = null;
boolean echo = false;
while(true){
capture.read(image);
final MatOfByte buf=new MatOfByte();
Imgcodecs.imencode(".png", image,buf);
imageData= buf.toArray();
icon=new ImageIcon(imageData);
Feed.setIcon(icon);
if(trigger==true){
name="Recognition";
Imgcodecs.imwrite("src/"+name+".png",image);
trigger=false; //Auslöser zurücksetzten
}
File kamera=new File("src/Recognition.png");
if(kamera.exists()==true){
//capture.release();
/*try {
Kamera=ImageIO.read(this.getClass().getResourceAsStream("/Recognition.png"));
} catch (IOException e) {
e.printStackTrace();
}*/
return echo=true;
}
}
}
for the main()
import java.awt.*;
import java.io.File;
import java.lang.String;
import GUI.*;
import org.opencv.core.Core;
public class main {
public static void main(String[] args){
FaceRecognition Fenster=new FaceRecognition();
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
//FaceRecognition Fenster=new FaceRecognition();
new Thread (new Runnable() {
#Override
public void run() {
Fenster.startCamera();
}
}).start();
//File kamera=new File(("src/Recognition.png"));
}
});
if(Fenster.startCamera()==true){
Thread.currentThread().interrupt();
System.out.println("Thread vorbei");
}
}
}
Please point out where I went wrong or what goes wrong.
Edit:
I have mean while heeded #pveentjers advice and reformed my code (see below). Yet in my main() the IDE proposes to make startCamera static which will not work because startCamera can not be static (or rather elements of it can't). Is there any way to move around this?
the startCamera function
public class startCamera implements Runnable{
private CountDownLatch end;
public startCamera(CountDownLatch one){
this.end=one;
}
#Override public void run(){
try {
capture= new VideoCapture(0);
image=new Mat();
byte[] imageData;
ImageIcon icon;
String name = null;
while(true){
capture.read(image);
final MatOfByte buf=new MatOfByte();
Imgcodecs.imencode(".png", image,buf);
imageData= buf.toArray();
icon=new ImageIcon(imageData);
Feed.setIcon(icon);
if(trigger==true){
name="Recognition";
Imgcodecs.imwrite("src/"+name+".png",image);
trigger=false; //Auslöser zurücksetzten
}
File kamera=new File("src/Recognition.png");
if(kamera.exists()==true){
capture.release();
end.countDown();
/*try {
Kamera=ImageIO.read(this.getClass().getResourceAsStream("/Recognition.png"));
} catch (IOException e) {
e.printStackTrace();
}*/
}
}
}
catch (Exception exception){
}
}
the reformed main()
import java.awt.*;
import java.io.File;
import java.lang.String;
import java.util.concurrent.CountDownLatch;
import GUI.*;
import GUI.FaceRecognition.startCamera;
import org.opencv.core.Core;
public class main {
public static void main(String[] args){
FaceRecognition Fenster=new FaceRecognition();
CountDownLatch mark=new CountDownLatch(1);
startCamera startCamera=new startCamera(mark);
try {
mark.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
Might be that I don't the wood for the trees but this the first time I am working with threads.
I'm trying to load a .wav file in my EnviromentAudio object, but I received only an UnsupportedAudioFileException and I don't know why. Because the file is a wav and I've tried to encode it as an unsigned 8 bit, as a signed 16 bit, with a 44100 bit rate, as a GSM, as a A-law... long story short I've tried a lot of encoding, as many people suggested, but no one worked. Probably I'm not getting something, so, I want to ask what I'm doing wrong.
EDIT:
As pointed out I should have specified some things: first of all, to set some context, I am using Java 8 to create a little pc game for a project, which must uses the basics components of java. Said that, I'm using the ClassLoader
, because I have a mess in the project folder. It does not follow the convention and I have to keep like that. It's structured like this:
-src
-app
-audio
EnviromentAudio.java // Class that need to load soundtrack.wav
-res
-audio
Soundtrack.wav // Audio to be loaded
And I know that a getResource.. should start always with a /, but if I add that slash, then every attempt to get a resource results in a NPE. Probably that's caused by the folders disposition and, by the way, the resources folder is set as source folder, so I'm not even quite sure about that, cause, also, I've already used the getResource to get other files without problems.
In this case The getResource works fine, that is it retrieves the file, but the AudioSystem generates an error. I've tried to isolate the parties involved, but the only problem seems to be here. I'm adding the AudioManager class, the Audio class inherited by EnviromentAudio, and the whole EnviromentAudio, with the hope that it will be of help for a better understanding. I also provided a main in the AudioManager class, which should be enough to replicate the error.
Audio class:
package application.core.audio;
import java.util.ArrayList;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.swing.JOptionPane;
public abstract class Audio
{
protected static final String AUDIOERROR="Error in loading audio. "
+ "Execution Failed, please, restart the game. "
protected static final String AUDIOERRORTITLE="Audio loading error";
protected ArrayList<Clip> multimedia;
protected Clip currentAudio;
protected FloatControl gainControl;
public Audio() {
multimedia=new ArrayList<Clip>();
currentAudio=null;
}
protected abstract void getResources();
public void playAudio(int index) {
try
{
currentAudio=multimedia.get(index);
gainControl=(FloatControl) currentAudio.getControl(
FloatControl.Type.MASTER_GAIN);
currentAudio.open();
} catch (LineUnavailableException e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(null, AUDIOERROR,
AUDIOERRORTITLE, JOptionPane.ERROR_MESSAGE);
}
currentAudio.start();
}
public void loopAudio(int index) {
currentAudio=multimedia.get(index);
// gainControl=(FloatControl) currentAudio.getControl(
// FloatControl.Type.MASTER_GAIN);
// currentAudio.open();
// currentAudio.start();
currentAudio.loop(Clip.LOOP_CONTINUOUSLY);
}
public void repeatAudio(int index, int times) {
try
{
currentAudio=multimedia.get(index);
gainControl=(FloatControl) currentAudio.getControl(
FloatControl.Type.MASTER_GAIN);
currentAudio.open();
} catch (LineUnavailableException e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(null, AUDIOERROR,
AUDIOERRORTITLE, JOptionPane.ERROR_MESSAGE);
}
currentAudio.loop(times);
}
public void stopAudio(int index) {
multimedia.get(index).stop();
multimedia.get(index).close();
}
public void setVolume(float volume) {
float range=gainControl.getMaximum()-gainControl.getMinimum();
float gain=(range-volume)+gainControl.getMinimum();
gainControl.setValue(gain);
}
public boolean currentAudioIsOpen() {return currentAudio.isOpen();}
public void openCurrentAudio() {
if (!currentAudio.isOpen())
try
{
currentAudio.open();
} catch (LineUnavailableException e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(null, AUDIOERROR,
AUDIOERRORTITLE, JOptionPane.ERROR_MESSAGE);
}
}
public void openAndPlayCurrentAudio() {
if (!currentAudio.isOpen())
openCurrentAudio();
currentAudio.start();
}
public void playCurrentAudio() {currentAudio.start();}
public void loopCurrentAudio() {currentAudio.loop(Clip.LOOP_CONTINUOUSLY);}
public void repeatCurrentAudio(int times) {currentAudio.loop(times);}
public void stopCurrentAudio() {currentAudio.stop();}
public void stopAndCloseCurrentAudio() {
currentAudio.stop();
currentAudio.close();
}
}
This is my EnviromentAudio class that produce the exception:
package application.core.audio;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class EnviromentAudio extends Audio
{
public static final int SOUNDTRACK=0;
public EnviromentAudio()
{
super();
getResources();
this.gainControl=(FloatControl) currentAudio.getControl(FloatControl.Type.MASTER_GAIN);
}
#Override
protected void getResources()
{
try
{
ClassLoader loader=EnviromentAudio.class.getClassLoader();
multimedia.add(AudioSystem.getClip());
multimedia.get(SOUNDTRACK).open(AudioSystem.getAudioInputStream( // here the exception is thrown (on getAudioInputStream)
loader.getResourceAsStream("resources"+File.separator+"audio"+File.separator+
"soundtrack"+File.separator+"igpeSoundtrack.wav")));
currentAudio=multimedia.get(SOUNDTRACK);
} catch (LineUnavailableException e)
{
e.printStackTrace();
} catch (IOException | UnsupportedAudioFileException e1)
{
e1.printStackTrace();
}
}
}
AudioManager class:
package application.core.audio;
public class AudioManager
{
private static AudioManager instance=null;
private EnviromentAudio soundtrack;
private PlayerAudio playerAudio;
private AudioManager() {
soundtrack=new EnviromentAudio();
// playerAudio=new PlayerAudio();
soundtrack.loopAudio(EnviromentAudio.SOUNDTRACK);
}
public static AudioManager getInstance() {
if (instance==null)
instance=new AudioManager();
return instance;
}
public Audio getSoundtrack() {return soundtrack;}
public Audio getPlayerSounds() {return playerAudio;}
public void setVolume(float volume) {
soundtrack.setVolume(volume);
playerAudio.setVolume(volume);
}
public float getVolume() {return soundtrack.gainControl.getValue();}
public static void main(String[] args)
{
AudioManager a=AudioManager.getInstance();
}
}
And here is the error:
javax.sound.sampled.UnsupportedAudioFileException: Stream of unsupported format
at java.desktop/javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1020)
at application.core.audio.EnviromentAudio.getResources(EnviromentAudio.java:29)
at application.core.audio.EnviromentAudio.<init>(EnviromentAudio.java:18)
at application.core.audio.AudioManager.<init>(AudioManager.java:11)
at application.core.audio.AudioManager.getInstance(AudioManager.java:19)
at application.MainApplication.audioInitialize(MainApplication.java:44)
at application.MainApplication.main(MainApplication.java:25)
This is more to help with troubleshooting than a solution (expanding on Andrew Thompson's suggestion of making an MRE. Are you using a particular framework? Or is it something of your own making? For a second I though it might be Android (due to presence of AudioManager).
Following is a more minimal example for play testing your .wav file. Put the wav file in the same folder as this class. Does your .wav file play when using this?
import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class BasicClipExample {
public static void main(String[] args) {
try {
BasicClipExample.run();
} catch (UnsupportedAudioFileException | IOException
| LineUnavailableException | InterruptedException e) {
e.printStackTrace();
}
}
private static void run() throws UnsupportedAudioFileException,
IOException, LineUnavailableException, InterruptedException
{
String filename = "yourSound.wav";
URL url = BasicClipExample.class.getResource(filename);
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
DataLine.Info info = new DataLine.Info(Clip.class, ais.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(ais);
clip.start();
Thread.sleep(6000); // plays up to 6 seconds of sound before exiting
clip.close();
}
}
If it works, then something is odd about your framing code. From here you can progressively check if things like the file separator logic are working. You can also add some lines to print out the AudioFormat if the file loads.
Another way I sometimes inspect files is to load them into Audacity, which is free. Info about the file format is pretty easy to inspect with that tool. If I had to wager, and the issue IS the .wav format, I'm guessing that the file is recorded at a higher quality level than Java is set to work with, e.g., 48000 (maybe Java supports?) or 96000 fps or 24- or 32-bit encoding rather than 16-bit.
I want to write a program that plays a sound everytime, a button on the Keyboard is pressed. (Even, if the program isn´t in focus)
I am using JNativeHook, but when i want to add a Key Listener, i get an error beacuse the method .getInstance isn´t contained in Global Screen. :(
Anyone got an idea?
My Code:
package test1;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
public class jNativeHookExample implements NativeKeyListener {
public void nativeKeyPressed(NativeKeyEvent e) {
System.out.println(NativeKeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == NativeKeyEvent.VC_F9) {
//play sound;
}
}
public void nativeKeyReleased(NativeKeyEvent e) {
System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
}
public void nativeKeyTyped(NativeKeyEvent e) {
System.out.println("Key Typed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
}
public static void main(String[] args) {
try {
/* Register jNativeHook */
GlobalScreen.registerNativeHook();
} catch (NativeHookException ex) {
/* Its error */
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
System.exit(1);
}
GlobalScreen.getInstance().addNativeKeyListener(new jNativeHookExample());
}
}
This code is probably ok for the version 1.1 of jnativehook.
Starting from the version 2.0 the GlobalScreen class has no getInstance() method, and addNativeKeyListener() is now static, so it should be called directly on the GlobalScreen:
GlobalScreen.addNativeKeyListener(new jNativeHookExample());
This is for a homework I'm doing on my walk learning java.
I'm writing a program and it is all working as expected except the read/write to file.
I have one class named Medico that holds only one string (typeOfMedico) and one int (valorFacturado). Medico is a sub class of Pessoa. Pessoa holds data like name and address. public class Medico extends Pessoa implements Serializable is the main function on Medicoclass.
On my main class, named Clinica, I ask for user input and at the end of I create a new Medico that its added to an Arraylist named medico.
For reading and writing to file I've created this class:
package clinica;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class FicheiroObjectos {
private ObjectInputStream iS;
private ObjectOutputStream oS;
public void abreLeitura(String nomeDoFicheiro) throws IOException {
iS = new ObjectInputStream(new FileInputStream(nomeDoFicheiro));
}
public void abreEscrita(String nomeDoFicheiro) throws IOException {
oS = new ObjectOutputStream(new FileOutputStream(nomeDoFicheiro));
}
public Object leObjecto() throws IOException, ClassNotFoundException {
return iS.readObject();
}
public void escreveObjecto(Object o) throws IOException {
oS.writeObject(o);
}
public void fechaLeitura() throws IOException {
iS.close();
}
public void fechaEscrita() throws IOException {
oS.close();
}
public void leFicheiroMedicos() {
Medico medicos;
while (true) {
try {
medicos = (Medico) this.leObjecto();
Clinica.medicos.add(medicos);
} catch (EOFException eof) {
break;
} catch (ClassNotFoundException cnf) {
System.out.print("\nClassNotFoundException!\nO programa vai terminar\n");
System.exit(-1);
} catch (IOException ioe) {
System.out.print("\nErro ao ler o ficheiro!\nO programa vai terminar\n");
System.exit(-1);
}
}
}
public void escreveFicheiroMedicos() {
try {
for (Medico medicos: Clinica.medicos) {
this.escreveObjecto(medicos);
}
} catch (IOException e) {
System.out.print("\nErro ao escrever no ficheiro!\nO programa vai terminar\n");
System.exit(-1);
}
}
}
On my main class I've created this two functions:
public static void insereDadosExistentes() {
try {
FicheiroObjectos file = new FicheiroObjectos();
file.abreLeitura("Medicos.dat");
file.leFicheiroMedicos();
file.fechaLeitura();
} catch (IOException ioe) {
}
}
public static void gravarMedicos() {
try {
FicheiroObjectos file = new FicheiroObjectos();
file.abreEscrita("Medicos.dat");
file.escreveFicheiroMedicos();
file.fechaEscrita();
} catch (IOException e) {
System.out.print("\nErro ao escrever no ficheiro!\nO programa vai terminar\n");
System.exit(-1);
}
}
}
Then added insereDadosExistentes() at the beginning of my mainfunction and added gravarMedicos() just after adding a Medico to my medicos arraylist.
When I run my program (On the first run, file Medicos.dat, does not exist) and create a Medico, Medico is added to my arraylist and the file Medicos.dat is created. Then I stop the program and on the next run, which now haves a Medicos.dat file, I get the error:
Erro ao ler o ficheiro!
O programa vai terminar
The problem is in writing the file or reading the file?
I know the error is given when reading the file but it could be because the writhing to file is not properly executed.
If I try to open Medicos.dat I can see some characters but nothing related with the info I input so I don't even know if the file writing is ok.
Remember that all besides file handling is working as expected.
Can you point me In some directions?
favolas
Make sure that you explicitly close the ObjectOutputStream so that all the data is written.
Your problem is an IOException. However, the backtrace will tell you what's going on: trouble opening, reading, what? you can call printStackTrace(), but better you can use a debugging and just look at the stack trace.
If you catch an exception dont just write something to system.out but print the stacktrace this will usually give you a clue whats wrong
try {
FicheiroObjectos file = new FicheiroObjectos();
file.abreEscrita("Medicos.dat");
file.escreveFicheiroMedicos();
file.fechaEscrita();
} catch (IOException e) {
e.printStackTrace();
}
Q: Are you trying to read and write DATA, or are you trying to serialize and deserialize OBJECTS?
I think all you need to do is open and write to a simple text file:
For example:
http://www.exampledepot.com/egs/java.io/AppendToFile.html
import java.io.*;
public class TestFile
{
public static void main (String[] args)
{
// Test "append"
// SOURCE: http://www.exampledepot.com/egs/java.io/AppendToFile.html
try {
BufferedWriter out =
new BufferedWriter(
new FileWriter("myfile.txt", true));
out.write("testing: a b c\n");
out.write("testing: d e f\n");
out.close();
}
catch (IOException e) {
}
}
}
Sample output:
testing: a b c
testing: d e f
I don't know Java's serialization stuff at all, but this seems "too easy":
public void escreveObjecto(Object o) throws IOException {
oS.writeObject(o);
}
How is the object output stream supposed to know what portions of your object needs to be written to disk? Could be that your object contains nothing but computed values that shouldn't be stored. Could be that your object's data needs to be stored completely. Perhaps references to String objects should just be dropped... or perhaps those Strings should be written to disk.
There must be more to using the ObjectStream stuff than you're showing here -- and paulsm4's answer shows how writing your own content by hand isn't too bad. Should you be taking that approach instead? Does your class have a defined storage format that you must adhere to?
I would like to install a custom icon in place of the standard JOptionPane information icon..
I tried
ImageIcon myCustomIcon = ...;
UIManager.put("OptionPane.informationIcon", myCustomIcon);
However, apparently this has no effect due to the following line:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Commenting out this line gives the correct behaviour. I have of course tried putting the icon into the UIManager both before/after the look and feel is being set.
Can I somehow combine the two to override the information icon globally?
I am working on Ubuntu 10.04 right now..
Regards,
Morten
Works fine for me using the Metal and Windows LAF's.
Maybe your LAF doesn't support the UIManager property. Check out UIManager Defaults for a list of properties.
If you need more help the post your SSCCE that demonstrates the problem.
Have you tried to specify your icon after setting look&feel, in such a way:
JOptionPane.showMessageDialog(frame,
"Eggs are not supposed to be green.",
"Inane custom dialog",
JOptionPane.INFORMATION_MESSAGE,
myCustomIcon);
Update:
The following code works fine on my Windows 7:
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class OptionPaneIcon {
public static void main (String[] args) {
ImageIcon myCustomIcon = loadImageIcon("image.png");
UIManager.put("OptionPane.informationIcon", myCustomIcon);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JOptionPane.showMessageDialog(null, "Hello!");
}
/** Returns an ImageIcon, or null if the path was invalid. */
private static ImageIcon loadImageIcon(String path) {
URL imgURL = OptionPaneIcon.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
}
P.S. Sorry for my impatience.