So I have two JFrames. The first one just has a button with an Event to call the second one. This second JFrame contains a table filled with data from a MySQL database, which is the following code:
public class NewClass extends JFrame {
public NewClass()
{
ArrayList columnNames = new ArrayList();
ArrayList data = new ArrayList();
String url = "jdbc:mysql://localhost:3306/MYDB";
String userid = "root";
String password = "password";
String sql = "SELECT * FROM MYTABLE";
try (Connection connection = DriverManager.getConnection( url, userid, password );
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql ))
{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++)
{
columnNames.add( md.getColumnName(i) );
}
while (rs.next())
{
ArrayList row = new ArrayList(columns);
for (int i = 1; i <= columns; i++)
{
row.add( rs.getObject(i) );
}
data.add( row );
}
}
catch (SQLException e)
{
System.out.println( e.getMessage() );
}
Vector columnNamesVector = new Vector();
Vector dataVector = new Vector();
for (int i = 0; i < data.size(); i++)
{
ArrayList subArray = (ArrayList)data.get(i);
Vector 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));
JTable table = new JTable(dataVector, columnNamesVector)
{
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;
}
};
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
}
public static void main(String[] args)
{
NewClass frame = new NewClass();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
When I run NewClass directly, pack() works as is supposed to and resizes the JFrame depending on the size of the talble that's within. However, whenever I run the first JFrame with the button and then press the button to call the event, NewClass pops up but the window is way too small. I have tried using setSize and obviously pack().
When I resize the JFrame manually the columns and rows are all there like they're supposed to, it's just that I can't figure out why pack() isn't working.
Do you have any ideas on how to resize this second JFrame without having to do it manually?
Thanks in advance!
EDIT:
The code for the button on first JFrame which calls NewClass is the following:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
NewClass frame = new NewClass();
frame.setVisible(true);
}
Change...
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
NewClass frame = new NewClass();
frame.setVisible(true);
}
to something more like...
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
NewClass frame = new NewClass();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
which would seem to match what you're doing in your main method
Related
I need to use the object 'urObjectInCell' in mouseListener of 'table' to another class BtnDelete1.
Here's my Mouse Listener Code:
JTable table;
public FirstSwingApp(){
super();
table = new JTable(model);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(final MouseEvent e) {
if (e.getClickCount() == 1) {
final JTable target = (JTable)e.getSource();
final int row = target.getSelectedRow();
final int column = 1;
// Cast to ur Object type
urObjctInCell = target.getValueAt(row, column);
}
}
});
friendNo = urObjctInCell.toString();
I tried storing the object in friendNo string which has been declared earlier. But I don't think the friendNo is taking the value of the object.
Here's my Class BtnDelete1 code:
public class BtnDelete1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
String fnumber = friendNo;
CallableStatement dstmt = null;
CallableStatement cstmt = null;
ResultSet rs;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Contact_Manager?user=root");
String SQL = "{call delete_contact (?)}";
String disQuery = "select * from FRIEND";
dstmt = conn.prepareCall(disQuery);
cstmt = conn.prepareCall(SQL);
cstmt.setString(1, fnumber);
cstmt.executeQuery();
rs = dstmt.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
// It creates and displays the table
model.setDataVector(data, columnNames);
// Closes the Connection
dstmt.close();
System.out.println("Success!!");
} catch (SQLException ex) {
System.out.println("Error in connection: " + ex.getMessage());
}
}
}
The value of urObjectInCell object obtained from mouseListener is to be used to delete a row in the Jtable 'table'.
I think that you may be thinking this out wrong. Rather than trying to mix a MouseListener and an ActionListener in some unholy matrimony, why not instead simply get the selected cell from the JTable when the ActionListener is notified?
You could do this by giving the JTable-holding class a method for extracting a reference to the selected JTable cell, give the ActionListener a reference to this class, and have the ActionListener call this method when it has been notified and its callback method called.
For example say you have a JTable held in a GUI called NoMouseListenerNeeded:
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
#SuppressWarnings("serial")
public class NoMouseListenerNeeded extends JPanel {
private static final Integer[][] DATA = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
private static final String[] COLS = { "A", "B", "C" };
private DefaultTableModel tblModel = new DefaultTableModel(DATA, COLS);
private JTable table = new JTable(tblModel);
public NoMouseListenerNeeded() {
JPanel btnPanel = new JPanel();
btnPanel.add(new JButton(new MyButtonListener(this)));
setLayout(new BorderLayout());
add(new JScrollPane(table));
add(btnPanel, BorderLayout.PAGE_END);
}
// get data held by selected cell in JTable
// returns null if no cell selected
public Object getSelectedCell() {
int col = table.getSelectedColumn();
int row = table.getSelectedRow();
if (col < 0 || row < 0) {
return null; // no selection made, return null
} else {
return table.getValueAt(row, col);
}
}
private static void createAndShowGui() {
NoMouseListenerNeeded mainPanel = new NoMouseListenerNeeded();
JFrame frame = new JFrame("NoMouseListenerNeeded");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
You could use an ActionListener (or AbstractAction) to get the selected cell by passing the GUI into the listener, and calling the GUI's method that returns the selected data:
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
#SuppressWarnings("serial")
public class MyButtonListener extends AbstractAction {
private NoMouseListenerNeeded mainGui;
public MyButtonListener(NoMouseListenerNeeded mainGui) {
super("Press Me");
putValue(MNEMONIC_KEY, KeyEvent.VK_P);
this.mainGui = mainGui;
}
#Override
public void actionPerformed(ActionEvent e) {
Object cell = mainGui.getSelectedCell();
if (cell != null) {
String message = "Selection is: " + cell;
JOptionPane.showMessageDialog(mainGui, message, "Selection", JOptionPane.PLAIN_MESSAGE);
}
}
}
I wnat to fill my Table with new Datas which i get by my DataBase(MySQL). I get all datas and create a new Model with them, but if i want to refresh the specific panel, then it wont be repainted.
public class PanelWest extends JPanel implements ActionListener {
private JButton but_selectBP;
private JButton but_selectBPAdr;
private JButton but_selectGerichte;
private GroupLayout layoutGroup;
private Connector stmtExecuter = new Connector();
// private PanelCenter tableViewer = new PanelCenter();
public PanelWest() {
layoutGroup = createLayout();
this.setLayout(layoutGroup);
createButtons();
}
private GroupLayout createLayout() {
GroupLayout layout = new GroupLayout(this);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
return layout;
}
void createButtons() {
this.but_selectBP = new JButton("Kunden anzeigen");
this.but_selectBP.addActionListener(this);
this.but_selectBPAdr = new JButton("Gerichte anzeigen");
this.but_selectBPAdr.addActionListener(this);
this.but_selectGerichte = new JButton("Lieferanten anzeigen");
this.but_selectGerichte.addActionListener(this);
this.layoutGroup.setHorizontalGroup(layoutGroup.createParallelGroup().addComponent(but_selectBP).addComponent(but_selectBPAdr).addComponent(but_selectGerichte));
this.layoutGroup.setVerticalGroup(layoutGroup.createSequentialGroup().addComponent(but_selectBP).addComponent(but_selectBPAdr).addComponent(but_selectGerichte));
}
#Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src.equals(this.but_selectBP)) {
String query = "SELECT * FROM Kunde";
ResultSet rst = this.stmtExecuter.getResultDBData(query);
// this.tableViewer.setTableName("Kunde");
new PanelCenter().createTable(fillHeader(rst), fillData(rst));
}
if (src.equals(this.but_selectBPAdr)) {
String query = "SELECT * FROM Gericht";
ResultSet rst = this.stmtExecuter.getResultDBData(query);
// this.tableViewer.createTable(fillHeader(rst), fillData(rst));
}
if (src.equals(this.but_selectGerichte)) {
String query = "SELECT * FROM Lieferant";
ResultSet rst = this.stmtExecuter.getResultDBData(query);
// this.tableViewer.createTable(fillHeader(rst), fillData(rst));
}
}
private String[] fillHeader(ResultSet rst) {
try {
ResultSetMetaData rstMetaData = rst.getMetaData();
String[] header = new String[rstMetaData.getColumnCount()];
ArrayList<String> headerDetails = new ArrayList<>();
for (int i = 1; i <= rstMetaData.getColumnCount(); i++) {
headerDetails.add(rstMetaData.getColumnName(i));
}
int j = 0;
for(String head : headerDetails){
header[j] = head;
j++;
}
return header;
} catch (SQLException se) {
se.printStackTrace();
}
return null;
}
private Object[][] fillData(ResultSet rst) {
try {
ResultSetMetaData rstMetaData = rst.getMetaData();
int rowCount = 0;
rst.last();
rowCount = rst.getRow();
System.out.println(rowCount + " Rows");
rst.beforeFirst();
Object[][] data = new Object[rowCount][rstMetaData.getColumnCount()];
int row = 0;
while (rst.next()) {
for (int i = 0; i < rstMetaData.getColumnCount(); i++) {
data[row][i] = rst.getObject(i + 1);
}
row++;
}
return data;
} catch (SQLException se) {
System.out.println("Hier bei Fill");
}
return null;
}
}
I use remove, add revalidate and repaint on my jpanel.
void createTable(String[] header, Object[][] data) {
this.tableData = new JTable();
this.tableData.setModel(new MyTableModel(header, data));
this.tableData.setFillsViewportHeight(true);
this.tableData.addKeyListener(this);
this.scrollPaneTable = new JScrollPane(tableData);
this.scrollPaneTable.setSize(500, 500);
this.remove(this.scrollPaneTable);
this.add(this.scrollPaneTable);
this.revalidate();
this.repaint();
}
You don't need to reinitialize the table, table model.
Put some global variables on the top
private MyTableModel tableModel; //Your own table model
private JTable table;
Initialize them on init
public PanelWest() {
layoutGroup = createLayout();
this.setLayout(layoutGroup);
createButtons();
tableModel = new MyTableModel(header, data); //Your own tablemodel
table = new JTable(tableModel); //Hook the model to your table
this.add(table)
//...Do other things else to your table
}
Once you want to update the table, simply clear the rows from the table model and fill with new rows.
And ask JTable to update its data by calling
void createTable(String[] header, Object[][] data){
int cols = header.length;
int rows = data.length;
//Remove all rows from model
tableModel.setRowCount(0); //(As said by HovercraftFullOfEels)
Object[] row = new Object[cols];
for (int j = 0; j < data.length; j++){
for (int i = 0; i < cols; i++){
row[i] = data[j][i];
}
tableModel.addRow(row);
}
tableModel.fireTableDataChanged();
}
Hope it will help.
Thanks for your help.
I add a small test to my createTable method. I create a new window to show the new table datas and it works. i think my jpanel doesn't repaint correctly cause my grouplayout.
this.tableData = new JTable();
this.tableData.setModel(new MyTableModel(header, data));
this.tableData.setFillsViewportHeight(true);
this.tableData.addKeyListener(this);
this.scrollPaneTable = new JScrollPane(tableData);
this.scrollPaneTable.setSize(500, 500);
this.layoutGroup.setVerticalGroup(layoutGroup.createSequentialGroup().addComponent(this.scrollPaneTable, 400, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(this.scrollPaneChanges).addComponent(this.but_user).addComponent(this.but_dataChange));
// JFrame fr = new JFrame("Hello");
// fr.setLayout(null);
// fr.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// fr.setVisible(true);
// fr.add(this.scrollPaneTable);
I'm currently working on a Java application that uses JTabbedPane.
I would like to refresh a tab in JTabbedPane, but when I click on the "tab" item the tab does not refresh.
What could be the problem?
public class MainClass
extends JFrame
{
private JTabbedPane tabbedPane;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
public JPanel panel4;
private JPanel panel5;
public MainClass()
{
setTitle( "Demandes d'autorisation d'absence" );
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize( 800 ,400 );
setBackground( Color.gray );
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
// Create the tab pages
createPage1();
createPage2();
createPage3();
createPage4();
createPage5();
// Create a tabbed pane
tabbedPane = new JTabbedPane();
tabbedPane.addTab( "Mise à jour", panel1 );
tabbedPane.addTab( "Demandes en cours", panel2 );
tabbedPane.addTab( "Demandes autorisées", panel3 );
tabbedPane.addTab( "Demandes autorisées mise à jour", panel4 );
tabbedPane.addTab( "A propos", panel5 );
topPanel.add( tabbedPane, BorderLayout.CENTER );
}
public void createPage1()
{
panel1 = new JPanel();
panel1.setLayout( null );
JLabel label1 = new JLabel( "Mise à jour des autorisations :" );
label1.setBounds( 10, 15, 300, 20 );
panel1.add( label1 );
JButton b = new JButton("Actualiser");
b.setBounds( 10, 55, 150, 20 );
b.addActionListener(new miseajour());
panel1.add( b );
}
public void createPage2()
{
panel2 = new JPanel();
panel2.setLayout( null );
ArrayList columnNames = new ArrayList();
ArrayList data = new ArrayList();
// Connect to an MySQL Database, run query, get result set
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/Autorisations";
String user = "root";
String password = "root";
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM Autorisations where etat='en cours'");
{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.add( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
ArrayList row = new ArrayList(columns);
for (int i = 1; i <= columns; i++)
{
row.add( rs.getObject(i) );
}
data.add( row );
}
}}
catch (SQLException e)
{
System.out.println( e.getMessage() );
}
// Create Vectors and copy over elements from ArrayLists to them
// Vector is deprecated but I am using them in this example to keep
// things simple - the best practice would be to create a custom defined
// class which inherits from the AbstractTableModel class
Vector columnNamesVector = new Vector();
Vector dataVector = new Vector();
for (int i = 0; i < data.size(); i++)
{
ArrayList subArray = (ArrayList)data.get(i);
Vector 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));
// Create table with database data
JTable table = new JTable(dataVector, columnNamesVector)
{
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;
}
};
JScrollPane sp = new JScrollPane( table );
sp.setBounds(10,25, 800, 1000);
panel2.add(sp);
}
public void createPage3()
{
....
}
public void createPage4()
{
....
}
public void createPage5()
{
...
}
// Main method to get things started
public static void main( String args[] )
{
// Create an instance of the test application
MainClass mainFrame = new MainClass();
mainFrame.setVisible( true );
}
If you want to know when a tab has been selected then you can use a ChangeListener.
tabbedPane.addChangeListener(...);
Then when the event fires you can get the selected index of the tabbed pane and do your processing.
I am working on adapter classes.
I made JTable in an adapter class TabCl and called that JTable class TabCl in my parent class method guiInt() and adding it to container con.add() and its not letting it to do.
I am new to Java and don't have sound knowledge in Java. Please check the following code and give some help or something that can make it work.
My java version is 1.6.
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
public class PersonProject {
JFrame myFrame;
Container cont;
BorderLayout bl;
GroupLayout gl;
FlowLayout fl;
JTable tl;
JScrollPane jsp;
JPanel flPanel, glPanel, jTPane;
JLabel lId;
JTextField tId;
// Db variable Declaration
Connection dbCon;
String url;
String con;
String sql;
ResultSet rs;
ResultSetMetaData rsmd;
PreparedStatement pstmt;
Vector columnName, data, row;
int columnCount;
public PersonProject() {
guiInt();
}
public void guiInt() {
myFrame = new JFrame();
glPanel = new JPanel();
cont = new Container();
bl = new BorderLayout();
fl = new FlowLayout();
flPanel = new JPanel();
flPanel.setLayout(fl);
cont = myFrame.getContentPane();
cont.setLayout(bl);
gl = new GroupLayout(glPanel);
glPanel.setLayout(gl);
gl.setAutoCreateGaps(true);
gl.setAutoCreateContainerGaps(true);
lId = new JLabel("Id");
tId = new JTextField();
// /////////
GroupLayout.SequentialGroup hGroup = gl.createSequentialGroup();
hGroup.addGroup(gl.createParallelGroup().addComponent(lId));
hGroup.addGroup(gl.createParallelGroup().addComponent(tId));
gl.setHorizontalGroup(hGroup);
GroupLayout.SequentialGroup vGroup = gl.createSequentialGroup();
vGroup.addGroup(gl.createParallelGroup(Alignment.BASELINE)
.addComponent(lId).addComponent(tId));
gl.setVerticalGroup(vGroup);
// ///////
TabCl tlb = new TabCl();// / class for making jatable
cont.add(flPanel, bl.NORTH);
cont.add(glPanel, bl.CENTER);
cont.add(tlb, bl.SOUTH);//// error at this point
myFrame.pack();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
myFrame.setSize(600, 300);
}// end of method guiinit
private class TabCl {// start of adapter class for making jtable
public TabCl() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
url = "jdbc:odbc:personDSN";
dbCon = DriverManager.getConnection(url);
sql = "select * from emp";
pstmt = dbCon.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = pstmt.executeQuery();
rsmd = rs.getMetaData();
columnCount = rsmd.getColumnCount();
columnName = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
columnName.add(rsmd.getColumnName(i));
}// end of for loop
System.out.println(columnName.get(1));
data = new Vector();
row = new Vector();
while (rs.next()) {
row = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
row.add(rs.getString(i));
}
data.add(row);
}// end of while loop
dbCon.close();
} catch (Exception ex) {
System.out.println(ex + ":Sql Exception at table level");
}
tl = new JTable(data, columnName);
jsp = new JScrollPane(tl);
jTPane = new JPanel();
tl.setPreferredScrollableViewportSize(new Dimension(500, 90));
tl.setVisible(true);
tl.setFillsViewportHeight(true);
jTPane.add(jsp);
}// end of method tabmethod
}// end of class TabCl
public static void main(String[] args) {
// TODO Auto-generated method stub
PersonProject perProj = new PersonProject();
}
}
TabCl implicitly extends Object, while add() expects a Component. Instead of this:
private class TabCl {…}
create a factory method that returns a JPanel like this:
private JPanel createTablePanel() {
…
jTPane.add(jsp);
return jTPane;
}// end of method createTablePanel
and use it like this:
JPanel tlb = createTablePanel();
cont.add(flPanel, bl.NORTH);
cont.add(glPanel, bl.CENTER);
cont.add(tlb, bl.SOUTH);//// error at this point
See also JDBCAdapter, cited here.
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.