How to call the run method from another class? - java

Sorry, if this is a stupid question.
I would like to find out how to call the run method that is located in
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FereastraPrincipala().setVisible(true);
from the class AdaugaComanda.java.
The run method is declared in FereastraPrincipala.java and I want to call this from AdaugaComanda.java, so that changes can be seen to FereastraPrincipala after introducing values in the textfields from AdaugaChitanta.java. If I don't call a method, then I have to run FereastraPrincipala.java again, in order to see the new info in the JTabbedPane.
Here is the code for FereastraPrincipala.java
package sakila.ui;
import java.util.List;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import org.hibernate.Session;
import sakila.entity.*;
import sakila.util.HibernateUtil;
public class FereastraPrincipala extends javax.swing.JFrame {
public FereastraPrincipala() {
initComponents();
}
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
AdaugaComanda ac = new AdaugaComanda();
ac.setVisible(true);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FereastraPrincipala().setVisible(true);
Session session = HibernateUtil.getSessionFactory().openSession();
try{
List<Comanda> comenzi = session.createQuery("from Comanda").list();
Vector<String> tableHeaders = new Vector<String>();
Vector tableData = new Vector();
tableHeaders.add("IdComanda");
tableHeaders.add("Depozit");
tableHeaders.add("Furnizor");
tableHeaders.add("Client");
tableHeaders.add("Produs");
tableHeaders.add("Cantitate");
tableHeaders.add("Unit de mas");
for (Comanda comanda : comenzi) {
Vector <Object> oneRow = new Vector <Object>();
oneRow.add(comanda.getIdcomanda());
oneRow.add(comanda.getDepozit() == null ? "" : comanda.getDepozit().toString());
oneRow.add(comanda.getFurnizor() == null ? "" : comanda.getFurnizor().toString());
oneRow.add(comanda.getClient() == null ? "" : comanda.getClient().toString());
oneRow.add(comanda.getProdus() == null ? "" : comanda.getProdus().toString());
oneRow.add(comanda.getCantitate());
oneRow.add(comanda.getUnitmas());
tableData.add(oneRow);
}
ComandaTable.setModel(new DefaultTableModel(tableData, tableHeaders));
}catch (Exception he){
he.printStackTrace();
}
}
});
}
}
Here is the code for AdaugaComanda.java
package sakila.ui;
import java.io.EOFException;
import java.util.List;
import sakila.entity.*;
import sakila.service.Functie;
import sakila.entity.Client;
public class AdaugaComanda extends javax.swing.JDialog {
public AdaugaComanda() {
initComponents();
initComboBoxes();
}
private void initComboBoxes() {
DepozitComboBox.removeAllItems();
FurnizorComboBox.removeAllItems();
ClientComboBox.removeAllItems();
ProdusComboBox.removeAllItems();
System.out.println("sterge itemurile");
List<Depozit> depozite = (List<Depozit>) sakila.client.Client.citeste(Functie.LISTEAZA_DEPOZITE);
for (Depozit depozit : depozite)
DepozitComboBox.addItem(depozit);
List<Furnizor> furnizori = (List<Furnizor>) sakila.client.Client.citeste(Functie.LISTEAZA_FURNIZORI);
for (Furnizor furnizor : furnizori)
FurnizorComboBox.addItem(furnizor);
List<Client> clienti = (List<Client>) sakila.client.Client.citeste(Functie.LISTEAZA_CLIENTI);
for (Client client : clienti)
ClientComboBox.addItem(client);
List<Produs> produse = (List<Produs>) sakila.client.Client.citeste(Functie.LISTEAZA_PRODUSE);
for (Produs produs : produse)
ProdusComboBox.addItem(produs);
System.out.println("adaugaitemuri");
}
private void ClientComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void InsereazaButtonActionPerformed(java.awt.event.ActionEvent evt) {
runQueryBasedOnInsert();
}
private void runQueryBasedOnInsert(){
Comanda comanda = new Comanda();
Depozit depozit = (Depozit)DepozitComboBox.getSelectedItem();
comanda.setDepozit(depozit);
Furnizor furnizor = ((Furnizor)FurnizorComboBox.getSelectedItem());
comanda.setFurnizor(furnizor);
sakila.entity.Client client = ((sakila.entity.Client)ClientComboBox.getSelectedItem());
comanda.setClient(client);
Produs produs = ((Produs)ProdusComboBox.getSelectedItem());
comanda.setProdus(produs);
comanda.setCantitate(Integer.parseInt(CantitateTextField.getText()));
comanda.setUnitmas(UnitMasTextField.getText());
sakila.client.Client.scrie(Functie.CREAZA_COMANDA, comanda);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AdaugaComanda().setVisible(true);
}
});
}
Maybe someone could help me. Thank you a lot!

