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);
}
Related
I'm building this form that I want to be able to change what fields are displayed based on what setting you select.
There's going to be 3 panels, first with text fields gathering information, second for notes, third for a checklist. The main frame will add those panels onto it and use one buttons to gather the information from each panel and compile it into a text area so you can just copy/paste it after it's been formatted.
So the problem I'm having is getting the information passed over to the main frame. I have created a formlistener to pass information from the form using an object FormEvent I have created which will carry over the necessary information. I have then created a method in the form to pull the relevant information depending on which form is being used at the time. My problem is getting that method to call properly. This is the ActionListener for the button:
confirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
form.getUbntInfo(); // this is where i have it set
form.setFormListener(new FormListener() {
// would like it to go here so that it creates the event
// object to pass before
// it passes the information, but it causes compile error here
public void formEventOccured(FormEvent e) {
String complaint = e.getComplaint();
String ping = e.getPing();
String ap = e.getAp();
signal0 = e.getSignal0();
signal1 = e.getSignal1();
chain0 = e.getChain0();
chain1 = e.getChain1();
sinr0 = e.getSinr0();
sinr1 = e.getSinr1();
sinr0 = e.getLan();
System.out.println("local signal: " + signal0);
}
});
Essentially the getUbntInfo(); method needs to have a formListener set so that it can pass create the object to pass along the information. As it stands I can press the button twice and it passes the information the second time but it will not do it the first time. What am I doing wrong?
This question already has answers here:
Pass a class variable to another class
(3 answers)
Closed 4 years ago.
I'm stuck on a simple problem that I just can't solve.
I have two classes (Fruits.java with main and FruitDetails.java).
Fruits.java is a small program with tons of stuff, really. It has a ComboBox and I need to transfer its currently selected option to FruitDetails.
The problem is... my understanding of setters and getters seems to be very flawed. I've researched it online for the last 2 hours and this is the closest I could get to something. I'm really tight on time and I can't help but ask you now...
Inside class Fruits.java
public void selectedFruit() {
currentFruit = (String) fruitList.getSelectedItem();
}
public String getSelectedFruit() {
return currentFruit;
}
Inside class FruitDetails.java
public void fruitChoice() {
Fruits fruitChoice = new Fruits();
String chosenFruit = fruitChoice.getSelectedFruit();
System.out.println(chosenFruit);
// Rest of the code
}
Not only this opens another copy of my program(which I really don't want), system prints out "null" for the result.
I really need to get this working and hopefully it'll help fix my understanding of encapsulation a bit. There's a ton of online resources I've found, but using them seems to be too hard for the thick head of mine.
Thanks in advance for any help.
public void fruitChoice() {
Fruits fruitChoice = new Fruits();
String chosenFruit = fruitChoice.getSelectedFruit();
System.out.println(chosenFruit);
// Rest of the code
}
In second line you are creating new object that's why you are getting null when you try to get the value of currentFruit.
it looks like you method selectedFruit() sets currentFruit but your not actually calling selectedFruit()?
Unless your missing some code above that calls selectedFruit() elsewhere?
Try calling selectedFruit() after instantiating your Fruit object.
This is because you have not actually linked your currentFruit to your combo box. You need to do two things - call selectedFruit when you first populate the combo box, then attach a listener that calls selectedFruit everytime the combo box selection changes.
If you are using JComboBox, insert this code after you have created the JComboBox.
combo.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
selectedFruit();
}
})
selectedFruit();
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.
I know that when creating buttons, like next and previous, that the code can be somewhat long to get those buttons to function.
My professor gave us this example to create the next button:
private void jbtnNext_Click() {
JOptionPane.showMessageDialog(null, "Next" ,"Button Pressed",
JOptionPane.INFORMATION_MESSAGE);
try {
if (rset.next()) {
fillTextFields(false);
}else{
//Display result in a dialog box
JOptionPane.showMessageDialog(null, "Not found");
}
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
Though, I do not really understand how that short and simple if statement is what makes the next button function. I see that the fillTextFields(false) uses a boolean value and that you need to initialize that boolean value in the beginning of the code I believe. I had put private fillTextFields boolean = false; but this does not seem to be right...
I'm just hoping someone could explain it better. Thanks :)
Well, fillTextFields(true); is a function call and when you pass in a true/false flag it does some things (you have to see the code inside the function in order to find out exactly what it does).
The field declaration private fillTextFields boolean = false; is invalid, you're supposed to provide the type before the name, e.g.: private boolean fillTextFields = false;. Aside from the invalid syntax that flag really doesn't do anything, especially if you're not using it anywhere.
I don't understand what else you expect to see in the jbtnNext_Click() method... when you declare your button and it gets clicked on the UI, then this method gets invoked. It doesn't make the button work, the button works even when you have nothing in the jbtnNext_Click() method. For example:
private void jbtnNext_Click() {
// The button will still work, but it simply won't do anything
}
Getting a button to function depends on what you view as a functioning button. What is supposed to happen when you click next/previous?
Update:
I thought that I needed the boolean
declaration to make the
"fillTextFields(false)" work.
Was the fillTextFields method given to you somewhere? If it was, then you don't need to declare anything, much less a variable. If it's already provided, then you just call the method, that's all. If it's not provided then you need to declare it:
private void fillTextFields(bool shouldFill)
{
if(shouldFill)
{
// fill the text fields
}
// possibly have an else statement if you need to do something else here
}
Otherwise what you see in that function is all you need to do in order to go to the next record in the database.
I think that the code provided is a bit short to provide a good explanation, posting the code for fillTextFields would be of more help.
What I can guess that the program is doing is that it is retrieving some data from a database. The next button allows the program to iterate through the items that have been returned.
Once that the next button is pressed, a message box is shown to let you "know" that the button has indeed been pressed.
rset.next returns true of there is another element in the list (retrieved from the database), or false if there isn't.
If it returns true, you are calling the fillTextFields methods, which I guess displays the data on screen (even though without the code I can just speculate). If there isn't anything left, a message box displaying "Not Found" is shown.
With regards to your question about
private fillTextFields boolean = false;
fillTextFields is a method, and you cannot assign values to methods. Also, in Java, when declaring both methods and variables, the type is written before the name, such as
private int number;
public float myMethod() { }
The next button won't do anything unless you register an action with the button. What I mean is, wherever your next button is defined looks something like this:
private JButton nextButton = new JButton("Next");
This creates a button that has the label, 'Next'. There might be some additional code for positioning the button. In order for that button to do anything when it is clicked, it needs to have an Action set on it, or it has to have an ActionListener added to it. Many times, the class that is creating the button implements ActionListener and has a method to respond to the click, something like:
nextButton.addActionListener(this);
...
...
...
public void actionPerformed(ActionEvent e) {
// some method implementation
}
The actionPerformed method is called when the button is clicked, AS LONG AS you've registered the action listener on the button. Is anything like this present in the code from your professor?
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!