get data searching from radiobutton to combobox - java

I want to search an item, but I get troubled that radio button and combo box show nothing. If you want to get show combo box, radio button must get picked please. I confused what code that I must type for radio button. Can you help me?
private void txtSearchKeyReleased(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
try {
String menu_name = txtSearch.getText();
Statement stmt;
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from menu WHERE menu_name like '%" + menu_name + "%' ");
if (rs.next()) {
txtMID.setText("" + rs.getString("menu_id"));
cmbMCat.setSelectedItem("" + rs.getString("menu_cat")); //combo box
txtMName.setText("" + rs.getString("menu_name"));
txtMPrice.setText("" + rs.getString("menu_price"));
//DefaultTableModel model = (DefaultTableModel) tblMenu.getModel();
//model.addRow(new Object[]{txtMID.getText(), type, cmbMCat.getSelectedItem(), txtMName.getText(), txtMPrice.getText()});
}
}
catch (SQLException | HeadlessException e) {
}
}
avocado roll from database
category and type database
now,

You have to write it like this:
try{
for (int i = 0; i < itemCount; i++) {
combo.removeItemAt(0);
}
rs = stmt.executeQuery("select * from menu_cat");
int i = 0;
String[] categories = new String[99];
while(rs.next()){
categories[i] = rs.getString("menu_cat");
i++;
}
i = 0;
while(!categories[i].equals("")){
combo.addItem(categories[i]);
i++;
}
}catch (Exception e){
System.out.println("Unimportant error: " + e);
}
So don't care about this error!

I would create two events, one on the radiobox "Food" and the other on the radiobox "Drink". I suppose, that you have the two radioboxes in one buttongroup.
private void radio_foodFocusGained(java.awt.event.FocusEvent evt) {
int itemCount = combo.getItemCount();
for (int i = 0; i < itemCount; i++) {
combo.removeItemAt(0);
}
combo.addItem("Food Item 1");
combo.addItem("Food Item 2");
}
private void radio_drinkFocusGained(java.awt.event.FocusEvent evt) {
int itemCount = combo.getItemCount();
for (int i = 0; i < itemCount; i++) {
combo.removeItemAt(0);
}
combo.addItem("Drink Item 1");
combo.addItem("Drink Item 2");
}
So the result is now when you're clicking on the radiobox "Food" the fooditems appear in the combobox and if you are clicking on the radiobox "Drink" the drinkitems appear in the combobox.

So second try, with this code it should work, it checks first the menu_typ and the application will decide between "Food" and "Drink". At the end the application set the selected item in your ComboBox to your menu_cat.
if(rs.getString("menu_type").equals("Food")){
radio_food.setSelected(true);
radio_drink.setSelected(false);
}else if(rs.getString("menu_type").equals("Drink")){
radio_drink.setSelected(true);
radio_food.setSelected(false);
}else{
System.out.println("No valid menu type");
}
combo.setSelectedItem(rs.getString("menu_cat"));
I hope I have helped you!

For filling your ComboBox you need to execute a new query first, this query gives you all different menu_cat back. First you need to delete the existing entries in the ComboBox.
for (int i = 0; i < itemCount; i++) {
combo.removeItemAt(0);
}
rs = stmt.executeQuery("select * from menu_cat");
int i = 0;
String[] categories = new String[99];
while(rs.next()){
categories[i] = rs.getString("menu_cat");
i++;
}
i = 0;
while(!categories[i].equals("")){
combo.addItem(categories[i]);
i++;
}
This code does the following steps:
Delete all entries in your ComboBox
Execute a new query
Save the all values in an array
Add all items in the array to your ComboBox

Related

Selecting Values from a Database with a Query in Java and Use them as a Variable and Insert it in another Table

