I have designed an inventory/sales information system using a Swing GUI for a computer store (fictional). One of the features is to display a basic bar graph of how certain products have sold in a year.
The data is called from a MySQL database called dbsales and the category of products is selected using a jComboBox (cboAnSales).
I have a method (public void graph()) that has the coding to generate the graph.
The data for the items displays in textfields and the graph uses that information to display. The method is called inside the cboAnSalesif statements for each category.
The problem now is it generates each item on its own graph. For example there are 7 items in the Cables category and when I select it, it generates 7 graphs (one for each item).
I need all 7 items to display on one single graph.
How can I achieve this?
Here is the Cables section of the cboAnSales:
private void cboAnSalesActionPerformed(java.awt.event.ActionEvent evt) {
if (cboAnSales.getSelectedIndex() == 1)
{
try
{
String sql = "select * from dbsales where category ='" + "Cable" + "'";
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/salventri","root","password");
Statement stmt=con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
DefaultListModel model = new DefaultListModel();
while(rs.next())
{
String ID = rs.getString("pid");
txtpid.setText(ID);
String brand = rs.getString("pbrand");
txtBrand.setText(brand);
String name = rs.getString("pname");
txtName.setText(name);
String category = rs.getString("category");
txtCategory.setText(category);
String unitSold = rs.getString("usold");
txtUnitsSold.setText(unitSold);
graph();
}
}
catch (Exception e)
{
}
}
Here is the coding for my graph in the public void graph() method:
String unitsSold = txtUnitsSold.getText();
String brand = txtBrand.getText();
String name = txtName.getText();
String cat = txtCategory.getText();
DefaultCategoryDataset ddataset = new DefaultCategoryDataset();
ddataset.setValue(new Double(unitsSold), cat, brand + " " + name);
JFreeChart chart = ChartFactory.createBarChart3D("Annual Sales Performance", cat, "Number of Units Sold", ddataset);
chart.getTitle().setPaint(Color.RED);
CategoryPlot p = chart.getCategoryPlot();
p.setRangeGridlinePaint(Color.BLUE);
ChartFrame frame2 = new ChartFrame("Annual Sales", chart);
frame2.setVisible(true);
frame2.setSize(450,350);
With credit to WillShackleford, the solution to my question resulted in the following code in my public void graph():
public void graph()
{
String year = cboAnnYear.getSelectedItem().toString();
if(cboAnSales.getSelectedIndex() == 1)
{
try
{
//declaring the type of category in the column
String text = "Cable";
//Select statement getting the row count
String sql = "select count(category) from dbsales where category ='" + text + "'";
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/salventri","root","password");
PreparedStatement stmt = con.prepareStatement("select * from dbsales where category=?");
stmt.setString(1, text);
ResultSet rs = stmt.executeQuery();
DefaultCategoryDataset ddataset = new DefaultCategoryDataset();
while (rs.next())
{
ddataset.setValue(new Double(rs.getDouble("usold")),
rs.getString("pbrand") + " " + rs.getString("pname"),
rs.getString("syear"));
}
JFreeChart chart = ChartFactory.createBarChart3D("Annual Sales Performance", text, "Number of Units Sold", ddataset);
chart.getTitle().setPaint(Color.RED);
CategoryPlot p = chart.getCategoryPlot();
p.setRangeGridlinePaint(Color.BLUE);
ChartFrame frame2 = new ChartFrame("Annual Sales", chart);
frame2.setVisible(true);
frame2.setSize(900,700);
}
Related
I'm trying to display the data from a access database; for some reason, whenever I run the program, only one row is displayed. Here's my code
try{
String coursec = jTextField9.getText().trim();
String sql5 = "SELECT * FROM Studentcourse WHERE ccode ='" +coursec+"'";
String url5 ="jdbc:ucanaccess://C:/Users/james_000/Documents/NetBeansProjects/Registration/Campus.accdb ";
Connection conn5 =DriverManager.getConnection(url5);
Statement statem = conn5.createStatement();
ResultSet rs5 = statem.executeQuery(sql5);
while (rs5.next()){
DefaultTableModel dm;
dm = new DefaultTableModel(10, 10);
String coursecode= rs5.getString(2);
String attend =rs5.getString(3);
String date =rs5.getString(4);
Vector <String> vector = new Vector<String>();
vector.add(coursecode);
vector.add(attend);
vector.add(date);
String s[] = new String[]{"ccode", "stnumattend", "Date"};
dm.setColumnIdentifiers(s);
jTable1.setModel(dm);
dm.addRow(vector);
jTable1.setVisible(true);
}
}
catch(Exception d){
System.err.println("Exception:" + d.getMessage());
}
You're creating a new DefaultTableModel each time through your while loop, so only the last such model is applied to jTable1. At a minimum, move the model creation out of the loop.
DefaultTableModel dm = new DefaultTableModel(10, 10);
jTable1.setModel(dm);
while (rs5.next()) {
String coursecode= rs5.getString(2);
…
}
How can I properly change the value of my Swing Controls like JComboBox and JTextfields every time I click the cells of my JTable which is my data? What I want to do if there are more than one record that has the same first letter of the I selected. Will change the value every time I click based on their row position?
Screenshot
When I clicked one of the values in the JTable it shows the current value in the JTextfield and JComboBox but If I click a again it didn't change? Any help?
SELECT (For retrieving)
private void SearchButtonActionPerformed(java.awt.event.ActionEvent evt) {
String searchSection = Section_SearchSection_Textfield.getText();
String searchSECTIONSETTINGS = "SELECT allsections_list.SECTION_ID, allsections_list.SECTION_NAME, allsections_settings.ADVISER_ASSIGNED, allsections_settings.SECTION_POPULIMIT, allsections_settings.ROOM_ASSGN,\n" +
"allsections_settings.YRLEVEL_ASSGN,allsections_settings.SCHOOL_YEAR,allsections_settings.SESSION_ASSIGNED\n" +
"FROM allsections_list\n" +
"RIGHT JOIN allsections_settings\n" +
"ON allsections_list.SECTION_ID = allsections_settings.SECTION_ID\n" +
"WHERE SECTION_NAME LIKE ?";
try (Connection myConn = DBUtil.connect();
PreparedStatement myFirstPs = myConn.prepareStatement(searchSECTIONSETTINGS);)
{
myFirstPs.setString(1, '%'+searchSection+'%' );
try (ResultSet myFirstRs = myFirstPs.executeQuery();)
{
sectionJTable.setModel(DbUtils.resultSetToTableModel(myFirstRs));
int result = 0;
while (myFirstRs.next())
{
String myName = myFirstRs.getString(2);
System.out.println(myName);
result++;
}
}//end of try myFirstRs (ResultSet)
}//end of try myFirstPs (PreparedStatement)
}
JTable (MouseClicked)
private void sectionJTableMouseClicked(java.awt.event.MouseEvent evt) {
if (evt.getClickCount() == 1) {
final JTable target = (JTable)evt.getSource();
final int row = target.getSelectedRow();
final int column = target.getSelectedColumn();
// Cast to ur Object type
Object value = target.getValueAt(row,column);
JOptionPane.showMessageDialog(null, value);
String selectSections = "SELECT * FROM allsections_list a JOIN allsections_settings b ON b.SECTION_ID = a.SECTION_ID";
try (Connection myConn = DBUtil.connect();
PreparedStatement myPs = myConn.prepareStatement(selectSections);)
{
try (ResultSet myRs = myPs.executeQuery())
{
int resultCounter = 0;
while(myRs.next())
{
Section_SectionName_TextField.setText(myRs.getString("SECTION_NAME"));
Section_Student_Limit_ComboBox.setSelectedItem(myRs.getString("SECTION_POPULIMIT"));
Section_Room_Assignment_ComboBox.setSelectedItem(myRs.getString("ROOM_ASSGN"));
Section_Student_Limit_ComboBox1.setSelectedItem(myRs.getString("ADVISER_ASSIGNED"));
Section_Session_Settings_ComboBox.setSelectedItem(myRs.getString("SESSION_ASSIGNED"));
Section_Session_Level_ComboBox.setSelectedItem(myRs.getString("YRLEVEL_ASSGN"));
Section_SchooYear_ComboBox.setSelectedItem(myRs.getString("SCHOOL_YEAR"));
resultCounter++;
}
}
}
}
When I try to add System.out.print(myRs.getString("SECTION_NAME")); in my second Result Set it prints out all the values of my SECTION_NAME not the current that I selected.
I think I found the problem:
while(myRs.next())
{
Section_SectionName_TextField.setText(myRs.getString("SECTION_NAME"));
Section_Student_Limit_ComboBox.setSelectedItem(myRs.getString("SECTION_POPULIMIT"));
Section_Room_Assignment_ComboBox.setSelectedItem(myRs.getString("ROOM_ASSGN"));
Section_Student_Limit_ComboBox1.setSelectedItem(myRs.getString("ADVISER_ASSIGNED"));
Section_Session_Settings_ComboBox.setSelectedItem(myRs.getString("SESSION_ASSIGNED"));
Section_Session_Level_ComboBox.setSelectedItem(myRs.getString("YRLEVEL_ASSGN"));
Section_SchooYear_ComboBox.setSelectedItem(myRs.getString("SCHOOL_YEAR"));
resultCounter++;
}
In the above part you are setting all records to the your components in a while statement. So components will show only the last record, in this case "Gold".
But actually there is no need to querying database in sectionJTableMouseClicked. You can get all values by getValueAt and set to the components.
I wanted to create an update button for a dropdown list that gets the data from the database in the netbeans. Tried this method below but couldn't get it to work. Any suggestions? Thanks alot.
public class ViewProduct extends javax.swing.JFrame {
ResultSet rs;
PreparedStatement pst;
Connection conn;
final void FillList(){
try{
//establish connection to table
String url = "jdbc:derby://localhost:1527/ProductInformation";
String username = "admin1";
String password = "admin1";
Connection conn = DriverManager.getConnection(url,username,password);
Statement stat = conn.createStatement();
// get data from table in sql database
String Query = "SELECT * FROM VIEWPRODUCT";
ResultSet rs = stat.executeQuery(Query);
//
DefaultListModel DLM = new DefaultListModel();
while(rs.next()){
JList list = new JList();
JComboBox ProductID_dropdown = new JComboBox();
DefaultComboBoxModel listModel = new DefaultComboBoxModel();
list.setModel(listModel);
ProductID_dropdown.setModel(listModel);
}
}catch(SQLException ex){
JOptionPane.showMessageDialog(null, ex.toString());
}
There are several things not right or missing in your code. For instance you have no GUI.
And as I dont know the exact structure of your project or your database, I have to improvise and give you a pseudo-code approach.
You will have to change and configure several things I am showing here.
First, create a JComboBox outside of your method and add it to a container like JPanel:
JPanel pane = new JPanel();
JComboBox productID_dropdown = new JComboBox();
JButton btn_updateViewProducts = new JButton("Update Results");
Here the Button for updating your results is added, it contains an ActionListener, that "listens" to when someone is clicking on the button.
Usually you want to retrieve a ResultSet and put its contents into variables, like in this example:
// ActionListener for the button
btn_updateViewProducts.add(new ActionListener{
#Override
// When the button is clicked...
public void actionPerformed(ActionEvent arg0) {
// ... get the results out of your database (here it's an example database!
// Configure for your own one)
ResultSet rs = stat.executeQuery(Query);
while(rs.next()){
// "de-construct" every result of the ResultList into variables
String query = "select COF_NAME, SUP_ID, PRICE, " + "SALES, TOTAL " + "from " + dbName + ".COFFEES";
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "\t" + supplierID + "\t" + price + "\t" + sales + "\t" + total);
// Put items into JComboBox
productID_dropdown.addItem(coffeeName);
}
}
});
// Add the now filled JComboBox to the pane
pane.add(productID_dropdown);
Other issues you should think about:
GUI is missing
the method FillList is final, which seems unusual, any reason behind this? final in a method means, that it cant be overridden by subclasses, it this needed here?
FillList is a method and should be written with a small letter at the start due to coding convention, the same goes for ProductID_dropdown (coding convention)
most of the time it's quite okay to use short variables like rs for a ResultSet, but if your projects get bigger, it gets harder to keep all those variables in mind. Better: make them tell you, what they are. Instead of rs -> resultSetViewProduct or similar.
PreparedStatement pst is never used
I hope this helps. :)
I have a JFrame form which asks the user to insert for example his name then it shows him the addresses of all houses he owns (user may own more than one house).
However, since i dunno how many result the query will come out with, i created a function of type vector and stored the data into it, then returned the vector. At the JFrame form i'm doing something like this.
Vector<String> data = User.getHouse(userName.getText());
if (data.isEmpty()) {
JOptionPane.showMessageDialog(null, "No Houses were found!");
}
else {
for(int i=0; i<data.size(); i++)
{
System.out.println(data.elementAt(i));
houses.setText(data.elementAt(i));
houses2.setText(data.elementAt(i+1));
}
}
the function code:
public static Vector<String> getHouse(String playerName) throws SQLException, ClassNotFoundException {
Connection con = DBConnect.getConnection();
PreparedStatement getId = con.prepareStatement("SELECT Player_Id from PLAYERS WHERE Name = ?");
getId.setString(1, playerName);
ResultSet y = getId.executeQuery();
if(y.next())
{
id = y.getString("Player_id");
System.out.println("playerID => " + id);
}
System.out.println("playerName => " + playerName);
PreparedStatement s = con.prepareStatement("SELECT House_Name FROM HOUSES WHERE Player_Id = ?");
s.setString(1, id);
System.out.println("getHouse => Query");
ResultSet x = s.executeQuery();
Vector<String> data = new Vector<String>();
while(x.next())
{
data.addElement(x.getString("House_Name"));
}
return data;
}
(query returns 2 rows). How can i correctly set the JLabel text with the query result?
I have a Jtable (tableSummary).
I need to format 2 columns of the table so it's content is in DECIMAL form (e.g. 1,400.00)
How can i do it?
here's my code for the table:
private void tableMarketMouseClicked(java.awt.event.MouseEvent evt) {
String sql = "SELECT tblClientInfo.ClientID, tblrefmarket.MarketDesc, tblclientinfo.LastName, tblledger.LoanAmount, "
+ "tblledger.DateStarted, tblledger.DailyPay, tblledger.Expiry FROM tblclientinfo Inner Join tblbusinessinfo ON tblbusinessinfo.ClientID = tblclientinfo.ClientID "
+ "Inner Join tblrefmarket ON tblbusinessinfo.MarketID = tblrefmarket.MarketID "
+ "Inner Join tblledger ON tblledger.ClientID = tblclientinfo.ClientID where MarketDesc = ?";
try {
//add column to the table model
model.setColumnCount(0); //sets the column to 0 para ig utro click, dili mapun-an ang columns
model.setRowCount(0); //sets the row to 0 para ig utro click, dili mapun-an ang rows
model.addColumn("C NO");
model.addColumn("MARKET");
model.addColumn("BORROWER");
model.addColumn("LOAN");
model.addColumn("START");
model.addColumn("DAILY");
model.addColumn("EXPIRY");
//model.addColumn("BALANCE");
int row = tableMarket.getSelectedRow();
pst = conn.prepareStatement(sql);
pst.setString(1, tableMarket.getModel().getValueAt(row, 0).toString());
rs = pst.executeQuery();
while(rs.next()){
String id = rs.getString(1);
String market = rs.getString(2);
String name = rs.getString(3);
String amt = rs.getString(4);
String start = rs.getString(5);
String daily = rs.getString(6);
String expiry = rs.getString(7);
//String area = rs.getString(3);
model.addRow(new Object[]{ id, market, name, amt, start, daily, expiry});
}
tableSummary.setModel(model);
renderer.setHorizontalAlignment( JLabel.RIGHT );
renderer2.setHorizontalAlignment( JLabel.CENTER );
tableSummary.getColumnModel().getColumn(0).setCellRenderer( renderer2 );
tableSummary.getColumnModel().getColumn(4).setCellRenderer( renderer2 );
tableSummary.getColumnModel().getColumn(6).setCellRenderer( renderer2 );
tableSummary.getColumnModel().getColumn(3).setCellRenderer( renderer );
tableSummary.getColumnModel().getColumn(5).setCellRenderer( renderer );
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
}
the columns, amt and daily are the columns i need to be formatted.
Thanks in Advance!
As kleopatra already suggested in her comments
The conversion from Object to a String representation (or any other representation) is the task of the renderer. Your TableModel should just contain the objects
Create and set the appropriate renderer on your JTable (for example by calling JTable#setDefaultRenderer or overriding JTable#getCellRenderer)
As renderer for your Number instances you can use one which uses the NumberFormat for formatting as shown in the answer of Samir
NumberFormat formatter = new DecimalFormat("#,###.00");
String str = formatter.format(1400);
System.out.println(str);