You could make FereastraPrincipala a member variable of AnduagaChitanta.
public class AnduagaChitanta
{
FereastraPrincipala fPrincipala = new FereastraPrincipala (); //Or inject it into the constructor
private void SomeMethod()
{
fPrincipala.run();
}
}
in the run method()
public void run()
{
setvisible(true);
}
If you are wondering how to inject it:
public class AnduagaChitanta
{
FereastraPrincipala fPrincipala
public AnduagaChitanta(FereastraPrincipala fPrinicipala)
{
this.fPrinicipala = fPrinicipala;
}
private void SomeMethod()
{
fPrincipala.run();
}
}
If you like you can make FereastraPrincipala implement an interface so the definition of the constructor can be:
public AnduagaChitanta(ISomethingPrinicipala fPrinicipala)
But now we are going into design patterns so I will leave it at that.
Update
After your update I would do something like this:
FereastraPrincipala extends JFrame implements Runnable
{
public void run()
{
setvisible(true) ;
}
}
I don't know where but maybe in your AnduagaChitanta class I would do this
public void SomeMethod()
{
java.awt.EventQueue.invokeLater(fPrinicpala)
}
I hope that makes sense

Never call run() method of thread. It executes in the current thread it self !! Always call start() method. Coming to your case, create a new class so that you could invoke start() on it from other places

Related

Use Soot to analyze a Java program

I am trying to use Soot to perform data flow analysis on a java file which is called Example.java.
Here is my Example.java file, my goal is to know which saySomething method animal.saySomething() will call. Here is the code for Example.java I am using:
package a1;
public class Example {
static Animal neverCalled() {
return new Fish();
}
static Animal selectAnimal() {
return new Cat();
}
public static void main(String[] args) {
Animal animal = selectAnimal();
animal.saySomething();
}
}
abstract class Animal {
public abstract void saySomething();
}
class Cat extends Animal {
public void saySomething() {
System.out.println("purr");
}
}
class Dog extends Animal {
public void saySomething() {
System.out.println("woof");
}
}
class Fish extends Animal {
public void saySomething() {
System.out.println("...");
}
}
class Car { // not an Animal
public void saySomething() {
System.out.println("honk!");
}
}
and here is the code I am using to analyze Example.java using Soot, this code is located in the file: TestSootCallGraph.java which follows here:
package a1;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import soot.*;
import soot.jimple.Stmt;
import soot.jimple.spark.SparkTransformer;
import soot.jimple.toolkits.callgraph.CHATransformer;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.Targets;
import soot.options.Options;
public class TestSootCallGraph extends SceneTransformer {
static LinkedList<String> excludeList;
public static void main(String[] args) {
String mainclass = "Example";
// //set classpath
String javapath = System.getProperty("java.class.path");
String jredir = System.getProperty("java.home")+"/lib/rt.jar";
String path = javapath+File.pathSeparator+jredir;
Scene.v().setSootClassPath(path);
//add an intra-procedural analysis phase to Soot
TestSootCallGraph analysis = new TestSootCallGraph();
PackManager.v().getPack("wjtp").add(new Transform("wjtp.TestSootCallGraph", analysis));
excludeJDKLibrary();
//whole program analysis
Options.v().set_whole_program(true);
//load and set main class
Options.v().set_app(true);
SootClass appclass = Scene.v().loadClassAndSupport(mainclass);
System.out.println(appclass);
Scene.v().setMainClass(appclass);
Scene.v().loadNecessaryClasses();
//enable call graph
//enableCHACallGraph();
//enableSparkCallGraph();
//start working
PackManager.v().runPacks();
}
private static void excludeJDKLibrary()
{
//exclude jdk classes
Options.v().set_exclude(excludeList());
//this option must be disabled for a sound call graph
Options.v().set_no_bodies_for_excluded(true);
Options.v().set_allow_phantom_refs(true);
}
private static void enableSparkCallGraph() {
//Enable Spark
HashMap<String,String> opt = new HashMap<String,String>();
//opt.put("propagator","worklist");
//opt.put("simple-edges-bidirectional","false");
opt.put("on-fly-cg","true");
//opt.put("set-impl","double");
//opt.put("double-set-old","hybrid");
//opt.put("double-set-new","hybrid");
//opt.put("pre_jimplify", "true");
SparkTransformer.v().transform("",opt);
PhaseOptions.v().setPhaseOption("cg.spark", "enabled:true");
}
private static void enableCHACallGraph() {
CHATransformer.v().transform();
}
private static LinkedList<String> excludeList()
{
if(excludeList==null)
{
excludeList = new LinkedList<String> ();
excludeList.add("java.");
excludeList.add("javax.");
excludeList.add("sun.");
excludeList.add("sunw.");
excludeList.add("com.sun.");
excludeList.add("com.ibm.");
excludeList.add("com.apple.");
excludeList.add("apple.awt.");
}
return excludeList;
}
#Override
protected void internalTransform(String phaseName,
Map options) {
int numOfEdges =0;
CallGraph callGraph = Scene.v().getCallGraph();
for(SootClass sc : Scene.v().getApplicationClasses()){
for(SootMethod m : sc.getMethods()){
Iterator<MethodOrMethodContext> targets = new Targets(
callGraph.edgesOutOf(m));
while (targets.hasNext()) {
numOfEdges++;
SootMethod tgt = (SootMethod) targets.next();
System.out.println(m + " may call " + tgt);
}
}
}
System.err.println("Total Edges:" + numOfEdges);
}
}
I receive the following error when executing TestSootCallGraph.java which aims at analyzing Example.java. How can I fix this?
Example
Exception in thread "main" java.lang.RuntimeException: Main-class has no main method!
at soot.Scene.setMainClass(Scene.java:171)
at a1.TestSootCallGraph.main(TestSootCallGraph.java:47)

