i’m still noob at java, only know the basics, and i’m with a little problem that i wish you could help me.
I this next piece of code that i use like 5 times in the project i’m making, and to keep the code simple i want to make it a method.
the only thing that i need to change in this piece of code is the Query, it is the only variable.
Thanks in advance. (sorry for my bad english).
Vector columnNames = new Vector();
Vector data = new Vector();
JPanel panel = new JPanel(); //
try {
Conectar();
String query = "Select * from Dados";
stm = (Statement) con.createStatement();
rs = stm.executeQuery(query);
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metaData.getColumnName(i));
}
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(rs.getObject(i));
}
data.addElement(row);
}
rs.close();
stm.close();
} catch (Exception e) {
System.out.println(e);
}
JTable table = new JTable(data, columnNames);
TableColumn column;
for (int i = 0; i < table.getColumnCount(); i++) {
column = table.getColumnModel().getColumn(i);
column.setMaxWidth(250);
}
table.setPreferredScrollableViewportSize(new Dimension(600, 400));
table.setEnabled(false);
JScrollPane scrollPane = new JScrollPane(table); panel.add(scrollPane);
JFrame frame = new JFrame();
frame.add(panel); //adiciona o panel à frame
frame.setResizable(false);
frame.setSize(640, 480); //define o tamanho da frame
frame.setLocationRelativeTo(null);
frame.setVisible(true); //torna a frame visivel
}
just surround your code with
and remove the line
from your code. Then you just call it like this: