here is my entire class. I read data from a text file, put them into an aeeaylist. then from that array list i want to show the data on a JTable, when the specific method is called.But is doesnt show anything
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author George
*/
import java.awt.*;
import java.util.ArrayList;
//import java.io.FileInputStream;
//import java.io.FileNotFoundException;
//import java.io.EOFException;
//import java.io.IOException;
//import java.io.ObjectInputStream;
/*import java.io.File;
import java.lang.IllegalStateException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import javax.swing.JOptionPane;*/
import java.io.*;
//import java.util.Locale;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Company extends JFrame {
private ArrayList<Employee> emp=new ArrayList<Employee>();
//Employee[] list=new Employee[7];
public void getEmployees(Employee emplo){
emp.add(emplo);
}
/*public void openTxt(){
try {
Scanner input=new Scanner(new File("Employees.txt"));
}
catch(FileNotFoundException e){
JOptionPane.showMessageDialog(null, "File Not Found.");
System.exit(1);
}
}*/
public void doRead() throws Exception{
//ArrayList<Employee> emp=new ArrayList<Employee>() ;
//Employee[] emp=new Employee[7];
//read from file
File data = new File("src/Employees.txt");
BufferedReader read = new BufferedReader(new FileReader(data));
String input;
int i = 0;
//int salesmen = 0;
while ((input = read.readLine()) != null) {
String [] lineParts = input.split(",");
/**
* the following block converts some of the strings inputted to
* the appropriate vartypes.
*/
String EmpNo=(lineParts[0]);
String type=lineParts[10];
String PostalCode = (lineParts[5]);
int phone = Integer.parseInt(lineParts[6]);
short DeptNo = (short) Integer.parseInt(lineParts[8]);
double Salary;
short card = (short) Integer.parseInt(lineParts[11]);
int dtype=0;
if(type.equals("FULL TIME")){
dtype=1;
}
else if(type.equals("SELLER")){
dtype=2;
}
else
dtype=3;
/**
* Creates employee instances depending on their type of employment
* (fulltime=1, parttime=3, salesman=2)
*/
switch (dtype) {
case 1 :
//empNo,firstname, lastname, address, city, PostalCode, phone,
//email, deptcode,Jobtype, salary, TimecardId, hoursW
Salary = Double.parseDouble(lineParts[10]);
emp.add(new FullTimeEmployee(EmpNo,lineParts[1], lineParts[2], lineParts[3],
lineParts[4], PostalCode, phone,
lineParts[7], DeptNo,type,Salary, card, 0.0));
i++;
break;
case 2 :
Salary = Double.parseDouble(lineParts[10]);
ArrayList<Orders> orders=new ArrayList<Orders>();
Salary = Double.parseDouble(lineParts[10]);
emp.add(new Salesman(EmpNo,lineParts[1], lineParts[2], lineParts[3],
lineParts[4], PostalCode, phone,
lineParts[7], DeptNo,type,Salary, card, 0.0, orders));
i++;
break;
case 3 :
Salary = Double.parseDouble(lineParts[10]);
emp.add(new PartTimeEmployee(EmpNo,lineParts[1], lineParts[2], lineParts[3],
lineParts[4], PostalCode, phone,
lineParts[7], DeptNo,type,Salary, card, 0.0));
i++;
break;
default :
break;
}
}
}
public ArrayList<Employee> getArray(){
return emp;
}
//test methodos gia tin proti epilogi-den deixnei tipota omws sto JTable ????
public /*JTable */ void getOptionA(){
ArrayList<Employee> list=getArray();
/*String[] columnNames = {"Code","First Name","Last Name","Address","Cisty","Postal Code","Phone","Email",
"Dept Code","Salary","Time Card","Hours"};*/
/* Object[][] data;
*/
JTable table = new JTable();
DefaultTableModel model = new DefaultTableModel();
table.setModel(model);
model.setColumnIdentifiers(new String[] {"Code","First Name","Last Name","Address","City","Postal Code","Phone","Email",
"Dept Code","Salary","Time Card","Hours"});
for( Employee current : list){
model.addRow(new Object[] {current.getCode(),current.getName(),current.getSurname(),
current.getAddress(),current.getCity(),current.getTK(),
current.getPhone(),current.getMail(),current.getDeptCode(),
current.getSalary(),current.getCard(),current.getHours()
});
}
/*JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);*/
//return table;
table.setPreferredScrollableViewportSize(new Dimension(500,50));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
public void showOptionA(){
getOptionA();
Company gui =new Company();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setSize(600, 400);
}
}
I call showOptionA() from a JButton located on another JFrame Class.
private void showEmployeesActionPerformed(java.awt.event.ActionEvent evt) {
Results showEmp=new Results();
//showEmp.setVisible(true);
//showEmp.setOptions(1);
Company company=new Company();
/*JTable table=company.getOptionA();
JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);
scrollPane.setViewportView(table);
table.setVisible(true);*/
company.showOptionA();
}
Basically i have a "main"JFrame with different options, and each button,representing a different option, calls the appropriate option method from Company Class.
When i click on the button "Show Employees Status". i want it to show the JTable above. Instead a new Frame opens but is blank??
EDIT: if i change showOptionA() to static, and then just call it inside showEmployeesActionPerformed , ( which is located in class PayrollForm)
public static void showOptionA(){
Company gui =new Company();
gui.getOptionA();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setSize(600, 400);
}
i now see the columns but with no data(empty)
This has nothing to do with calling revalidate as recommended by another and likely has all to do with calling a method on the wrong object. In your showEmployeesActionPerformed method you create a new Company object, one that is not visualized. The key is to call this method on the proper reference, on the visualized GUI. You do this by passing a reference to the visualized GUI object into the class that is wanting to call methods on it. This can be done via a setCompany method:
setCompany(Company company) {
this.company = company);
}
or via a constructor parameter.
I think the reason is your method showOptionA():
first you add your JTable and Model to your Company Object, which is your Frame. But right after it, you create a new Company Object, set the wanted Frame settings and show that object instead of your first Company object, where the table is.
You just could leave the gui thing out, and set DefaultCloseOperation directly on your Company object and set it visible true.
Some other suggestions:
You also should set the size of your frame, before you set it visible true.
And getters normally just give back the related object, instead of putting it on some list.
Might be there are some more mistakes in it, but it should at least show your table.
Call revalidate() after adding anything to JTable (or its model).
Ok problem Solved!. The problem was in getOptionA() method.
i set the model of the Jtable, but not the option to be visible. SO thats why it appeared empty. I corrected this by moving
try {
//try to read from text file
doRead();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "An Exception has Occured! The application will now close.");
System.exit(0);
}
table.revalidate();
add(scrollPane);
setVisible(true);
setSize(600, 400);
up,from showOptionA, up to getOptionA() method. By doing this showOptionA becomes useless(and thus i deleted it). Now i call getOptionA from the showEmployeesActionPerformed and its all ok :). Thanks to all people who replied to my wuestion, and special thanks to Hovercraft Full Of Eels . He helped me undeestand why the table wasnt appearing the way i wanted it to
Related
Good evening.
I have a problem using NetBeans v 11.1 for Windows.
I try to open two Frame Forms when the user select an item from a Combo Box.
The forms I want open have a string param in their constructors.
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
Visualizza visualizza = new Visualizza(this.auth);
Inserisci inserisci = new Inserisci(this.auth);
var getItem = jComboBox1.getSelectedItem();
switch(getItem.toString()){
case ("Visualizza Iscritti nel Sistema"):
visualizza.setVisible(true);
break;
case ("Inserisci Atleti nel Sistema"):
inserisci.setVisible(true);
break;
default:
break;
}
} catch (IOException ex) {
Logger.getLogger(Select.class.getName()).log(Level.SEVERE, null, ex);
}
}
The constructors code is:
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonGroup;
import org.json.*;
public class Visualizza extends javax.swing.JFrame {
//Attributes declaration
...
public Visualizza(String auth) throws IOException {
initComponents();
btnRicerca.setVisible(false);
txtField.setVisible(false);
this.auth = auth;
Player[] player;
Requests r = new Requests("https://www.kingofthecage.it/API/getAllPlayers.php", auth);
r.sendGet();
if (r.res.equals("Errore") || r.res.equals("[]"))
{
List.removeAll();
List.add(errorMessage);
}
else
{
JSONArray arr = new JSONArray(r.res);
player = new Player[arr.length()];
String[] list = new String[arr.length()];
for (int i = 0; i < arr.length(); i++)
{
String id = arr.getJSONObject(i).getString("ID");
String name = arr.getJSONObject(i).getString("NOME");
String surname = arr.getJSONObject(i).getString("COGNOME");
String date = arr.getJSONObject(i).getString("DATA_NASCITA");
String birthplace = arr.getJSONObject(i).getString("LUOGO_NASCITA");
String residence = arr.getJSONObject(i).getString("RESIDENZA");
String cf = arr.getJSONObject(i).getString("CODICE_FISCALE");
String mail = arr.getJSONObject(i).getString("MAIL");
String mobile = arr.getJSONObject(i).getString("CELLULARE");
String team = arr.getJSONObject(i).getString("NOME_SQUADRA");
player[i] = new Player(id, name, surname, date, birthplace, residence, cf, mobile, mail, team);
List.add(list[i] = player[i].getPlayerString());
}
}
I import the library org.json to parse and interact with a response from a server, called with an HTTP Request and in the for cycle I returned params in a class called Player.
If I run the project from NetBeans works perfectly, the issue come when I build the project and I try to execute the .jar file saved in "./dist" folder. Substantially when I select a value from the ComboBox nothing happens but, as i've said, if I try to run the same code in NetBeans IDE it works.
I specify that I never change any setting from NetBeans IDE.
I hope you can solve my problem!
I'm a beginner. I want to write a weather app that gets some information from the web and show it to the user. But I have trouble to pass the user input to the JSON method. Can anybody help me?
the problem is in ActionListener part.
import com.google.gson.*;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.imageio.*;
public class Weather extends JFrame implements ActionListener {
static JButton getWeather;
static JTextField inputZip, showCity, showState, showCondition, showTemp;
static JLabel enterZip, city, state, condition, temp, image;
public static double temp_f, temp_c;
static Image pic;
public static String zip, jCity, jState, jCondition, fORc;
public Weather() throws Exception {
//Button
getWeather = new JButton("Get Weather");
getWeather.addActionListener(this);
//TextFiels
inputZip = new JTextField(10);
showCity = new JTextField(10);
showState = new JTextField(10);
showCondition = new JTextField(10);
showTemp = new JTextField(10);
//Labels
enterZip = new JLabel ("Enter Zipcode:");
city = new JLabel ("City:");
state = new JLabel ("State:");
condition = new JLabel ("Condition:");
temp = new JLabel ("temp:");
//Radio Buttons
CheckboxGroup tUnit = new CheckboxGroup();
Checkbox f = new Checkbox ("f", tUnit, true);
Checkbox c = new Checkbox ("c", tUnit, false);
//Image
URL coldPicURL = new URL("https://cdn1.iconfinder.com/data/icons/xmas-color/512/snow_snowflake_winter_cold_weather-128.png");
URL hotPicURL = new URL("http://yowindow.com/img/yo_128.png");
URL picURL = new URL ("http://findicons.com/files/icons/2796/metro_uinvert_dock/128/the_weather_channel.png");
if (temp_f!=0 && temp_f<=60)
pic = ImageIO.read(coldPicURL);
else if (temp_f > 60)
pic = ImageIO.read(hotPicURL);
else
pic = ImageIO.read(picURL);
image = new JLabel(new ImageIcon(pic));
//Frame
JFrame weather = new JFrame ("Weather App");
weather.setVisible(true);
weather.setSize(500,250);
weather.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Panels
JPanel pInput = new JPanel();
JPanel pDisplay = new JPanel();
JPanel pDisplayInfo = new JPanel();
JPanel pTempUnits = new JPanel();
JPanel pImage = new JPanel();
//Panels' Layout
pInput.setLayout(new FlowLayout());
pDisplay.setLayout(new BorderLayout());
pDisplayInfo.setLayout(new GridLayout(5,2));
pTempUnits.setLayout(new FlowLayout());
//Frame Layout
weather.add(pInput, BorderLayout.NORTH);
weather.add(pDisplay, BorderLayout.CENTER);
pDisplay.add(pDisplayInfo, BorderLayout.NORTH);
pDisplay.add(pTempUnits, BorderLayout.CENTER);
weather.add(pImage, BorderLayout.EAST);
//Insertion the objects into the panels
pInput.add(enterZip);
pInput.add(inputZip);
pInput.add(getWeather);
pDisplayInfo.add(city);
pDisplayInfo.add(showCity);
pDisplayInfo.add(state);
pDisplayInfo.add(showState);
pDisplayInfo.add(condition);
pDisplayInfo.add(showCondition);
pDisplayInfo.add(temp);
pDisplayInfo.add(showTemp);
pTempUnits.add(c);
pTempUnits.add(f);
pImage.add(image);
}
public void actionPerformed(ActionEvent e) {
zip = Weather.inputZip.getText();
//HERE'S WHERE I'M STUCKED !!! :(
getJson (zip);
showCity.setText(jCity);
showState.setText(jState);
showCondition.setText(jCondition);
if (fORc.equals("f"))
showTemp.setText(Double.toString(temp_f));
if (fORc.equals("c"))
showTemp.setText(Double.toString(temp_c));
}
public static void getJson(String zip) throws Exception {
String json="", line;
JsonElement jse;
final String key = "7b86aadc43344a90";
JsonParser parser = new JsonParser();
URL url = new URL("http://api.wunderground.com/api/" +
key + "/conditions/q/" + zip + ".json");
InputStream is = url.openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
while ((line = rd.readLine()) != null)
json += line;
rd.close();
jse = parser.parse(json);
jCity=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("display_location").getAsJsonObject().get("city").getAsString();
jState=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("display_location").getAsJsonObject().get("state").getAsString();
jCondition=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("weather").getAsString();
temp_f=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("temp_f").getAsDouble();
temp_c=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("temp_c").getAsDouble();
}
public void itemStateChanged (ItemEvent ie){
Checkbox cb = (Checkbox)ie.getItemSelectable();
fORc = cb.getLabel();
}
public static void main(String[] args) throws Exception {
Weather w = new Weather();
}
}
On a first level:
getJson (zip);
that call throws an exception. And in Java you have to either try/catch that exception; or add it to the signature of the method this happens (using the throws keyword). In your case, that is not possible, as you are actually overriding an existing method; and then you can't add a throws statement to the method signature.
But the real answer here is: slow down. The above compiler error is about a super basic thing within Java. When you don't know what an Exception is, and how to properly deal with that, then you are many hours of learning away from writing a Swing UI application that wants to deal with JSON data from a remote site.
This also becomes obvious when looking in how you structure your code. You clearly separate responsibilities; you create classes around those that help you coming up with a clean OO based model. For example, you would fully separate the UI layer (swing) that displays information from the specifics where such information is coming from. Your JFrame shouldn't know anything about JSON input.
Your code shows nothing of that. I call this the "you should learn to crawl before going for hurdle racing" syndrome.
First,I think you'd better provide more detail information, what kind of problem is? Is that kind of exception for an unexpected result? Or you can just post the result for others to take a look.
Second, I tried to run your program. There are two issue in that.
1. in the code that you wrote a comment : //HERE'S WHERE I'M STUCKED !!! :(
zip = Weather.inputZip.getText();
//HERE'S WHERE I'M STUCKED !!! :(
getJson (zip);
showCity.setText(jCity);
showState.setText(jState);
the method getJson() you have "throws Exception", so when you invoke the method, you also need to deal with the exception maybe you can just catch the exception like this:
zip = Weather.inputZip.getText();
//HERE'S WHERE I'M STUCKED !!! :(
try {
getJson (zip);
} catch (Exception e1) {
e1.printStackTrace();
}
showCity.setText(jCity);
showState.setText(jState);
Or you can continue throw the exception.
when finished the previous problem, I found the "fORc" will meet a null pointer exception which you need to check your process when to pass the var.
Third,still about the fORc, in your code, you wrote
if (fORc.equals("f"))
showTemp.setText(Double.toString(temp_f));
if (fORc.equals("c"))
showTemp.setText(Double.toString(temp_c));
But I suggest you can change like this, then you can deal when the fORc is a null:
if (null == fORc)
//do something. like throw exception
if ("f".equals(fORc))
showTemp.setText(Double.toString(temp_f));
if ("c".equals(fORc))
showTemp.setText(Double.toString(temp_c));
Hope could help you.
I am a greenhand on Lucene, and I want to implement auto suggest, just like google, when I input a character like 'G', it would give me a list, you can try your self.
I have searched on the whole net.
Nobody has done this , and it gives us some new tools in package suggest
But i need an example to tell me how to do that
Is there anyone can help ?
I'll give you a pretty complete example that shows you how to use AnalyzingInfixSuggester. In this example we'll pretend that we're Amazon, and we want to autocomplete a product search field. We'll take advantage of features of the Lucene suggestion system to implement the following:
Ranked results: We will suggest the most popular matching products first.
Region-restricted results: We will only suggest products that we sell in the customer's country.
Product photos: We will store product photo URLs in the suggestion index so we can display them in the search results, without having to do an additional database lookup.
First I'll define a simple class to hold information about a product in Product.java:
import java.util.Set;
class Product implements java.io.Serializable
{
String name;
String image;
String[] regions;
int numberSold;
public Product(String name, String image, String[] regions,
int numberSold) {
this.name = name;
this.image = image;
this.regions = regions;
this.numberSold = numberSold;
}
}
To index records in with the AnalyzingInfixSuggester's build method you need to pass it an object that implements the org.apache.lucene.search.suggest.InputIterator interface. An InputIterator gives access to the key, contexts, payload and weight for each record.
The key is the text you actually want to search on and autocomplete against. In our example, it will be the name of the product.
The contexts are a set of additional, arbitrary data that you can use to filter records against. In our example, the contexts are the set of ISO codes for the countries we will ship a particular product to.
The payload is additional arbitrary data you want to store in the index for the record. In this example, we will actually serialize each Product instance and store the resulting bytes as the payload. Then when we later do lookups, we can deserialize the payload and access information in the product instance like the image URL.
The weight is used to order suggestion results; results with a higher weight are returned first. We'll use the number of sales for a given product as its weight.
Here's the contents of ProductIterator.java:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.lucene.search.suggest.InputIterator;
import org.apache.lucene.util.BytesRef;
class ProductIterator implements InputIterator
{
private Iterator<Product> productIterator;
private Product currentProduct;
ProductIterator(Iterator<Product> productIterator) {
this.productIterator = productIterator;
}
public boolean hasContexts() {
return true;
}
public boolean hasPayloads() {
return true;
}
public Comparator<BytesRef> getComparator() {
return null;
}
// This method needs to return the key for the record; this is the
// text we'll be autocompleting against.
public BytesRef next() {
if (productIterator.hasNext()) {
currentProduct = productIterator.next();
try {
return new BytesRef(currentProduct.name.getBytes("UTF8"));
} catch (UnsupportedEncodingException e) {
throw new Error("Couldn't convert to UTF-8");
}
} else {
return null;
}
}
// This method returns the payload for the record, which is
// additional data that can be associated with a record and
// returned when we do suggestion lookups. In this example the
// payload is a serialized Java object representing our product.
public BytesRef payload() {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(currentProduct);
out.close();
return new BytesRef(bos.toByteArray());
} catch (IOException e) {
throw new Error("Well that's unfortunate.");
}
}
// This method returns the contexts for the record, which we can
// use to restrict suggestions. In this example we use the
// regions in which a product is sold.
public Set<BytesRef> contexts() {
try {
Set<BytesRef> regions = new HashSet();
for (String region : currentProduct.regions) {
regions.add(new BytesRef(region.getBytes("UTF8")));
}
return regions;
} catch (UnsupportedEncodingException e) {
throw new Error("Couldn't convert to UTF-8");
}
}
// This method helps us order our suggestions. In this example we
// use the number of products of this type that we've sold.
public long weight() {
return currentProduct.numberSold;
}
}
In our driver program, we will do the following things:
Create an index directory in RAM.
Create a StandardTokenizer.
Create an AnalyzingInfixSuggester using the RAM directory and tokenizer.
Index a number of products using ProductIterator.
Print the results of some sample lookups.
Here's the driver program, SuggestProducts.java:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.search.suggest.analyzing.AnalyzingInfixSuggester;
import org.apache.lucene.search.suggest.Lookup;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.Version;
public class SuggestProducts
{
// Get suggestions given a prefix and a region.
private static void lookup(AnalyzingInfixSuggester suggester, String name,
String region) {
try {
List<Lookup.LookupResult> results;
HashSet<BytesRef> contexts = new HashSet<BytesRef>();
contexts.add(new BytesRef(region.getBytes("UTF8")));
// Do the actual lookup. We ask for the top 2 results.
results = suggester.lookup(name, contexts, 2, true, false);
System.out.println("-- \"" + name + "\" (" + region + "):");
for (Lookup.LookupResult result : results) {
System.out.println(result.key);
Product p = getProduct(result);
if (p != null) {
System.out.println(" image: " + p.image);
System.out.println(" # sold: " + p.numberSold);
}
}
} catch (IOException e) {
System.err.println("Error");
}
}
// Deserialize a Product from a LookupResult payload.
private static Product getProduct(Lookup.LookupResult result)
{
try {
BytesRef payload = result.payload;
if (payload != null) {
ByteArrayInputStream bis = new ByteArrayInputStream(payload.bytes);
ObjectInputStream in = new ObjectInputStream(bis);
Product p = (Product) in.readObject();
return p;
} else {
return null;
}
} catch (IOException|ClassNotFoundException e) {
throw new Error("Could not decode payload :(");
}
}
public static void main(String[] args) {
try {
RAMDirectory index_dir = new RAMDirectory();
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_48);
AnalyzingInfixSuggester suggester = new AnalyzingInfixSuggester(
Version.LUCENE_48, index_dir, analyzer);
// Create our list of products.
ArrayList<Product> products = new ArrayList<Product>();
products.add(
new Product(
"Electric Guitar",
"http://images.example/electric-guitar.jpg",
new String[]{"US", "CA"},
100));
products.add(
new Product(
"Electric Train",
"http://images.example/train.jpg",
new String[]{"US", "CA"},
100));
products.add(
new Product(
"Acoustic Guitar",
"http://images.example/acoustic-guitar.jpg",
new String[]{"US", "ZA"},
80));
products.add(
new Product(
"Guarana Soda",
"http://images.example/soda.jpg",
new String[]{"ZA", "IE"},
130));
// Index the products with the suggester.
suggester.build(new ProductIterator(products.iterator()));
// Do some example lookups.
lookup(suggester, "Gu", "US");
lookup(suggester, "Gu", "ZA");
lookup(suggester, "Gui", "CA");
lookup(suggester, "Electric guit", "US");
} catch (IOException e) {
System.err.println("Error!");
}
}
}
And here is the output from the driver program:
-- "Gu" (US):
Electric Guitar
image: http://images.example/electric-guitar.jpg
# sold: 100
Acoustic Guitar
image: http://images.example/acoustic-guitar.jpg
# sold: 80
-- "Gu" (ZA):
Guarana Soda
image: http://images.example/soda.jpg
# sold: 130
Acoustic Guitar
image: http://images.example/acoustic-guitar.jpg
# sold: 80
-- "Gui" (CA):
Electric Guitar
image: http://images.example/electric-guitar.jpg
# sold: 100
-- "Electric guit" (US):
Electric Guitar
image: http://images.example/electric-guitar.jpg
# sold: 100
Appendix
There's a way to avoid writing a full InputIterator that you might find easier. You can write a stub InputIterator that returns null from its next, payload and contexts methods. Pass an instance of it to AnalyzingInfixSuggester's build method:
suggester.build(new ProductIterator(new ArrayList<Product>().iterator()));
Then for each item you want to index, call the AnalyzingInfixSuggester add method:
suggester.add(text, contexts, weight, payload)
After you've indexed everything, call refresh:
suggester.refresh();
If you're indexing large amounts of data, it's possible to significantly speedup indexing using this method with multiple threads: Call build, then use multiple threads to add items, then finally call refresh.
[Edited 2015-04-23 to demonstrate deserializing info from the LookupResult payload.]
I am trying to pass values from my database java file to my frame java file.BY creating a function like "frame java . get value (name ,phone, date ) " and receiving the value in the frame java file . I tried to print the passed value in the console it works fine, but when i try to set value to the text field it doesn't display the text in the text filed... I don't what's wrong can any one help me to sort out this issue.
Here is database java function
public void check_room(String roomno, String date) throws SQLException {
String sql = "select * from customerinfo where roomno='" + roomno
+ "'and cdate='" + date + "' ";
System.out.print("search method called \n ");
System.out.print("\n ");
try {
con = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe", "hotel", "hotel");
} catch (SQLException ex) {
// Logger.getLogger(checkout.class.getName()).log(Level.SEVERE,
// null, ex);
}
sate = con.createStatement();
rs = sate.executeQuery(sql);
int tmp = 0;
try {
while (rs.next()) {
System.out.print("search found \n ");
String name = rs.getString("GUEST_NAME");
String phono = rs.getString("GUEST_PHO");
String addr = rs.getString("G_ADDR");
String paid = rs.getString("PAID");
String total = rs.getString("TOTAL");
String balance = rs.getString("BALANCE");
System.out.println(name);
mainmenu menu = new mainmenu();
menu.getvalue(name, phono, addr, paid, total, balance);
tmp++;
}
} catch (SQLException ex) {
// Logger.getLogger(checkout.class.getName()).log(Level.SEVERE,
// null, ex);
}
if (tmp <= 0) {
JOptionPane.showMessageDialog(null, "no details found ");
}
}
==========================================================================
This is my frame java file
public void getvalue(String name, String phono, String addr, String paid,String total, String balance) {
nam.setText(name);
pho.setText(phono);
// mainmenu();
}
I edited as u said but getting error . I have attached my skeleton code
and the error i get, below
edited code.
database file
public class OracelThinconnection
{
private MainMenu menu;
public OracelThinconnection(MainMenu menu)
{
this.menu=menu;
..................
.................
.............
========================================================================
Error i get
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - cannot find symbol
symbol: constructor OracelThinconnection()
location: class bookingapp.OracelThinconnection
at bookingapp.MainMenu.jButton1ActionPerformed(MainMenu.java:1438)
at bookingapp.MainMenu.access$300(MainMenu.java:33)
at bookingapp.MainMenu$4.actionPerformed(MainMenu.java:379)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6263)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6028)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
I don't understand the code you've not shown, but a guess as to your problem is that you're creating a new instance of your GUI, one not visualized, and trying to send information to it, while the visualized GUI sits unperturbed and un-updated.
The key is that you're creating a new instance of your mainmenu GUI, one that has no relationship to the one that is displayed. Passing data to this new instance will have no effect on the displayed GUI.
Here:
mainmenu menu= new mainmenu();
menu. getvalue (name, phono, addr, paid, total, balance);
You're creating a new mainmenu object (the class should be named MainMenu).
A solution, give your Database class a MainMenu field, and pass into this field a valid reference to the main gui, and then call methods on the GUI, but only on the Swing event thread. For example:
public class MyDataBase {
private MyGui gui;
// constructor gets passed a reference to the valid displayed GUI
public MyDataBase(MyGui gui) {
this.gui = gui;
}
public void someDataBaseMethod() {
// get database information
// now you can call methods on the actual displayed GUI
// but on the Swing event thread only. The SwingUtilities.invokeLater
// with the Runnable is required to be sure that you don't mess up
// Swing's threading model.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// this method below is being called on the
// displayed MyGui instance.
gui.updateGuiWithInformation(....); // some update method of the GUI
}
});
}
The key -- don't create a new GUI instance inside of the database code.
OK, you've changed your code and now have a constructor that looks like so:
public OracelThinconnection(MainMenu menu) {
// ....
}
Now you need to look at the line that the error is pointing to, MainMenu.java:1438, line 1438 (1438????) of the MainMenu class. On that line you likely call the OracelThinconnection constructor but are not passing the current MainMenu instance into it. The new constructor will accept a MainMenu reference, but when you call the constructor, you now have to remember to pass that reference in to the constructor.
Specifically, change it from
// not sure what you name the variable below
// but I just gave it thinConnection for now.
OracelThinconnection thinConnection = new OracelThinconnection();
to this:
OracelThinconnection thinConnection = new OracelThinconnection(this);
or if this doesn't work, then
OracelThinconnection thinConnection = new OracelThinconnection(MainMenu.this);
As an addendum, your code obviously has more than 1400 lines which tells you that you've got some huge God class that tries to do any thing and everything. I strongly urge you to refactor this code, to make smaller classes, each with their own sphere of responsibilities, else you will not be able to debug or enhance this program.
I'm new to wicket. I have a table called students2modules with 2 fields: Stud_Username,Module_Code which links students to modules taken. I want to register a student as taking a particular module. When the user selects a student, only the modules that student is not yet registered for should come up:
package myapp.project;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.Model;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
public class AddStud2Mod extends BasePage {
private List students =new ArrayList();
private List modules=new ArrayList();
private ModalWindow message;
private InformationPanel panel;
private DropDownChoice studChoice;
private DropDownChoice moduleChoice;
public AddStud2Mod(){
super();
Form stud2mod = new Form("addstud2mod");
add(stud2mod);
try{
DB db=new DB();
String query="select Stud_Username from students;";
System.out.println(query);
db.connect();
ResultSet rs=db.execSQL(query);
while(rs.next()){
String studentUname=rs.getString("Stud_Username");
students.add(studentUname);
}
db.close();
}
catch(Exception e){
e.printStackTrace();
}
studChoice = new DropDownChoice("studentChoice",new Model(),students);
moduleChoice = new DropDownChoice("modChoice",new Model(),modules);
studChoice.add(new AjaxFormComponentUpdatingBehavior("onchange")
{
#Override
protected void onUpdate(AjaxRequestTarget target)
{
try{
DB db=new DB();
db.connect();
String query="select distinct Module_Code from modules where Module_Code NOT IN(Select Module_Code from students2modules where Stud_Username="+"'"+getUserName()+"');";
System.out.println(query);
ResultSet rs=db.execSQL(query);
while(rs.next()){
String moduleNotRegistered =rs.getString("Module_Code");
modules.add(moduleNotRegistered);
}
moduleChoice.setChoices(modules);
}
catch(Exception e){
e.printStackTrace();
}
target.addComponent(moduleChoice);
}
});
final FeedbackPanel feedback=new FeedbackPanel("msgs");
feedback.setOutputMarkupId(true);
add(feedback);
final InvalidInputIndicator codeLabel = new InvalidInputIndicator("codeLabel",moduleChoice);
codeLabel.setOutputMarkupId(true);
stud2mod.add(codeLabel);
final InvalidInputIndicator studLabel = new InvalidInputIndicator("usernameLabel",studChoice);
studLabel.setOutputMarkupId(true);
stud2mod.add(studLabel);
AjaxButton ok=new AjaxButton("confirm"){
public void onSubmit(AjaxRequestTarget target,Form form){
try{
DB db=new DB();
db.connect();
String query= "Insert into students2modules Values('"+getUserName()+"'"+",'"+moduleChoice.getDefaultModelObjectAsString()+"')";
System.out.println(query);
db.updateSQL(query);
modules.clear();
db.close();
}
catch(Exception e){
e.printStackTrace();
}
InformationPanel.add2ModuleMessage();
message.show(target);
}
protected void onError(AjaxRequestTarget target,Form form){
target.addComponent(feedback);
target.addComponent(studLabel);
target.addComponent(codeLabel);
}
};
stud2mod.add(ok);
Button cancel=new Button("cancel"){
public void onSubmit(){
AddStud2Mod lecturer=new AddStud2Mod();
setResponsePage(lecturer);
}
};
stud2mod.add(cancel);
studChoice.setRequired(false);
studChoice.setOutputMarkupId(true);
moduleChoice.setRequired(false);
moduleChoice.setOutputMarkupId(true);
stud2mod.add(moduleChoice);
stud2mod.add(studChoice);
message=new ModalWindow("InformationDialog");
add(message);
panel=new InformationPanel(message.getContentId(),message);
message.setContent(panel);
message.setCssClassName(ModalWindow.CSS_CLASS_BLUE);
message.setTitle("Important Information");
message.setResizable(false);
message.setInitialHeight(150);
message.setInitialWidth(150);
message.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
public void onClose(AjaxRequestTarget target) {
AddStud2Mod as2mod =new AddStud2Mod();
setResponsePage(as2mod);
}
});
}
private String getUserName(){
return studChoice.getDefaultModelObjectAsString();
}
}
Here is the problem-the insert statement in the onSubmit- '' seems to get inserted for Module_Code, no matter what module code has been selected and I have no idea why. The student username is inserted ok but not the module code. Thank you so much for your help and sorry for the large chunks of code(included so you can read all my code for the class).
A few general remarks: you have UI logic (Ajax,..) and 'bussiness' logic ('get modules for student') all mixed up. Consider to separete them by introducing a 'service' layer. Also, i would NOT use the student name as you do in your data model. What if a student changes the name? Or a modul gets renamed? Use generated ID's instead.
The way you use jdbc opens your app to sql injections. Never ever build your queries concatinating user provided input. Use prepared statements for this (the query cache of your DB will like this too ;))
Your actual problem: You use ajax. With Ajax, the changes in the UI do not get pushed into the Model. You get the student name ok because you have an AjaxFormComponentUpdatingBehavior added to the DDC.
hope that helps
Edit: looking at your profile, i see that you have asked a few questions here, but never accepted an answer for any of these. I strongly suggest you do so, otherwise people will just ignore your questions.