why dont my filechooser open a dialog - java

I don't know what is wrong with the code. Can you help me figure it out?
private void doOpenFile() {
int result = myFileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
Path path = myFileChooser.getSelectedFile().toPath();
try {
String contentString = "";
for (String s : Files.readAllLines(path, StandardCharsets.UTF_8)) {
contentString += s;
}
jText.setText(contentString);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void doSaveFile() {
int result = myFileChooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
// We'll be making a mytmp.txt file, write in there, then move it to
// the selected
// file. This takes care of clearing that file, should there be
// content in it.
File targetFile = myFileChooser.getSelectedFile();
try {
if (!targetFile.exists()) {
targetFile.createNewFile();
}
FileWriter fw = new FileWriter(targetFile);
fw.write(jText.getText());
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

I'm not sure how do you use your myFileChooser and how do you instantiate them but this code works well :
public class ForTestApplication {
public static void main(String[] args) {
Window window = new Window();
window.setVisible(true);
window.showFileChooser();
}
static class Window extends JFrame {
JFileChooser jFileChooser = new JFileChooser();
public void showFileChooser() {
jFileChooser.showDialog(this, "Just for test");
}
}
}
Here is screenshot :
Please, provide more code to figure out what is going on.

Related

JavaFX Update TextField in Loop

I have a problem with my application JavaFX.
Image: https://picload.org/image/rlwpwdgi/javafx.png
With the button (1) showing the second window.
With the key (2) start the search in a path.
I need that the TextField (3) update as searching finds files.
In the Controller class of the second window, the button (2) perform this method.
public void startSuchen() {
String text = textFieldPfad.getText();
if (text.length() > 0) {
dateiGef = 0;
dateiGes = 0;
listf(pfad);
textFieldDateiGef.setText(String.valueOf(dateiGef));
textFieldDateiGes.setText(String.valueOf(dateiGes));
}
}
And this is the procedure listf:
private void listf(File directory) {
try {
File[] fileList = directory.listFiles();
for (File file : fileList) {
// Platform.runLater(new Runnable() {
// #Override
// public void run() {
// textFieldDateiGef.setText(String.valueOf(getDateiGef()));
// textFieldDateiGes.setText(String.valueOf(getDateiGes()));
// }
// });
// Thread thrd = new Thread() {
// public void run() {
// Platform.runLater(new Runnable() {
// #Override
// public void run() {
// textFieldDateiGef.setText(String.valueOf(getDateiGef()));
// textFieldDateiGes.setText(String.valueOf(getDateiGes()));
// }
// });
// }
// };
// thrd.start();
if (file.isFile()) {
dateiGes += 1;
String fileName = file.getName().toLowerCase();
String nome = textFieldName.getText().toLowerCase();
Pattern r = Pattern.compile(nome);
Matcher m = r.matcher(fileName);
if (m.find()) {
dateiGef += 1;
}
} else if (file.isDirectory()) {
listf(file);
}
}
} catch (NullPointerException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
The commented lines are my tests to update the GUI, I also tried with the Task, but unfortunately it does not work. Someone please help me understand why?
Here is the solution:
public void startSuchen() {
String text = textFieldPfad.getText();
if (text.length() > 0) {
dateiGef = 0;
dateiGes = 0;
// Solution
new Thread(() -> listf(pfad)).start();
// End Solution
textFieldDateiGef.setText(String.valueOf(dateiGef));
textFieldDateiGes.setText(String.valueOf(dateiGes));
}
}
And this is the procedure listf:
private void listf(File directory) {
try {
File[] fileList = directory.listFiles();
for (File file : fileList) {
// Solution
Platform.runLater(new Runnable() {
#Override
public void run() {
textFieldDateiGef.setText(String.valueOf(getDateiGef()));
textFieldDateiGes.setText(String.valueOf(getDateiGes()));
}
});
// End Solution
if (file.isFile()) {
dateiGes += 1;
String fileName = file.getName().toLowerCase();
String nome = textFieldName.getText().toLowerCase();
Pattern r = Pattern.compile(nome);
Matcher m = r.matcher(fileName);
if (m.find()) {
dateiGef += 1;
}
} else if (file.isDirectory()) {
listf(file);
}
}
} catch (NullPointerException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
Many thanks to James_D

How to pass a text in java editor as parameter to my netbeans module?

I'm creating a Netbeans module. How do I pass a selected text in the java editor as a parameter to my ActionListener class and, after process it, how do I replace this old text (passed as parameter) by the new processed text in the java editor?
#ActionID(category = "Edit", id = "com.beg.regextester.RegexTesterListener")
#ActionRegistration(displayName = "Regex Tester")
#ActionReference(path = "Editors/text/x-java/Popup")
public class RegexTesterListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
//the code here
}
After a long research, I got it.
#ActionID(category = "Edit", id = "com.beg.regextester.RegexTesterListener")
#ActionRegistration(displayName = "Regex Tester")
#ActionReference(path = "Editors/text/x-java/Popup")
public class RegexTesterListener implements ActionListener {
private final DataObject context;
public RegexTesterListener(DataObject context) {
this.context = context;
}
#Override
public void actionPerformed(ActionEvent e) {
//Identify java object in the context
FileObject fileObject = context.getPrimaryFile();
JavaSource javaSrc = JavaSource.forFileObject(fileObject);
if (javaSrc == null) {
StatusDisplayer.getDefault().setStatusText(fileObject.getPath() + " is not a java file");
} else {
try {
javaSrc.runUserActionTask(new org.netbeans.api.java.source.Task<CompilationController>() {
#Override
public void run(CompilationController p) throws Exception {
p.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
Document doc = p.getDocument();
if (doc == null) {
StatusDisplayer.getDefault().setStatusText("Java file is closed");
} else {
new MemberVisitor(p).scan(p.getCompilationUnit(), null);
}
}
}, true);
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}//end else
}//end actionPerformed
private static class MemberVisitor extends TreePathScanner<Void, Void> {
private CompilationInfo info;
public MemberVisitor(CompilationInfo info) {
this.info = info;
}
#Override
public Void visitClass(ClassTree t, Void v) {
try {
JTextComponent editor = EditorRegistry.lastFocusedComponent();
if (editor.getDocument() == info.getDocument()) {
int dot = editor.getCaret().getDot();
TreePath tp = info.getTreeUtilities().pathFor(dot);
Element el = info.getTrees().getElement(tp);
if (el != null) {
StatusDisplayer.getDefault().setStatusText("Please, select a string");
} else {
//get the selected text
String str = editor.getSelectedText();
//process the string and pass it to the clipboard
...
//replacing the old str by the new one
editor.paste();
}
}
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
return null;
}
}
}//end class

Java, javazoom program for playing MP3 files(AdvancedPlayer), event.getFrame() is giving random things

I'm trying to write a program that plays .mp3 files, playing them works perfectly. But pausing is causing some trouble. When I pause the song (stop the song and ask for the frame) I get an incorrect value.
class PauseStartMP3Test {
private static AdvancedPlayer player;
private static int pausedOnFrame = 0;
private static boolean playing = false;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(true) {
String s = in.next();
if(!s.equals("")) {
if(!playing) {
playing = true;
play();
}
else {
player.stop();
}
}
}
}
public static void play() {
File file = null;
file = new File("C:\\Users\\Remco\\Desktop\\Programming\\musictest/throughglass.mp3");
try {
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
player = new AdvancedPlayer(bis);
new Thread() {
public void run() {
try {
if(playing) {
player.setPlayBackListener(new PlaybackListener() {
#Override
public void playbackFinished(PlaybackEvent event) {
pausedOnFrame = event.getFrame();
System.out.println(pausedOnFrame);
playing = false;
}
});
player.play(pausedOnFrame, Integer.MAX_VALUE);
}
else {
player.stop();
}
}
catch (Exception e) {
System.out.println(e);
}
}
}.start();
} catch (JavaLayerException ex) {
System.out.println(ex);
}
} catch (FileNotFoundException ex) {
System.out.println(ex);
}
}

Why do Clipboard Listener use more CPU usage?

I wrote program that listen Clipboard and worked correctly, but i saw that the program use more CPU usage. CPU usage is more 70%. Why? Can i reduce it? or i want Listener that listen windows's copy action. Is there Listener in java for this?
This is my code:
package yoxlama;
import java.awt.*;
import java.awt.datatransfer.*;
import java.io.IOException;
import java.net.MalformedURLException;
class ClipBoardListener extends Thread implements ClipboardOwner {
Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
static ClipBoardListener b;
Interlsoft interlsoft = new Interlsoft();
public void run() {
try{
Transferable trans = sysClip.getContents(this);
regainOwnership(trans);
}catch (Exception e) {
try {
b.finalize();
} catch (Throwable e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
b= new ClipBoardListener();
b.start();
System.out.println("NESE1");
}
System.out.println("Listening to board...");
while(true) {}
}
public void lostOwnership(Clipboard c, Transferable t) {
try {
Thread.sleep(50);
} catch(Exception e) {
System.out.println("Exception: " + e);
}
try{
Transferable contents = sysClip.getContents(this);
processContents(contents);
regainOwnership(contents);
}catch (Exception e) {
try {
b.finalize();
b= new ClipBoardListener();
b.start();
} catch (Throwable e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("nese");
}
}
void processContents(Transferable t) throws MalformedURLException, IOException {
String str = getClipboard(t);
if(str!=null){
str= str.replace("\n", "%0D%0A");
str= str.replace("\r", "");
str= str.replace("\t", "");
str= str.replace("/", "");
str= str.replace("-", "");
interlsoft.translate(str);
}
// System.out.println("Processing: " + getClipboard(t));
}
void regainOwnership(Transferable t) {
sysClip.setContents(t, this);
}
public static void main(String[] args) {
b = new ClipBoardListener();
b.start();
}
public static String getClipboard(Transferable t) {
// Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
try {
if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String text = (String)t.getTransferData(DataFlavor.stringFlavor);
return text;
}
} catch (UnsupportedFlavorException e) {
System.out.println("BURDA1");
} catch (IOException e) {
System.out.println("BURDA1");
}
return null;
}
}
This: while(true) {}
Your poor CPU. Instead of while true, just make that thread sleep indefinitely. See: How do you hang a thread in Java in one line?

Audio on J2ME, I don't know where is wrong?

I want to do 2 task at same time:
Play an audio file.
Read raw data of it to do something
Here is my code:
String wavPath = "file:///" + currentPath + fileName;
FileConnection fc;
try {
fc = (FileConnection) Connector.open( wavPath );
if ( !fc.exists() ) {
throw new IOException( "File does not exists." );
}
InputStream is = fc.openInputStream();
// to do something with raw data as print samples of it
Player player = Manager.createPlayer( wavPath );
player.realize();
player.prefetch();
player.start();
} catch ( IOException e1 ) {
e1.printStackTrace();
}
But nothing run, audio file doesn't not run. If I remove line:
InputStream is = fc.openInputStream();
Audio file run very well. But I want to do 2 task at same time, i don't know how to do it. Anybody can help me ?
I have tried use 2 thread, but it still doesn't work, audio file run (thread 1) but thread 2 not run:
new Thread( new Runnable() {
public void run() {
try {
Manager.createPlayer( "file:///E:/" + fileName ).start();
} catch ( MediaException e ) {
e.printStackTrace();
} catch ( IOException e ) {
e.printStackTrace();
}
}
}).start();
new Thread( new Runnable() {
public void run() {
FileConnection fc;
try {
fc = (FileConnection) Connector.open( "file:///E:/" + fileName );
InputStream is = fc.openInputStream();
byte[] b = new byte[10];
int length = is.read( b, 0, 10 );
for ( int i = 0; i < length; i++ ) {
form.append( b[i] + "" );
}
} catch ( IOException e ) {
e.printStackTrace();
}
}
}).start();
why don't you use threading...
create a thread to play the wav file
and use another thread to do read a file...
refer here for further details on threading in J2ME
public class View_PlayMidlet extends MIDlet {
PlayerThread musicPlayer = new PlayerThread();
public void startApp() {
String fileName = "file://e:/abcd.wav";
musicPlayer.setPlayableFile(fileName);
FileConnection fc = null;
InputStream is = null;
String fileContent = null;
try {
fc = (FileConnection) Connector.open("file:///E:/" + fileName);
is = fc.openInputStream();
byte[] b = new byte[10];
int length = is.read(b, 0, 10);
fileContent = new String(b);
// display the content of fileContent variable in a form.
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
}
}
if (fc != null) {
try {
fc.close();
} catch (IOException ex) {
}
}
}
// by this time the file is displayed & you can start playing the file.
Thread t = new Thread(musicPlayer);
t.start();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
public class PlayerThread implements Runnable {
private String fileName;
private Player player;
public PlayerThread() {
}
public void run() {
try {
player = Manager.createPlayer(fileName);
player.prefetch();
player.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopMusic() {
try {
player.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
public void setPlayableFile(String fileName) {
this.fileName=fileName;
}
}
this would roughly be what you are looking for.
Your Player instances are garbage collected. Also, file access during playback will likely be 'implementation specific', meaning that it will work on some models and not others. So read the data first, copy it to another file etc, if you want something solid.
You can always go the DataSource-path too.

Categories