I faced a problem that the typed data can not be persistent. I want to store java Swing GUI to XML file and reuse them latter. Now I store the GUI successfully. But after I type some data into the textfield. The typed data can not be encoded into XML file. Could you help me store both the GUI and the typed content? Below is the code using javabeans XMLencoder:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import java.beans.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class ResourceName extends JFrame implements ActionListener{
static JFileChooser chooser;
JButton save,load;
JTextField tf;
static JFrame frame;
public ResourceName(){
chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
frame = new JFrame("ResourceName");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
save = new JButton("Save");
save.setActionCommand("Save");
save.addActionListener(this);
load = new JButton("Load");
load.setActionCommand("Load");
load.addActionListener(this);
tf = new JTextField(10);
frame.add(save);
frame.add(tf);
frame.add(load);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e){
if((e.getActionCommand()).equals("Save"))
{
save();
}else if((e.getActionCommand()).equals("Load"))
{
load();
}
}
public void save()
{
if(chooser.showSaveDialog(null)==JFileChooser.APPROVE_OPTION)
{
try{
File file = chooser.getSelectedFile();
XMLEncoder encoder = new XMLEncoder(new FileOutputStream(file));
encoder.writeObject(frame);
encoder.close();
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null, e);
}
}
}
public void load()
{
//show file chooser dialog
int r = chooser.showOpenDialog(null);
// if file selected, open
if(r == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
XMLDecoder decoder = new XMLDecoder(new FileInputStream(file));
decoder.readObject();
decoder.close();
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null, e);
}
}
}
public static void main(String[] args) {
ResourceName test = new ResourceName();
}
}
Please help me solve this problem. Many Thanks!
it may be that the text property, is transient, this means it won't be saved to the output automatically, by an ObjectOutputStream. You'll probably have to explicitly write that field.
Related
What's wrong in this code? Still get error when declaring playMusicMethod. Sitting with this for about hour and still can't figure out. Tried to use this method in another class with only main method and It worked.
import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
import java.awt.event.*;
import javax.swing.*;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import sun.audio.*;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
public class MainClass extends JFrame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(200, 200);
JButton click = new JButton("Click me");
click.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
playMusic("Music\\somebody.wav");
}
});
frame.add(click);
}
public static void playMusic(String filePath) {
String filePath1 = filePath;
InputStream audio;
try {
audio = FileInputStream(new File(filePath1));
AudioStream music = new AudioStream(audio);
AudioPlayer.player.start();
}
catch(Exception e) {
}
}
}
You are incorrectly instantiating your FileInputStream.
Replace this:
audio = FileInputStream(new File(filePath1));
by
audio = new FileInputStream(new File(filePath1));
I am creating a user interface for a pdf reader, and I want to have a list with recent open files. (Not the content of the files, just the name of the file).
From the snap shared, I assume that you are using JFileChooser for your dialog to open file. Hope this helps!
int result = fileChooser.showOpenDialog(panel);
//where panel is an instance of a Component such as JFrame, JDialog or JPanelwhich is parent of the dialog.
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
textArea.setText(selectedFile.getName());
}
The example below uses a JFileChooser with setMultiSelectionEnabled(true) to add() one or more files to a List<File> and update() a JTextArea with the current list. As suggested here, you can use Action to maintain a menu or tool bar of recent files.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
/**
* #see https://stackoverflow.com/a/37153404/230513
* #see https://stackoverflow.com/a/4039359/230513
*/
public class Test {
private final List<File> recentFiles = new ArrayList<>();
private final JTextArea textArea = new JTextArea(12, 12);
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea.setBorder(BorderFactory.createTitledBorder("Recent Files"));
f.add(textArea);
JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT));
p.add(new JButton(new AbstractAction("Open") {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc = new JFileChooser(".");
jfc.setMultiSelectionEnabled(true);
if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
recentFiles.addAll(Arrays.asList(jfc.getSelectedFiles()));
update();
}
}
}));
f.add(p, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private void update() {
textArea.setText("");
for (File file : recentFiles) {
textArea.append(file.getName() + "\n");
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Test()::display);
}
}
I'm trying to set up face detection with JavaCV. I've got working code with cvLoadImage but when I try to load an image via Highgui.imread there's an error: 'Highgui cannot be resolved' and 'Highgui' has red wavy underlining. For some reason Eclipse cannot deal properly with imported com.googlecode.javacv.cpp.opencv_highgui or ...?
Problem here:
CvMat myImg = Highgui.imread(myFileName);
Full code:
import java.awt.EventQueue;
import java.awt.Insets;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import com.googlecode.javacv.cpp.opencv_core.CvMemStorage;
import com.googlecode.javacv.cpp.opencv_core.CvRect;
import com.googlecode.javacv.cpp.opencv_core.CvScalar;
import com.googlecode.javacv.cpp.opencv_core.CvSeq;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import com.googlecode.javacv.cpp.opencv_objdetect.CvHaarClassifierCascade;
import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_highgui.*;
import static com.googlecode.javacv.cpp.opencv_objdetect.*;
import java.awt.Button;
import java.io.File;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import com.googlecode.javacv.cpp.opencv_core.CvMat;
import com.googlecode.javacv.cpp.opencv_highgui;
//import opencv_highgui;
public class Form1 {
static private final String newline = "\n";
JButton openButton, saveButton;
JTextArea log;
JFileChooser fc;
String myFileName = "";
//Load haar classifier XML file
public static final String XML_FILE =
"resources/!--master--haarcascade_frontalface_alt_tree.xml";
private JFrame frame;
//Detect for face using classifier XML file
public static void detect(IplImage src){
//Define classifier
CvHaarClassifierCascade cascade = new CvHaarClassifierCascade(cvLoad(XML_FILE));
CvMemStorage storage = CvMemStorage.create();
//Detect objects
CvSeq sign = cvHaarDetectObjects(
src,
cascade,
storage,
1.1,
3,
0);
cvClearMemStorage(storage);
int total_Faces = sign.total();
//Draw rectangles around detected objects
for(int i = 0; i < total_Faces; i++){
CvRect r = new CvRect(cvGetSeqElem(sign, i));
cvRectangle (
src,
cvPoint(r.x(), r.y()),
cvPoint(r.width() + r.x(), r.height() + r.y()),
CvScalar.RED,
2,
CV_AA,
0);
}
//Display result
cvShowImage("Result", src);
cvWaitKey(0);
}
/**
* Create the application.
*/
public Form1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
JLabel Label1 = new JLabel(" ");
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 301, 222);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnDetect = new JButton("Detect");
btnDetect.setVerticalAlignment(SwingConstants.TOP);
btnDetect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//IplImage img = cvLoadImage("resources/lena.jpg");
IplImage img = cvLoadImage(myFileName);
CvMat myImg = Highgui.imread(myFileName);
detect(img);
}
});
frame.getContentPane().add(btnDetect, BorderLayout.SOUTH);
Label1.setHorizontalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(Label1, BorderLayout.CENTER);
JButton btnNewButton = new JButton("Open");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser fileopen = new JFileChooser();
int ret = fileopen.showDialog(null, "Открыть файл");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fileopen.getSelectedFile();
myFileName = file.getAbsolutePath();
Label1.setText(myFileName);
}
}
});
frame.getContentPane().add(btnNewButton, BorderLayout.NORTH);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Form1 window = new Form1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
//Load image
//IplImage img = cvLoadImage("resources/lena.jpg");
//detect(img);
}
}
External JARs: http://pasteboard.co/jwqNHC9.png
Full project in ZIP
I've also followed all steps from here: http://opencvlover.blogspot.in/2012/04/javacv-setup-with-eclipse-on-windows-7.html
Any help will be appreciated.
Mat m = Highgui.imread(myFileName); is from the builtin opencv java wrappers , not from javacv ( which is a independant, 3rd party wrapper ).
unfortunately, both concurrent apis are pretty incompatible, as javacv is wrapping the outdated c-api, and the opencv ones are wrapping the more modern c++ api.
Ok so I have a text editor made that can so far create new files and open files using jFileChooser.
What I am trying to do is get the saving of files to work.
Everytime you add or open a few file it adds a new tab to the tabbedpane and the name will be either file 1 etc or the name of the file opened.
When you click the save button the save dialog opens up
int returnVal = fileChooser.showSaveDialog(this);
I want the name on the tab to be inserted to the name of file field.
Also how do I make a file of the current selected tabs textarea? I have tried this but its a no go:
int index = tabbedPane.getSelectedIndex();
Component c = tabbedPane.getComponentAt(index);
JTextArea a = (JTextArea) c;
System.out.println(a.getText());
File file = new File(a.getText());
fileChooser.setSelectedFile(file);
So I need to make a file of the string in the textArea I guess.
Following up #Andrew's answer, here is a snippet illustrating what he meant. I took the liberty to rather use a OutputStreamWriter than a FileWriter because this allows you to choose the charset used to write the file, which is something that you usually want to control and not rely on the "random" default platform charset.
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class TestTextArea {
private JTextArea textArea;
private JButton save;
protected void initUI() {
JFrame frame = new JFrame(TestTextArea.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea = new JTextArea(24, 80);
save = new JButton("Save to file");
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
saveToFile();
}
});
frame.add(new JScrollPane(textArea));
JPanel buttonPanel = new JPanel();
buttonPanel.add(save);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setSize(500, 400);
frame.setVisible(true);
}
protected void saveToFile() {
JFileChooser fileChooser = new JFileChooser();
int retval = fileChooser.showSaveDialog(save);
if (retval == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (file != null) {
if (!file.getName().toLowerCase().endsWith(".txt")) {
file = new File(file.getParentFile(), file.getName() + ".txt");
}
try {
textArea.write(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
Desktop.getDesktop().open(file);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestTextArea().initUI();
}
});
}
}
An easy way is to use JTextComponent.write(Writer). JTextArea extends JTextComponent.
For the Writer use a FileWriter.
You need to, some how associate the File that was opened with the tab. That way, you can look up the File associated based on the selected tab.
Something like HashMap<Component, File> for example
following this question, error message with JButton and JFileChooser, I want to have a JButton to browse a file using JFileChooser. This is the code we have:
package main;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
private static Component frame;
private static String fullPath;
public static void main(String args[]) throws FileNotFoundException, IOException {
Date start_time = new Date();
try {
GridBagConstraints gbc = new GridBagConstraints();
JButton inputButton = new JButton("Browse input file");
final JFileChooser inputFile = new JFileChooser();
inputFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
JPanel myPanel = new JPanel(new GridBagLayout());
myPanel.add(inputButton, gbc);
inputButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser inputFile = new JFileChooser();
inputFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (inputFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File file1 = inputFile.getSelectedFile();
String fullpathTemp = (String) file1.getAbsolutePath();
fullpathTemp = fullPath;
}
}
});
Date stop_time = new Date();
double etime = (stop_time.getTime() - start_time.getTime()) / 1000.;
System.out.println("\nElapsed Time = " + etime + " seconds\n");
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
} finally {
}
}
}
The problem is that after clicking on button "Browse the input file" and choose the file, as soon as I click on OK, I get this error message:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at main.Main$1.actionPerformed(Main.java:195)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
You've declared inputFile 3 times
Once as a static class variable
private static JFileChooser inputFile;
Then in you're main method
final JFileChooser inputFile = new JFileChooser();
// this can't possible compile
inputfile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
And then in your ActionListener
inputButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser inputFile = new JFileChooser();
inputFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (inputFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File file1 = inputFile.getSelectedFile();
String fullpathTemp = (String) file1.getAbsolutePath();
fullpathTemp = fullPath;
}
}
});
It should be possible for any of these to interfere with each other that would produce your NullPointerException that I can see, but given the fact that your code example won't actually compile I can only imagine we're not seeing everything