I have a database table named tree1, which has a table names student_details.This table has 3 columns student_name,student_details,student_phone
Now, am able to retrieve student details from the database but only in static way.
Question is when I insert a new student detail row {student_name,student_details,student_phone} I want it to show on my Jtree. Although Hashmap is the solution I am not able to understand how to use hashmap in a Jtree to create dynamic nodes.
below is the code from which I could do a static Jtree, and i want to make it dynamic. Can anyone tell me how to do this with a code sample?
package tree_try;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.beans.Statement;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.*;
public class SimpleTree extends JFrame
{
public Connection connect = null;
public Statement statement = null;
public Statement statement2 = null;
public Statement statement3 = null;
public Statement statement4 = null;
public Statement statement5 = null;
public Statement statement6 = null;
public ResultSet resultSet = null;
public ResultSet resultSet2 = null;
public ResultSet resultSet3 = null;
public ResultSet resultSet4 = null;
public ResultSet resultSet5 = null;
public ResultSet resultSet6 = null;
public ArrayList arrayList = new ArrayList();
public ArrayList arrayList2 = new ArrayList();
public ArrayList arrayList3 = new ArrayList();
public ArrayList arrayList4 = new ArrayList();
static String store[] = new String[10];
static String store2[] = new String[10];
static String store3[] = new String[10];
//for the panel
static String store4[] = new String[10];
static String store5[] = new String[10];
static String store6[] = new String[10];
static String store7[] = new String[10];
//for panel over
int i=0;
int i1=0;
int i2=0;
int i3=0;
JPanel jp1 = new JPanel();
JPanel jp2 = new JPanel();
JFrame jf1 = new JFrame();
JButton jb1 = new JButton("Save");
JButton jb2 = new JButton("Cancel");
JTextField jt1= new JTextField();
JTextField jt2 = new JTextField();
JTextField jt3= new JTextField();
JTextField jt4 = new JTextField();
JLabel jl0 = new JLabel();
JLabel jl1 = new JLabel("Name : ");
JLabel jl2 = new JLabel("Adress : ");
JLabel jl3 = new JLabel("Phone Number : ");
JLabel jl4 = new JLabel("Other Deatils : ");
JLabel jl5 = new JLabel("");
public static void main(String[] args)
{
new SimpleTree();
}
public SimpleTree()
{
super("Schools database");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
//db part
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
connect = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata1","suraj","suraj");
PreparedStatement statement = connect.prepareStatement("SELECT * from school_details");
PreparedStatement statement2 = connect.prepareStatement("select student_name from student_details where s_id =1");
PreparedStatement statement3 = connect.prepareStatement("select student_name from student_details where s_id =2");
//for the panel display
//PreparedStatement statement5 = connect.prepareStatement("select student_name from student_details where s_id =1");
//PreparedStatement statement6 = connect.prepareStatement("select student_name from student_details where s_id =2");
resultSet = statement.executeQuery();
while (resultSet.next())
{
String sname = resultSet.getString("school_name");
String sid = resultSet.getString("s_id");
arrayList.add(sname);
System.out.println("this is stsement one"+sname);
//arrayList.add(number);
}
resultSet2 = statement2.executeQuery();
while (resultSet2.next())
{
String user2 = resultSet2.getString("student_name");
//int number2 = resultSet2.getInt("s_id");
arrayList2.add(user2);
System.out.println("this is stsement two"+user2);
}
// System.out.println(arrayList);
resultSet3 = statement3.executeQuery();
while (resultSet3.next())
{
String user3 = resultSet3.getString("student_name");
//int number2 = resultSet2.getInt("s_id");
arrayList3.add(user3);
System.out.println("this is stsement three"+user3);
}
System.out.println("this is after statement 3 before 4");
}
catch (Exception e2)
{
e2.printStackTrace();
}
//
Iterator it = arrayList.iterator();
while (it.hasNext())
{
store[i]= (String) it.next();
i++;
//System.out.println(it.next());
}
Iterator it2 = arrayList2.iterator();
while (it2.hasNext())
{
store2[i1]= (String) it2.next();
i1++;
//System.out.println(it.next());
}
Iterator it3 = arrayList3.iterator();
while (it3.hasNext())
{
store3[i2]= (String) it3.next();
i2++;
// System.out.println(it.next());
}
// ------------------------- Visible Settings start here --------------------//
Object[] hierarchy ={"Click for schools",new Object[] {store[0],new Object[] { "Student Details",store2[0],store2[1] } },new Object[] { store[1],new Object[] { "Student Details",store3[0],store3[1]}}};
DefaultMutableTreeNode root = processHierarchy(hierarchy);
final JTree tree = new JTree(root);
// setSize(275, 300);
jp1.setSize(50,50);
jp1.setBackground(Color.WHITE);
jf1.setExtendedState(Frame.MAXIMIZED_BOTH);
jf1.setLayout(new GridLayout(1,2));
jf1.setVisible(true);
jf1.add(new JScrollPane(tree), BorderLayout.WEST);
jf1.add(jp1);
jp1.setLayout(null);
jl0.setBounds(10,1,500,100);
jp1.add(jl0);
jl1.setBounds(55,90,150,100);
jt1.setBounds(225,130, 155, 25);
jp1.add(jl1);
jp1.add(jt1);
jl2.setBounds(55,160, 150, 100);
jt2.setBounds(225,200, 155, 25);
jp1.add(jl2);
jp1.add(jt2);
jl3.setBounds(55,230,150,100);
jt3.setBounds(225,270, 155, 25);
jp1.add(jl3);
jp1.add(jt3);
jl4.setBounds(55,295, 150, 100);
jt4.setBounds(225,330, 155, 25);
jp1.add(jl4);
jp1.add(jt4);
jb1.setEnabled(false);
jb2.setEnabled(false);
jb1.setBounds(150,430, 100, 50);
jb2.setBounds(350,430, 100, 50);
jp1.add(jb1);
jp1.add(jb2);
//-----------------Visible setting stop here--------------------------//
//------------------- Element actions here------------------------//
jt1.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e)
{
jb1.setEnabled(true);
jb2.setEnabled(true);
}
#Override
public void focusLost(FocusEvent e)
{
jb1.setEnabled(false);
jb2.setEnabled(false);
}
});
//now for the tree
tree.addTreeSelectionListener(new TreeSelectionListener() {
#Override
public void valueChanged(TreeSelectionEvent e) {
jf1.dispose();
//jl0.setText("Displaying information About : "+tree.getLastSelectedPathComponent().toString());
store7[0]= tree.getLastSelectedPathComponent().toString();
System.out.println("in store 7 of 0"+store7[0]);
dbaction db = new dbaction(store7[0]);
}
});
}
//------------------------------------end of action listening-------------------------
private DefaultMutableTreeNode processHierarchy(Object[] hierarchy)
{
DefaultMutableTreeNode node = new DefaultMutableTreeNode(hierarchy[0]);DefaultMutableTreeNode child;
for(int i=1; i<hierarchy.length; i++)
{
Object nodeSpecifier = hierarchy[i];
if (nodeSpecifier instanceof Object[]) // Ie node with children
child = processHierarchy((Object[])nodeSpecifier);
else
child = new DefaultMutableTreeNode(nodeSpecifier); // Ie Leaf
node.add(child);
}
return(node);
}
private void close()
{
try {
if (resultSet != null)
{
resultSet.close();
}
if (statement != null)
{
//statement.
}
if (connect != null)
{
connect.close();
}
}
catch (Exception e3)
{
e3.printStackTrace();
}
}
}
of course dbaction.java is where I connect to the database and get details.
It is best to create a data model for the tree. How to Use Trees tutorial has good examples. Also go through Understanding the TreeModel for more details.
By the way, don't execute long running tasks such as accessing database on Event Dispatch Thread . Look into SwingWorker for such tasks.
The JTree tutorial to which Max linked has a section covering 'Dynamic updates of a JTree' which contains the necessary snippets on how to update a TreeModel. The basic idea is that you update the model behind the JTree (the TreeModel) and fire the correct events from the TreeModel. The JTree will listen for those events and update itself accordingly.
Next to that, some other advise:
You should only access Swing components on the Event Dispatch Thread (EDT), which is currently not the case in your example. See the Concurrency in Swing tutorial for more information
The moment you adjust your main method to run on the EDT, you should avoid the long running taks (the database access), as it will block the EDT and leave you with an unresponsive UI (as Max already indicated).
You should avoid the null layout and the manual placing of all your components using setBounds. Otherwise simple things like resizing the UI will results in a messed-up layout. Use a LayoutManager instead. The usage of LayoutManagers is also covered in the 'LayoutManager tutorial' on the Oracle site.
Related
I want to create a login page but it's not working properly. When I type in a username and password and click on the Login button, nothing is happening and I am not seeing any error message.
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Font;
public class acclogin extends JFrame {
Connection con;
Statement st;
ImageIcon bg = new ImageIcon("wb1.jpg");
JFrame f = new JFrame("User Login");
ResultSet rs;
JLabel l = new JLabel("Username");
JLabel l1 = new JLabel("Password");
JLabel l2 = new JLabel(bg);
JTextField t = new JTextField(15);
JPasswordField t1 = new JPasswordField(15);
JButton b = new JButton("Login");
public acclogin() {
frame();
}
public void frame() {
f.setSize(620, 300);
l.setBounds(10, 20, 100, 10);
t.setBounds(100, 20, 100, 20);
l1.setBounds(10, 50, 100, 80);
t1.setBounds(100, 70, 100, 20);
b.setBounds(100, 130, 100, 30);
l2.setBounds(0, 0, 600, 300);
f.add(l);
f.add(t);
f.add(l1);
f.add(t1);
f.add(b);
f.add(l2);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
LoginButton lb = new LoginButton();
b.addActionListener(lb);
}
class LoginButton implements ActionListener {
public void actionPerformed(ActionEvent ae) {
Object obj = ae.getSource();
if (obj == b) {
try {
String user = t.getText().trim();
String pass = t1.getText().trim();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con1 = DriverManager.getConnection("jdbc:odbc:balogin");
Statement stat;
stat = con1.createStatement();
ResultSet rs = stat.executeQuery("select * from Table1 where user='" + user + "' and pass='" + pass + "'");
System.out.println("select * from Table1 where user='" + user + "' and pass='" + pass + "'");
int count = 0;
while (rs.next()) {
{
count = count + 1;
}
if (count == 1) {
JOptionPane.showMessageDialog(null, "User Found,Access Granted");
ControlPanel cp1 = new ControlPanel();
cp1.display();
} else {
JOptionPane.showMessageDialog(null, "User not found");
}
}
} catch (Exception ex) {
}
}
}
}
public static void main(String args[]) {
new acclogin();
}
}
This is not exactly a solution for the problem, but this code has so many issues that you should solve before moving on.
This is what I would do:
split the code into multiple methods to take apart UI code from working with database
do not concat SQL query from strings, use prepared statement instead (omiting this could lead to an SQL injection, try login as ';DROP TABLE user;--)
usage of int count just for checking an existence of an element is confusing, you can use boolean or change SQL query to SELECT COUNT(*) ... or SELECT 1 IF EXISTS (SELECT * FROM ...)
you do not have to check the action event source, it will be always be the login button unless you assign the listener to something else
add e.printStackTrace() on catching exception
I also believe that you should use JPasswordTextField.getPassword() instead of getText()
remember closing ResultSet and Statement after use by calling .close()
try this :
Object obj = ae.getSource();
if ((JButton)obj ==(JButton)b) {
......... }
So my aim is to make a runnable jar. I've made a program using swings which uses MS Access database to fetch records. So, I've used an absolute path to refer to the database for connection.
Now, I intend to distribute this runnable jar to other people as well. So I guess the best option would be to embed the MS Access database as well in the jar file. But I don't know how to do that. Where should I keep the database in my Project Explorer ? Should I use a relative path etc. Any form of help would be appreciable.
I've found many tutorials for using Derby database that would implement the same but none pertaining to Ms Access database. Suggestions are welcome !
This is my code:-
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class r_search extends JFrame implements ActionListener {
JFrame frame1;
JLabel l0, l1, l2;
JComboBox c1;
JButton b1;
Connection con;
ResultSet rs, rs1;
Statement st, st1;
PreparedStatement pst;
String ids;
static JTable table;
String[] columnNames = {"SECTION NAME", "REPORT NAME", "CONTACT", "LINK"};
String from;
r_search() {
l0 = new JLabel("Fetching Search Results...");
l0.setForeground(Color.blue);
l0.setFont(new Font("Serif", Font.BOLD, 20));
l1 = new JLabel("Search");
b1 = new JButton("submit");
l0.setBounds(100, 50, 350, 40);
l1.setBounds(75, 110, 75, 20);
b1.setBounds(150, 150, 150, 20);
b1.addActionListener(this);
setTitle("Search Executive Reports :) ");
setLayout(null);
//setVisible(true);
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
add(l0);
add(l1);;
add(b1);
try {
Vector v = new Vector();
String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\users\\ppreeti\\executive_db.accdb";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection(url,"","");
/*con = DriverManager.getConnection("jdbc:oracle:thin:#mcndesktop07:1521:xe", "sandeep", "welcome");*/
st = con.createStatement();
rs = st.executeQuery("select index_name from Index1");
// Vector v = new Vector();
while (rs.next()) {
ids = rs.getString(1);
v.add(ids);
}
c1 = new JComboBox(v);
c1.setBounds(150, 110, 150, 20);
add(c1);
st.close();
rs.close();
} catch (Exception e) {
}
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == b1) {
showTableData();
}
}
public void showTableData() {
frame1 = new JFrame("Database Search Result");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLayout(new BorderLayout());
//TableModel tm = new TableModel();
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
//DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames());
//table = new JTable(model);
table = new JTable();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
from = (String) c1.getSelectedItem();
//String textvalue = textbox.getText();
String uname = "";
String email = "";
String pass = "";
String cou = "";
try {
/* pst = con.prepareStatement("select * from emp where UNAME='" + from + "'");*/
pst = con.prepareStatement("select distinct Section.Section_Name,Report.Report_Name,Report.Link,Contact.Contact_Name "
+ "FROM (( Section INNER JOIN Report ON Report.Section_ID=Section.Section_ID ) INNER JOIN Contact ON Contact.Contact_ID=Report.Contact_ID ) LEFT JOIN Metrics ON Metrics.Report_ID=Report.Report_ID "
+ " WHERE Section.Section_Name LIKE '%"+from+"%' OR Report.Report_Name LIKE '%"+from+"%' OR Metrics.Metric_Name LIKE '%"+from+"%' OR Contact.Contact_Name LIKE '%"+from+"%' ");
ResultSet rs = pst.executeQuery();
int i = 0;
while (rs.next()) {
uname = rs.getString("Section_Name");
email = rs.getString("Report_Name");
pass = rs.getString("Contact_Name");
cou = rs.getString("Link");
model.addRow(new Object[]{uname, email, pass, cou});
i++;
}
if (i < 1) {
JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
}
if (i == 1) {
System.out.println(i + " Record Found");
} else {
System.out.println(i + " Records Found");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
frame1.setSize(1000, 400);
}
public static void main(String args[]) {
new r_search();
}
}
The following worked for me using Eclipse and JavaSE-1.7. Eclipse shows the following in its Package Explorer
The [folders] and files in my project folder are
[C:]
[Users]
[Gord]
[workspace]
[com.example.jartest]
[src]
[com]
[example]
[jartest]
JarTestMain.java
[resources]
JarData.mdb
The Java code in JarTestMain.java is
package com.example.jartest;
import java.io.*;
import java.nio.file.*;
import java.sql.*;
public class JarTestMain {
public static void main(String[] args) {
String mdbFileName = "JarData.mdb";
String tempDbPath = System.getenv("TEMP").replace('\\', '/') + "/" + mdbFileName;
// retrieve .mdb database from the JAR file and save to %TEMP% folder
InputStream strmIn = JarTestMain.class.getResourceAsStream("resources/" + mdbFileName);
File f = new File(tempDbPath);
try {
Files.copy(strmIn, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
// open the copy of the database in %TEMP% folder and read from its table
String connectionString =
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};" +
"DBQ=" + tempDbPath;
try (Connection con = DriverManager.getConnection(connectionString)) {
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM Table1");
while (rs.next()) {
System.out.println(String.format(
"%d: %s",
rs.getInt("ID"),
rs.getString("TextField")));
}
rs.close();
con.close();
f.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
After I exported the project to a "Runnable JAR file" named JarTest.jar I was able to run it on my 32-bit Windows test machine using...
"C:\Program Files\Java\jre7\bin\java" -jar JarTest.jar
...and on my 64-bit Windows development machine via
"C:\Program Files (x86)\Java\jre7\bin\java" -jar JarTest.jar
I have two JFrames, the first one is used to display SQL table using JTable and the second one is used to update the data on the SQL table. On the first frame, there's a button used to show the second frame and it has radio buttons. However, I can't set it to true. What I want to happen is set the radio button to true based on what value I get from a Label where the Label's value came from the database. Here's what I have done:
FIRST JFRAME:
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
String hours = null;
try
{
DbUpdate up = new DbUpdate();
// To connect on SQL and get the JTable's value
int get = (int)jTable2.getModel().getValueAt(jTable2.getSelectedRow(), 0);
String query= "SELECT * FROM roominfo WHERE CustomerNo = '"+get+"' " ;
String url = "jdbc:mysql://localhost:3306/adve";
Connection conn = DriverManager.getConnection(url,"root","sa");
Statement st = conn.createStatement();
rs = st.executeQuery(query);
while(rs.next())
{
hours= rs.getString("Hours"); // This is where I can get the value for hours and to be passed on a label
}
up.jLabel12.setText(hours); //I set on a Jlabel for the next frame
}
catch(SQLException e){
JOptionPane.showMessageDialog(null, "Please select a record to update");
}
}
SECOND JFRAME:
public void set(){ //THIS SUPPOSE TO SET THE BUTTONS BASED ON THE VALUE OF THE LABEL
if (jLabel12.getText().equals("12-Hours")) { // if 12-Hours, Rdn12 should be true or selected
Rdn12.isSelected();
Rdn12.setSelected(true);
Rdn24.setSelected(false);
}
else if (jLabel12.getText().equals("24-Hours")) { // if 24-Hours, Rdn24 should be true or selected
Rdn12.setSelected(false);
Rdn24.setSelected(true);
}
jTextField1.setEditable(false);
jLabel20.setVisible(false);
}
However, The radiobutton still won't get selected. What am I doing wrong? Any suggestions? Please help.
UPDATE: I don't know, whether I did quite understand your question. Is this application kind of what you were looking for?
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
public class DatabaseRadioButtons extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new DatabaseRadioButtons().setVisible(true);
}
});
}
JTable table = new JTable();
JButton showSecondFrame = new JButton("Show second frame");
SecondFrame secondFrame = new SecondFrame();
public DatabaseRadioButtons() {
table.setModel(new DefaultTableModel(new Object[][] {
new Object[] { "first", "entry" },
new Object[] { "second", "entry" } }, new Object[] { "column",
"names" }));
ListSelectionModel selectionModel = table.getSelectionModel();
selectionModel.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return; // ignore this event, if we expect another event
// right after this one
int selectedRow = table.getSelectedRow();
refreshRadioButtonsAccordingToDatabaseValues(selectedRow);
}
});
showSecondFrame.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
secondFrame.setVisible(true);
}
});
}
});
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JScrollPane(table), BorderLayout.CENTER);
panel.add(showSecondFrame, BorderLayout.SOUTH);
setContentPane(panel);
setSize(400, 300);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
protected void refreshRadioButtonsAccordingToDatabaseValues(int selectedRow) {
String databaseValue;
// put you database SELECT here, instead of this fixed value
System.out.println("Make Database select for row " + selectedRow);
databaseValue = selectedRow == 0 ? "12-Hours" : "24-Hours";
// Choose what to do, according to database values
if (databaseValue.equals("12-Hours")) {
// you can change the fields of the second frame directly in here
secondFrame.Rdn12.isSelected();
secondFrame.Rdn12.setSelected(true);
secondFrame.Rdn24.setSelected(false);
} else if (databaseValue.equals("24-Hours")) {
secondFrame.Rdn12.setSelected(false);
secondFrame.Rdn24.setSelected(true);
}
}
}
class SecondFrame extends JFrame {
JRadioButton Rdn12 = new JRadioButton("Radio 12");
JRadioButton Rdn24 = new JRadioButton("Radio 24");
public SecondFrame() {
setSize(400, 300);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setLocation(100, 100);
JPanel panel = new JPanel(new GridLayout(10, 1));
panel.add(Rdn12);
panel.add(Rdn24);
setContentPane(panel);
}
}
You can change a value of a Label in your Second Frame, but you don't necessarily have to. As my example shows you can just change your checkboxes of your second frame from within the code of your first frame.
Update the refreshRadioButtonsAccordingToDatabaseValues() method to read actual data from your database.
You should do something like this:
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
String hours = null;
try
{
DbUpdate up = new DbUpdate();
int get = (int)jTable2.getModel().getValueAt(jTable2.getSelectedRow(), 0);
String query= "SELECT * FROM roominfo WHERE CustomerNo = '"+get+"' " ;
String url = "jdbc:mysql://localhost:3306/adv";
Connection conn = DriverManager.getConnection(url,"root","sa");
Statement st = conn.createStatement();
rs = st.executeQuery(query);
while(rs.next())
{
hours= rs.getString("Hours");
}
if (hours.equals("12-Hours")) {
// you can change the fields of the second frame directly in here
up.Rdn12.isSelected();
up.Rdn12.setSelected(true);
up.Rdn24.setSelected(false);
} else if (hours.equals("24-Hours")) {
up.Rdn24.isSelected();
up.Rdn12.setSelected(false);
up.Rdn24.setSelected(true);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Please select a record to update");
}
}
I am trying to make a combo box which populates the item inside according to my database. at the moment the database contains 5 records which are test1,test2,test3,test4,test5. I've made a loop which is meant to populate it with each record.
private void selectschoolActionPerformed(java.awt.event.ActionEvent evt) {
ResultSet rs = null;
selectschool.setVisible(true);
try{
rs = DAO.getAllSchool();
ArrayList allSchoolName = new ArrayList();
int count = 0;
while(rs.next()){
allSchoolName.add(rs.getString("SchoolName"));
count++;
}
Object ob[] = new Object[count];
for (int i = 0; i < count; i++){
ob[i] = allSchoolName.get(i);
selectschool.addItem(ob[i]);
}
}catch (Exception e){
System.out.println("Exception: " + e);
}
CreateTimeTable ctt = new CreateTimeTable();
ctt.setVisible(true);
String sch = selectschool.getSelectedItem().toString();
ctt.jTextArea1.setText(sch);
I have tested in the for loop and it loops the right amount of times to fill the array will all the records no more no less. but in the GUI when I drop down the combo box, it is empty. But when I click and hold the mouse down, drag it below to the empty field below, it will select test1 and only test 1. How could I make the rest of the values show up? I've tested it and the ob[] holds the right records which need to be entered into the combo box. I think it might be the selectschool.addItem() which isn't working right.
Much appreciated, Thanks.
(DAO.getAllSchool(); just retrieves the database records from sql)
You need to create the JComboBox and add an ActionListener to it. Not create the ActionPerformed and inside that set the JComboBox.
Try it like this:
// fill with values from ResultSet rs (however you obtain it)
ArrayList<String> schools = new ArrayList<String>();
while(rs.next())
schools.add(rs.getString("SchoolName"));
// create the JComboBox
final JComboBox<String> selectSchool = new JComboBox<String>(schools.toArray(new String[]{}));
// add an actionlistener
selectSchool.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something with e.g. printing the selection
String school = (String) selectSchool.getSelectedItem();
System.out.println("You selected " + school);
}
});
edit: Or in a complete, very simple but working example:
package sto;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
// create school list (in your example here would be the ResultSet)
ArrayList<String> schools = new ArrayList<String>();
schools.add("School 1");
schools.add("School 2");
schools.add("School 3");
schools.add("School 4");
// create the JComboBox
final JComboBox<String> selectSchool = new JComboBox<String>(schools.toArray(new String[]{}));
// add an actionlistener
selectSchool.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something with e.g. printing the selection
String school = (String) selectSchool.getSelectedItem();
System.out.println("You selected " + school);
}
});
// create a JFrame and add the JComboBox
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(selectSchool);
frame.pack();
frame.setVisible(true);
}
}
Application is simple with two panels in one frame
First panel, retrieve from database all student s, use multiple hashmap get parent and child arrangement and show it on tree.
Second panel, when you click on a student all details of that student (selectionlistener) shown in textboxes.
Now when I alter the name of the student on the 2nd panel, the database updates it properly but the tree shows the old value.
I have tried treepanel.reload(), I have tried treemodellistener.
Can anyone help me out here. Going through a lot of solutions online, all are partial which i could not apply to my code.
Thanks in advance.
Main frame.java
/**
* #author Suraj Baliga
*
* Returns a JFrame with two Panels one having the Jtree and other
* having the details of the selected tree component.It also has dynamic tree and
* dynamic textbox where updation of text in the textbox will change the value in
* databse on click of save button.The JDBC localhost url may change with each machine
* as the database location and port number may vary.
*/
package Student_Details;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import org.apache.commons.collections.MultiHashMap;
public final class Main_frame extends JPanel
{
String sname,sschool;
ArrayList StudName_arrylst = new ArrayList();
ArrayList SchlName_arrylst = new ArrayList();
ArrayList StudDetailTxtFld_arrylst = new ArrayList();
static public Connection connect,connect_update;
public ResultSet resultSet;
public static ResultSet resultset2;
MultiHashMap SchlStud_hashmap = new MultiHashMap();
int i,j,k,k2,z;
DefaultMutableTreeNode tree_parent;
int SchlName_arylist_length, StudNamearrylst_length;
private tree_generation treePanel;
static JButton save_button = new JButton("Save");
static JButton cancel_button = new JButton("Cancel");
static JTextField studName_txtbox= new JTextField();
static JTextField studAddress_txtbox = new JTextField();
static JTextField studOthr_txtbox = new JTextField();
static public String user_name;
static public String user_add;
static public String user_other;
static JLabel name_label = new JLabel("Name : ");
static JLabel address_label = new JLabel("Adress : ");
static JLabel other_label = new JLabel("Other Deatils : ");
static String studDetailsTxtbox_disp[] = new String[10];
static String studDetailsTxtbx_disp_db[] = new String[10];
static String studDetailsTxtbxchange[] = new String[10];
public JPanel panel;
static JPanel panel_boxes = new JPanel();
public Main_frame()
{
super(new BorderLayout());
//Create the components.
treePanel = new tree_generation();
populateTree(treePanel);
//Lay everything out.
treePanel.setPreferredSize(new Dimension(300, 150));
add(treePanel, BorderLayout.WEST);
panel = new JPanel(new GridLayout(1, 2));
add(panel, BorderLayout.CENTER);
}
public void populateTree(tree_generation treePanel)
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
PreparedStatement AllStuddetails = connect.prepareStatement("SELECT * from student_details");
resultSet = AllStuddetails.executeQuery();
while (resultSet.next())
{
sname = resultSet.getString(1);
sschool = resultSet.getString(3);
SchlStud_hashmap.put(sschool, sname);
}
}
catch (Exception e)
{
}
Set keySet = SchlStud_hashmap.keySet();
Iterator keyIterator = keySet.iterator();
while (keyIterator.hasNext())
{
Object key = keyIterator.next();
SchlName_arrylst.add(key);
Collection values = (Collection) SchlStud_hashmap.get(key);
Iterator valuesIterator = values.iterator();
while (valuesIterator.hasNext())
{
StudName_arrylst.add(valuesIterator.next());
}
SchlName_arylist_length = SchlName_arrylst.size();
StudNamearrylst_length = StudName_arrylst.size();
String schlname_tree[] = new String[SchlName_arylist_length];
String studname_tree[] = new String[StudNamearrylst_length];
Iterator SchlName_iterator = SchlName_arrylst.iterator();
i = 0;
while (SchlName_iterator.hasNext())
{
schlname_tree[i] = SchlName_iterator.next().toString();
}
Iterator StudName_iterator = StudName_arrylst.iterator();
j = 0;
while (StudName_iterator.hasNext())
{
studname_tree[j] = StudName_iterator.next().toString();
j++;
}
for (k = 0; k < schlname_tree.length; k++)
{
tree_parent = treePanel.addObject(null, schlname_tree[k]);
for (k2 = 0; k2 < studname_tree.length; k2++)
{
treePanel.addObject(tree_parent, studname_tree[k2]);
}
}
StudName_arrylst.clear();
SchlName_arrylst.clear();
}
}
/**
* Create the GUI and show it.
*/
private static void createAndShowGUI()
{
//Create and set up the window.
JFrame frame = new JFrame("Student Details");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
Main_frame newContentPane = new Main_frame();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
panel_boxes.setLayout(null);
name_label.setBounds(55,90,150,100);
studName_txtbox.setBounds(225,130, 155, 25);
panel_boxes.add(name_label);
panel_boxes.add(studName_txtbox);
address_label.setBounds(55,160, 150, 100);
studAddress_txtbox.setBounds(225,200, 155, 25);
panel_boxes.add(address_label);
panel_boxes.add(studAddress_txtbox);
other_label.setBounds(55,220, 150, 100);
studOthr_txtbox.setBounds(225,270, 155, 25);
panel_boxes.add(other_label);
panel_boxes.add(studOthr_txtbox);
save_button.setBounds(150,350, 100, 50);
cancel_button.setBounds(350,350, 100, 50);
panel_boxes.add(save_button);
panel_boxes.add(cancel_button);
frame.add(panel_boxes);
//Display the window.
frame.pack();
frame.setSize(1000,700);
frame.setVisible(true);
save_button.setEnabled(false);
cancel_button.setEnabled(false);
studName_txtbox.addFocusListener(new FocusListener()
{
#Override //since some additional functionality is added by the user to
//the inbuilt function #override notation is used
public void focusGained(FocusEvent e)
{
save_button.setEnabled(true);
cancel_button.setEnabled(true);
}
#Override
public void focusLost(FocusEvent e)
{
System.out.println("out of focus textbox");
}
});
studAddress_txtbox.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e)
{
save_button.setEnabled(true);
cancel_button.setEnabled(true);
}
#Override
public void focusLost(FocusEvent e)
{
save_button.setEnabled(false);
cancel_button.setEnabled(false);
}
});
studOthr_txtbox.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e)
{
save_button.setEnabled(true);
cancel_button.setEnabled(true);
}
#Override
public void focusLost(FocusEvent e)
{
save_button.setEnabled(false);
cancel_button.setEnabled(false);
}
});
cancel_button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== cancel_button )
{
clear_textboxes();
}
}
} );
save_button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== save_button )
{
selectionButtonPressed();
}
}
} );
}
public void fill_textboxes(ArrayList a1)
{
Iterator alldetails = a1.iterator();
z=0;
while (alldetails.hasNext())
{
studDetailsTxtbx_disp_db[z]= (String) alldetails.next();
System.out.println("this is the Detail : "+studDetailsTxtbx_disp_db[z]);
z++;
}
studName_txtbox.setText(studDetailsTxtbx_disp_db[0]);
studAddress_txtbox.setText(studDetailsTxtbx_disp_db[1].toString());
studOthr_txtbox.setText(studDetailsTxtbx_disp_db[2]);
}
public static void selectionButtonPressed()
{
studDetailsTxtbxchange[0]=studName_txtbox.getText();
studDetailsTxtbxchange[1]=studAddress_txtbox.getText();
studDetailsTxtbxchange[2]=studOthr_txtbox.getText();
try
{
if((studDetailsTxtbxchange[0].equals(""))||(studDetailsTxtbxchange[0] == null)||(studDetailsTxtbxchange[1].equals(""))||(studDetailsTxtbxchange[1] == null)||(studDetailsTxtbxchange[2].equals(""))||(studDetailsTxtbxchange[2] == null))
{
JOptionPane.showMessageDialog(null,"One of the Fields is Blank","Error",JOptionPane.ERROR_MESSAGE);
}
else
{
System.out.println("control here inside else baby..that has : : "+studDetailsTxtbxchange[0]);
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect_update = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
PreparedStatement execqry = connect.prepareStatement("select * from student_details where student_name='"+studDetailsTxtbxchange[0]+"'");
resultset2=execqry.executeQuery();
System.out.println("control at end if else");
if(resultset2.next())
{
JOptionPane.showMessageDialog(null,"Sorry This name already exists","Error",JOptionPane.ERROR_MESSAGE);
}
else
{
System.out.println("control here");
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect_update = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
PreparedStatement updateQry = connect.prepareStatement("UPDATE student_details SET student_name='"+studDetailsTxtbxchange[0]+"',student_address='"+studDetailsTxtbxchange[1]+"',student_school='"+studDetailsTxtbxchange[2]+"' WHERE student_name='"+user_name+"' and student_address='"+user_add+"'and student_school='"+user_other+"'");
updateQry.executeUpdate();
JOptionPane.showMessageDialog(null,"Record Updated!","UPDATED",JOptionPane.OK_OPTION);
tree_generation.loadit();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void clear_textboxes()
{
studName_txtbox.setText(studDetailsTxtbx_disp_db[0]);
studAddress_txtbox.setText(studDetailsTxtbx_disp_db[1].toString());
studOthr_txtbox.setText(studDetailsTxtbx_disp_db[2]);
}
void dbaction(String string)
{
studDetailsTxtbox_disp[0]= string;
System.out.println("This is the stuff :" + studDetailsTxtbox_disp[0]);
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
connect = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2","suraj","suraj");
PreparedStatement statement4 = connect.prepareStatement("SELECT * from student_details where student_name ='"+studDetailsTxtbox_disp[0]+"'");
resultSet = statement4.executeQuery();
while(resultSet.next())
{
user_name = resultSet.getString("student_name");
StudDetailTxtFld_arrylst.add(user_name);
System.out.println("name :"+user_name);
user_add = resultSet.getString("student_address");
StudDetailTxtFld_arrylst.add(user_add);
System.out.println("address : "+ user_add);
user_other = resultSet.getString("student_school");
StudDetailTxtFld_arrylst.add(user_other);
System.out.println("school : "+user_other);
}
}
catch (Exception e1)
{
e1.printStackTrace();
}
fill_textboxes(StudDetailTxtFld_arrylst);
}
public static void main(String[] args)
{
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run()
{
createAndShowGUI();
}
});
}
}
tree_generation.java
/**
* #author Suraj
*
* Tree generation and actions such as adding new parent or child takes place here
* Section Listeners for displaying relavent details of the selected student.
*/
package Student_Details;
import java.awt.GridLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
public class tree_generation extends JPanel
{
protected DefaultMutableTreeNode rootNode;
protected DefaultTreeModel treeModel;
protected JTree tree;
public String studDetailsTxtbox_disp[] = new String[10];
public tree_generation()
{
super(new GridLayout(1,0));
rootNode = new DefaultMutableTreeNode("Click for Student Details");
treeModel = new DefaultTreeModel(rootNode);
tree = new JTree(treeModel);
tree.setEditable(true);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(new TreeSelectionListener()
{
#Override
public void valueChanged(TreeSelectionEvent e)
{
studDetailsTxtbox_disp[0]= tree.getLastSelectedPathComponent().toString();
Main_frame db = new Main_frame();
db.dbaction(studDetailsTxtbox_disp[0]);
}
});
tree.setShowsRootHandles(true);
JScrollPane scrollPane = new JScrollPane(tree);
add(scrollPane);
}
/** Add child to the currently selected node. */
public DefaultMutableTreeNode addObject(Object child)
{
DefaultMutableTreeNode parentNode = null;
TreePath parentPath = tree.getSelectionPath();
if (parentPath == null) {
parentNode = rootNode;
}
else
{
parentNode = (DefaultMutableTreeNode)
(parentPath.getLastPathComponent());
}
return addObject(parentNode, child, true);
}
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
Object child)
{
return addObject(parent, child, false);
}
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
Object child,
boolean shouldBeVisible)
{
DefaultMutableTreeNode childNode =
new DefaultMutableTreeNode(child);
if (parent == null)
{
parent = rootNode;
}
//It is key to invoke this on the TreeModel
treeModel.insertNodeInto(childNode, parent,
parent.getChildCount());
//Make sure the user can see the new node.
if (shouldBeVisible)
{
tree.scrollPathToVisible(new TreePath(childNode.getPath()));
}
return childNode;
}
static void loadit()
{
tree_generation.treeModel.reload();
//i tried this too//
//treePanel = new tree_generation();
// populateTree(treePanel);
}
class MyTreeModelListener implements TreeModelListener {
public void treeNodesChanged(TreeModelEvent e) {
DefaultMutableTreeNode node;
node = (DefaultMutableTreeNode)(e.getTreePath().getLastPathComponent());
node.setUserObject("HELLO WORLD");
/*
* If the event lists children, then the changed
* node is the child of the node we've already
* gotten. Otherwise, the changed node and the
* specified node are the same.
*/
int index = e.getChildIndices()[0];
node = (DefaultMutableTreeNode)(node.getChildAt(index));
System.out.println("The user has finished editing the node.");
System.out.println("New value: " + node.getUserObject());
}
public void treeNodesInserted(TreeModelEvent e) {
}
public void treeNodesRemoved(TreeModelEvent e) {
}
#Override
public void treeStructureChanged(TreeModelEvent e)
{
System.out.println("tree sturct changed") ;
DefaultMutableTreeNode node;
node = (DefaultMutableTreeNode)(e.getTreePath().getLastPathComponent());
node.setUserObject("HELLO WORLD");
tree.updateUI();
e.getTreePath();
}
}
}
Queries - DATABASE NAME : treedata2
create table student_details(student_name varchar(20),student_address varchar(30),student_school varchar(20));
insert into student_details values('suraj','mangalore','dps');
insert into student_details values('prassana','Bangalore lalbagh 23/16 2nd main road','dps');
insert into student_details values('deepika','Mangalore kadri park , 177b','dav');
insert into student_details values('sujith','delhi , rajinder nagar, d black','dav');
insert into student_details values('sanjay','bombay marina drive, 12/34','dav');
insert into student_details values('suresh','jaipur , lalbagh cjhowki','kv');
insert into student_details values('manu','surat, pune warior house','kv');
insert into student_details values('tarun','chennai, glof club','salwan');
insert into student_details values('vinay','haryana, indutrial area','hindu senior');
insert into student_details values('veeru','trivendrum, kottayam 12/77','canara')
Ok, I think I found what's not working in your code, but you should probably try it yourself and confirm.
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect_update = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
PreparedStatement updateQry = connect.prepareStatement("UPDATE student_details SET student_name='"+studDetailsTxtbxchange[0]+"',student_address='"+studDetailsTxtbxchange[1]+"',student_school='"+studDetailsTxtbxchange[2]+"' WHERE student_name='"+user_name+"' and student_address='"+user_add+"'and student_school='"+user_other+"'");
updateQry.executeUpdate();
JOptionPane.showMessageDialog(null,"Record Updated!","UPDATED",JOptionPane.OK_OPTION);
tree_generation.loadit();
In this code, you indeed update the database but you don't update the model of the tree. You are calling the static method loadit() but that method does not contain any code. In order to worker you should probably refresh/reload your TreeModel. There are different ways to do that. One would be to directly spot the TreeNode to refresh and update it with the new values. Another would be to recreate your entire TreeModel (but this can be costly if your tree is big). Using an object-mapping model (for instance JPA/Hibernate) you could have something much cleaner with an appropriate MVC-pattern and a model notifying the views of the updated values, but it requires extra-effort to set up.
For what it is worth, you should consider dropping those static keywords as they are not necessary nor appropriately used. Whenever possible, you should try to avoid using that keyword (unless it is used in conjunction with finalto describe a constant value).
One more thing, try to use appropriate LayoutManager's instead of using absolute-positionning. Using appropriate layout manager makes your code easier to maintain and more portable across different platforms/look and feels.