Im trying to filter my Jtabke using my Jcomboox but i cant do it and in the :
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting
it only says how to filter using search txt field or sort using headers but not how to use a JComboBox change event to filter a JTable is there a simple code to do this??
EDITED
GOT iT WORKING
This is my Code:
public class Sql extends JFrame{
JTable table = new JTable();
DefaultTableModel model = new DefaultTableModel(new Object[][]{},new String[]{"fecha","clave_pdv","pdv","turno","clave_platillo","platillo","precio","total sin iva"});
public TableRowSorter<DefaultTableModel> sorter;
Connection conn = null;
Connection conn1 = null;
Statement st = null;
Statement st1 = null;
ResultSet rs = null;
ResultSet rs1 = null;
//Create list of values
private final JComboBox comboBox = new JComboBox();
private final JComboBox comboBox_1 = new JComboBox();
private JTextField textField;
public Sql(){
table.setAutoCreateRowSorter(true);
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://ARTURO-LAPTOP;user=sa;password=sacompusis;database=PDV");
st = conn.createStatement();
rs= st.executeQuery("SELECT DISTINCT Nombre_Pdv FROM VENTA_PLATILLOS");
while(rs.next()){
comboBox.addItem(rs.getString(1));
}
}
catch(Exception e){
e.printStackTrace();
}
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn1 = DriverManager.getConnection("jdbc:sqlserver://ARTURO-LAPTOP;user=sa;password=sacompusis;database=PDV");
st1 = conn.createStatement();
rs1 = st1.executeQuery("SELECT DISTINCT Nombre_Turno FROM VENTA_PLATILLOS");
while(rs1.next()){
comboBox_1.addItem(rs1.getString(1));
}
}
catch(Exception e){
e.printStackTrace();
}
getContentPane().setLayout(null);
table.setModel(model);
table.setBounds(50, 50, 50, 50);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(139, 88, 535, 227);
getContentPane().add(scrollPane);
comboBox.setBounds(404, 11, 130, 31);
getContentPane().add(comboBox);
comboBox_1.setBounds(544, 11, 130, 31);
getContentPane().add(comboBox_1);
textField = new JTextField();
textField.setBounds(24, 16, 86, 20);
getContentPane().add(textField);
textField.setColumns(10);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
RowFilter<DefaultTableModel, Object> rf = RowFilter.regexFilter(comboBox.getSelectedItem().toString(), 2);
sorter.setRowFilter(rf);
}
});
comboBox_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
RowFilter<DefaultTableModel, Object> rf = RowFilter.regexFilter(comboBox_1.getSelectedItem().toString(), 3);
sorter.setRowFilter(rf);
}
});
sorter = new TableRowSorter<DefaultTableModel>(model);
table.setRowSorter(sorter);
//Populate table
sqlConection bd = new sqlConection();
List<Value> values = bd.selectAll();
for(Value v : values){
model.addRow(new Object[]{v.fecha,v.clave_pdv,v.pdv,v.turno,v.clave_platillo,v.platillo,v.precio,v.total});
}
}
Try this, using a TableRowSorter, fill the table with some numbers and filter it ...
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
public class TableFilter extends JFrame {
private JTable table;
private DefaultTableModel model;
private TableRowSorter<DefaultTableModel> sorter;
public TableFilter() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
pack();
setVisible(true);
}
public static void main(String args[]) {
new TableFilter();
}
private void initComponents() {
JPanel panel = new JPanel();
final JComboBox<String> comboBox = new JComboBox<>(new String[]{"","1","2","3"});
JButton button = new JButton("filter");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
RowFilter<DefaultTableModel, Object> rf = RowFilter.regexFilter(comboBox.getSelectedItem().toString(), 0);
sorter.setRowFilter(rf);
}
});
panel.add(comboBox);
panel.add(button);
table = new JTable(model = new DefaultTableModel(3,3));
sorter = new TableRowSorter<DefaultTableModel>(model);
table.setRowSorter(sorter);
add(panel,BorderLayout.SOUTH);
add(new JScrollPane(table));
}
}
Fill the table with some numbers
filter it
Related
I'm trying to open this gui from an action listener in another class but for whatever reason it's not doing it, any and all help appreciated.
package gui;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.table.DefaultTableModel;
import database.DBConnection;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JTextArea;
import javax.swing.JTable;
public class OrderExample {
static JFrame frame;
public static void main(String[] args){
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
JFrame frame = new JFrame();
JTable table= new JTable();
table.setBounds(428, 445, 396, -328);
Object[] columns = {"Product Id", "Product Name", "Description", "Price"};
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columns);
table.setModel(model);
table.setBackground(Color.white);
table.setForeground(Color.black);
Font font = new Font("", 1, 22);
table.setRowHeight(30);
JTextField prodId = new JTextField();
JTextField prodName = new JTextField();
JTextField prodPrice = new JTextField();
JButton btnAdd = new JButton("Add");
JButton btnDelete = new JButton("Delete");
JButton btnExit = new JButton("Exit");
prodId.setBounds(20, 56, 230, 38);
prodName.setBounds(20, 129, 230, 38);
prodPrice.setBounds(21, 201, 229, 39);
btnAdd.setBounds(20, 451, 100, 38);
btnDelete.setBounds(150, 451, 100, 38);
btnExit.setBounds(20, 511, 100, 39);
JScrollPane pane = new JScrollPane(table);
pane.setBounds(281, 32, 440, 518);
frame.getContentPane().setLayout(null);
frame.getContentPane().add(pane);
frame.getContentPane().add(prodId);
frame.getContentPane().add(prodName);
frame.getContentPane().add(prodPrice);
frame.getContentPane().add(btnAdd);
frame.getContentPane().add(btnDelete);
frame.getContentPane().add(btnExit);
JLabel lblAddId = new JLabel("Product ID");
lblAddId.setBounds(20, 32, 79, 14);
frame.getContentPane().add(lblAddId);
JLabel lblProduct = new JLabel("Product Name");
lblProduct.setBounds(20, 105, 100, 14);
frame.getContentPane().add(lblProduct);
JLabel lblProductPrice = new JLabel("Product Price");
lblProductPrice.setBounds(20, 178, 90, 14);
frame.getContentPane().add(lblProductPrice);
JButton btnListProducts = new JButton("List Products");
btnListProducts.setBounds(150, 511, 100, 39);
frame.getContentPane().add(btnListProducts);
JTextArea description = new JTextArea();
description.setBounds(20, 276, 230, 164);
frame.getContentPane().add(description);
JLabel lblDescription = new JLabel("Description");
lblDescription.setBounds(20, 251, 116, 14);
frame.getContentPane().add(lblDescription);
Object[] row = new Object[4];
btnAdd.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
row[0] = prodId.getText();
row[1] = prodName.getText();
row[2] = description.getText();
row[3] = prodPrice.getText();
model.addRow(row);
try{
Connection connection = DBConnection.getConnection();
PreparedStatement ps = connection.prepareStatement("insert into stock(sname, description, quantity , price) values(?,?,20,?);");
ps.setString(1, prodName.getText());
ps.setString(2, description.getText());
ps.setDouble(3, Double.parseDouble( prodPrice.getText()));
ps.executeUpdate();
}
catch(SQLException sqle){
sqle.printStackTrace();
}
}
});
btnDelete.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
int i = table.getSelectedRow();
if(i >= 0){
model.removeRow(i);
}
else{
System.out.print("Delete ");
}
}
});
table.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e) {
int i = table.getSelectedRow();
prodId.setText(model.getValueAt(i, 0). toString());
prodName.setText(model.getValueAt(i, 1).toString());
prodPrice.setText(model.getValueAt(i, 3).toString());
description.setText(model.getValueAt(i, 2).toString());
}
});
btnListProducts.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
int i = table.getSelectedRow();
try{
Connection connection = DBConnection.getConnection();
Statement statement = connection.createStatement();
ResultSet rs;
if(prodId.getText().equalsIgnoreCase(""))
rs = statement.executeQuery("select * from stock;");
else
rs = statement.executeQuery("select * from stock where stockID = " + prodId.getText() + ";");
while(rs.next()){
row[0] = rs.getInt("stockID");
row[1] = rs.getString("sname");
row[2] = rs.getString("description");
row[3] = rs.getDouble("price");
model.addRow(row);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
btnExit.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
frame.dispose();
}
});
frame.setSize(771, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
This is the actionlistener code
btnStock.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
OrderExample window = new OrderExample();
}
});
I've tried to set window to visible but it just gives me an error.
The class OrderExamplehas all of its functionality in its (static) main method which is never been called by your Actionlistener implementation.
You could simply add the call to OrderExample.main to your Actionlistener implementation, but you should better first move the content of main to a non static method (e.g.: init) and call that.
Evening all,
So I've been working on creating a local database using SQLite. (As a plugin that is part of Firefox). It uses three classes:
databaseConnection
Login
Display
and two tables (which come under the database MyFilms) called:
Users
MyFilms
databaseConnection is used to simply just connect to my SQLite database MyFilms, which it does fine.
The second class, Login, access my Users table from my database so it can access the logins and proceed to my GUI called Display.
Display will load the following GUI, which consists of a button, which when clicked is supposed to load the data from my database table MyFilms into a JTable:
However, when I click the button, nothing loads... it even looks like the JTable is not there, but when I check my code it defiantly is!
The code where I think the problem might lie is:
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query ="Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception anException){
anException.printStackTrace();
}
}
});
Any idea why the database is not showing here? Please find the code to each class below:
databaseConnection:
import java.sql.*;
import javax.swing.*;
public class databaseConnection {
Connection conn = null;
public static Connection dbConnector(){
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Joe\\workspace\\MyFilms.sqlite");
JOptionPane.showMessageDialog(null, "Connection Successful!");
return conn;
}
catch(Exception anException)
{
JOptionPane.showMessageDialog(null, anException);
return null;
}
}
}
Login:
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.sql.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login {
private JFrame frmTest;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.frmTest.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
private JTextField textFieldUN;
private JPasswordField passwordField;
/**
* Create the application.
*/
public Login() {
initialize();
connection = databaseConnection.dbConnector();
}
/**
* Initialise the contents of the frame.
*/
private void initialize() {
frmTest = new JFrame();
frmTest.setTitle("Database Login");
frmTest.setBounds(100, 100, 345, 184);
frmTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTest.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("Username:");
lblNewLabel.setBounds(34, 37, 64, 14);
frmTest.getContentPane().add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Password:");
lblNewLabel_1.setBounds(34, 66, 64, 14);
frmTest.getContentPane().add(lblNewLabel_1);
textFieldUN = new JTextField();
textFieldUN.setBounds(126, 34, 151, 20);
frmTest.getContentPane().add(textFieldUN);
textFieldUN.setColumns(10);
JButton btnLogin = new JButton("Login");
frmTest.getRootPane().setDefaultButton(btnLogin);
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query = "Select * from Users where username=? and password=?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, textFieldUN.getText());
pst.setString(2, passwordField.getText());
ResultSet rs = pst.executeQuery();
int count = 0;
while(rs.next()){
count = count +1;
}
if (count == 1){
frmTest.dispose();
Display GUI = new Display();
GUI.setVisible(true);
}
else if (count > 1){
JOptionPane.showMessageDialog(null, "Duplicate Username and Password");
}
else{
JOptionPane.showMessageDialog(null, "Username or Password is not correct - Please try again..");
}
rs.close();
pst.close();
}
catch (Exception anException){
JOptionPane.showMessageDialog(null, anException);
}
}
});
btnLogin.setBounds(126, 111, 89, 23);
frmTest.getContentPane().add(btnLogin);
passwordField = new JPasswordField();
passwordField.setBounds(126, 64, 151, 17);
frmTest.getContentPane().add(passwordField);
}
}
Display:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
public class Display extends JFrame {
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Display frame = new Display();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
/**
* Create the frame.
*/
public Display() {
connection = databaseConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 711, 443);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query ="Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception anException){
anException.printStackTrace();
}
}
});
btnLoadData.setBounds(596, 11, 89, 23);
contentPane.add(btnLoadData);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(684, 45, -675, 349);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
}
}
Any help would be greatly appreciated! Cheers..
However, when I run it in Eclipse I receive no errors at all. It runs fine, just does not display the database in the JTable.
Could you please replace your Display.java with the following:
Display.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
public class Display extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Display frame = new Display();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
/**
* Create the frame.
*/
public Display() {
connection = databaseConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 711, 443);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout());
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception anException) {
anException.printStackTrace();
}
}
});
// btnLoadData.setBounds(596, 11, 89, 23);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BorderLayout());
buttonPanel.add(btnLoadData, BorderLayout.EAST);
contentPane.add(buttonPanel, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane();
// scrollPane.setBounds(684, 45, -675, 349);
table = new JTable();
scrollPane.setViewportView(table);
contentPane.add(scrollPane, BorderLayout.CENTER);
}
}
and see the results?
Few changes have been made to your code. They are:
1) You first added scrollPane to the contentPane then you added table to scrollPane. I changed the order.
2) You used absolute layout. I changed that with BorderLayout.
The result displayed on my system is:
Hope this helps!
I have a JTable displaying the content of a table in MYSQL database. I am able also to add a record in my JTable and my database.. The edit and delete operations are only possible in my JTable (the changes are not diplayed to my database). I want to add hibernate code in my buttons events so the changes can be displayed to MySQL database.
Any help will be appreciated.
Here's the class concerned:
package com.hibernate.stock;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTable;
import javax.swing.JButton;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Gestion extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTable table;
List biens;
int i;
PersistantBien bien = new PersistantBien();
final String columnNames[] = {"ID", "Nom", "Catégorie", "Quantité"};
final DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Gestion frame = new Gestion();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Gestion() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblId = new JLabel("ID:");
lblId.setBounds(12, 12, 70, 15);
contentPane.add(lblId);
JLabel lblNom = new JLabel("nom:");
lblNom.setBounds(12, 39, 70, 15);
contentPane.add(lblNom);
JLabel lblCatgorie = new JLabel("catégorie:");
lblCatgorie.setBounds(12, 69, 70, 15);
contentPane.add(lblCatgorie);
JLabel lblQuantit = new JLabel("quantité:");
lblQuantit.setBounds(12, 108, 70, 15);
contentPane.add(lblQuantit);
textField = new JTextField();
textField.setBounds(106, 10, 114, 19);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(106, 37, 114, 19);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(106, 67, 114, 19);
contentPane.add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(106, 106, 114, 19);
contentPane.add(textField_3);
textField_3.setColumns(10);
table = new JTable();
table.setBounds(361, 50, 1, 1);
contentPane.add(table);
final JScrollPane tableScrollPane = new JScrollPane(table);
tableScrollPane.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
tableModel = (DefaultTableModel) table.getModel();
textField.setText(tableModel.getValueAt(table.getSelectedRow(), 0).toString());
textField_1.setText(tableModel.getValueAt(table.getSelectedRow(), 1).toString());
textField_2.setText(tableModel.getValueAt(table.getSelectedRow(), 2).toString());
textField_3.setText(tableModel.getValueAt(table.getSelectedRow(), 3).toString());
}
});
tableScrollPane.setBounds(240, 11, 198, 135);
contentPane.add(tableScrollPane);
JButton btnAjouter = new JButton("Ajouter");
btnAjouter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
bien.setId_article(textField.getText());
bien.setNom_article(textField_1.getText());
bien.setCategorie(textField_2.getText());
bien.setQuantite(textField_3.getText());
s.save(bien);
s.flush();
tx.commit();
s.close();
}
});
btnAjouter.setBounds(12, 158, 117, 25);
contentPane.add(btnAjouter);
JButton btnEditer = new JButton("Editer");
btnEditer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
tableModel = (DefaultTableModel) table.getModel();
tableModel.setValueAt(textField.getText(), table.getSelectedRow(), 0);
tableModel.setValueAt(textField_1.getText(), table.getSelectedRow(), 1);
tableModel.setValueAt(textField_2.getText(), table.getSelectedRow(), 2);
tableModel.setValueAt(textField_3.getText(), table.getSelectedRow(), 3);
s.save(bien);
s.flush();
tx.commit();
s.close();
}
});
btnEditer.setBounds(150, 158, 117, 25);
contentPane.add(btnEditer);
JButton btnSupprimer = new JButton("supprimer");
btnSupprimer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
tableModel = (DefaultTableModel) table.getModel();
tableModel.removeRow(table.getSelectedRow());
SQLQuery query=s.createSQLQuery("DELETE * FROM TBiens WHERE id-article='"+textField.getText()+"'");
s.flush();
tx.commit();
s.close();
}
});
btnSupprimer.setBounds(303, 158, 117, 25);
contentPane.add(btnSupprimer);
JButton btnAfficher = new JButton("Afficher");
btnAfficher.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
SQLQuery query=s.createSQLQuery("select * from TBiens");
biens = query.list();
ArrayList<Object[]> res = new ArrayList<Object[]>(biens);
final DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
table.setModel(tableModel);
for (final Object[] bien : res) {
// Assuming each row in the biens list is a list of strings...
final Object[] row = bien;
tableModel.addRow(row);
}
biens.size();
System.out.print(i);
s.flush();
tx.commit();
s.close();
}
catch (ClassCastException e) {
e.printStackTrace();
}
}
});
btnAfficher.setBounds(166, 235, 117, 25);
contentPane.add(btnAfficher);
}
}
Output:
Editing
By default, DefaultTableModel will make all the cells editable, just double click the cell you want to change and it will enter "edit" model.
To save the values back to the database will depend on what approach you want to take, you could override the setValueAt of the TableModel method and push the changes when this method is called, personally, I'd add a Save button and push the changes as a batch
Deleting
This is a little more difficult. The problem is, once you remove one row, all the indices for all the other selected items will change...
A better solution would be devise a hibernate bean/data class and load this via Hibernate. You could then use a custom implementation of the TableModel, extending from something like AbstractTableModel, which would give you management control of the content.
You would then, get all the objects that are selected (this would be a method in your custom TableModel, something like getValueAt(int row) which returned the hibernate object at the specified row) and then pass this to some kind of delete method (ie removeValue(TBiens bean)), firing the appropriate event notifications...
I finally succeeded in deleting and editing rows from my JTable and database.
Here's the code :
package com.hibernate.stock;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTable;
import javax.swing.JButton;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Gestion extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTable table;
List biens;
int i;
PersistantBien bien = new PersistantBien();
final String columnNames[] = {"ID", "Nom", "Catégorie", "Quantité"};
final DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Gestion frame = new Gestion();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Gestion() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblId = new JLabel("ID:");
lblId.setBounds(12, 12, 70, 15);
contentPane.add(lblId);
JLabel lblNom = new JLabel("nom:");
lblNom.setBounds(12, 39, 70, 15);
contentPane.add(lblNom);
JLabel lblCatgorie = new JLabel("catégorie:");
lblCatgorie.setBounds(12, 69, 70, 15);
contentPane.add(lblCatgorie);
JLabel lblQuantit = new JLabel("quantité:");
lblQuantit.setBounds(12, 108, 70, 15);
contentPane.add(lblQuantit);
textField = new JTextField();
textField.setBounds(106, 10, 114, 19);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(106, 37, 114, 19);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(106, 67, 114, 19);
contentPane.add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(106, 106, 114, 19);
contentPane.add(textField_3);
textField_3.setColumns(10);
table = new JTable();
table.setBounds(361, 50, 1, 1);
contentPane.add(table);
final JScrollPane tableScrollPane = new JScrollPane(table);
tableScrollPane.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
tableModel = (DefaultTableModel) table.getModel();
textField.setText(tableModel.getValueAt(table.getSelectedRow(), 0).toString());
textField_1.setText(tableModel.getValueAt(table.getSelectedRow(), 1).toString());
textField_2.setText(tableModel.getValueAt(table.getSelectedRow(), 2).toString());
textField_3.setText(tableModel.getValueAt(table.getSelectedRow(), 3).toString());
}
});
tableScrollPane.setBounds(240, 11, 198, 135);
contentPane.add(tableScrollPane);
JButton btnAjouter = new JButton("Ajouter");
btnAjouter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
bien.setId_article(textField.getText());
bien.setNom_article(textField_1.getText());
bien.setCategorie(textField_2.getText());
bien.setQuantite(textField_3.getText());
s.save(bien);
s.flush();
tx.commit();
s.close();
}
});
btnAjouter.setBounds(12, 158, 117, 25);
contentPane.add(btnAjouter);
JButton btnEditer = new JButton("Editer");
btnEditer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
tableModel = (DefaultTableModel) table.getModel();
tableModel.setValueAt(textField.getText(), table.getSelectedRow(), 0);
tableModel.setValueAt(textField_1.getText(), table.getSelectedRow(), 1);
tableModel.setValueAt(textField_2.getText(), table.getSelectedRow(), 2);
tableModel.setValueAt(textField_3.getText(), table.getSelectedRow(), 3);
SQLQuery query=s.createSQLQuery("update TBiens "
+ "set id_article='"+ table.getValueAt(table.getSelectedRow(),0) +"', "
+ "nom_article= '"+ table.getValueAt(table.getSelectedRow(),1) +"', "
+ "categorie= '"+ table.getValueAt(table.getSelectedRow(),2) +"' , "
+ "quantite= '"+ table.getValueAt(table.getSelectedRow(),0) +"' "
+ "where id_article = '"+ table.getValueAt(table.getSelectedRow(),0) +"'");
query.executeUpdate();
s.flush();
tx.commit();
s.close();
}
});
btnEditer.setBounds(150, 158, 117, 25);
contentPane.add(btnEditer);
JButton btnSupprimer = new JButton("supprimer");
btnSupprimer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
tableModel = (DefaultTableModel) table.getModel();
SQLQuery query=s.createSQLQuery("delete from TBiens where id_article = '"+ table.getValueAt(table.getSelectedRow(),0) +"'");
query.executeUpdate();
tableModel.removeRow(table.getSelectedRow());
s.flush();
tx.commit();
s.close();
}
});
btnSupprimer.setBounds(303, 158, 117, 25);
contentPane.add(btnSupprimer);
JButton btnAfficher = new JButton("Afficher");
btnAfficher.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
SQLQuery query=s.createSQLQuery("select * from TBiens");
biens = query.list();
ArrayList<Object[]> res = new ArrayList<Object[]>(biens);
final DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
table.setModel(tableModel);
for (final Object[] bien : res) {
// Assuming each row in the biens list is a list of strings...
final Object[] row = bien;
tableModel.addRow(row);
}
biens.size();
System.out.print(i);
s.flush();
tx.commit();
s.close();
}
catch (ClassCastException e) {
e.printStackTrace();
}
}
});
btnAfficher.setBounds(166, 235, 117, 25);
contentPane.add(btnAfficher);
}
}
Im made a program that takes strings from the whole jtable and populates my database in ms access. But whenever i run it my database has [] instead of the actual information. How do i take the information in my jtable and use that to populate my database?
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class apples extends JPanel {
static JTable table;
static JFrame frame;
static apples a;
static ActionListener actionListener;
static ActionListener actionListenerImport;
static ActionListener actionListenerAddrow;
static String[] columns = {"Fname","Lname"};
static String[][] data;
static DefaultTableModel model = new DefaultTableModel(data, columns);
public static void main(String[] args) {
table = new JTable(model);
frame = new JFrame();
table.setPreferredScrollableViewportSize(new Dimension(450, 200));
table.setFillsViewportHeight(true);
JScrollPane jps = new JScrollPane(table);
JPanel panel = new JPanel(new GridBagLayout());
panel.add(jps);
GridBagConstraints c = new GridBagConstraints();
JButton b1 = new JButton("Start");
c.gridx = 1;
c.gridy = 0;
c.insets = new Insets(10, 10, 10, 10);
panel.add(b1, c);
JButton b2 = new JButton("Import");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10, 10, 10, 10);
panel.add(b2, c);
JButton b3 = new JButton("Add Row");
c.gridx = 3;
c.gridy = 0;
c.insets = new Insets(10,10,10,10);
panel.add(b3, c);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel, BorderLayout.NORTH);
frame.getContentPane().add(jps, BorderLayout.CENTER);
frame.setVisible(true);
frame.pack();
actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:TestDatabase");
Statement s = con.createStatement();
String deleteRows = "DELETE FROM Table1";
s.execute(deleteRows);
ArrayList<String> numdata = new ArrayList<String>();
ArrayList<String> numdata2 = new ArrayList<String>();
String insertTable = ("INSERT INTO Table1(Fname,Lname) VALUES('"+numdata+"','"+numdata2+"');");//get data from table and put in here
for (int count = 0; count < model.getRowCount(); count++){
numdata.add(model.getValueAt(count, 0).toString());
for (int count1 = 0; count1 < model.getRowCount(); count1++){
numdata2.add(model.getValueAt(count, 1).toString());
s.executeUpdate(insertTable);
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
e.getMessage();
} catch (SQLException e) {
e.printStackTrace();
e.getMessage();
}
}
};
actionListenerImport = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:TestDatabase");
Statement s = con.createStatement();
String selTable = "SELECT * FROM Table1";
s.execute(selTable);
ResultSet rs = s.getResultSet();
while((rs!= null) && (rs.next())) {
model.addRow(new String[]{rs.getString(1),rs.getString(2)});
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
e.getMessage();
} catch (SQLException e) {
e.printStackTrace();
e.getMessage();
}
}
};
actionListenerAddrow = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
model.addRow(new String[]{"",""});
}
};
b1.addActionListener(actionListener);
b2.addActionListener(actionListenerImport);
b3.addActionListener(actionListenerAddrow);
}
}
ArrayList<String> numdata = new ArrayList<String>();
ArrayList<String> numdata2 = new ArrayList<String>();
String insertTable = ("INSERT INTO Table1(Fname,Lname) VALUES('"+numdata+"','"+numdata2+"');");
You are attempting to add an ArrayList into your database. You can't just change the values of numdata and numdata2 in your loop.
Instead you need to create a dynamic SQL statement. The easiest way to do this is to use a PreparedStatement, then you can dynamically change the parameters. The code would be something like:
String sql = "INSERT INTO Table1(Fname,Lname) VALUES(?,?)";
PreparedStatement stmt = connection.prepareStatement(sql);
for (int count = 0; count < model.getRowCount(); count++)
{
String numdata = model.getValueAt(count, 0).toString();
String numdata2 = model.getValueAt(count, 1).toString();
stmt.setString( 1, numdata );
stmt.setString( 2, numdata2 );
stmt.executeUpdate();
}
Guys I have a problem with my JTable, my JTable(tblLivro) which contents should be the result(ArrayList) of my query (working) , but when I try to put the rsult in my jtable it just doesn't work, it doesn't show any errors, yet not show it. Why?
Here is my code
package view;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import model.Livro;
import control.LivroControl;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
public class LivroView extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel lblIdLivro, lblLombada, lblTitulo, lblTituloInternacional, lblEdicao, lblEditora, lblAutor ;
private JTextField txtIdLivro, txtTombo, txtTitulo, txtTituloInternacional, txtEdicao, txtEditora, txtAutor;
private JButton btnAdicionar, btnPesquisar, btnExcluir;
private JPanel painelPrincipal, painelGeral, painelBotoes, painelJPanel;
private JTable tblLivros;
private List<Livro> encontrados;
DefaultTableModel modelo;
public LivroView() {
super("Manutenção de Livros");
encontrados = new ArrayList<Livro>();
lblIdLivro = new JLabel("Código do livro:");
lblLombada = new JLabel("Tombo:");
lblTitulo = new JLabel("Título:");
lblTituloInternacional = new JLabel("Título Internacional:");
lblEdicao = new JLabel("Edição:");
lblEditora = new JLabel("Editora:");
lblAutor = new JLabel("Autor:");
txtIdLivro = new JTextField(20);
txtTombo= new JTextField("Tombo");
txtTitulo = new JTextField(20);
txtTituloInternacional= new JTextField(20);
txtEdicao = new JTextField(20);
txtEditora= new JTextField(20);
txtAutor= new JTextField("Autor");
txtIdLivro.setText("");
txtTombo.setText("");
txtTitulo.setText("");
txtTituloInternacional.setText("");
txtEdicao.setText("");
txtEditora.setText("");
txtAutor.setText("");
btnAdicionar = new JButton("Adicionar");
btnExcluir = new JButton("Excluir");
btnPesquisar = new JButton("Pesquisar");
btnAdicionar.addActionListener(this);
btnPesquisar.addActionListener(this);
btnExcluir.addActionListener(this);
painelPrincipal = new JPanel();
painelGeral = new JPanel();
painelBotoes = new JPanel();
painelJPanel = new JPanel();
painelPrincipal.setLayout(new BorderLayout());
painelGeral.setLayout(new GridLayout(7,2));
painelBotoes.setLayout(new GridLayout(2,1));
painelGeral.add(lblIdLivro);
painelGeral.add(txtIdLivro);
painelGeral.add(lblLombada);
painelGeral.add(txtTombo);
painelGeral.add(lblTitulo);
painelGeral.add(txtTitulo);
painelGeral.add(lblTituloInternacional);
painelGeral.add(txtTituloInternacional);
painelGeral.add(lblEdicao);
painelGeral.add(txtEdicao);
painelGeral.add(lblEditora);
painelGeral.add(txtEditora);
painelGeral.add(lblAutor);
painelGeral.add(txtAutor);
painelBotoes.add(btnAdicionar);
painelBotoes.add(btnPesquisar);
painelBotoes.add(btnExcluir);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(55, 80, 359, 235);
painelJPanel.add(scrollPane);
tblLivros = new JTable();
tblLivros.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Tombo", "T\u00EDtulo", "T\u00EDtulo Internacional", "Edi\u00E7\u00E3o", "Autor", "Editora"
}
));
modelo = new DefaultTableModel();
tblLivros.getColumnModel().getColumn(0).setPreferredWidth(54);
tblLivros.getColumnModel().getColumn(1).setPreferredWidth(104);
tblLivros.getColumnModel().getColumn(2).setPreferredWidth(136);
tblLivros.getColumnModel().getColumn(4).setPreferredWidth(102);
// modelo = (DefaultTableModel) tblLivros.getModel();
scrollPane.setViewportView(tblLivros);
painelJPanel.setLayout(null);
painelPrincipal.add(painelGeral, BorderLayout.NORTH);
painelPrincipal.add(painelBotoes, BorderLayout.CENTER);
this.setSize(500,300);
this.setVisible(true);
this.setContentPane(painelPrincipal);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
LivroControl control = new LivroControl();
if ("Adicionar".equalsIgnoreCase(cmd)){
boolean adicionado = false;
adicionado = control.adicionarLivro(txtIdLivro.getText(), txtTitulo.getText(), txtTituloInternacional.getText(), txtTombo.getText(), txtAutor.getText(), txtEdicao.getText(), txtEditora.getText());
if (adicionado == true){
txtIdLivro.setText("");
txtTombo.setText("");
txtTitulo.setText("");
txtTituloInternacional.setText("");
txtEdicao.setText("");
txtEditora.setText("");
txtAutor.setText("");
txtIdLivro.requestFocus();
}
}
else if("Excluir".equalsIgnoreCase(cmd)){
control.excluirLivro(txtTombo.getText());
txtTombo.setText("");
}
else if("Pesquisar".equalsIgnoreCase(cmd)){
if (!txtTombo.getText().equals("")){
Livro l = control.pesquisarLivroPorTombo(txtTombo.getText());
if (l!=null){
txtIdLivro.setText(String.valueOf(l.getIdLivro()));
txtTombo.setText(l.getTombo());
txtTitulo.setText(l.getTitulo());
txtTituloInternacional.setText(l.getTituloInternacional());
txtEdicao.setText(l.getEdicao());
txtEditora.setText(l.getEditora());
txtAutor.setText(l.getAutor());
}
}
else if (!txtAutor.getText().equals("")){
encontrados = control.pesquisarLivroPorAutor(txtAutor.getText());
if (encontrados!= null){
for (Livro dados : encontrados){
Object[] objetoTombo = new Object[1];
Object[] objetoTitulo = new Object[2];
Object[] objetoTituloInternacional = new Object[3];
Object[] objetoEdicao = new Object[4];
Object[] objetoAutor = new Object[5];
Object[] objetoEditora = new Object[6];
objetoTombo[0] = dados.getTombo();
objetoTitulo[0] = dados.getTitulo();
objetoTituloInternacional[0] = dados.getTituloInternacional();
objetoEdicao[0] = dados.getEdicao();
objetoAutor[0]= dados.getAutor();
objetoEditora[0]= dados.getEditora();
//modelo.setNumRows(0);
modelo.addRow(objetoTombo);
modelo.addRow(objetoTitulo);
modelo.addRow(objetoTituloInternacional);
modelo.addRow(objetoEdicao);
modelo.addRow(objetoAutor);
modelo.addRow(objetoEditora);
}
this.setSize(700,500);
tblLivros.setModel(modelo);
painelJPanel.add(tblLivros);
painelJPanel.setVisible(true);
painelJPanel.repaint();
painelPrincipal.add(painelJPanel, BorderLayout.SOUTH);
painelPrincipal.repaint();
}
}
else {
encontrados = control.pesquisarLivroPorNome(txtTitulo.getText());
if (encontrados!= null){
}
}
}
}
public static void main(String[] args) {
new LivroView();
}
}
Thank you!
Because you didn't even added JScrollPane on your painelPrincipal. You can do it like this:
painelPrincipal.add(scrollPane, BorderLayout.SOUTH);
Also:
Do not call setVisible for JFrame before all components are added.
Call pack instead of setSize for JFrame
Avoid using null layout and absolute positioning.
Regards and good luck!
EDIT:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LivroView extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel lblIdLivro, lblLombada, lblTitulo, lblTituloInternacional, lblEdicao, lblEditora, lblAutor ;
private JTextField txtIdLivro, txtTombo, txtTitulo, txtTituloInternacional, txtEdicao, txtEditora, txtAutor;
private JButton btnAdicionar, btnPesquisar, btnExcluir;
private JPanel painelPrincipal, painelGeral, painelBotoes, painelJPanel;
private JTable tblLivros;
DefaultTableModel modelo;
public LivroView() {
super("Manutenção de Livros");
lblIdLivro = new JLabel("Código do livro:");
lblLombada = new JLabel("Tombo:");
lblTitulo = new JLabel("Título:");
lblTituloInternacional = new JLabel("Título Internacional:");
lblEdicao = new JLabel("Edição:");
lblEditora = new JLabel("Editora:");
lblAutor = new JLabel("Autor:");
txtIdLivro = new JTextField(20);
txtTombo= new JTextField("Tombo");
txtTitulo = new JTextField(20);
txtTituloInternacional= new JTextField(20);
txtEdicao = new JTextField(20);
txtEditora= new JTextField(20);
txtAutor= new JTextField("Autor");
txtIdLivro.setText("");
txtTombo.setText("");
txtTitulo.setText("");
txtTituloInternacional.setText("");
txtEdicao.setText("");
txtEditora.setText("");
txtAutor.setText("");
btnAdicionar = new JButton("Adicionar");
btnExcluir = new JButton("Excluir");
btnPesquisar = new JButton("Pesquisar");
btnAdicionar.addActionListener(this);
btnPesquisar.addActionListener(this);
btnExcluir.addActionListener(this);
painelPrincipal = new JPanel();
painelGeral = new JPanel();
painelBotoes = new JPanel();
painelJPanel = new JPanel();
painelPrincipal.setLayout(new BorderLayout());
painelGeral.setLayout(new GridLayout(7,2));
painelBotoes.setLayout(new GridLayout(2,1));
painelGeral.add(lblIdLivro);
painelGeral.add(txtIdLivro);
painelGeral.add(lblLombada);
painelGeral.add(txtTombo);
painelGeral.add(lblTitulo);
painelGeral.add(txtTitulo);
painelGeral.add(lblTituloInternacional);
painelGeral.add(txtTituloInternacional);
painelGeral.add(lblEdicao);
painelGeral.add(txtEdicao);
painelGeral.add(lblEditora);
painelGeral.add(txtEditora);
painelGeral.add(lblAutor);
painelGeral.add(txtAutor);
painelBotoes.add(btnAdicionar);
painelBotoes.add(btnPesquisar);
painelBotoes.add(btnExcluir);
tblLivros = new JTable();
tblLivros.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Tombo", "T\u00EDtulo", "T\u00EDtulo Internacional", "Edi\u00E7\u00E3o", "Autor", "Editora"
}
));
JScrollPane scrollPane = new JScrollPane(tblLivros);
painelPrincipal.add(painelGeral, BorderLayout.NORTH);
painelPrincipal.add(painelBotoes, BorderLayout.CENTER);
painelPrincipal.add(scrollPane, BorderLayout.SOUTH);
this.setContentPane(painelPrincipal);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if ("Adicionar".equalsIgnoreCase(cmd)){
boolean adicionado = false;
if (adicionado == true){
txtIdLivro.setText("");
txtTombo.setText("");
txtTitulo.setText("");
txtTituloInternacional.setText("");
txtEdicao.setText("");
txtEditora.setText("");
txtAutor.setText("");
txtIdLivro.requestFocus();
}
}
else if("Excluir".equalsIgnoreCase(cmd)){
txtTombo.setText("");
}
else if("Pesquisar".equalsIgnoreCase(cmd)){
if (!txtTombo.getText().equals("")){
}
else if (!txtAutor.getText().equals("")){
} }
}
public static void main(String[] args) {
new LivroView();
}
}
Ok, here is your code. Altough I had to remove some pieces of code to make it functional.
First of all, stop using null layouts. Swing was designed to be used with layout managers.
You add the table to the scroll pane which is a good thing.
scrollPane.setViewportView(tblLivros);
Later on it looks like you update the model (which is a good thing), but then you add the table to another panel (which is a bad thing). This removes the table from the scrollpane. The table will no longer have a header unless the table is displayed in a scrollpane. All you need to do is invoke the setModel() method and the table will automatically repaint itself.
tblLivros.setModel(modelo);
//painelJPanel.add(tblLivros);
//painelJPanel.setVisible(true);
//painelJPanel.repaint();
//painelPrincipal.add(painelJPanel, BorderLayout.SOUTH);
If you ever do need to add a component to a visible GUI then the code should be:
panel.add(..)
panel.revalidate();
panel.repaint();
just got help from a friend, here is the final code:
public class LivroView extends JFrame implements ActionListener {
private JTable tblLivros;
DefaultTableModel modeloTabela;
private List<Livro> encontrados;
public LivroView() {
super("Manutenção de Livros");
encontrados = new ArrayList<Livro>();
modeloTabela = new DefaultTableModel(
new String[] {
"Tombo", "Título", "Título Internacional", "Edição", "Autor", "Editora"
}, 0);
tblLivros = new JTable(modeloTabela);
tblLivros.getColumnModel().getColumn(0).setPreferredWidth(54);
tblLivros.getColumnModel().getColumn(1).setPreferredWidth(104);
tblLivros.getColumnModel().getColumn(2).setPreferredWidth(136);
tblLivros.getColumnModel().getColumn(4).setPreferredWidth(102);
painelTabela = new JScrollPane(tblLivros);
painelTabela.setVisible(false);
painelPrincipal.add(painelGeral, BorderLayout.NORTH);
painelPrincipal.add(painelBotoes, BorderLayout.CENTER);
painelPrincipal.add(painelTabela, BorderLayout.SOUTH);
//this.setSize(500,300);
this.setContentPane(painelPrincipal);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
LivroControl control = new LivroControl();
if ("Adicionar".equalsIgnoreCase(cmd)){
}
else if("Excluir".equalsIgnoreCase(cmd)){
}
else if("Pesquisar".equalsIgnoreCase(cmd)){
if (!txtTombo.getText().equals("")){
Livro l = control.pesquisarLivroPorTombo(txtTombo.getText());
if (l!=null){
txtIdLivro.setText(String.valueOf(l.getIdLivro()));
txtTombo.setText(l.getTombo());
txtTitulo.setText(l.getTitulo());
txtTituloInternacional.setText(l.getTituloInternacional());
txtEdicao.setText(l.getEdicao());
txtEditora.setText(l.getEditora());
txtAutor.setText(l.getAutor());
}
}
else if (!txtAutor.getText().equals("")){
encontrados = control.pesquisarLivroPorAutor(txtAutor.getText());
if (encontrados!= null){
for (Livro dados : encontrados){
Object[] row = new Object[6];
row[0] = dados.getTombo();
row[1] = dados.getTitulo();
row[2] = dados.getTituloInternacional();
row[3] = dados.getEdicao();
row[4]= dados.getAutor();
row[5]= dados.getEditora();
modeloTabela.addRow(row);
}
painelTabela.setVisible(true);
painelPrincipal.repaint();
this.pack();
}
}
else {
//the same
}
}
}
public static void main(String[] args) {
new LivroView();
}
}
Thank you so much for the help!