So I selected some values from a database table to divide them in little groups and insert it into another table within the database by putting the selected values in an ArrayList and taking the size of that ArrayList to do the math.
But after I do the math, I'm just left with the variables containing the information I need. But, I cant put them into the other table because they're not the same things that I selected in the beginning. They're just numbers now. I really need to insert those variables into the other table but when I do, I get foreign key constraint fails error and I think that's because the variable is not a foreign key anymore but just a number. I don't know if there is a solution but it would help me allot. Here is my code:
private void spelersVerdelenMouseClicked(java.awt.event.MouseEvent evt) {
String comboBoxValue = jComboBoxDeelnemer.getSelectedItem().toString();
String spelerRonde1 = "SELECT lid, toernooi FROM deelnemer where toernooi LIKE " + comboBoxValue ;
ArrayList<String> dlnmrs = new ArrayList<>();
try {
PreparedStatement pstat = con.prepareStatement(spelerRonde1);
ResultSet rs = pstat.executeQuery();
while (rs.next()) {
dlnmrs.add(rs.getString("lid"));
for (int i = 0; i < dlnmrs.size(); i++) {
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane,e);
}
verdeelTafels(1, dlnmrs.size());
private void verdeelTafels(int ronde, int aantalDeelnemers) {
System.out.println(aantalDeelnemers);
int aantalTafels = (int) aantalDeelnemers / AANTAL_SPELERS_PER_TAFEL;
int restSpelerPerRonde = aantalDeelnemers % AANTAL_SPELERS_PER_TAFEL;
if (aantalDeelnemers == (AANTAL_SPELERS_PER_TAFEL * 2)) {
aantalTafels = 1;
restSpelerPerRonde = 0;
}
for (int i = 0; i < aantalTafels; i++) {
int maxSpelersPerTafel = AANTAL_SPELERS_PER_TAFEL;
if (i == aantalTafels - 1) {
maxSpelersPerTafel += restSpelerPerRonde;
}
System.out.println("Tafel " + (i + 1) + " heeft " + maxSpelersPerTafel + " deelnemers.");
//spelersDoorlopen
for (int j = 0; j < maxSpelersPerTafel; j++) {
String query = "insert into spelerPerTafel (lid,tafel,ronde) select lcode,tfcode,rcode from lid,tafel,ronde ";
try{
PreparedStatement pstat = con.prepareStatement(query);
pstat.execute(query);
}
catch (Exception e) {
JOptionPane.showMessageDialog(rootPane,e);
System.out.println(e);
}
}
}
}
try
String query = "insert into tableA select * from tableB where XXX";
using where condition can implement to divide the tableB

How to create a list using PreparedStatement?

I have following codes:
-------class------------
private class SystemHealthAlert implements Work {
List<MonitorAlertInstance> systemHealthAlertList;
private String queryString;
// private java.util.Date startDate;
// private java.util.Date endDate;
#Override
public void execute(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(queryString);
int index = 1;
ResultSet rs = ps.executeQuery();
int columnCount = rs.getMetaData().getColumnCount();
while(rs.next())
{
//String[] row = new String[columnCount];
//results.set(index, element);
//for (int i=0; i <columnCount ; i++)
// {
// row[i] = rs.getString(i + 1);
// }
systemHealthAlertList.add(row);
}
rs.close();
ps.close();
}
}
---------Method-----------
public List<MonitorAlertInstance> getSystemHealthAlert(Long selectedSensorId) {
List<MonitorAlertInstance> systemHealthAlertList;
try {
// Add SELECT with a nested select to get the 1st row
String queryString = "select min(MONITOR_ALERT_INSTANCE_ID) as MONITOR_ALERT_INSTANCE_ID, description" +
" from ems.monitor_alert_instance " +
" where description in (select description from monitor_alert_instance" +
" where co_mod_asset_id = " + selectedSensorId +
" )" +
" group by description";
SystemHealthAlert work = new SystemHealthAlert();
// work.coModAssetId = coModAssetId;
work.queryString = queryString;
getSession().doWork(work);
systemHealthAlertList = work.systemHealthAlertList;
} catch (RuntimeException re) {
// log.error("getMostRecentObservationId() failed", re);
throw re;
}
//log.info("End");
return systemHealthAlertList;
}
My query returns three rows from DB. How can I return systemHealthAlertList from the class that will have all the three rows of the query.
In method execute, you should fill your List<MonitorAlertInstance> systemHealthAlertList with instances of MonitorAlertInstance. Create a new instance of MonitorAlertInstance inside the while loop where you retrieve the data:
//You don't need this line, remove it
//int columnCount = rs.getMetaData().getColumnCount();
while(rs.next()) {
//create a new instance of MonitorAlertInstance per ResultSet row
MonitorAlertInstance monitor = new MonitorAlertInstance();
//set the fields from the ResultSet in your MonitorAlertInstance fields
//since I don't know the fields of this class, I would use field1 and field2 as examples
monitor.setField1(rs.getInt(1));
monitor.setField2(rs.getString(2));
//and on...
systemHealthAlertList.add(monitor);
}
Apart from this problem, you should initialize your List<MonitorAlertInstance> systemHealthAlertList variable before use it:
systemHealthAlertList = new ArrayList<MonitorAlertInstance>();
while(rs.next()) {
//content from previous code...
}
Define a class/bean to hold the data from one given row. Loop through your rows, and create one instance of that class for each row you have. Add these instances to some List. Return the List of these 3 instances.

INSERT row does not update JTable in GUI

As mentioned in the header I cannot get my JTable to update with a new row unless I restart the program. When I restart, the new row is there and everything is as it should be. I have tried revalidating/repainting the panel and frame, I have tried the fire methods. I'm at a loss. Thanks in advance
ActionListener (in adminGUI class) for 'Add' button:
if(source.equals(add2)){
String c = itb.getText();
int a = main.getResults();
boolean matches = Pattern.matches("[A-Z][a-z]+", c);
if(matches == true){
main.addGenre(a, c);
}
String Method(in main class) to add a row to the database table:
public static void addGenre(int a, String b){
int rowsAdded;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection connect =DriverManager.getConnection("jdbc:odbc:MovieDB");
Statement stmt = connect.createStatement();
String query = "INSERT INTO Genres (genre_id, genre_name)" + "VALUES(" + a + ", '" + b + "')";
rowsAdded = stmt.executeUpdate(query);
}catch(Exception exc){}
}
Method(also in main class) to increment the auto-increment-key column:
public static int getResults(){
int a = 0;
ResultSet ints = main.getResults("Select genre_id from Genres");
try {
while(ints.next()){
int d = ints.getInt("genre_id");
if(d>a){
a = d;
}
a++;
}
} catch (SQLException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
return a;
}
JTable details:
ResultSet rs1 = main.getResults("Select * from Genres");
JTable tab1 = new JTable(DbUtils.resultSetToTableModel(rs1));
DbUtils.resultSetToTableModel details :
public class DbUtils {
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector columnNames = new Vector();
// Get the column names
for (int column = 0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1));
}
// Get all rows.
Vector rows = new Vector();
while (rs.next()) {
Vector newRow = new Vector();
for (int i = 1; i <= numberOfColumns; i++) {
newRow.addElement(rs.getObject(i));
}
rows.addElement(newRow);
}
return new DefaultTableModel(rows, columnNames);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
"I cannot get my JTable to update with a new row unless I restart the program."
I think what you're expecting is that when the database table update, so should your JTable. It doesn't really work like that. You need to update the TableModel, and the JTable will be automatically updated
Since resultSetToTableModel returns a DefuaultTableModel, you can use either of the two methods from DefaultTableModel:
public void addRow(Object[] rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
public void addRow(Vector rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
So when your are adding the data to the database, you also want to update the DefaultTableModel like this
public static void addGenre(Integer a, String b){
...
rowsAdded = stmt.executeUpdate(query);
if (rowsAdded > 0) {
DefaultTableModel model = (DefaultTableModel)tab1.getModel();
model.addRow( new Object[] { a, b });
}
}
Also noticed I changed the method signature to Integer instead of int so it will fit with the Object[] passed to addRow. The int you pass to it will get autoboxed to Integer
SIDE NOTES
Don't swallow you exception by putting nothing in the catch block. Put something meaningful that will notify you of any exceptions that may occur, like
catch(Exception ex) {
ex.printStackTrace();
}
You should also close your Connections, Statements, and ResultSets
You should use PreparedStatement instead of Statement, to avoid SQL injection.
private void resetListData() throws ClassNotFoundException, SQLException
{
Connection cne = null;
try {
Class.forName("org.sqlite.JDBC");
cne = DriverManager.getConnection("jdbc:sqlite:table.sqlite");
cne.setAutoCommit(false);
PreparedStatement psd = (PreparedStatement) cne.prepareStatement("Select * from Genres");
psd.execute();
ResultSet r = psd.getResultSet();
ResultSetMetaData rsmd = r.getMetaData();
int count = rsmd.getColumnCount();
String[] meta = new String[count];
for (int i = 0; i < count; i++)
{
String name = rsmd.getColumnName(i + 1);
meta[i] = name;
//System.out.println(name);
}
model = new DefaultTableModel(new Object[][]{}, new String[]{"name", "address"});
jTable1.setModel(model);
while (r.next())
{
Object[] row = new Object[count];
for (int i = 1; i <= count; ++i)
{
row[i - 1] = r.getString(i); // Or even rs.getObject()
}
model.addRow(row);
}
cne.close();
} catch (ClassNotFoundException | SQLException e) {
}
}
Use this code. so you can insert one row at the end of Jtable without restarting application.,
Thanks..

javafx 2.1 combobox

I used this code to get values from database but can get only one record but I want to put all records in to the combobox.
My code is:
try {
stm = db.con.createStatement();
rs = stm.executeQuery("select code from accounts");
while (rs.next()) {
for (int i = 1; i <= 5; i++) {
ol = rs.getObject(i);
}
}
} catch (SQLException sqlException) {
}
ObservableList<Object> options = FXCollections.observableArrayList(ol);
final ComboBox code = new ComboBox();
code.getItems().addAll(options);
The problem appears to be that your variable ol simply contains the last object that you extracted from the ResultsSet. It appears what you intended to do was something like the following:
ArrayList<Object> ol = new ArrayList<Object>();
while (rs.next()) {
for (int i = 1; i <= 5; i++) {
ol.add(rs.getObject(i));
}
}
I am not sure if this does exactly what you want, but hopefully this demonstrates why you are only getting one object in your combo box.

Dynamically create print statement in Java

I query a database and get a lot information back that should be presented to the user. In the database I have fields a, b, c, d and e. Now, the user should be able to indicate which of these fields that should be printed on screen (i.e. the user can choose to view only a subset of the data retrieved from the database).
How do I dynamically create a print statement that sometimes prints two of the fields, sometimes four, sometimes three etc. depending on what the user wants?
If all the hard work is already done and you just have a result set to print, then it could be as simple as a succession of calls to System.out.print() for each result and then finish the line with a \n. It can be nested in a FOR loop, so if you have an int with the number of fields to print, just iterate through them.
In a more complicated case when you have a full list where some fields are chosen and others not, then you could use a (slightly) crude method like this:
...
String[] chosenFields = {"Field 1", "Field 2" /*, (et cetera) */};
for (int i = 0; i < numberOfFields; i++)
{
for (int j = 0; j < chosenFields.length; j++)
{
if (fieldsName[i].equals(chosenFields[j]))
System.out.print(fields[i] + " ");
break;
}
}
System.out.println();
...
Sorry about bad indentation; not sure how to sort it on here!
If field names are indeterminate at runtime and you're using Java to execute queries, consider using class ResultSetMetaData to get them.
EDIT:
As an example, here's some of my code which gets all the field names from a table, then creates a tickbox for each, which the user can select or deselect. All the JFrame GUI stuff I've omitted. When the user presses a submit button, the application check each tickbox and constructs an SQL statement to suit the users request.
...
JCheckBox[] jcb;
ResultSetMetaData rsmd;
private void makeCheckBoxes()
{
initConnection(); // Establish connection to MySQL server
try
{
Statement query = connection.createStatement();
ResultSet rs = query.executeQuery("SELECT * FROM client_db;");
rsmd = rs.getMetaData();
noOfColumns = rsmd.getColumnCount();
jcb = new JCheckBox[noOfColumns];
for (int i = 0; i < noOfColumns; i++)
{
jcb[i] = new JCheckBox(rsmd.getColumnName(i + 1));
jpCheckBoxes.add(jcb[i]);
jcb[i].setEnabled(false);
jcbComboBox.addItem(rsmd.getColumnName(i + 1));
}
jcb[0].setSelected(true);
rs.close();
query.close();
connection.close();
}
catch (SQLException e)
{
System.err.println("!> Caught SQLException:\n" + e.getMessage());
System.exit(1);
}
}
...
if (e.getSource() == jbSubmit)
{
String query = "";
initConnection();
if (jtfSearch.getText().isEmpty() == true) // JTextField
{
jtaResults.setText(null); // JTextArea
jtaResults.append("Please enter some search text in the text box above!\n");
return;
}
else
{
int selectedFields;
if (jrbAll.isSelected() == true) // JRadioButton
{
query = "SELECT *";
selectedFields = -1;
}
else
{
query = "SELECT";
selectedFields = 0;
for (int i = 0; i < noOfColumns; i++)
if (jcb[i].isSelected() == true)
{
try
{
if (selectedFields > 0)
query += ",";
query += " " + rsmd.getColumnName(i + 1);
}
catch (SQLException err)
{
System.err.println("!> Caught SQLException:\n" + err.getMessage());
System.exit(1);
}
selectedFields++;
}
}
if (selectedFields == 0)
{
jtaResults.setText(null);
jtaResults.append("No fields were selected!!\n");
return;
}
else
{
query += " FROM client_db WHERE " + jcbComboBox.getSelectedItem() + " LIKE '%" + jtfSearch.getText() + "%'";
if (jcbCurrentClients.isSelected() == true)
query += " AND currentClient LIKE 'y'";
query += ";";
}
}
System.out.println("Query = \"" + query + "\"");
/* Now, print it out in the text area!! */
try
{
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsMetaData = rs.getMetaData();
int columnCount = rsMetaData.getColumnCount();
jtaResults.append("--------------------------------\n");
int noOfResults = 0;
jtaResults.setText(null);
while (rs.next() == true)
{
if (noOfResults > 0)
jtaResults.append("\n");
jtaResults.append("* Search match " + (noOfResults + 1) + ":\n");
for (int i = 0; i < columnCount; i++)
{
jtaResults.append("-> " + rsMetaData.getColumnName(i + 1) + ": " +
rs.getString(i + 1) + "\n");
}
noOfResults++;
}
if (noOfResults == 0)
{
jtaResults.append("No results were returned; please try again with more ambiguous search terms.\n\n");
}
//scroller.setScrollPosition(0, 1048576);
rs.close();
stmt.close();
connection.close();
}
catch (SQLException err)
{
System.err.println("!> Caught SQLException:\n" + err.getMessage());
System.exit(1);
}
}
}
Hopefully this helps. The sustained concatenation to query forms a valid SQL statement based on the fields the user chose. Hopefully a few modifications to this to just print certain fields will help you. The System.out.println() call to print query about two-thirds down is a good place to work from.
The natural way to switch an optional value on or off would be a radiobutton. For 5 fields i.e. an array of 5 radiobuttons.
StringBuffer sb = new StringBuffer (5 * 10);
for (int i = 0; i < 5; ++i)
if (rb[i])
s.append (field[i]).append (" ");
Maybe you're better of only selecting interesting columns from the database? Then a dummy-column is helpful:
sql = new StringBuffer ("SELECT 1 "); // the dummy-column
for (int i = 0; i < 5; ++i)
if (rb[i])
sql.append (", ").append (fieldname[i]);

Categories

Resources