I have a applet program which reads data from an xml file and puts the elements in a list of movie objects. It then puts it in a JTable which has a custom table model to handle the data as well as a renderer to draw the title of the movie name into the table cells. I originally placed it in a JFrame and it worked perfectly as show in the image below.
However when I place it in a class which extends JApplet and call the getContentPane method it appears as this.
cells appear as "no programmes available" as the custom renderer writes it when the String movieName is "null".
Here is the applet code
public class BackEndApplet extends JApplet{
private ArrayList<Channel> al;
public void init() {
setUp();
try{
SwingUtilities.invokeLater(new Runnable(){
public void run(){
createGUI();
}
});
} catch (Exception e){
System.err.println("Did not run successfully");
}
}
private void setUp(){
//parse xml file into Java
String fileName = "XMLFiles/bondFilms.xml";
MovieParser movieParser = new MovieParser();
movieParser.parseMovie(fileName);
//sort movie list to channel and sort by time
MovieChannelSorter mcSorter = new MovieChannelSorter();
mcSorter.sortMovieList(movieParser.getMovieList());
//retrieves channels from channel sorter
al = mcSorter.getChannels();
}
private void createGUI(){
ProgrammeGuidePanel gPane = new ProgrammeGuidePanel(al);
gPane.setOpaque(true);
setContentPane(gPane);
}
}
and this my Main Panel code:
public class ProgrammeGuidePanel extends JPanel{
private ArrayList <Channel> channels;
private String [] channelNames = {"Sean Connery",
"George Lazenby",
"Roger Moore",
"Timothy Dalton",
"Pierce Brosnan",
"Daniel Craig"};
private String [] pHeader = {"Slot 1","Slot 2","Slot 3","Slot 4"};
private CustomTModel customModel;
public ProgrammeGuidePanel(ArrayList <Channel> ch) {
super(new BorderLayout());
channels = ch;
//create title table
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Channels",channelNames);
JTable channelTable = new JTable(model);
channelTable.setRowSelectionAllowed(false);
//Create and fill Programme table
customModel = new CustomTModel(channels,pHeader);
JTable programmeTable = new JTable(customModel);
//set up panel for titles
JScrollPane scroller1 = new JScrollPane(channelTable);
scroller1.setMinimumSize(new Dimension(100,500));
scroller1.setPreferredSize(new Dimension(150,250));
//set up panel for movies
JScrollPane scroller2 = new JScrollPane(programmeTable);
//scroller1.setMinimumSize(new Dimension(100,100));
//scroller1.setPreferredSize(new Dimension(300,250));
//add scrollPanes to main panel
add(scroller1,BorderLayout.WEST);
add(scroller2,BorderLayout.CENTER);
}
}
I also tried using appletviewer in command line but it doesnt appear when i run the html file.
I'm completely stumped at why its doing it. So any help will be greatly appreciated.
UPDATE:
I may have figured out why its displaying the wrong data. In my Sax parser I was using
InputStream xmlInput = new FileInputStream(fileName);
I tried creating an executable jar in eclipse and got the results of picture 2. So I assume my parser class was returning a list full of empty objects since it couldn'f find the xml file. I did some research and saw I had to use
InputStream xmlInput = getClass().getResourceAsStream("file.xml");
However it keeps returning null when I run it i eclipse. I've looked into some of the same questions in stackoverflow but I cant seem to get my head around on how to implement getResourceAsStream(). I've also used the getClassLoader() method and setting an absolute path with "/" but to no avail.
Here's an SSCCE of my parser.
public class XMLParser {
public static void main(String [] args){
XMLParser x = new XMLParser();
x.parse();
}
public void parse(){
SAXParserFactory factory = SAXParserFactory.newInstance();
try{
InputStream xmlInput = getClass().getResourceAsStream("file.xml");
//InputStream xmlInput = new FileInputStream("file.xml");
SAXParser saxParser = factory.newSAXParser();
Handler handler = new Handler();
saxParser.parse(xmlInput,handler);
for(int i = 0;i<handler.plist.size();i++){
System.out.println(handler.plist.get(i));
}
} catch (Throwable err){
err.printStackTrace();
}
}
private class Handler extends DefaultHandler{
ArrayList<String>plist = new ArrayList<String>();
private String name;
private String lastName;
private boolean bname;
private boolean blname;
#Override
public void startElement(String uri,String localName, String qName,
Attributes attributes) throws SAXException{
System.out.println("end element: " + qName);
if (qName.equalsIgnoreCase("NAME")) {
bname = true;
}
if (qName.equalsIgnoreCase("LASTNAME")) {
blname = true;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
System.out.println("end element: " + qName);
}
#Override
public void characters(char ch[], int start, int length)
throws SAXException {
if(bname){
name = new String(ch,start,length);
plist.add(name);
bname = false;
}
if(blname){
lastName = new String(ch,start,length);
plist.add(lastName);
blname = false;
}
}
}
}
Here's what the structure looks like in Eclipse
Related
I am able to create 10 threads. But the problem is when I try to access individual page using those threads in parallel style. I have tried putting the private static PDFTextStripper instance into synchronized block as well. Still I get below exception:
COSStream has been closed and cannot be read. Perhaps its enclosing PDDocument has been closed?
trying to print first word from each page for first 10 pages, but its not working. This is my first experiment with Multithreading and PDF reading. Any help would be much appreciated.
public class ReadPDFFile extends Thread implements FileInstance {
private static String fileLocation;
private static String fileNameIV;
private static String userInput;
private static int userConfidence;
private static int totalPages;
private static ConcurrentHashMap<Integer, List<String>> map = null;
private Iterator<PDDocument> iteratorForThisDoc;
private PDFTextStripperByArea text;
private static PDFTextStripper pdfStrip = null;
private static PDFParser pdParser = null;
private Splitter splitter;
private static int counter=0;
private StringWriter writer;
private static ReentrantLock counterLock = new ReentrantLock(true);
private static PDDocument doc;
private static PDDocument doc2;
private static boolean flag = false;
List<PDDocument> listOfPages;
ReadPDFFile(String filePath, String fileName, String userSearch, int confidence) throws FileNotFoundException{
fileLocation= filePath;
fileNameIV = fileName;
userInput= userSearch;
userConfidence = confidence;
System.out.println("object created");
}
#Override
public void createFileInstance(String filePath, String fileName) {
List<String> list = new ArrayList<String>();
map = new ConcurrentHashMap<Integer, List<String>>();
try(PDDocument document = PDDocument.load(new File(filePath))){
doc = document;
pdfStrip = new PDFTextStripper();
this.splitter = new Splitter();
text = new PDFTextStripperByArea();
document.getClass();
if(!document.isEncrypted()) {
totalPages = document.getNumberOfPages();
System.out.println("Number of pages in this book "+totalPages);
listOfPages = splitter.split(document);
iteratorForThisDoc = listOfPages.iterator();
}
this.createThreads();
/*
* for(int i=0;i<1759;i++) { readThisPage(i, pdfStrip); } flag= true;
*/
}
catch(IOException ie) {
ie.printStackTrace();
}
}
public void createThreads() {
counter=1;
for(int i=0;i<=9;i++) {
ReadPDFFile pdf = new ReadPDFFile();
pdf.setName("Reader"+i);
pdf.start();
}
}
public void run() {
try {
while(counter < 10){
int pgNum= pageCounterReentrant();
readThisPage(pgNum, pdfStrip);
}
doc.close();
}catch(Exception e) {
}
flag= true;
}
public static int getCounter() {
counter= counter+1;
return counter;
}
public static int pageCounterReentrant() {
counterLock.lock();
try {
counter = getCounter();
} finally {
counterLock.unlock();
}
return counter;
}
public static void readThisPage(int pageNum, PDFTextStripper ts) {
counter++;
System.out.println(Thread.currentThread().getName()+" reading page: "+pageNum+", counter: "+counter);
synchronized(ts){
String currentpageContent= new String();
try {
ts.setStartPage(pageNum);
ts.setEndPage(pageNum);
System.out.println("-->"+ts.getPageEnd());
currentpageContent = ts.getText(doc);
currentpageContent = currentpageContent.substring(0, 10);
System.out.println("\n\n "+currentpageContent);
}
/*
* further operations on currentpageContent here
*/
catch(IOException io) {
io.printStackTrace();
}finally {
}
}
}
public static void printFinalResult(ConcurrentHashMap<Integer, List<String>> map) {
/*
* simply display content of ConcurrentHashMap
*/
}
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
System.out.println("Search Word");
userInput = sc.nextLine();
System.out.println("Confidence");
userConfidence = sc.nextInt();
ReadPDFFile pef = new ReadPDFFile("file path", "file name",userInput, userConfidence);
pef.createFileInstance("file path ","file name");
if(flag==true)
printFinalResult(map);
}
}
If I read each page in a for loop sequentially using one thread then it is able to print the content, but not with multithreads. You can see that code commented in void createFileInstance(), after this.createThreads(); I wish to get string content of each pdf page individually, using threads, and then perform operation on it. I have the logic to collect each word token into List but before moving ahead, I need to solve this problem.
Your code looks like this:
try(PDDocument document = PDDocument.load(new File(filePath))){
doc = document;
....
this.createThreads();
} // document gets closed here
...
//threads that do text extraction still running here (and using a closed object)
These threads use doc to extract the text (ts.getText(doc)). However at this time, the PDDocument object is already closed due to the usage of try-with-resources, and its streams also closed. Thus the error message "Perhaps its enclosing PDDocument has been closed?".
You should create the thread before closing the document, and waiting for all threads to finish before closing it.
I'd advise against using multithreading on one PDDocument, see PDFBOX-4559. You could create several PDDocuments and then extract on these, or not do it at all. Text extraction works pretty fast in PDFBox (compared to rendering).
I have an issue to print a PDF using java. I know that Java doesn't support print PDF natively cause java doesn't have a PDF renderer. So to solve this problem I'm using a PDFRenderer library and here is an example for printing with it:
File f = new File("myfile.pdf");
FileInputStream fis = new FileInputStream(f);
FileChannel fc = fis.getChannel();
ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0,
fc.size());
PDFFile pdfFile = new PDFFile(bb);
PDFPrintPage pages = new PDFPrintPage(pdfFile);
PrinterJob pjob = PrinterJob.getPrinterJob();
PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
pjob.setJobName(f.getName());
pjob.setPrintService(mPrintService);
Book book = new Book();
book.append(pages, pf, pdfFile.getNumPages());
pjob.setPageable(book);
pjob.print();
It works fine, but I need some way to get status of my printer job. I need to know when my printer job was finished that I can start another. Java API has a good solution with DocPrintJob and PrintJobListener but I need to use PrinterJob for my PDF printing. So how I can listen the job status from my PrinterJob like it does in DocPrintJob?
javafx.print
Enum PrinterJob.JobStatus
java.lang.Object
java.lang.Enum<PrinterJob.JobStatus>
javafx.print.PrinterJob.JobStatus
public static PrinterJob.JobStatus[] values()
Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows:
for (PrinterJob.JobStatus c : PrinterJob.JobStatus.values())
System.out.println(c);
For anyone dealing with this problem here in 2020, I found a pretty slick way of printing PDF files while being able to monitor the print job, without using JavaFX - as people don't seem to be too hip on using JavaFX for printing PDF files, and I'm not to keen on object node printing, as it is really diffiult to get the print out to look like a normal document in my opinion ... JavaFX seems to like the idea of - basically - screen shotting a portion of your form, then rendering that snap shot as a graphic, then you have to scale it for the printer and it just ends up looking kinda weird ... whereas taking something like nicely formatted HTML, and printing it through a PDF library is really clean, and really fast. So here is what I found:
First, I used this library, which is free, to render my HTML String into a PDF file. Here is the Maven source for the library:
<dependency>
<groupId>org.icepdf.os</groupId>
<artifactId>icepdf-core</artifactId>
<version>6.2.2</version>
</dependency>
And here is my code for rendering the PDF:
String docPath = "/Users/michael/Documents/JavaFile.pdf";
String html = "<html>Any HTML Code you want, including embedded CSS for a really clean look</html>
OutputStream outputStream = new FileOutputStream(docPath);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html);
renderer.layout();
renderer.createPDF(outputStream);
outputStream.close();
And here is my class for printing the PDF ... its a little lengthy, but VERY simple, and it uses native Java API which is nice (i'm using 1.8):
import javafx.application.Platform;
import javafx.scene.control.Label;
import java.io.*;
import javax.print.*;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;
public class PrintHandler {
private void delay(int msec) {
try {
Thread.sleep(msec);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public PrintHandler (FileInputStream fis, Label statusLabel) {
this.statusLabel = statusLabel;
this.fis = fis;
}
private FileInputStream fis;
private Label statusLabel;
private String state;
public void startPrintJob () {
try {
Platform.runLater(()->statusLabel.setText("PRINTING"));
delay(5000);
InputStream is = new BufferedInputStream(this.fis);
DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob printJob = service.createPrintJob();
JobMonitor monitor = new JobMonitor();
printJob.addPrintJobListener(monitor);
Doc doc = new SimpleDoc(is, flavor, null);
printJob.print(doc, null);
monitor.waitForJobCompletion();
is.close();
} catch (PrintException | IOException e) {
e.printStackTrace();
}
}
private class JobMonitor extends PrintJobAdapter {
private boolean notify = false;
final int DATA_TRANSFERRED = 10;
final int JOB_COMPLETE = 11;
final int JOB_FAILED = 12;
final int JOB_CANCELED = 13;
final int JOB_NO_MORE_EVENTS = 14;
final int JOB_NEEDS_ATTENTION = 15;
private int status;
#Override
public void printDataTransferCompleted(PrintJobEvent pje) {
status = DATA_TRANSFERRED;
markAction();
}
#Override
public void printJobCompleted(PrintJobEvent pje) {
status = JOB_COMPLETE;
markAction();
}
#Override
public void printJobFailed(PrintJobEvent pje) {
status = JOB_FAILED;
markAction();
}
#Override
public void printJobCanceled(PrintJobEvent pje) {
status = JOB_CANCELED;
markAction();
}
#Override
public void printJobNoMoreEvents(PrintJobEvent pje) {
status = JOB_NO_MORE_EVENTS;
markAction();
}
#Override
public void printJobRequiresAttention(PrintJobEvent pje) {
status = JOB_NEEDS_ATTENTION;
markAction();
}
private void markAction() {
synchronized (JobMonitor.this) {
notify = true;
JobMonitor.this.notify();
}
}
public synchronized void waitForJobCompletion() {
Runnable runner = ()->{
boolean keepRunning = true;
while (keepRunning) {
try {
while (!notify) {
wait();
}
switch(this.status){
case DATA_TRANSFERRED:
state = "DATA_TRANSFERRED";
break;
case JOB_COMPLETE:
state = "JOB_FINISHED";
keepRunning = false;
break;
case JOB_FAILED:
state = "JOB_FAILED";
keepRunning = false;
break;
case JOB_CANCELED:
state = "JOB_CANCELED";
keepRunning = false;
break;
case JOB_NO_MORE_EVENTS:
state = "JOB_COMPLETE";
keepRunning = false;
break;
case JOB_NEEDS_ATTENTION:
state = "JOB_NEEDS_ATTENTION";
break;
}
Platform.runLater(()->statusLabel.setText(state));
delay(5000);
notify = false;
}
catch (InterruptedException e) {}
}
delay(5000);
Platform.runLater(()->statusLabel.setText(""));
};
Thread monitor = new Thread(runner);
monitor.start();
}
}
}
And here is how I invoke the class to print and monitor the job:
FileInputStream fis = new FileInputStream(docPath);
Label jobStatus = new Label(); //Already in my AnchorPane but included here for clarity
new PrintHandler(fis,jobStatus).startPrintJob();
I am building a java clone code detector in swing that implemented the ANTLR. This is the Screenshot :
https://www.dropbox.com/s/wnumgsjmpps33v5/SemogaYaAllah.png
if you see the screenshot, there are a main file that compared to another files. The way that I do is compared thats token main file to another file. The problem is, I am failed to get the ID Lexemes or tokens from my lexer class.
This is my ANTLR3JavaLexer
public class Antlr3JavaLexer extends Lexer {
public static final int PACKAGE=84;
public static final int EXPONENT=173;
public static final int STAR=49;
public static final int WHILE=103;
public static final int MOD=32;
public static final int MOD_ASSIGN=33;
public static final int CASE=58;
public static final int CHAR=60;
I ve created a JavaParser.class like this to use that lexer:
public final class JavaParser extends AParser { //Parser is my Abstract Class
JavaParser() {
}
#Override
protected boolean parseFile(JCCDFile f, final ASTManager treeContainer)throws ParseException, IOException {
BufferedReader in = new BufferedReader(new FileReader(f.getFile()));
String filePath = f.getNama(); // getName of file
final Antlr3JavaLexer lexer = new Antlr3JavaLexer();
lexer.preserveWhitespacesAndComments = false;
try {
lexer.setCharStream(new ANTLRReaderStream(in));
} catch (IOException e) {
e.printStackTrace();
return false;
}
//This is the problem
//When I am activated this code pieces, I get the output like this
https://www.dropbox.com/s/80uyva56mk1r5xy/Bismillah2.png
/*
StringBuilder sbu = new StringBuilder();
while (true) {
org.antlr.runtime.Token token = lexer.nextToken();
if (token.getType() == Antlr3JavaLexer.EOF) {
break;
}
sbu.append(token.getType());
System.out.println(token.getType() + ": :" + token.getText());
}*/
final CommonTokenStream tokens = new CommonTokenStream();
tokens.setTokenSource(lexer);
tokens.LT(10); // force load
// Create the parser
Antlr3JavaParser parser = new Antlr3JavaParser(tokens);
StringBuffer sb = new StringBuffer();
sb.append(tokens.toString());
DefaultTableModel model = (DefaultTableModel) Main_Menu.jTable2.getModel();
List<final_tugas_akhir.Report2> theListData = new ArrayList<Report2>();
final_tugas_akhir.Report2 theResult = new final_tugas_akhir.Report2();
theResult.setFile(filePath);
theResult.setId(sb.toString());
theResult.setNum(sbu.toString());
theListData.add(theResult);
for (Report2 report : theListData) {
System.out.println(report.getFile());
System.out.println(report.getId());
model.addRow(new Object[]{
report.getFile(),
report.getId(),
report.getNum(),
});
}
// in CompilationUnit
CommonTree tree;
try {
tree = (CommonTree) parser.compilationUnit().getTree();
DOTTreeGenerator gen = new DOTTreeGenerator();
StringTemplate st = gen.toDOT(tree);
} catch (RecognitionException e) {
e.printStackTrace();
return false;
}
walkThroughChildren(tree, treeContainer, parser.getTokenStream()); //this is my method to check the similiar tokens
in.close();
this.posisiFix(treeContainer); //fix position
return true;
}
Once again, this is the error code my java program link: https://www.dropbox.com/s/80uyva56mk1r5xy/Bismillah2.png.
The tokens always give me a null value.
I have an XML file containing nested records. I have to get records from the file and write to an Excel file. Right now, the file I have produced is a flat file. (I used Apache POI to write to the Excel file). I need it to maintain the hierarchical information, such that the nested records are indented.
My XML file looks like:
<node>
<id>123</id>
<label>ABC</label>
<node>
<id>456</id>
<label>DEF</label>
....... so on
My current Excel looks like :
I need something like (representing the hierarchy in XML file):
Does anyone have any experience with something like that? I would really appreciate the help.
If you are willing to test out Sax Parser I may have a solution you could try. Below is the class I have used, it contains a Default Handler for the SAXParser as well as the code I used to format the xml file before inputting it to the xlsx file. It looks a tad hefty and so I have tried to add comments wherever possible to try and make it understandable.
public class SO2 {
private SO2(File xml){
wb = new XSSFWorkbook(); //Workbook to create
sheet = wb.createSheet(); //Sheet to write to
try {
SO2.retrieveSaxParser().parse(xml, SO2.retrieveHandler()); //Begin parse
Path file = Paths.get(System.getProperty("user.home"), "Desktop", "XMLTest.xlsx"); //Where to write file
wb.write(new FileOutputStream(file.toString()));
} catch (SAXException | IOException | ParserConfigurationException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
System.exit(0);
}
protected static void instertUpdate(String data, int columnNum, int rowNum) {//Method to add to spreadsheet
/*The below writes to the file, the row if statements are there to stop the method
* overwriting any rows already created
*/
if(row != null){
if(row.getRowNum() != rowNum){
row = sheet.createRow(rowNum);
}
} else {
row = sheet.createRow(rowNum);
}
cell = row.createCell(columnNum);//Make our cell
cell.setCellValue(data);//Write to it
}
private static SAXParser retrieveSaxParser() throws ParserConfigurationException, SAXException{
return SAXParserFactory.newInstance().newSAXParser();//Get parser
}
private static DefaultHandler retrieveHandler() {
DefaultHandler handler = new DefaultHandler(){//Handler with methods required for parsing xml
#Override
public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
if(startWasPrevious == true){//Start indenting after the first element tag processed
indent++;
}
rowNumber++;//Move row down for each tag
columnNumber = indent; //Cell number set to current indent level
SO2.instertUpdate("<" + qName + ">", columnNumber, rowNumber);//Insert
startWasPrevious = true; //For formatting
previous = startTag;//For formatting
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(startWasPrevious == false){//For removal of indentation
indent--;
}
if(!previous.equals("text")){//If text wasn't last part parsed then set column to indent
columnNumber = indent;
} else{//If text was processed last move cell across
columnNumber++;
}
if(previous.equals("end")){//Move to a newline if last parsed element was an ending tag
rowNumber++;
}
if(startWasPrevious == false){ //If there was no text previously
SO2.instertUpdate("</" + qName + ">", columnNumber, rowNumber);
} else { //If there was text then this will be enclosing end tag
SO2.instertUpdate("</" + qName + ">", columnNumber, rowNumber);
}
startWasPrevious = false; //For formatting
previous = endTag;
}
#Override
public void characters(char ch[], int start, int length) throws SAXException {
String s = new String(ch, start, length).trim();//Get text
if(s.length() > 0){
columnNumber++; //Move column number along
SO2.instertUpdate(s, columnNumber, rowNumber);
previous = text;
}
}
};
return handler;
}
//Main
public static void main(String[] args) {
JFrame file = new JFrame("File choice. . .");
file.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
FileDialog dialog = new FileDialog(file, "Choose a file", FileDialog.LOAD);//Get XML File
dialog.setDirectory(Paths.get(System.getProperty("user.home")).resolve("Desktop").toString());
dialog.setFile("*.xml");
dialog.setVisible(true);
if(dialog.getFile() == null){
System.exit(0);
} else {
xmlFile = new File(dialog.getDirectory() + dialog.getFile());
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new SO2(xmlFile);
}
});
}
}
private static File xmlFile;
private static XSSFWorkbook wb;
private static Sheet sheet;
private static Row row;
private static Cell cell;
private static boolean startWasPrevious = false; //For formatting purposes
private static int rowNumber = -1; //Hold row number
private static int columnNumber = 0;//Hold number of cell to wtite to
private static int indent;//For indenting
private static String previous = "";//To know what was last processed
private static final String endTag = "end";//Values for previous to hold
private static final String text = "text";//Values for previous to hold
private static final String startTag = "start";//Values for previous to hold
}
This was the xml file I used:
<?xml version="1.0"?>
<empire>
<darkness>
<sith>
<title>Darth</title>
<name>Vader</name>
<power>Grip</power>
</sith>
<sith>
<title>Darth</title>
<name>Sidious</name>
<power>Lightning</power>
</sith>
</darkness>
Hope it helps,
good luck
in netbeans I've got a JFrame and a JavaClass. In my JFrame I have a combobox to select a file that will be used in the operations within the Java class.
Java class:
public class WekaTest {
public static BufferedReader readDataFile(String filename) {
BufferedReader inputReader = null;
try {
inputReader = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException ex) {
System.err.println("Ficheiro " + filename + " não encontrado");
}
return inputReader;
}
(...)
public static void main(String[] args) throws Exception {
JFrame1 form = new JFrame1();
form.setVisible(true);
BufferedReader datafile = readDataFile("weather.nominal.arff");
Instances data = new Instances(datafile);
data.setClassIndex(data.numAttributes() - 1);
(...)
}
}
What I need is, from the JFrame's combobox, to select a different datafile to read from. So, as I change the selected item in my combobox, I want to set my datafile as that value.
Here's the JFrame code:
public class JFrame1 extends javax.swing.JFrame {
public JFrame1() {
initComponents();
}
(...)
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jTextField1.setText(arffComboBox.getSelectedItem().toString());;
}
private void arffComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
(...)
}
How can I do this?
Make the following a private (or public) member:
private BufferedReader datafile = null;
Then do the read within the action listener you've assigned to the combobox:
private void arffComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
String pth = arffComboBox.getSelectedItem();
datafile = readDataFile(pth);
}
Then you can use datafile either in the listener or elsewhere as necessary.
Something like that should do what you're after.
EDIT
Given the new information, you're probably going to do best with a PropertyChangeListener that subscribes to the JFrame1 (form.addPropertyChangeListener) object and listens to PropertyChangeEvents that you fire from within your arffComboBoxActionPerformed method.
In the arffComboBoxActionPerformed:
private void arffComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
String pth = arffComboBox.getSelectedItem();
firePropertyChange('combo_changed', null, pth);
}
Then in the main:
JFrame1 form = new JFrame1();
form.setVisible(true);
form.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent pce) {
// Handle the change here
String pth = (String) pce.getNewValue();
BufferedReader datafile = readDataFile(pth);
Instances data = new Instances(datafile);
data.setClassIndex(data.numAttributes() - 1);
(...)
}
});