What I am trying to do is open up a JFilechooser that filters jpeg,gif and png images, then gets the user's selection and inserts it into the JEditorPane. Can this be done? or am i attempting something impossible? Here is a sample of my program.(insert is a JMenuItem and mainText is a JEditorPane)
insert.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JFileChooser imageChooser = new JFileChooser();
imageChooser.setFileFilter(new FileNameExtensionFilter("Image Format","jpg","jpeg","gif","png"));
int choice = imageChooser.showOpenDialog(mainText);
if (choice == JFileChooser.APPROVE_OPTION) {
mainText.add(imageChooser.getSelectedFile());
}
}
});
What i tried to do is use the add method, i know it's wrong but just to give you an idea of what i'm trying to do.
Before you complain, i'm sorry about the code formatting, i don't really know all the conventions of what is considered good or bad style.
Thank you very much.
This is the part of the code i use to save the html file.
else if (e.getSource() == save) {
JFileChooser saver = new JFileChooser();
saver.setFileFilter(new FileNameExtensionFilter(".html (webpage format)" , "html"));
int option = saver.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter(saver.getSelectedFile().getPath()));
out.write(mainText.getText());
out.close();
} catch (Exception exception) {
System.out.println(exception.getMessage());
}
}
}
Its easier to just use a JTextPane. Then you can use insertIcon(...) anywhere in the text.
Edit:
I have never had much luck trying to manipulate HTML but I've used code like the following before:
HTMLEditorKit editorKit = (HTMLEditorKit)textPane.getEditorKit();
text = "hyperlink";
editorKit.insertHTML(doc, textPane.getCaretPosition(), text, 0, 0, HTML.Tag.A);
So presumably the code would be similiar for the IMG tag.
This should do it:
mainText.setContentType("text/html");
String image = String.format("<img src=\"%s\">", imageChooser.getSelectedFile());
mainText.setText(image);
Related
I have a Problem with my saving Loop of my .txt-Files. It always saves the last File twice (if I put in 2 for the for loop)
Currently I tried using int writingLength = fc.getSelectedFiles().length;, which then results in
no saving Option in total. Appreciate any thought that could help me to solve my problem, since I'm fairly new to Java.
Here the whole code snipped to give a better overview of my code:
private void prepareTDDExcelDoc() {
fc.setMultiSelectionEnabled(true);
fc.resetChoosableFileFilters();
fc.setAcceptAllFileFilterUsed(false);
final FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel document (*.csv)", "csv");
fc.setFileFilter(filter);
int writingLength = fc.getSelectedFiles().length;
for(int i=0;i<writingLength;i++) {
final String suggestedFilename = reportName.replaceAll("\\W+", "_") + ".xlsx";
fc.setSelectedFile(new File(suggestedFilename));
final int returnVal = fc.showSaveDialog(frmCognosTddBuilder);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
enableUserInteraction(false);
outputFilename = fc.getSelectedFile().getCanonicalPath();
final ExportedOutputInterface exportedExcelOutput = new ExcelOutput(this, outputFilename);
progressMonitor = new ProgressMonitor(getFrame(), "Builing TDD", "", 0, 100);
task = new ReportDataExtracter(this, exportedExcelOutput);
task.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(final PropertyChangeEvent evt) {
if ("progress" == evt.getPropertyName()) {
final int progress = (Integer) evt.getNewValue();
progressMonitor.setProgress(progress);
final String message = String.format("Completed %d%%.\n", progress);
progressMonitor.setNote(message);
if (progressMonitor.isCanceled() || task.isDone()) {
if (progressMonitor.isCanceled()) {
task.cancel(true);
} else {
progressMonitor.close();
}
}
}
}
});
task.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
I see this "reportName" variable, which doesn't appear to be declared in this function, so I suppose it's an instance variable. In any case, you're doing a small transformation on that value and setting it as the output file name for ALL the entries of the list. I imagine the output file is only ever going to have the last file in the list.
It's really helpful to execute code like this in the debugger, so you can step through it and watch the values of variables. As your code is creating UI components, you'll probably need to use two displays. It's been a few years since I had to debug UI code.
Can anyone help obtaining text from "Font Patterns (FNG)" field from an AFP file. Is there any library (preferably Java) which can be used for this task?
Thank you,
You can try afplib. It has some sample code that dumps all structured fields (org.afplib.samples.DumpAFP). It produces output like this:
...
FNG number:47,offset:49787,id:13889161,length:8201,rawData:null,charset:null,PatData:[B#4e3958e7,
FNG number:48,offset:57988,id:13889161,length:8201,rawData:null,charset:null,PatData:[B#77f80c04,
FNG number:49,offset:66189,id:13889161,length:8201,rawData:null,charset:null,PatData:[B#1dac5ef,
FNG number:50,offset:74390,id:13889161,length:6991,rawData:null,charset:null,PatData:[B#5c90e579,
EFN number:51,offset:81381,id:13871497,length:17,rawData:null,charset:null,RSName:C0EX0480,
You could use the binary array PatData to extract the font pattern like this:
try (AfpInputStream in = new AfpInputStream(
new BufferedInputStream(new FileInputStream(args[0])))) {
SF sf;
while((sf = in.readStructuredField()) != null) {
if(sf instanceof FNG) {
byte[] pattern = ((FNG)sf).getPatData();
}
}
} catch (IOException e) {
e.printStackTrace();
}
I need to save information for my final project and need one little thing to complete it.
My Question is: How do I save a selected checkbox or radio button in notepad?
I know how to save any string-based information, but I don't know how to save the selected checkbox/radio button to my notepad - so, as I open it back and it will select it automatically. I tried if(chkE.isSelected() == true), but I don't know what to write to make it save into my notepad.
Thank you in advance!
Here is my code:
try {
JFileChooser flcFile = new JFileChooser("c:/");
int rep = flcFile.showSaveDialog(this);
File filesave = flcFile.getSelectedFile();
if (rep == JFileChooser.APPROVE_OPTION) {
try(FileWriter writer = new FileWriter(filesave)) {
//if(chkE.isSelected() == true){
//do stuff
//}
writer.write(String.valueOf(txtNom1.getText()));
writer.write("\r\n");
writer.write(String.valueOf(txtPre1.getText()));
writer.write("\r\n");
writer.write(String.valueOf(optoui.getText()));
writer.write("\r\n");
writer.write(String.valueOf(optoui.getText()));
writer.write("\r\n");
writer.write(String.valueOf(optnon.getText()));
writer.write("\r\n");
writer.write(String.valueOf(chkanimaux.getText()));
writer.write("\r\n");
writer.write(String.valueOf(chkChauffer.getText()));
writer.write("\r\n");
writer.write(String.valueOf(chkE.getText()));
writer.write("\r\n");
writer.write(String.valueOf(txttel.getText()));
writer.write("\r\n");
writer.close();
}
}
} catch(IOException err1) {
}
English isn't my native language.
It is hard to tell what you really want to do from your question. As I understand it, you have a dialog with different input elements that you want to save and then reload.
Since the value of a checkbox is a boolean value, just store the String representation of that value like this:
writer.write(String.valueOf(chkE.isSelected()));
When reading back, you convert the text by using
chkE.setSelected(Boolean.valueOf(text));
However, you should add some error handling code.
I am writing a code in java to display text file in JTextArea. Can Anyone tell me what is wrong with this code. It is saying cannnot find symbol file..
FOpen.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
final JFileChooser FileDialog = new JFileChooser();
int ReturnValue=FileDialog.showOpenDialog(null);
if(ReturnValue==JFileChooser.APPROVE_OPTION)
{
File file = FileDialog.getSelectedFile();
}
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while(line!=null)
{
WritingArea.append(line+"\n");
line=in.readLine();
}
}
});
Look up 'variable scope/visibility'. Since the file attribute is declared inside the brackets, only code in that code block has access to it.
Other notes/tips:
If ReturnValue!= .. it does not make much sense to continue with the rest, so the rest of that method should also be inside the brackets.
That code will bloc the EDT for as long as it takes to load the File. Don't block the EDT (Event Dispatch Thread) - the GUI will 'freeze' when that happens. Instead of calling Thread.sleep(n) implement a Swing Timer for repeating tasks or a SwingWorker for long running tasks. See Concurrency in Swing for more details.
Please learn common Java naming conventions (specifically the case used for the names) for class, method & attribute names & use them consistently.
if WritingArea is a JTextComponent there is an easier way to load the data.
Always copy/paste error & exception output.
For better help sooner, post an SSCCE.
You really need to learn about scopes. Currently you File object is encapsulated in the if block's scope. If you want to use that File object anywhere else, it isn't allowed. So put everything into the if block, where they will be in the same scope as the File object
FOpen.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
final JFileChooser FileDialog = new JFileChooser();
int ReturnValue=FileDialog.showOpenDialog(null);
if(ReturnValue==JFileChooser.APPROVE_OPTION)
{
File file = FileDialog.getSelectedFile();
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while(line!=null)
{
WritingArea.append(line+"\n");
line=in.readLine();
}
}
}
});
Is it right to think that when you create a text file in Java, you are essentially creating a text file like the one that appears with programs like notepad?
I have a JComboBox menu with various selections. I also created a text file and had it so that the user selection will be written in the text file. So the question is, how can I have this text file that I've created to appear? (as a GUI or any other way...)
My Code:
static JFrame frame;
FileWriter f;
BufferedWriter bw;
int myAge;
String myStringAge;
for (int i = 1; i <= 100; ++i) {
ageList.add(i);
}
DefaultComboBoxModel modelAge = new DefaultComboBoxModel();
for (Integer i : ageList) {
modelAge.addElement(i);
}
JComboBox ageEntries = new JComboBox();
ageEntries.setModel(modelAge);
//Add ItemListener
ageEntries.addItemListener(new ageListener());
class ageListener implements ItemListener {
public void itemStateChanged(ItemEvent event){
myAge = (Integer) event.getItem();
myStringAge = Integer.toString(myAge);
try {
bw.write(myStringAge);
bw.close();
} catch (Exception e){
}
}
A text file is not a GUI. Use JTextArea to display text. Have a look at http://docs.oracle.com/javase/tutorial/uiswing/components/textarea.html
You can do so using JEditorPane. You might want to create a new JFrame for it. Don't forget to setContentType() to "text/plain". Then you can just create a FileReader for your file and pass it to the editor pane throught the read() method.
Start with Basic I/O. That should answer your question (and the next 9).