Custom EventListener check what abstract method the class is overriding

Hello so i got the following code:
Event Handler.java
package me.xenopyax.edla.watcher;
import static java.nio.file.StandardWatchEventKinds.*;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.util.ArrayList;
import java.util.List;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class EventHandler {
private Path folderPath = Paths.get(System.getProperty("user.dir") + "/Saved Games/Frontier Developments/Elite Dangerous");
private String watchFile;
private List<EventListener> listeners = new ArrayList<>();
public EventHandler() {
// We obtain the file system of the Path
FileSystem fileSystem = folderPath.getFileSystem();
// We create the new WatchService using the try-with-resources block
try (WatchService service = fileSystem.newWatchService()) {
// We watch for modification events
folderPath.register(service, ENTRY_MODIFY);
// Start the infinite polling loop
while (true) {
// Wait for the next event
WatchKey watchKey = service.take();
for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
// Get the type of the event
Kind<?> kind = watchEvent.kind();
if (kind == ENTRY_MODIFY) {
Path watchEventPath = (Path) watchEvent.context();
// Call this if the right file is involved
if (watchEventPath.toString().equals(watchFile)) {
//File has been modified, call event registered
}
}
}
if (!watchKey.reset()) {
// Exit if no longer valid
break;
}
}
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void registerListener(EventListener listener) {
listeners.add(listener);
}
}
and Main.java
package me.xenopyax.edla;
import java.io.File;
import me.xenopyax.edla.discord.EDLARPC;
import me.xenopyax.edla.watcher.EventHandler;
import me.xenopyax.edla.watcher.GameStartListener;
public class Main {
private EDLARPC edlarpc = new EDLARPC();
private File journalDir = new File(System.getProperty("user.home") + "/Saved Games/Frontier Developments/Elite Dangerous");
public static void main(String[] args) {
EventHandler handler = new EventHandler();
handler.registerListener(new GameStartListener());
}
public EDLARPC getRPC() {
return edlarpc;
}
public File getJournalDirectory() {
return journalDir;
}
and EventListener.java
package me.xenopyax.edla.watcher;
public abstract class EventListener {
public void onGameStart(){};
}
and GameStartListener.java
package me.xenopyax.edla.watcher;
public class GameStartListener extends EventListener {
#Override
public void onGameStart() {
}
}
Now my question is how do I call the abstract method from EventListener.java in EventHandler.java and how do i check in the ArrayList which methods are overridden? I am trying to create an EventHandler that listens to an file and when changes happen it looks up what changed and fires the approperiate abstract method from EventListener.java.
You can check a declaring class of a method if it's not your abstract class then the method was overridden.
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
class Main {
static abstract class EventListener {
public void onFileChanged() {
throw new NotImplementedException();
}
}
static class EventListenerNotImpl extends EventListener {
}
static class EventListenerImpl extends EventListener {
private String id;
public EventListenerImpl(String id) {
this.id = id;
}
public void onFileChanged() {
System.out.println(id + ":" + EventListenerImpl.class.getCanonicalName() + ".onFileChanged() was called");
}
}
static class EventHandler {
private List<EventListener> listeners = new ArrayList<>();
public void addListener(EventListener listener) {
listeners.add(listener);
}
private void propagateOnFileChangedEvent() {
listeners.forEach(l -> {
try {
Method m = l.getClass().getMethod("onFileChanged");
if (!m.getDeclaringClass().equals(EventListener.class)) {
l.onFileChanged();
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
});
}
}
public static void main(String[] args) {
EventHandler handler = new EventHandler();
handler.addListener(new EventListenerImpl("listener-1"));
handler.addListener(new EventListenerNotImpl()); // Not will be invoked onFileChangedEvent
handler.addListener(new EventListenerImpl("listener-3"));
handler.propagateOnFileChangedEvent();
}
}
Output:
listener-1:Main.EventListenerImpl.onFileChanged() was called
listener-3:Main.EventListenerImpl.onFileChanged() was called

Know when a different class is exited

I'm currently coding a project Java in eclipse which has two classes. The first class (open) I use to send a specific string to my second class (viewer) and then run my second class. The second class (viewer) I have imported into my program in the form of a jar file. I have done it this way as class viewer is a pdf viewer that i created using apache PDFBox and class open sends the file to the viewer to use, but the file will be different depending on many conditions (that are not relevant) in class open. The point is that class open needs to be separate from class viewer and can not simply be two different methods in one class. I would like to know if there is a way for class open to know when class viewer has been closed, as currently I am using a while loop, which just eats up memory and is very inefficient. The code I have does currently work, but I feel there is a better way, perhaps using listeners. This is the code for closing class viewer:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//and import swing components ect
Public class viewer extends javax.swing.JFrame
implements KeyListener,
ActionListener{
private javax.swing.JButton zoomIn;
private javax.swing.JButton zoomOut;
//and a bunch more swing components
public static boolean closed = false;
public static String fileName = "";
public viewer()
{
}
private void initComponents() throws IOException
{
addWindowListener(new java.awt.event.WindowAdapter()
{
#Override
public void windowClosing(java.awt.event.WindowEvent evt)
{
exitApplication();
}
});
}
private void exitMenuItemActionPerformed(ActionEvent evt)
{
if( document != null )
{
try
{
document.close();
}
catch( IOException e )
{
throw new RuntimeException(e);
}
}
closed = true;
System.exit(0);
}
public static void main(String filename) throws Exception
{
fileName = filename;
viewer mainViewer = new viewer();
String[] splittedStr = fileName.split("/");
BASETITLE = splittedStr[splittedStr.length - 1];
if (fileName != null)
{
mainViewer.openPDFFile(fileName);
}
mainViewer.setVisible(true);
}
This is my code from class open:
public static void main(String[] args) throws Exception {
String fileName = "C:/Files/Test.pdf";
viewer.main(fileName);
while(viewer.closed == false)
{
if(viewer.closed == true)
{
System.out.print("The Viewer Has Been Closed");
}
}
}
I want to know when it is closed so I can delete the file on the local drive. Thanks for your help!
Either you pass a callback (e.g. a Runnable) as argument to viewer.main, like viewer.main(fileName, () -> System.out.print("The Viewer Has Been Closed")) and make sure that it is called when the process is done, or you do as you've done except that you sleep your main thread a short time in the while loop, like Thread.sleep(100).
okay so I actually found an answer to my question and I'll just post it in case someone else had the same problem as me. I added a interface to the open class with the method close as shown:
import mainpackage.viewer;
public class Open implements closeInterface{
public Open() { }
public static String fileName;
public static void main(String[] args) throws Exception {
fileName = "C:/Files/Test.pdf";
run();
}
#Override
public void close() {
System.out.print("The Viewer Has Been Closed");
}
public static void run() throws Exception
{
viewer view = new viewer();
view.main(fileName);
view.addListener(new Open());
}
}
This was my code for my interface:
package mainpackage;
public interface closeInterface {
public void close();
}
And this was the snipit of code for my Viewer class
public class viewer extends javax.swing.JFrame {
private static closeInterface Closed;
private void initComponents() throws IOException
{
addWindowListener(new java.awt.event.WindowAdapter()
{
#Override
public void windowClosing(java.awt.event.WindowEvent evt)
{
exitApplication();
}
});
}
private void exitApplication()
{
try
{
if( document != null )
{
document.close();
}
}
catch( IOException io )
{
//do nothing because we are closing the application
}
Closed.close();
this.setVisible( false );
this.dispose();
}
public void addListener(closeInterface closed){
Closed = closed;
}
}
Thanks for everyone's help!

Get value from JtextField to another class [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Im trying to get jTextField value in another class but always get error null exception. Here is my code :
Class Main :
public class FormTambahDoc extends javax.swing.JFrame {
Utility utility;
public FormTambahDoc() {
initComponents();
utility = new Utility();
setButton();
}
public String gettextIdentitasPengguna() {
return textIdentitasPengguna.getText();
}
private void setButton() {
btnSimpan.addActionListener(new ActionListener() {#Override
public void actionPerformed(ActionEvent e) { utility.cek();} });
}
}
Class another:
public class Utility {
FormTambahDoc formTambahDoc;
//FileJpaController controller;
public void cek()
{
String inputText = formTambahDoc.gettextIdentitasPengguna();
System.out.println(inputText);
//return `Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException`
}
}
What's wrong in this code ?
You should create instance of FormTambahDoc before you ca use it:
FormTambahDoc formTambahDoc = new FormTambahDoc(); or get the instance from somewhere. Otherwise formTambahDoc will always be null. Check again your AWT tutorial.
Try following
public class FormTambahDoc extends javax.swing.JFrame {
Utility utility;
public FormTambahDoc() {
initComponents();
utility = new Utility(this);
setButton();
}
public String gettextIdentitasPengguna() {
return textIdentitasPengguna.getText();
}
private void setButton() {
btnSimpan.addActionListener(new ActionListener() {#Override
public void actionPerformed(ActionEvent e) { utility.cek();} });
}
}
public class Utility {
FormTambahDoc formTambahDoc;
//FileJpaController controller;
public Utility(FormTambahDoc aForm) {
formTambahDoc = aForm;
}
public void cek()
{
String inputText = formTambahDoc.gettextIdentitasPengguna();
System.out.println(inputText);
//return `Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException`
}
}

Function works in main class but not it test class

I have a class which compiles and runs as expected (adds one test node per execution):
public class ReqsDb {
private final String STORE_DIR;
public GraphDatabaseService graphDb;
private static enum RelTypes implements RelationshipType {
IDENTIFIES, SATIFIES
}
public ReqsDb(String dbPath) {
STORE_DIR = dbPath;
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(STORE_DIR);
registerShutdownHook(graphDb);
}
public void createTestNode() {
Transaction tx = graphDb.beginTx();
Node newNode;
try {
newNode = graphDb.createNode();
newNode.setProperty("test", "test");
tx.success();
} finally {
tx.finish();
}
}
private static void registerShutdownHook(final GraphDatabaseService graphDb) {
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
graphDb.shutdown();
}
});
}
void shutDown() {
graphDb.shutdown();
}
public static void main(String[] args) {
ReqsDb testDb = new ReqsDb("target/testDb");
testDb.createTestNode();
}
}
However the test function, testCreateTestNode() causes error:
java.lang.RuntimeException: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.StoreLockerLifecycleAdapter#4e3a2be1' was successfully initialized, but failed to start.
Since the function works as called from main(), I think there is something wrong with the test class.
package com.github.dprentiss;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class ReqsDbTest extends TestCase {
protected ReqsDb testDb = new ReqsDb("target/testDb");
public ReqsDbTest(String testName) {
super(testName);
}
public static Test suite() {
return new TestSuite(ReqsDbTest.class);
}
public void testDbService() {
assertNotNull(testDb);
}
public void testCreateTestNode() {
testDb.createTestNode();
}
public void tearDown() {
testDb.shutDown();
}
Is there something wrong with my test set up?
Try to put
protected ReqsDb testDb = new ReqsDb("target/testDb");
in an init method . Follow this example:
Is there a basic template I can use to create a test?

Categories