I have two classes.
The main one opens the second one in a jframe in which the user will press a button and trigger a method from the main class/jframe editare(String value) that will automatically add some data to some jtextfields in the main jframe.The problem is that it won't trigger the method.I tried calling other methods from the main class,it doesn't call them either.I tried a lot of stuff for like the past 1-2 hours,can't figure it out.
Here is some code :
From the second jframe :
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
Test2 test2=new Test2();
test2.citireser(list.getSelectedValue().toString()); //won't work.works if i call it from the same method,the main one
test2.restart(); //won't work either
this.dispose(); }
From the first jframe,the main one :
public void citireser(String cur) {
try {
serializedPath = "C:/Inter/" + cur;
InputStream file = new FileInputStream(serializedPath);
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream(buffer);
String[] storeAllArraysREAD[] = (String[][]) input.readObject();
prodr = storeAllArraysREAD[0];
cantr = storeAllArraysREAD[1];
pretr = storeAllArraysREAD[2];
input.close();
buffer.close();
file.close();
System.err.println("prodr[1]= "+prodr[1].toString());
for (int m = 0; m < prodr.length - 1; m++) {
allprod.get(m).setText(prodr[m]);
allcant.get(m).setText(cantr[m]);
allpret.get(m).setText(pretr[m]);
produsnou();
}
} catch (ClassNotFoundException ex) {
System.err.println("EROARE");
} catch (IOException ex) {
System.err.println("EROARE");
}
}
EDIT : Ok,after trying different stuff for a couple of hours i've got it.
public class Opt extends javax.swing.JFrame implements Printable {
private final Test2 main;
public Opt(Test2 aMain) {
main = aMain;
try {
} catch (Exception e) {
e.printStackTrace();
}
initComponents();
jScrollPane2.getVerticalScrollBar().setPreferredSize(new Dimension(0, 0));
jScrollPane2.getVerticalScrollBar().setUnitIncrement(16);
citirel();
if (list.getModel().getSize() == 0) {
jButton1.setEnabled(false);
jButton2.setEnabled(false);
}
}
Thanks for your help,i don't know who i should pick as the right answer :( Sorry to the other guy
The problem here is that you're working with a new instance of Test2. In the action performed (first block of code), you're creating a new Test2 (which would be the first frame). You have to keep somewhere (usually a field) the reference to the first Test2 created.
If you're having further issues, consider editing your question and posting the full code (the two frames entirely, at least). My spider senses are telling me that there's some context missing.
Also, we have similar family names. :-)
Please correct me if any of this is wrong, as I'm trying to understand your program from incomplete code:
Test2 (a JFrame containing your program entry point main(string[])) at some point creates a second class (also a JFrame) and opens it.
When you click a certain button in your second window, you wish to modify some elements of the Test2 window, and close the secondary window.
Assuming the above is correct, there is one obvious problem I can see in the code snippets you've posted.
In jButton3ActionPerformed, you're creating a new Test2 object, and modifying that. If you want to modify the original window, you need to be storing a reference to it. For example, require a Test2 object as a parameter to your second class, and store that parameter as a field in the class.
Related
Actually, I have a JFrame(the main window) with a JTable in it. And couple of buttons, like Add,Delete,Refresh.
Refresh uses the function(updateTable) that has the following code below and works fine:
try
{
ResultSet R = Home.getStatement().executeQuery("Select * from Schooldata");
int count =0;
while(R.next()) { count++; }
school_data = new String[count][6];
R = Home.getStatement().executeQuery("Select Schoolname,city,ProgramOpted,coordinator_name,Trainers,contactnum from Schooldata");
count =0;
while(R.next())
{
for(int i=0;i<6;i++)
{ school_data[count][i]= R.getString(i+1);
System.out.println(R.getString(i+1));
}
count++;
}
}
catch(SQLException S) {JOptionPane.showMessageDialog(null,S);}
jTable1.setModel(new DefaultTableModel(school_data,new String [] {
"School Name", "City", "Program", "Coordinator", "Trainers", "Contact Number"
}));
When I click on "Add, another JFrame window appears and asks for Details that is further saved to Database and shows a confirmation message and refreshes the table(on a different JFrame i.e the main Window) using above function.
The Issue is, I'm calling the same function but from an another JFrame.Expecting the changes to be reflected in the main JFrame.
Using the method,new Main().updateTable(); in the below code.It's just not working.
try
{
int confirm = Home.getStatement().executeUpdate(Query);
if(confirm == 1)
{
JOptionPane.showMessageDialog(null,"Record Added","Saved",1);
new Main().updateTable();
}
else JOptionPane.showMessageDialog(null,"There is some Error.....","Error",0);
}
catch(SQLException S)
{
JOptionPane.showMessageDialog(null,S,"Error",0);
}
Your problem I believe is here (it's hard to tell without a minimal example program:
int confirm = Home.getStatement().executeUpdate(Query);
if(confirm == 1)
{
JOptionPane.showMessageDialog(null,"Record Added","Saved",1);
new Main().updateTable(); // ****** HERE ******
}
You're creating a completely new Main object, changing its state, and hoping that this will change the state of the visualized Main object, but you're finding out that no, it won't.
Instead you need to pass a reference of the visualized Main object into the code above, and then call methods on it, not on a newly created completely unique object.
Whatever you do, don't try solving this by making fields or methods static. Yes, that might work, but it breaks OOPs and makes your program difficult to test or extend.
As an aside, that second dependent window should not be another JFrame, and in fact likely should be a modal JDialog. For if you use a JDialog, then there would be no need for the dialog code to push information into the calling window. Rather the calling code will know when you're done dealing with the dialog, and so at this point if the dialog's state is good (if you didn't say cancel it with no changes), then the calling code can easily pull information from the dialog code. For a concrete example of what I"m talking about, please look at my answer to a similar question about passing information between two windows here.
Also a similar problem and solution can be found here.
See weather you are disposing the main or not. If not then try creating object of Main frame and try accessing it to refresh table. You can also add import for Main Frame .java file in your refresh dialog file and try refreshing the table. Also check if your table is public static or not so that to access it from another frame. If you create a refresh function for this purpose then it will be best. My code for function goes as -
import package.mainframe;
or
MainFrame mainframe = new MainFrame();
try
{
int confirm = Home.getStatement().executeUpdate(Query);
if(confirm == 1)
{
JOptionPane.showMessageDialog(null,"Record Added","Saved",1);
mainframe.updateTable(); //or mainframe.functioncall();
}
else JOptionPane.showMessageDialog(null,"There is some Error.....","Error",0);
}
catch(SQLException S)
{
JOptionPane.showMessageDialog(null,S,"Error",0);
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm running the main method by clicking a jButton in this class. First tried by using
public static void main(String[]args)
All the java swing components started to show non static variable cannot be referenced from static content errors. So I changed
public static void main(String[]args)
to
public void main(String[]args)
No errors shown for the swing components but expected result are not displaying in the jTextArea. IF i print the expected output in System.out.println, it shows correctly. What am I doing wrong here? This is how i trigger main() to run by clicking on jButton
jButton4.setText("Analyze");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try{
TestTextRazor test = new TestTextRazor();
test.main(new String[0]);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
This is my main()
public void main(String[] args) throws NetworkException, AnalysisException {
File textSRC = new File("MyText.txt");
String myTextCount = null;
BufferedReader myTextBr = null;
String check = "";
try {
String myTextCurrentLine;
myTextBr = new BufferedReader(new FileReader(textSRC));
while ((myTextCurrentLine = myTextBr.readLine()) != null) {
myTextCount = myTextCount + " " + myTextCurrentLine;
}
// Sample request, showcasing a couple of TextRazor features
String API_KEY = "7d5066bec76cb47f4eb4e557c60e9b979f9a748aacbdc5a44ef9375a";
TextRazor client = new TextRazor(API_KEY);
client.addExtractor("words");
client.addExtractor("entities");
client.addExtractor("entailments");
client.addExtractor("senses");
client.addExtractor("entity_companies");
String rules = "entity_companies(CompanyEntity) :- entity_type(CompanyEntity, 'Company').";
client.setRules(rules);
AnalyzedText response = client.analyze(myTextCount);
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
for (Sentence sentence : response.getResponse().getSentences()) {
for (Word word : sentence.getWords()) {
System.out.println("----------------");
System.out.println("Word: " + word.getLemma());
for (Entity entity : word.getEntities()) {
///System.out.println("Matched Entity: " + entity.getEntityId());
}
for (Sense sense: word.getSenses()) {
//System.out.println("Word sense: " + sense.getSynset() + " has score: " + sense.getScore());
}
}
}
// Use a custom rule to match 'Company' type entities
for (Custom custom : response.getResponse().getCustomAnnotations()) {
for (Custom.BoundVariable variable : custom.getContents()) {
if (null != variable.getEntityValue()) {
for (Entity entity : variable.getEntityValue()) {
String CompanyFound = ("Variable: " + variable.getKey() +"\n"+ "Value:" + entity.getEntityId());
System.out.println(CompanyFound);
jTextArea3.append(CompanyFound);
writer.write(CompanyFound);
writer.flush();
writer.close();
}
}
}
}
String ObjButtons[] = {"Yes","No"};
int PromptResult;
PromptResult = JOptionPane.showOptionDialog(null,"Completed Analysis!\nIs there any error in the Analysis?","Homonym Entity Extraction Application",JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE,null,ObjButtons,ObjButtons[1]);
//JOptionPane.getAlignmentX(Component.BOTTOM_ALIGNMENT);
if(PromptResult==JOptionPane.YES_OPTION)
{
System.out.println("YEs!!!!!");
jTextArea2.setEditable(true);
jTextArea3.setEditable(true);
jButton4.setEnabled(false);
jButton5.setEnabled(true);
}
else{
JOptionPane.showMessageDialog(null, "Completed Analysis!","Alert", 1);
System.out.println("No!!!!!!!!!!");
jTextArea2.setEditable(false);
jTextArea3.setEditable(false);
jButton4.setEnabled(false);
}
}catch (IOException ex) {
}
}
Please guide me.
Basically, the error is saying, you are trying to reference non-static variables from a static context.
Non-static variables (often referred to as instance variables or fields) require an instance of their parent class in order to have some kind referencing context.
Take a look at Understanding Instance and Class Members for more details.
Without much more of an example to go by, I would create a class constructor and move the contents of the main method to it.
I would then fix the main method to be static and create a new instance of the class from the main method...
The reason I would refrain from making Swing components static is it's way to easy to mix up you references and end up referencing something that isn't actually displayed on the screen...
Updated
Two things.
Make sure that the context of your main method is correct, that the UI components that you have created are not static and you are referencing them correctly.
Don't call the TestTextRazor class directly. This is just an example of how the API works. Take the time to understand it and incorporate into your own class(es) as required
Firs of all, what you need to understand is that a static method cannot access class fields or other methods that are non-static. So look at your code. The main has to be static as that is its natural signature, which must remain in tact as is. So all your class fields that you are trying to access in the main method, need to be static. Is this good practice? Absolutely not. You can browse through the Swing tutorial to pick up on good practices. I'm sure if you run through 20 examples, you'll pick up on a lot of good coding practices for Swing. Good Luck!
"I'm running the main method by clicking a jButton in this class"
One thing I noticed that you are doing complete wrong is trying to call the main method from inside your actionPerformed. The main method should never be called. The JVM using that method as an entry point for your program.
Another thing you have to understand is that a Swing program is event-driven. One button, should not run a complete program, unless it is a very small program.
I would consider creating methods for different tasks like
public String getSomethingFromFile(String filename) throws IOExceptions {
}
where you can call that method from an actionPerformed or something to append data to a text area.
Learn to use class members and initialize them in your constructor or some initialization method.
If you want everything that's going on the main method to be performed on a button click, put all that code in the actionPerformed , not in the main. A typical form of what goes inside the main is just something like this, where you just need to initialize your class to get the program running
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
JFrame frame = new JFrame();
frame.add(new MyGUIPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
where new MyGUIPanel() is an instance of your Main class
Another option is to create a method to perform all the tasks that are in the main like
public void performTextRazorTask() throws NetworkException, AnalysisException {
...
}
and just call that method from the actionPerformed
Again, I stress that you have a look at the tutorials I linked for better practices, as this site isn't really a tutorial site, I don't want to get into a tutorial type answer.
First of all you can not make main method as non static.
As per this line non static variable cannot be referenced from static content errors. make those variables as static
I am attempting to make a GUI for a program that reads and writes information from a random access file and display it at will. I cannot manipulate anything but the GUI and must refer to prebuilt methods( if the methods truly are unusable then I can make an exception).
The Part I am having issues with is dealing with an IOException while writing to a file.
public static class EdtButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Confirm")) //if the confirm button is pressed
{
writeAll(); //runs all write methods using the strings from the text field
frameAddMovie.setVisible(false);
}
The writeAll refers to a series of methods that write from a file based on the string it is passed, these strings come from textfields on my GUI Window. They all look something like this;
public static void writeDirector(int recordNum, String directorIn)throws IOException
{
int position;
RandomAccessFile recordFile = new RandomAccessFile("RecordFile", "rw");
position = recSize * (recordNum-1)+32; // read 32 spaces into the record to the start of the director line
recordFile.seek(position);
recordFile.writeBytes(directorIn);
}
At the point were the Confirm button is pressed and writeAll() is run there is an IOException thrown that cannot be caught with the method or the Class.
if (e.getActionCommand().equals("Confirm")) //if the confirm button is pressed
wouldn't you want that to be
if (e.getSource() = buttonname)
Is there a simple way to clear all fields of an instance from a an instance? I mean, I would like to remove all values assigned to the fields of an instance.
ADDED
From the main thread I start a window and another thread which controls state of the window (the last thread, for example, display certain panels for a certain period of time). I have a class which contains state of the window (on which stage the user is, which buttons he already clicked).
In the end, user may want to start the whole process from the beginning (it is a game). So, I decided. So, if everything is executed from the beginning, I would like to have all parameter to be clean (fresh, unassigned).
ADDED
The main thread, creates the new object which is executed in a new thread (and the old thread is finished). So, I cannot create a new object from the old thread. I just have a loop in the second thread.
I don't get it. How can you programmatically decide how to clear various fields?
For normal attributes it can be easy (var = null) but what about composite things or collection? Should it be collection = null, or collection.removeAll()?
This question is looking for synctactic sugar that wouldn't make so much sense..
The best way is to write out your own reset() method to customize the behaviour for every single object.. maybe you can patternize it using an
interface Resettable
{
void reset()
}
but nothing more than that..
Is there a simple way to clear all fields of an instance from a an instance? I mean, I would like to remove all values assigned to the fields of an instance.
Yes, just assign a default value to each one of them. It would take you about 20-30 mins. and will run well forever*( YMMV)
Create a method: reset and invoke it
class YourClass {
int a;
int b;
boolean c;
double d;
String f;
// and so on...
public void method1(){}
public void method2(){}
public void method3(){}
// etc.
// Magic method, reset all the attributes of your instance...
public void reset(){
a = 0;
b = 0;
c = false;
d = 0.0;
f = "";
}
}
And then just invoke it in your code:
....
YourClass object = new YourClass();
Thread thread = YourSpecificNewThread( object );
thread.start();
... // Later on you decide you have to reset the object just call your method:
object.reset(); // like new
I don't really see where's the problem with this approach.
You may use reflection:
Try something like this:
Field[] fields = object.getClass().getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
f.set(object, null);
}
It's not a beautifull solution, but may work for you.
There is no other way than setting null to all of them.
As an aside, i find that a particular weird idea. You would have better re-creating a new instance, instead of trying to reset your old one.
If you want to clear a filter (Serializable) that your application "can handle his null" fields, you can use BeanUtils (Apache Commons):
Field[] fields = filter.getClass().getDeclaredFields();
for (Field f : fields) {
if (f.getName().endsWith("serialVersionUID")) {
continue;
}
try {
BeanUtils.setProperty(filter, f.getName(), null);
} catch (IllegalAccessException | InvocationTargetException e) {
FacesUtils.handleError(LOG, "Erro limpar filtro...", e);
}
}
I hope it can help you.
I have a Main Frame and a JDialog ,I make an object in the Main Frame and I sent it to the JDialog with its constructor ,and I assign it to the new object which has type like that.and I add some information to the new object in the JDialog but after that I need the new object's information in the Main Frame what should I do?
Should I send the new object from JDialog to the Main Frame ? If yes, how?
No, you don't have to send something back (in your case). It really works like this:
public void addStudentAction() {
AddStudent myAddStudentDialog = new AddStudent(this, true, this.management);
myAddStudentDialog.setVisible(true);
// now you enter a password on the dialog
if (this.management.getStudentsPasswort() == null) {
// There's a bug in AddStudent class
} else {
System.out.println("HipHipHooray");
}
}
(I guess the problem is related to your previous question, that's why I chose this - otherwise strange - example)
Hope it helps!