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);
(...)
}
});
Related
I am calling class guibuilder from my class batchrun. code for batchrun is :-
public class batchrun {
public static String md5gen(String a) throws NoSuchAlgorithmException
{
MessageDigest m= MessageDigest.getInstance("MD5");
m.reset();
m.update(a.getBytes());
byte[] digest=m.digest();
BigInteger bigInt = new BigInteger(1,digest);
String hashtext = bigInt.toString(16);
while(hashtext.length() < 32 ){
hashtext = "0"+hashtext;
}
return hashtext;
}
private static String getInputAsString(InputStream is)
{
try(java.util.Scanner s = new java.util.Scanner(is))
{
return s.useDelimiter("\\A").hasNext() ? s.next() : "";
}
}
public static void main(String[] args) throws InterruptedException {
try {
guibuilder.main(args);
guibuilder gb=new guibuilder();
String fg=guibuilder.antd;
String arg1=gb.arg;
String userinp1=gb.userinp;
System.out.println("FG="+fg+" arg1="+arg1+" userinp="+userinp1);
Process pan = Runtime.getRuntime().exec(new String[] {"C:\\test1.bat",arg1,fg});
pan.waitFor();
String extra="\\";
extra+=userinp1;
String patha=fg+extra;
ProcessBuilder pb = new ProcessBuilder("adb","shell","getprop","ro.csc.sales_code");
Process p=pb.start();
p.waitFor();
String stdout = getInputAsString(p.getInputStream());
String newstring=stdout.substring(0,3);;
String fn=fg+"\\"+newstring+".txt";
ZipFile zipFile = new ZipFile(patha);
Enumeration<?> enu = zipFile.entries();
int flag=0;
String so="so";
File file = new File(fn);
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
while (enu.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enu.nextElement();
String name = zipEntry.getName();
long size= zipEntry.getSize();
String extension= name.substring(name.lastIndexOf(".")+1,name.length());
if(extension.equals(so))
{
String plaintext=name+size;
String md5result=md5gen(plaintext);
System.out.println(name+" "+size+" "+md5result);
++flag;
}
}
if(flag==0)
System.out.println("fail");
}catch (IOException ex){
System.out.println(ex.getMessage());
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The code for guibuilder is
public class guibuilder {
private JFrame frame;
public static String antd;
public static String arg;
public static String userinp;
/**
* Launch the application.
* #return
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
guibuilder window = new guibuilder();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public guibuilder() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnExtract = new JButton("Extract");
btnExtract.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.dispose();
fchooser fc1=new fchooser();
antd=fc1.demo();
arg=JOptionPane.showInputDialog("Enter the apk path");
userinp=JOptionPane.showInputDialog("Enter the apk name");
}
});
btnExtract.setBounds(69, 55, 89, 23);
frame.getContentPane().add(btnExtract);
JButton btnCompare = new JButton("Compare");
btnCompare.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.dispose();
newjframe n = new newjframe();
n.setVisible(true);
}
});
btnCompare.setBounds(261, 55, 89, 23);
frame.getContentPane().add(btnCompare);
}
}
I want the program to wait for the execution of guibuilder before continuing with the code from batchrun. But in this code, i have not even selected the files in guibuilder and the program continues execution and System.out.println("FG="+fg+" arg1="+arg1+" userinp="+userinp1); this line is printed before i choose anything in guibuilder.
Your code shows that your java project has two main classes. one in batchrun class another is in guibuilder class. [from your statement guibuilder.main(args)]
Use only one main class in your project. This may fix your problem.
I think your guibuilder class has structure like this
class guibuilder{
...... //global variables
public static void main(String[] args){
......... //statments
}
}
Don't use two main method in a single project.
you need to structure your guibuilder class like this (shown below)
class guibuilder{
...... //global variables
public static void buildGui(){//you can use any method name here
......... //statments
}
}
to invoke this method from another class just use this statement
guibuilder.buildGui()
or, another way
class guibuilder{
...... //global variables
public void buildGui(){//you can use any method name here
......... //statments
}
}
to invoke this method from another class use this statement
guibuilder gui=new guibuilder();
gui.buildGui();
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
I've asked a similar question before, but realised the main issue at hand which I cannot solve:
Currently have an ArrayList called SundayList which is loaded as soon as the frame AddStudent is loaded (bit of GUI)
The Add Student class:
Edited
public class AddStudent extends javax.swing.JFrame {
public AddStudent() {
initComponents();
}
private void loadLists() throws IOException
{
//Creating the array of Activities to put into the ComboBoxes
File f = new File("Activities.dat");
sundayList = new ArrayList<>();
mondayList= new ArrayList<>();
tuesdayList= new ArrayList<>();
wednesdayList= new ArrayList<>();
thursdayList= new ArrayList<>();
try{
BufferedReader reader = new BufferedReader(new FileReader(f));
while(reader.ready())
{
String CDay = reader.readLine();
String CActivityName = reader.readLine();
String CSupervisor = reader.readLine();
String CLocation = reader.readLine();
String CPaid = reader.readLine();
String nothing = reader.readLine();
if(CDay.equals("Sunday"))
{
sundayList.add(CActivityName);
}
else if(CDay.equals("Monday"))
{
mondayList.add(CActivityName);
}
else if(CDay.equals("Tuesday"))
{
tuesdayList.add(CActivityName);
}
else if(CDay.equals("Wednesday"))
{
wednesdayList.add(CActivityName);
}
else if(CDay.equals("Thursday"))
{
thursdayList.add(CActivityName);
}
}
reader.close();
}
catch (IOException ex)
{
Logger.getLogger(StartUpFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
...
comboboxSunday = new javax.swing.JComboBox();
...
}
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AddStudent().setVisible(true);
}
});
}
For a start,I've tried to call the list SundayList into the combo box comboboxSunday to populate it, but only got the cannot find symbol error.
What do I need to do to make this possible?
Also, I plan on avoiding the mySQL involved method I've seen before, as I'm not familiar with it..
Current Coding for Combo box
The code automatically generated for the combo box by Netbeans is:
comboboxSunday = new javax.swing.JComboBox();
comboboxSunday.setModel(new javax.swing.DefaultComboBoxModel<>(sundayList.toArray(new String[sundayList.size()])));
The variable SundayList is limited to the scope of your constructor. Assuming you are creating your JComboBox in your initComponents method, you will not be able to access this variable.
You could however make SundayList a class member variable allowing you to use the variable accross methods. Also better to have a method to load data rather than having non-UI functionality in a UI constructor:
public class AddStudent {
private List<String> sundayList;
private List<String> mondayList;
...
private void loadLists() throws IOException {
sundayList = new ArrayList<>();
...
Then to add:
comboboxSunday.setModel(new DefaultComboBoxModel<>(sundayList.toArray(new String[sundayList.size()])));
Don't forget to call your new load method:
AddStudent addStudent = new AddStudent();
addStudent.loadLists();
addStudent.setVisible(true);
Aside: note that Java naming conventions indicate that variable start with a lowercase letter which would make SundayList sundayList.
I have looked at How to access resources in JAR file? and How do I copy a text file from a jar into a file outside of the jar? and many other questiions but couldnt actually get an answer. What I'm trying to do is copy contents of a file in res/CDC.txt that is in jar, to somewhere out of a jar. Now, on my computer it works but when I try it on different computer I get FileNotFoundException. So, I figured out why it works on mine. I have a CLASSPATH set to .;D:\myname\Java\JavaFiles where all my java files are located in packages. In "JavaFiles" directory there is also "res/CDC.txt". So, when I start my application, it first checks the current directory myapp.jar is located in for "res/CDC.txt", and then it checks "JavaFiles" and finds it. Other computers do not have it. So, this was my initial code:
public final class CT
{
//Other fields
private static CT ct;
private NTSystem nts;
private File f1;
private File f6;
private PrintWriter pw1;
private BufferedReader br1;
//Other fields
public static void main(String[] args)
{
try
{
showMessage("Executing program...");
ct = new CT();
ct.init();
ct.create();
ct.insertData();
//Other code
showMessage("Program executed!");
}
catch(Exception e)
{
showMessage("An exception occured! Program closed.");
e.printStackTrace();
System.exit(0);
}
}
private void init()
throws IOException
{
//Other initialization
nts = new NTSystem();
f1 = new File("C:\\Users\\" + nts.getName() + "\\blahblah");
f6 = new File("res\\CDC.txt");
br1 = new BufferedReader(new FileReader(f6));
//Other initialization
showMessage("Initialized");
}
private void create()
throws IOException
{
//Makes sure file/dir exists, etc
pw1 = new PrintWriter(new BufferedWriter(new FileWriter(f1)), true);
//Other Stuff
showMessage("Created");
}
private void insertData()
throws IOException
{
String line = br1.readLine();
while(line != null)
{
pw1.println(line);
line = br1.readLine();
}
//Other stuff
showMessage("Data inserted");
}
private static void showMessage(String msg)
{
System.out.println(msg);
}
}
which I changed to
public final class CT
{
//Other fields
private static CT ct;
private NTSystem nts;
private byte[] buffer;
private File f1;
private URL url1;
private FileOutputStream fos1;
private InputStream is1;
//Other fields
public static void main(String[] args)
{
try
{
showMessage("Executing program...");
ct = new CT();
ct.init();
ct.create();
ct.insertData();
//Other code
showMessage("Program executed!");
}
catch(Exception e)
{
showMessage("An exception occured! Program closed.");
e.printStackTrace();
System.exit(0);
}
}
private void init()
throws IOException
{
//Other initialization
nts = new NTSystem();
buffer = new byte[4096];
f1 = new File("C:\\Users\\" + nts.getName() + "\\blahblah");
url1 = getClass().getClassLoader.getResource("res\\CDC.txt"); //Also tried url1 = ct.getClass().getClassLoader.getResource("res\\CDC.txt"); or url1 = this.getClass().getClassLoader.getResource("res\\CDC.txt"); or url1 = CT.getClass().getClassLoader.getResource("res\\CDC.txt");
is1 = url1.openStream();
//Other initialization
showMessage("Initialized");
}
private void create()
throws IOException
{
//Makes sure file/dir exists, etc
pw1 = new PrintWriter(new BufferedWriter(new FileWriter(f1)), true);
//Other Stuff
showMessage("Created");
}
private void insertData()
throws IOException
{
int read = is1.read(buffer);
while(line != null)
{
fos1.write(buffer, 0, read);
read = is1.read(buffer);
}
//Other stuff
showMessage("Data inserted");
}
private static void showMessage(String msg)
{
System.out.println(msg);
}
}
And this time I always get NullPointerException. So, how to read folders and files that are within jar?
Thanks
You will want to use getSystemResourceAsStream() to read the contents from files in a jar.
This of course is assuming the file is actually on the classpath of the other users computers.
I created an interface that allows to add instances in an rdf file. I put the filepath in the readRDFfile parameter and the same filepath in Filewriter (in order to update the file when user add instances). But i'd like to allow user enter the name file he want to create when I execute the code. And FileWriter must take this file in parameter when user add instances.
My problem is that I don't know how to put the file that user has chosen and that was read in readRDFfile, in Filewriter parameter in order to be updated when he adds instances.
import java.util.*;
import java.util.List;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.ontology.*;
import com.hp.hpl.jena.ontology.impl.*;
import com.hp.hpl.jena.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.XSD;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
public class FamilyModel extends Frame
{
TextField[]tabTF=new TextField[4];
Button bAjout, bModifier, bSupprimer, bPrecedent, bSuivant, bValiderModif; //buttons Add, Remove, Previous, Next
OntModel model;
Onto onto;
int indice=0;
int p=0;
Resource p1;
Button creerBouton(String S, int x, int y)
{
Button b=new Button(S);
add(b);
b.setBounds(x,y,120,30);
return b;
}
void creerLabel(String etiquette, int x, int y)
{
Label la=new Label(etiquette);
la.setBounds(x,y,100,25);
add(la);
}
public FamilyModel ()
{
setLayout (null);
setBackground (Color.pink);
setBounds (100,200,900,450);
creerLabel("Prenom : ",10,50);
creerLabel("Nom : ",10,100);
creerLabel("Date de Naissance: ",10,145);
creerLabel("Genre (H ou F): ",10,190);
//TextFields
for(int i=0;i<4;i++)
{
tabTF[i]=new TextField("");
tabTF[i].setBackground(Color.white);
add(tabTF[i]);
}
tabTF[0].setBounds(120,45,150,25);
tabTF[1].setBounds(120,100,150,25);
tabTF[2].setBounds(120,145, 100,25);
tabTF[3].setBounds(120,190, 45,25);
bAjout=creerBouton("Ajouter",20,250);
setVisible(true);
bModifier=creerBouton("Modifier",138,250);
setVisible(true);
//bSupprimer=creerBouton("Supprimer",250,250);
//setVisible(true);
bPrecedent=creerBouton("Precedent",360,250);
bSuivant=creerBouton("Suivant",450,250);
bSupprimer=creerBouton("Supprimer",600,250);
setVisible(true);
onto = new Onto();
readRDFfile();
traitement(this);
}
void traitement(Frame fenetre)
{
bAjout.addActionListener(new ActionAjoutPersonne());
//bModifier.addActionListener(new ActionModifier());
//bValiderModif.addActionListener(new ActionModif());
bSuivant.addActionListener(new ActionSuivant());
bPrecedent.addActionListener(new ActionPrecedent());
bSupprimer.addActionListener(new ActionSupprimer());
}
//Button Add
public class ActionAjoutPersonne implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
p1=onto.model.createResource(onto.uriBase+"#"+tabTF[0].getText());
p1.addProperty(onto.aPourPrenom, tabTF[0].getText());
p1.addProperty(onto.aPourNom, tabTF[1].getText());
p1.addProperty(onto.aDateNaiss, tabTF[2].getText());
if (tabTF[3].getText().equals("F"))
{
p1.addProperty(onto.aGenre, tabTF[3].getText());
p1.addProperty(RDF.type, onto.femme);
}
else if (tabTF[3].getText().equals("H"))
{
p1.addProperty(onto.aGenre, tabTF[3].getText());
p1.addProperty(RDF.type, onto.homme);
}
StringWriter sw = new StringWriter();
onto.model.write(sw, "RDF/XML-ABBREV");
String owlCode = sw.toString();
File file = new File("d:/Onto.rdf");
try{
FileWriter fw = new FileWriter(file);
fw.write(owlCode);
fw.close();
} catch(FileNotFoundException fnfe){
fnfe.printStackTrace();}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
//Button Remove
public class ActionSupprimer implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
List<Statement> statementsToRemove = new ArrayList<Statement>();
StmtIterator iter = onto.model.listStatements();
while (iter.hasNext())
{
Statement stmt = iter.nextStatement();
Resource subject = stmt.getSubject();
Property predicate = stmt.getPredicate();
RDFNode object = stmt.getObject();
if(subject.toString().equals (onto.uriBase+"#"+tabTF[0].getText()))
{
statementsToRemove.add(stmt);
}
}
for( Statement stmt : statementsToRemove)
{
onto.model.remove(stmt);
}
StringWriter sw = new StringWriter();
onto.model.write(sw, "RDF/XML-ABBREV");
String owlCode = sw.toString();
File file = new File("d:/Onto.rdf");
try{
FileWriter fw = new FileWriter(file);
fw.write(owlCode);
fw.close();
} catch(FileNotFoundException fnfe){
fnfe.printStackTrace();}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
//Read Onto.rdf
public void readRDFfile()
{
String inputFile="D:/Onto.rdf";
try
{
InputStream in =new FileInputStream(inputFile);
if (in == null) {
System.out.println("File not found");
}
onto.model.read(in, null);
}catch(Exception e) {
System.out.println("model.read catched error: " + e);
}
}
//Button Next
class ActionSuivant implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
++indice;
ExtendedIterator instances = onto.personne.listInstances();
Individual instance = null;
Individual firstInstance = null;
for (p = 0; p < indice && instances.hasNext(); p++) {
instance = (Individual) instances.next();
if (firstInstance == null) {
firstInstance = instance;
}
}
if (p < indice) {
indice = 1;
instance = firstInstance;
}
tabTF[0].setText(instance.getPropertyValue(onto.aPourPrenom).toString());
tabTF[1].setText(instance.getPropertyValue(onto.aPourNom).toString());
tabTF[2].setText(instance.getPropertyValue(onto.aDateNaiss).toString());
tabTF[3].setText(instance.getPropertyValue(onto.aGenre).toString());
}
}
class ActionPrecedent implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
--indice;
//Instances de la Classe Personne
ExtendedIterator instances=onto.personne.listInstances();
Individual instance = null;
for(p = 0; p < indice && instances.hasNext(); p++)
{
instance = (Individual) instances.next();
}
tabTF[0].setText(instance.getPropertyValue(onto.aPourPrenom).toString());
tabTF[1].setText(instance.getPropertyValue(onto.aPourNom).toString());
tabTF[2].setText(instance.getPropertyValue(onto.aDateNaiss).toString());
tabTF[3].setText(instance.getPropertyValue(onto.aGenre).toString());
}
}
//Ontology
public class Onto
{
OntClass personne, genre, homme, femme, feminin, masculin, evenement, deces, mariage, divorce;
OntModel model;
String uriBase;
ObjectProperty aPourFils, aPourFille, aGenre;
DatatypeProperty aPourNom, aPourPrenom, aDateNaiss;
public Onto (){
model = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM_MICRO_RULE_INF );
uriBase = "http://www.something.com/FAM";
model.createOntology(uriBase);
//Classes
personne = model.createClass(uriBase+"personne");
femme = model.createClass(uriBase+"femme");
homme = model.createClass(uriBase+"homme");
genre = model.createClass(uriBase+"genre");
feminin = model.createClass(uriBase+"feminin");
masculin = model.createClass(uriBase+"masculin");
evenement = model.createClass(uriBase+"evenement");
deces = model.createClass(uriBase+"deces");
mariage = model.createClass(uriBase+"mariage");
divorce = model.createClass(uriBase+"divorce");
//Sub-classes
genre.addSubClass(feminin);
genre.addSubClass(masculin);
personne.addSubClass(homme);
personne.addSubClass(femme);
evenement.addSubClass(deces);
evenement.addSubClass(mariage);
evenement.addSubClass(divorce);
aPourFils = model.createObjectProperty(uriBase+"aPourFils");
aPourFils.setDomain(personne);
aPourFils.setRange(homme);
aPourFille = model.createObjectProperty(uriBase+"aPourFille");
aPourFille.setDomain(personne);
aPourFille.setRange(femme);
aGenre = model.createObjectProperty(uriBase+"aGenre");
aGenre.setDomain(personne);
aGenre.setRange(genre);
aPourNom = model.createDatatypeProperty(uriBase+"aPourNom");
aPourNom.setDomain(personne);
aPourNom.setRange(XSD.xstring);
aPourPrenom = model.createDatatypeProperty(uriBase+"aPourPrenom");
aPourPrenom.setDomain(personne);
aPourPrenom.setRange(XSD.xstring);
aDateNaiss = model.createDatatypeProperty(uriBase+"aDateNaiss");
aDateNaiss.setDomain(personne);
aDateNaiss.setRange(XSD.xstring);
}
}
public static void main(String args[])
{
new FamilyModel();
}
}
If your app has a GUI, the standard way to select an input file would be to use a file chooser, for example JFileChooser if your app is Swing based, or FileDialog if you want to stick to AWT components.
Here is an exmaple for JFileChooser:
int returnVal = fc.showOpenDialog(FileChooserDemo.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
String filename = file.getName();
}
JFileChooser Tutorial:
http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html
If your app is command line based (which I gather it not the case from your code for handling button clicks), you could make the input be one of the command line arguments when you run the app, and you could read it out of args[] array passed into main().
There are many options and schools of thought regarding how to get data from the user. Most of this depends on who the user will be and how they are going to be interacting with this program. A couple I've listed.
Command Line Interface This is my favorite because I'm in the terminal a lot and write a lot of bash scripts. Very simple and low development overhead, while still being extensible. You'll need to add code in your main method to retrieve options and values. I like using Apache Commons CLI even though it's not under active development, there is a good tutorial.
Graphical User Interface Use Java Swing or a web application to create a UI around your app. This will inevitably take much longer than any other option but will be the most accessible for non-technical users.
Standard In If you just want the program to pause and prompt the user on the console with no bells or whistles use this in main (if you using
Console con = System.console();
String file = con.readLine("File Name: ");