perform methods from other class when button is clicked in jFrame - java

I have a class named Parser which gets some input and do some calculations and output the results. I also have a jFrame, which has some text fields. I am misunderstanding how to run the parser and use the inputs from the jFrame. I don't know if I should implement the action Listener in my Parser class? or should I import all my Parser class methods in the jFrame? should I have run method in my main of the Parser or should I use the void run in the jframe class??
Here is my class Parser:
public class Parser{
public static List getXKeywords(String Url, int X, String html) throws Exception {
//somemethod with someoutput
}
public static void main(String[] args) throws Exception {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
SpyBiteDemo Sp = new SpyBiteDemo();
Sp.setVisible(true);
int X=Sp.getKeywordcount();
//this top line is not correct because it can only be done when the jframe jButton1 was clicked
}
});
}
}
and here is the jFrame;
public class SpyBiteDemo extends javax.swing.JFrame {
/**
* Creates new form SpyBiteDemo
*/
public SpyBiteDemo() {
initComponents();
}
public String getKeywordcount()
{
return jTextField4.getText();
}
//some methods
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//get the input from the jframe
//feed it to the parser?? how???
String SeedUrl=jTextField1.getText();
Parser P=new Parser();
//I don't have access to methods
because they are static
}
}
here I am trying to get keywordcount variable from the jFrame which is the int X in the getXKeywords method.

I solved my problem with the help of this link
I created a constructor in my parser class and also included a jframe in the parser class as follow:
public class Parser {
SpyBiteDemo Sp=new SpyBiteDemo();
public Parser(SpyBiteDemo Sp)
{
this.Sp=Sp;
int X = Sp.getXKeywords();
//do whatever
}
and in the action performed of the jframe class I call my parser constructor class:
public class SpyBiteDemo extends javax.swing.JFrame {
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Parser P=new Parser(this);
}
}

Related

SetText To textfiled or lable From other Window javafx

lets say you have lable in MainWindow ..
and you want change value of this lable
from Window2
Not in Same Window !!
i want the changes while the MainWindow its open
It's easy if ur using 2 .fxml files with there own controllers
if that's the case create a new class file namely 'AllControllers'
you have two 2 controllers namely ControllerWindow1 and ControllerWindow2
public class AllControllers {
private static ControllerWindow1 control1;
private static ControllerWindow2 control2;
public static ControllerWindow1 getControl1() {
return control1;
}
public static void setControl1(ControllerWindow1 control1) {
Controlls.control1 = control1;
}
public static ControllerWindow2 getControl2() {
return control2;
}
public static void setControl2(ControllerWindow2 control2) {
Controlls.control2 = control2;
}
}
You have to initialize each controller like this
public class ControllerWindow1 implements Initializable{
#FXML
public Label mylabel;
#Override
public void initialize(URL location, ResourceBundle resources) {
AllControllers.setControl1(this);
}
}
Now you can access your controller from any class. Just use
AllControllers.getControl1().mylabel.setText("hello");

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!

"Multiple markers at this line" error at constructor

So I am using gpdraw as a library to draw stuff for my computer science class, and I'm trying to run this in Eclipse and I put the main method but I'm still getting errors.
import gpdraw.*;
public class House {
public static void main(String[] args) {
private DrawingTool myPencil;
private SketchPad myPaper;
public House() {
myPaper = new SketchPad(500, 500);
myPencil = new DrawingTool(myPaper);
}
public void draw() {
myPencil.up();
myPencil.turnRight(90);
myPencil.forward(20);
myPencil.turnLeft(90);
myPencil.forward(20);
myPencil.turnRight(20);
myPencil.forward(200);
}
}
}
You're trying to stuff everything into the main method. That won't work. Instead, have main call draw (on an instance of the class, a context which a static method does not have available) and define everything in the class, not a method.
import gpdraw.*;
public class House {
public static void main(String[] args) {
House instance = new House();
instance.draw();
}
private DrawingTool myPencil;
private SketchPad myPaper;
public House() {
myPaper = new SketchPad(500, 500);
myPencil = new DrawingTool(myPaper);
}
public void draw() {
// stuff
}
}
Java does not allow nesting methods and/or constructors.
You need something like this:
import gpdraw.*;
public class House {
private DrawingTool myPencil;
private SketchPad myPaper;
public House() {
myPaper = new SketchPad(500, 500);
myPencil = new DrawingTool(myPaper);
}
public void draw() {
myPencil.up();
myPencil.turnRight(90);
myPencil.forward(20);
myPencil.turnLeft(90);
myPencil.forward(20);
myPencil.turnRight(20);
myPencil.forward(200);
}
public static void main(String[] args) {
// whatever
}
}

Java - force implementation of a method for each child of an abstract class

I have an abstract class Action with children like SendMessageAction.
I would like to run these actions in a service but how could I force implementation of each child ?
For example I would like to implement an abstract method : void run(Action action)
and methods "run" for each possible Action with an error if some methods are missing.
Any idea ?
Something like below should help you to get started. Happy coding!
Action.java
public abstract class Action {
protected abstract void runAction();
}
MessageSenderAction.java
public class MessageSenderAction extends Action {
public void runAction() {
//send message
}
}
SomeOtherAction.java
public class SomeOtherAction extends Action {
public void runAction() {
//do something else
}
}
ActionHandler.java
public class ActionHandler {
private final static ActionHandler INSTANCE = new ActionHandler();
private ActionHandler() {}
public static ActionHandler getInstance() {
return INSTANCE;
}
private List<Action> allActions = new ArrayList<Action>();
public void addAction(Action action) {
allActions.add(action);
}
public void runAllActions() {
for(Action action: allActions) {
//just to handle exception if there is any. Not to hamper other actions in case of any failures
try {
action.runAction();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
ActionDemo.java
public class ActionDemo {
public static void main(String... args) {
ActionHandler actionHandler = ActionHandler.getInstance();
Action msgSenderAction = new MessageSenderAction();
Action someOtherAction = new SomeOtherAction();
actionHandler.addAction(msgSenderAction);
actionHandler.addAction(someOtherAction);
actionHandler.runAllActions();
}
}

How to call the run method from another class?

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

Categories