I have the following cod!
when i call the fruitsTable() from refreshButton() it refreshes the JTable! but when i call it from another class it does not refresh the Table! bellow is the simplified code
public ResultSet sqlCommand(String sqlStatement) throws SQLException
{
this.sqlStatement = sqlStatement;
ConnectingToMysql fruitsConnection = new ConnectingToMysql();
Connection myConnection = fruitsConnection.ConnectingToMysql();
Statement st = myConnection.createStatement();
ResultSet result = st.executeQuery(sqlStatement);
return result;
}
public Vector<String> getColumnData() throws SQLException
{
ResultSetMetaData metaData = sqlCommand(sqlStatement).getMetaData();
int columnCount = metaData.getColumnCount();
Vector<String> allColumn = new Vector<String>();
for(int i = 1; i <= columnCount; i++)
{
allColumn.add(metaData.getColumnName(i));
}
return allColumn;
}
public Vector<Vector<String>> getData() throws SQLException
{
ResultSet result = sqlCommand(sqlStatement);
ResultSetMetaData metaData = result.getMetaData();
int columnCount = metaData.getColumnCount();
Vector<Vector<String>> allRow = new Vector<Vector<String>>(columnCount);
while(result.next())
{
Vector<String> eachRow = new Vector<String>();
for(int i = 1; i <= columnCount; i++)
{
eachRow.add(result.getString(i));
}
allRow.add(eachRow);
}
return allRow;
}
public JScrollPane fruitsTable() throws SQLException
{
Vector<String> columnData = getColumnData();
Vector<Vector<String>> rowData = getData();
fruitsTableModel.setDataVector(rowData,columnData);
Font font = new Font("Courier", Font.PLAIN,16);
fruitsTable = new JTable();
fruitsTable.setModel(fruitsTableModel);
fruitsTable.setPreferredScrollableViewportSize(new Dimension(850,310));
fruitsTable.setRowHeight(30);
fruitsTable.setFont(font);
JScrollPane fruitsScrollPane = new JScrollPane(fruitsTable);
dataValue();
return fruitsScrollPane;
}
private JButton refreshButton() throws SQLException
{
JButton refreshButton = new JButton("Refresh Record");
refreshButton.setPreferredSize(new Dimension(100,40));
refreshButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
fruitsTable();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
return refreshButton;
}
and this is the only code from the other class that calls the fruitsTable().
saveButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
try
{
String number = numberTextField.getText();
int ID = Integer.parseInt(number);
String fruit = fruitTextField.getText();
String color = colorTextField.getText();
String taste = tasteTextField.getText();
System.out.println("The value is: " + number + " " + fruit + " " + color + " " + taste);
String sqlText = "Insert into fruits(ID,Fruit,Color,Tast) values(?,?,?,?)";
ConnectingToMysql connectingToMysql = new ConnectingToMysql();
Connection makeConnection = connectingToMysql.ConnectingToMysql();
PreparedStatement pdt = makeConnection.prepareStatement(sqlText);
pdt.setInt(1,ID);
if(fruit.isEmpty())
{
pdt.setNull(2,java.sql.Types.VARCHAR);
}
else
{
pdt.setString(2,fruit);
}
if(color.isEmpty())
{
pdt.setNull(3,java.sql.Types.VARCHAR);
}
else
{
pdt.setString(3,color);
}
if(taste.isEmpty())
{
pdt.setNull(4,java.sql.Types.VARCHAR);
}
else
{
pdt.setString(4,taste);
}
pdt.executeUpdate();
GetFruits getFruits = new GetFruits();
getFruits.fruitsTable();
}
catch(SQLIntegrityConstraintViolationException e)
{
JOptionPane.showMessageDialog(null, "The 'Number' you entered already exist!", "Error", JOptionPane.ERROR_MESSAGE);
System.out.println(e);
}
GetFruits getFruits = new GetFruits();
getFruits.fruitsTable();
You're creating a new GetFruits object and refreshing it's table instead of updating the existing one. Try creating a class variable of GetFruits so you're using the same instance instead of creating a new one each time. Just guessing since I can't see all the code that contains the action listener.
Related
I'm working on a Java database application, where the user has one side to insert data and another to show in a JTable (in a JScrollPane) the content of the linked HSQLDB database. Everthing works so far so good, but I searched for a very long time without finding how to update my JTable dynamically when a change is made to the database (add, update or delete) for each instance of my program because several persons can work on it simultaneously.
It actually works by replacing my table model for local update, but for other instances, i have set a Timer which is not very clean.
Could you help me resolving this please ?
Here is my code (I have an Interface.java for "visible" part and a SQL.java to manage my db) :
My timer
JTable table = new JTable(sql.showTable("SELECT * FROM suivi_flotte"));
Timer timer = new Timer(900000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sql.updateTable();
nbLinesOrRefresh.setText("Actualisation...");
Timer timer2 = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
nbLinesOrRefresh.setText("");
}
});
timer2.start();
timer2.setRepeats(false);
}
});
timer.setDelay(900000);
timer.start();
formatTable(table);
My updateTable() method (called each time there is an insert, update or delete)
protected void updateTable() {
Interface.f.table.setModel(showTable("SELECT * FROM suivi_flotte"));
Interface.f.formatTable(Interface.f.table); // a method to custom JTable appearance
}
My showTable(String query) method
protected DefaultTableModel showTable(String query) {
String[] columnsTitles = {"N°", "Propriétaire", "Service", "Grade", "Nom", "Prénom", "Mail", "N° SIM", "N° Tél", "Modèle", "N° Série", "IMEI", "N° Crypto", "Date début", "Date fin", "DS", "Commentaire", "Date de création"};
ArrayList<String> columnNames = new ArrayList<>();
ArrayList<Object> data = new ArrayList<>();
connectDB(); // only to connect to db
try (ResultSet rs = stmt.executeQuery(query)) {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.add(columnsTitles[i - 1]);
}
while (rs.next()) {
ArrayList<Object> row = new ArrayList<>(columns);
for (int i = 1; i <= columns; i++) {
row.add(rs.getObject(i));
}
data.add(row);
}
shutdownDB(); // to fully disconnect from db
} catch (SQLException e) {
System.out.println(e.getMessage());
}
Vector<Vector<?>> dataVector = new Vector<>();
Vector<String> columnNamesVector = new Vector<>();
for (int i = 0; i < data.size(); i++) {
ArrayList<?> subArray = (ArrayList<?>) data.get(i);
Vector<Object> subVector = new Vector<>();
for (int j = 0; j < subArray.size(); j++) {
subVector.add(subArray.get(j));
}
dataVector.add(subVector);
}
for (int i = 0; i < columnNames.size(); i++) {
columnNamesVector.add(columnNames.get(i));
}
DefaultTableModel tModel = new DefaultTableModel(dataVector, columnNamesVector) {
private static final long serialVersionUID = 1L;
public Class<?> getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object o = getValueAt(row, column);
if (o != null) {
return o.getClass();
}
}
return Object.class;
}
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
// tModel.fireTableDataChanged(); // <-- does not work
return tModel;
}
Thank you for your help.
UPDATE 1 :
All my connection/disconnection code :
private void connectDB() {
JFrame op = new JFrame();
op.setAlwaysOnTop(true);
try {
Class.forName("org.hsqldb.jdbcDriver");
co = DriverManager.getConnection("jdbc:hsqldb:file:db;shutdown=true");
stmt = co.createStatement();
} catch (SQLException | ClassNotFoundException e) {
JOptionPane.showMessageDialog(op, "Erreur de connexion à la base de données :\n" + e.getMessage(), Interface.windowTitle, JOptionPane.ERROR_MESSAGE);
}
}
private void openDB() throws IOException {
try {
BufferedReader br = new BufferedReader(new FileReader("db.sql"));
String line;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
stmt.executeUpdate(sb.toString());
} catch (SQLException e) {}
}
private void shutdownDB() throws SQLException {
stmt.close();
co.close();
}
UPDATE 2 :
I changed everything in SQL.java to non-static. Each SQL.[...] has been changed to sql.[...] with private SQL sql = new SQL(); on top of the class and public SQL() {} in the class. I also changed it in the above code.
I'm making a simple program that show the teams, the matches and racking goal of Euro2016 in France.
I have some problem with JTable when changing query.
Here is what happens:
when I change from a Table of (for example) 10 rows to another one that contains only 5 rows it works. But if I change from a table that contains 5 rows to another of 10, the table doesn't change, it displays only 5 rows.
Here the code:
public class Euro2016GUI extends JFrame {
private Container container;
private Sfondo pnlSfondo;
JTable table;
JPanel panel;
static Vector<Vector<String>> data = new Vector<Vector<String>>();
static Vector<String> headers = new Vector<String>();
public Euro2016GUI() {
data.removeAll(data);
headers.removeAll(headers);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600, 400);
this.setTitle("Euro2016");
this.setLocationRelativeTo(null);
pnlSfondo = new Sfondo();
container = this.getContentPane();
container.add(pnlSfondo);
}
public void createTable(String pQuery) {
data.removeAll(data);
headers.removeAll(headers);
Control control = new Control();
panel = new JPanel(new BorderLayout());
panel.setSize(300, 300);
panel.setBackground(Color.red);
control.getData(pQuery);
data = control.getData();
headers = control.getHeaders();
//this is the model which contain actual body of JTable
DefaultTableModel model = new DefaultTableModel(data, headers);
table = new JTable(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setEnabled(false);
table.setMaximumSize(new Dimension(100, 300));
header_size();
JScrollPane scroll = new JScrollPane(table);
//scroll.setSize(600, 400);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
this.getContentPane().add(panel);
panel.add(scroll, BorderLayout.CENTER);
}
public void header_size() {
int colonne = table.getColumnModel().getColumnCount();
TableColumn column;
for (int i = 0; i < colonne; i++) {
column = table.getColumnModel().getColumn(i);
column.setPreferredWidth(200);
}
}
public void cleanData() {
if (table != null) {
DefaultTableModel dm = (DefaultTableModel) table.getModel();
dm.setRowCount(0);
table.revalidate();
}
data.removeAll(data);
headers.removeAll(headers);
}
}
CLASS CONTROL
public class Control {
private static Vector<Vector<String>> data = new Vector<Vector<String>>();
private static Vector<String> headers = new Vector<String>();
public void getData(String pQuery) {
// Enter Your MySQL Database Table name in below Select Query.
String query = pQuery;
Connection con = null;
ResultSet rs;
Statement st = null;
int colonne = 0;
data.removeAll(data);
headers.removeAll(headers);
try {
con = DBConnectionPool.getConnection();
st = con.createStatement();
rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
colonne = rsmd.getColumnCount();
for (int i = 1; i <= colonne; i++) {
headers.add(rsmd.getColumnName(i));
}
while (rs.next()) {
Vector<String> d = new Vector<String>();
for (int i = 1; i <= colonne; i++) {
d.add(rs.getString(i));
}
data.add(d);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (st != null) {
try {
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataInJTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (con != null) {
DBConnectionPool.releaseConnection(con);
}
}
}
public Vector<Vector<String>> getData() {
return this.data;
}
public Vector<String> getHeaders() {
return this.headers;
}
}
HERE THE ACTION LISTENER IN THE MENU:
...
//----ROSE---//
private class OnClickRose implements ActionListener {
Sfondo sfondo;
#Override
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
str = str.replace("[", "");
str = str.replace("]", "");
String sx = "'";
String dx = "'";
String query = query2.concat(sx.concat(str.concat(dx)));
//frame.cleanData();
sfondo = frame.getPnlSfondo();
if (sfondo.isVisible() && sfondo.getParent().isVisible()) {
sfondo.setVisible(false);
}
frame.createTable(query);
}
}
//----CALENDARIO----//
private class OnClickCalendario implements ActionListener {
Sfondo sfondo;
#Override
public void actionPerformed(ActionEvent e) {
frame.cleanData();
sfondo = frame.getPnlSfondo();
if (sfondo.isVisible() && sfondo.getParent().isVisible()) {
sfondo.setVisible(false);
}
frame.createTable(query4);
}
}
//----CLASSIFICA MARCATORI----//
private class OnClickMarcatori implements ActionListener {
Sfondo sfondo;
#Override
public void actionPerformed(ActionEvent e) {
frame.cleanData();
sfondo = frame.getPnlSfondo();
if (sfondo.isVisible() && sfondo.getParent().isVisible()) {
sfondo.setVisible(false);
}
frame.createTable(query3);
}
}
...
Could anybody tell me where I wrong?
Basically to tell the table to refresh itself, you just call the method fireTableDataChanged() of it's table model.
So in your example, after you run the query, you could just call:
((DefaultTableModel)yourTable.getModel()).fireTableDataChanged();
But I suggest you to stop using default table model, and implement your own table model. It's a lot easier to work.
I could really need your help, I tried to solve this problem for over one week, but haven't found a solution yet.
My Aim: I want to create a table, which can read the Data from a Database. I can also add Data to the DB by inserting it in my program.
My Problem: After inserting the Data i want the Database to refresh, so that it also shows my new record set. But no matter what i tried, it didn't work.
My Code: Here is my Mainframe-Class:
public class Gui_Test extends JFrame {
JButton addMovieButton;
JFrame frame = new JFrame("Movie Database");
JPanel panel;
JMenuBar menubar;
JMenu fileMenu;
JLabel label;
JTable table = new JTable();
MovieTableModel mtm;
public static void main(String[] args) {
Gui_Test test = new Gui_Test();
test.run();
}
public void run() {
// Gui ///
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
panel = new JPanel();
panel.setVisible(true);
panel.setBackground(Color.black);
// Add - Movie Button ///
addMovieButton = new JButton("Add Movie");
addMovieButton.addActionListener(new addMovieButtonListener());
panel.add(addMovieButton);
// Table select ///
mtm = new MovieTableModel();
table.setModel(mtm);
JScrollPane pane = new JScrollPane(table);
frame.getContentPane().add(pane);
frame.getContentPane().add(BorderLayout.WEST, panel);
}
class addMovieButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
AddMoviePanel addmoviepanel = new AddMoviePanel();
addmoviepanel.moviepanel(mtm);
}
}}
Here is my TableModel:
public class MovieTableModel extends AbstractTableModel {
Connection con = null;
Vector columnNames = new Vector();
Vector data = new Vector();
ResultSet rs;
ResultSetMetaData meta;
public MovieTableModel() {
showResult();
}
void showResult() {
Connection con;
try {
con = DriverManager.getConnection(
"jdbc:hsqldb:file:C:/Users/...", "sa",
"");
java.sql.Statement stmt = con.createStatement();
String query = "SELECT * FROM movies ORDER BY id DESC";
ResultSet rs = stmt.executeQuery(query);
meta = rs.getMetaData();
int columns = meta.getColumnCount();
// get column names
for (int i = 1; i <= columns; i++) {
columnNames.addElement(meta.getColumnName(i));
}
// get row data
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(rs.getObject(i));
}
data.addElement(row);
}
if (con != null)
try {
rs.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
#Override
public String getColumnName(int column) {
return columnNames.get(column).toString();
}
#Override
public int getColumnCount() {
try {
return meta.getColumnCount();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
#Override
public Class getColumnClass(int column) {
// TODO Auto-generated method stub
return getValueAt(0, column).getClass();
}
#Override
public int getRowCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getValueAt(int row, int column) {
return ((Vector) data.get(row)).get(column);
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
void addRow(final String value1, final String value2, final String value3,
final String value4, final String value5, final String value6,
final String value7) {
try {
Connection con = DriverManager.getConnection(
"jdbc:hsqldb:file:C:/Users/Jonas/workspace/movieDB", "sa",
"");
try {
final java.sql.Statement state = con.createStatement();
try {
state.addBatch("INSERT INTO movies VALUES (DEFAULT, '"
+ value1 + "', '" + value2 + "'," + value3 + ", '"
+ value4 + "', " + value5 + ", '" + value6 + "', '"
+ value7 + "')");
state.executeBatch();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} finally {
if (con != null)
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}}
And here is my addMovieFrame, which opens to add new Movies:
public class AddMoviePanel {
MovieTableModel mtm;
JPanel addMoviePanel;
JFrame addMovieFrame;
JTextField value1Input;
JTextField value2Input;
// ... value3 - value7
Connection con = null;
public void moviepanel(MovieTableModel mtm) {
this.mtm = mtm;
addMovieFrame = new JFrame("Add Movie");
addMovieFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMovieFrame.setVisible(true);
addMovieFrame.setSize(550, 300);
addMoviePanel = new JPanel();
GroupLayout layout = new GroupLayout(addMoviePanel);
addMoviePanel.setLayout(layout);
JLabel label1 = new JLabel("label1:");
JLabel label2 = new JLabel("label2");
// ...JLabel 3-7 same as Label 1&2
addMoviePanel.add(label1);
addMoviePanel.add(label2);
// ...add Label 3-7
value1Input = new JTextField();
value2Input = new JTextField();
// ... value3- value7 Input
addMoviePanel.add(value1Input);
addMoviePanel.add(value2Input);
// ... add value3Input - value7Input
JButton ok = new JButton("Ok");
ok.addActionListener(new okActionListener());
addMovieFrame.add(ok);
addMovieFrame.getContentPane().add(addMoviePanel);
// here was just Layout Stuff //
}
class okActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
mtm.addRow(value1Input.getText(), value2Input.getText()
// ... value3Input.getText() - value7Input.getText()
);
mtm.fireTableDataChanged();
addMovieFrame.dispose();
}
}}
I already tried several types and positions of fireXXX-Methods...
Maybe somebody got an idea, how to refresh my jtable, when hitting the OK-Button in my addMovie-Frame? :)
As shown here and discuseed here, only your TableModel should fire table model events. While this is typically done in setValueAt(), you can insert a whole row and fire a single event, as shown here.
I have a class A and a class B.
In class A there is a constructor:
public A() {
getSelectedRow();
}
This constructor calls:
public int getSelectedRow() {
System.out.println("The row is : " + table.getSelectedRow());
return table.getSelectedRow();
}
Up to here everything works fine!
The class B then calls the method getSelectedRow() like that:
A results = new A();
System.out.println("YEAH! IT'S: " + results.getSelectedRow());
I just want to find out the selected table row from class A. The problem is that I am getting a null pointer exception and i dont know why. if I dont call the method everything works fine.
CLASS A:
public class AllResultsFromDB extends JFrame {
#SuppressWarnings("compatibility:9056676689615464658")
private static final long serialVersionUID = 188850508334531506L;
GUI ins = new GUI();
JTable table;
public AllResultsFromDB(GUI x) {
final Vector columnNames = new Vector();
final Vector data = new Vector();
this.ins = x;
try {
/** Initializing GUI class
* in order to call
* getSelectedTable() method. **/
Login sgui = new Login();
String dburl = "jdbc:oracle:thin:#localhost:1521:ORCL";
Connection connection = DriverManager.getConnection(dburl, sgui.getUsername(), sgui.getPassword());
// Fetch data from table specified by user
String query = "SELECT * FROM " + ins.getSelectedTable() + " ORDER BY id";
System.out.println(query);
Statement stmt = connection.createStatement();
ResultSet rset = stmt.executeQuery(query);
ResultSetMetaData metad = rset.getMetaData();
int columns = metad.getColumnCount();
// This loop gets the names of the columns
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metad.getColumnName(i));
}
// This loop gets the data inside the rows
while (rset.next()) {
final Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(rset.getObject(i));
}
data.addElement(row);
}
rset.close();
stmt.close();
connection.close();
// Create table with results
table = new JTable(data, columnNames) {
public boolean isCellEditable(int row, int col) {
return false;
}
public Class getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object obj = getValueAt(row, column);
if (obj != null) {
return obj.getClass();
}
}
return Object.class;
}
};
JScrollPane scroll = new JScrollPane(table);
getContentPane().add(scroll);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.SOUTH);
table.addMouseListener(new MouseListener() {
public void mousePressed(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseReleased(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseEntered(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseExited(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseClicked(MouseEvent e) {
getSelectedRow();
if (e.getClickCount() == 2) {
//System.out.println(table.getSelectedRow());
Profile profile = new Profile();
try {
profile.getData();
//wait(500000);
profile.getImage();
} catch (Exception f) {
}
profile.setVisible(true);
}
}
});
} catch (SQLException e) {
}
}
public AllResultsFromDB(int x) {
x = getSelectedRow();
System.out.println(table.getSelectedRow());
}
public int getSelectedRow() {
System.out.println("The row is : " + table.getSelectedRow());
return table.getSelectedRow();
}
}
CLASS B:
public class Profile extends JFrame {
AllResultsFromDB results = new AllResultsFromDB();
public Profile(AllResultsFromDB x) {
this.results=x;
try {
getData();
getImage();
} catch (Exception e) {
e.printStackTrace();
}
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
public void getImage() throws Exception {
JLabel label;
Image img;
ImageIcon pic;
JPanel panel;
img = new ImageIcon("java.jpg").getImage();
pic = new ImageIcon(img);
label = new JLabel("", pic, JLabel.CENTER);
panel = new JPanel(new BorderLayout());
panel.setBounds(new Rectangle(0, 0, 340, 310));
panel.add(label, null);
panel.add(label, BorderLayout.CENTER);
this.getContentPane().setLayout(null);
this.setSize(new Dimension(1148, 336));
this.getContentPane().add(panel, null);
}
public void getData() throws Exception {
String url = "jdbc:oracle:thin:#localhost:1521:ORCL";
String username = "c##lambros";
String password = "16111111";
Connection conn = null;
try {
System.out.println("YEAH! IT'S: " + results.getSelectedRow());
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, username, password);
String sql = "SELECT foto FROM criminals WHERE id = 5";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet resultSet = stmt.executeQuery();
while (resultSet.next()) {
//String name = resultSet.getString(1);
//System.out.println("Name = " + name);
File image = new File("java.jpg");
FileOutputStream fos = new FileOutputStream(image);
byte[] buffer = new byte[256];
//
// Get the binary stream of our BLOB data
//
InputStream is = resultSet.getBinaryStream(1);
while (is.read(buffer) > 0) {
fos.write(buffer);
}
fos.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null && !conn.isClosed()) {
conn.close();
}
}
}
private void jbInit() throws Exception {
this.setSize(new Dimension(816, 380));
JLabel label;
Image img;
ImageIcon pic;
JPanel panel;
img = new ImageIcon("java.jpg").getImage();
pic = new ImageIcon(img);
label = new JLabel("", pic, JLabel.CENTER);
panel = new JPanel(new BorderLayout());
panel.setBounds(new Rectangle(0, 0, 340, 310));
panel.add(label, null);
panel.add(label, BorderLayout.CENTER);
this.getContentPane().setLayout(null);
this.setSize(new Dimension(1148, 336));
this.getContentPane().add(panel, null);
}
}
In the classB since you are creating a new instance
A results = new A();
The value present in the table.getSelectedRow() also gets created newly and will point to null.
So make sure that you do somthing
A results = new A(selectedRow);
and in the constructor of the A,pass the argument to the function
getSelectedRow(selectedRow);
Please note : Make sure that the value of the "table.selectedRow" is maintained
If table is your instance variable in Class A then it might not be initialized when you are trying to access it in constructor of A.
And calling getSelectedRow from the constructor is not making any sense too.
Try to initialize the table variable in constructor instead of calling that method, it should work after it.
This is because the table object is not being initialized.
Try to initialize the table object in constructor....it is a good practice
I use DefaultTableModel for my JTable model, But not show my table!
public class RecordTableGUI2 extends JFrame {
JTable table;
RecordTableModel2 model2;
public RecordTableGUI2() {
model2 = new RecordTableModel2();
table = new JTable(model2);
add(new JScrollPane(table), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RecordTableGUI2();
}
});
}
}
Model Class:
public class RecordTableModel2 extends DefaultTableModel {
Connection con;
Statement statement;
ResultSet result;
String dbUrl = "jdbc:mysql://localhost/mydb";
String query = "Select * from mytable";
Vector data = new Vector();
Vector column = new Vector();
public RecordTableModel2() {
try {
con = DriverManager.getConnection(dbUrl, "root", "2323");
statement = con.createStatement();
result = statement.executeQuery(query);
int c = result.getMetaData().getColumnCount();
for (int i = 1; i <= c; i++) {
column.add(result.getMetaData().getColumnName(i));
System.out.println(result.getMetaData().getColumnName(i)); //prints correct
}
while (result.next()) {
Vector eachRow = new Vector(c);
for (int i = 1; i <= c; i++) {
eachRow.add(result.getString(i));
System.out.println(result.getString(i)); //prints correct
}
data.add(eachRow);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
} finally {
try {
if (con != null) {
con.close();
}
if (statement != null) {
statement.close();
}
} catch (SQLException sqlee) {
sqlee.printStackTrace();
}
}
}
}
How to introduce vectors to DefaultTableModel?
Output just show a blank JFrame
Add this at first statement of constructor:
super(data,column);
And declare data and column as static