Using one button to pull information from several panels - java

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?

Related

Using SELECT statement with a WHERE clause in Netbeans derby with JFrame forms

I have made a JFrame form and a database that feeds data from a jTable into one of the panels of the JFrame form. When the user types in something to the jTextField used as a search bar, the SEARCH query displays the whole table and not just a specific record. I have no idea how to add a WHERE condition to the code.
As of right now, the user can type anything in the search bar, press the search button and view all the information in the database. I tried using the statement :
myDataObj = myStatObj.executeQuery ("Select* from Gabrielle.PlantData where PName = 'search'");
but all this shows is a blank table.
Connection myConObj = null;
Statement myStatObj = null;
ResultSet myDataObj = null;
public WikiPlantGUI()
{
initComponents();
selectionAll();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
public void selectionAll()
{
try
{
myConObj= DriverManager.getConnection ("jdbc:derby://localhost:1527/InfoDB", "Gabrielle", "plants");
myStatObj = myConObj.createStatement();
myDataObj = myStatObj.executeQuery ("Select* from Gabrielle.PlantData where PName = 'search'");
guiTable.setModel(DbUtils.resultSetToTableModel(myDataObj) );
}
//Then there is some code that creates the JFrame form
private void mainSearchbtnActionPerformed(java.awt.event.ActionEvent evt) {
boolean valid = true;
String search = mainSearch.getText();
if (search.length() ==0)
{
valid = false;
}
else
{
basePanel.removeAll();
basePanel.add(dispPanel);
basePanel.repaint();
basePanel.revalidate();
}
I created the database using the design view, so I don't know how to show the code. The database has the following fields:
ID (the primary key),
PName (the field involved in the search),
PLevel,
PArea,
PType,
PWater,
PSun.
All of them are VARCHAR, except for PSun, which is INTEGER.
What I want to do now is to take data that the user has entered in a jTextField (saved as String search), search for that data in a database,and then display only the single record in the table where the data the user has entered matches a certain field in the table called PName.
I apologise if anything is too general, this is my first time using this website. Please try to use simple explanations, because I am also relatively new to programming. Any help is appreciated.
I appreciate the answers so far, but I have changed the program so much that it is unrecognizable.
The mistake I made was trying to manage the database and the GUI in the same program. I have now broken the program up into two pieces. There is the main class called "Backend" which manages reading in data from the database. There is then another class called "GUI" that handles the display of the information that is gotten from the Backend class.
As a result, much of the program's functions have changed.

Updating JTable from a different JFrame

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);
}

Manipulate combobox using dictionary in java

I am consuming a web service which is returning me result of type "ArrayOfKeyValueOfintstring"
I am confused how to add this data to my combo box in java.
Here is my code
org.tempuri.ThirdPartyService service = new org.tempuri.ThirdPartyService();
org.tempuri.IThirdPartyService port = service.getBasicHttpBindingIThirdPartyService();
// TODO initialize WS operation arguments here
java.lang.String key = line.trim();
// TODO process result here
String>)port.getTests(key).getKeyValueOfintstring();
com.microsoft.schemas._2003._10.serialization.arrays.ArrayOfKeyValueOfintstring result = port.getVulnerabilities(key);
EDIT
for(int i=0;i<=result.getKeyValueOfintstring().size();i++)
{
result.getKeyValueOfintstring().get(i).getKey();
result.getKeyValueOfintstring().get(i).getValue();
JOptionPane.showMessageDialog(null, "key is"+result.getKeyValueOfintstring().get(i).getKey());
JOptionPane.showMessageDialog(null, "Value is"+result.getKeyValueOfintstring().get(i).getValue());
model.addElement(new Item(key, value));
}
I have tried to get the key pair in dialog box and i got it correctly. But now i am not getting how to add them to my ComboBox. I have created table "Vector model = new Vector();" and adding it to the combo box like this "cbTestName = new JComboBox(model);"
Is it the correct way or do i need to apply anything else to add the key value pair to my combo box.
If you'll go to declaration of
port.getTests(key).getKeyValueOfintstring(),
you'll probably find its implemented as
List<KeyValuePairOfintstring>
and KeyValuePairOfintstring is looks like
...
protected Integer key;
...
protected String value;
So one of the ways you can do - is run over port.getTests(key).getKeyValueOfintstring() in the loop, and build your map with your java business objects, you want to display in Combo Box.
You can override your object's toString method as a simplest way to control how will they look in the ComboBox.

JList only updating on first insertion

This is my first attempt at a decent GUI for a Java app and I needed to use JLists with custom ListModels in order to represent certain structures.
//The 2 below structures implement the ListModel interface, using an internal
//ArrayList, in order to be used as
//a model for 2 different JLists in my GUI.
private PropertyList propertiesList = new PropertyList();
private SelectedProperties selProperties = new SelectedProperties();
//and these are the two JLists they are the models for
private javax.swing.JList Properties_JList;
private javax.swing.JList SelectedProperties_JList;
Here I populate my first JList via a stream:
private void OpenFile_MenuItemActionPerformed(java.awt.event.ActionEvent evt) {
final JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(null);
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
this.Properties_JList.setModel(propertiesList);
this.propertiesList.AddFromFile(file);
} else {
//...
}
}
which happens to be working perfectly fine. I import a few entries by reading the file and they are all displayed as expected in a .toString() representation.
The problem is the second JList:
private void AddToSelected_JButtonActionPerformed(java.awt.event.ActionEvent evt) {
Property p = (Property) this.Properties_JList.getSelectedValue();
this.SelectedProperties_JList.setModel(selProperties);
this.selProperties.InsertProperty(p);
this.SelectedProperties_JList.revalidate();
}
Which appears to be displaying only the very first item I attempt to add to it through the above button event, and I have no idea why. I considered moving both .setModel(...) calls right after the form's initComponents() call but if I do that none of the lists gets populated, at all.
Logging messages made it clear that the internal structures are getting populated, but even though they are both respective ListModels for my JLists, one of them isn't working as expected.
A sufficient portion of the code is generated by Netbeans and I have spent hours looking up the API but still have trouble finding out what I'm doing wrong. Any ideas?

Simplest way of creating java next/previous buttons

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?

Categories

Resources