JTable not shown columns titles - java

I have a little problem in this code. I want to display a JTable with Column Headers but the problem is that the column's titles are not being displayed, as the Screenshot shows below:
private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DB_CONNECTION = "jdbc:oracle:thin:#localhost:1521:DB";
private static final String DB_USER = "*******";
private static final String DB_PASSWORD = "********";
Connection conn = null;
Statement stmt = null;
static Vector<Vector<String>> dataJ, dataC, data;
Vector<String> columnJ,
public void getCleubJoueurData() {
data = new Vector<Vector<String>>();
colum = new Vector<String>();
colum.add("nom");
colum.add("nom_cleub");
colum.add("numero_maillot");
colum.add("nationalite");
String query = "SELECT joueur.NOM,CLEUB.NOM_CLEUB," +
"JOUEUR_CLEUB.NUMERO_MAILLOT, joueur.NATIONALITE " +
"FROM joueur JOIN JOUEUR_CLEUB ON joueur.ID_J=" +
"JOUEUR_CLEUB.ID_J JOIN CLEUB ON JOUEUR_CLEUB.ID_C=CLEUB.ID_C";
try {
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Vector<String> vstring = new Vector<String>();
vstring.add(rs.getString("nom"));
vstring.add(rs.getString("nom_cleub"));
vstring.add(rs.getString("numero_maillot"));
vstring.add(rs.getString("nationalite"));
data.add(vstring);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
}
}
}
}
public App() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 882, 477);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBackground(Color.WHITE);
tabbedPane.setBounds(40, 43, 812, 390);
contentPane.add(tabbedPane);
JPanel panel = new JPanel();
tabbedPane.addTab("joueurs", null, panel, null);
panel.setLayout(null);
getJoueurData();
DefaultTableModel mode = new DefaultTableModel(data, column);
table = new JTable(model);
table.setToolTipText("");
table.setBounds(0, 94, 819, 269);
panel.add(table);
}

Don't use null layouts. (And don't set the bounds)
Wrap your table in a JScrollPane. The JScrollPane will show the headers. If you don't want to use a JScrollPane, then you can get the JTableHeader of the table and add it separately
Former: (with JScrollPane)
JPanel container = new JPanel(); // default FlowLayout
JScrollPane scrollPane = new JScrollPane(table);
//container.add(table); // don't add the table, just the JScrollPane
container.add(scrollPane);
Latter: (without JScrollPane)
JPanel container = new JPanel(new BorderLayout());
container.add(table, BorderLayout.CENTER);
container.add(table.getTableHeader(), BorderLayout.PAGE_START);

The JTable documentation states that you'd typically want to use JTable in conjunction with a JScrollPane. If not:
JTables are typically placed inside of a JScrollPane. [...] Note that if you wish to
use a JTable in a standalone view (outside of a JScrollPane) and want
the header displayed, you can get it using getTableHeader() and
display it separately.
I'd recommend wrapping in a JScrollPane myself:
...
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane);
...

Related

Can I add a Table inside of a JTabbedPane?

I'm very new at using JPanels/Tabs and so have run into a bunch of issues with my code.
I've created a table from SQL that I want to be able to be viewed inside of a tab.
So I have a class first of all that includes a login and then takes you to a window with three tabs:
public class UserInterface
{
UserInterface() {
JFrame frame = new JFrame(); //create a frame
frame.setTitle("Bet Worthiness"); //sets title of frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //system exit when user closes window
frame.setResizable(false); //prevents user from resizing frame
JTextField text = new JTextField(10); //creates a text box
frame.getContentPane().setBackground(new Color(255, 243, 181)); //background colour
//Create panels
JPanel accountTab = new JPanel();
JPanel bettingTab = new JPanel();
JPanel leaderboardTab = new JPanel();
JTabbedPane tabs = new JTabbedPane(); //Create the tab container
tabs.setBounds(40, 20, 1400, 700); //Set tab container position
//Account Details label
JLabel accountLabel = new JLabel();
accountLabel.setText("Account Details");
accountLabel.setFont(new Font("Helvetica", Font.BOLD, 20));
accountTab.add(accountLabel);
//Betting label
JLabel bettingLabel = new JLabel();
bettingLabel.setText("Place Bets");
bettingLabel.setFont(new Font("Helvetica", Font.BOLD, 20));
bettingTab.add(bettingLabel);
//Leaderboard label
JLabel leaderboardLabel = new JLabel();
leaderboardLabel.setText("Leaderboard");
leaderboardLabel.setFont(new Font("Helvetica", Font.BOLD, 20));
leaderboardTab.add(leaderboardLabel);
//Associate each panel with the corresponding tab
tabs.add("Account", accountTab);
tabs.add("Betting", bettingTab);
tabs.add("Leaderboard", leaderboardTab);
frame.add(tabs); //Add tabs to the frame
frame.setSize(1500, 800);
frame.setLayout(null);
frame.setVisible(true);
}
}
I have then created a table on SQL in a separate class that I want to be embedded in the 'leaderboard' tab:
public class Leaderboard extends JFrame {
public void displayLeaderboard() {
try
{
String url = "jdbc:mysql://localhost:3306/bettingappdb";
String user = "root";
String password = "lucyb";
Connection con = DriverManager.getConnection(url, user, password);
String query = "SELECT * FROM users";
Statement stm = con.createStatement();
ResultSet res = stm.executeQuery(query);
String columns[] = { "Username", "Success Rate" };
String data[][] = new String[20][3];
int i = 0;
while (res.next()) {
String nom = res.getString("Username");
int successRate = res.getInt("SuccessRate");
data[i][0] = nom;
data[i][1] = successRate + "";
i++;
}
DefaultTableModel model = new DefaultTableModel(data, columns);
JTable table = new JTable(model);
table.setShowGrid(true);
table.setShowVerticalLines(true);
JScrollPane pane = new JScrollPane(table);
JFrame f = new JFrame("Leaderboard");
JPanel panel = new JPanel();
panel.add(pane);
f.add(panel);
f.setSize(500, 500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
} catch(SQLException e) {
e.printStackTrace();
}
}
}
Is there any way to put this table within the tab? Thank you :)
You could add the following to your Code.
JPanel lbTab = new JPanel();
Leaderboard leaderboard = new Leaderboard();
lbTab.add(leaderboard);
the Leaderboard is now in your JTabbedPane. If you want to add the Leaderboard as well as the leaderboardLabel in one Tab i suggest something like https://docs.oracle.com/javase/tutorial/uiswing/components/panel.html or How to layout? (JFrame, JPanel, etc.) for your first steps :) .

Sort the JTable by JRadioButton

I want sort the JTable by the JRadioButton component's ActionListener method. When I click "name" the table will sorted out by name. But now I click name radio button, all is blank.
The Main code for query the database all is fine. So I have problem for add another table to the JScrollPane. For the simplicity, I deleted all the import related code. But all the code is working except the radio button's action listener.
public class JtableDemo extends JPanel implements ActionListener {
private static JFrame frame;
JTextField textField;
JScrollPane scrollPanel;
JRadioButton nameButton = new JRadioButton("name");
JRadioButton departmentButton =new JRadioButton("department");
JRadioButton salaryButton =new JRadioButton("Salary");
JRadioButton dateButton = new JRadioButton("date");
ButtonGroup orderbyButtonGroup = new ButtonGroup();
JTable jTable = new JTable();
String orderbyname = "select * from emp where salary >6000 order by name";
String orderbydepartment = "select * from emp where salary >6000 order by department";
String orderbysalary = "select * from emp where salary >6000 order by salary";
public JtableDemo() throws SQLException {
nameButton.addActionListener(this);
departmentButton.addActionListener(this);
salaryButton.addActionListener(this);
dateButton.addActionListener(this);
orderbyButtonGroup.add(nameButton);
orderbyButtonGroup.add(departmentButton);
orderbyButtonGroup.add(salaryButton);
orderbyButtonGroup.add(dateButton);
this.add(nameButton);
this.add(departmentButton);
this.add(salaryButton);
this.add(dateButton);
String query = "select * from emp where salary>? ";
PreparedStatement statement = Main.connection.prepareStatement(query);
statement.setInt(1,6000);
//statement.setString(2,"id");
ResultSet resultSet = statement.executeQuery();
jTable.setModel(DbUtils.resultSetToTableModel(resultSet));
jTable.setPreferredScrollableViewportSize(new Dimension(500,200));
jTable.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(jTable);
add(scrollPane);
String title = "all emp's salary less than 5600";
this.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),title, TitledBorder.CENTER,TitledBorder.TOP));
}
public static void createandShowGUI() throws SQLException {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JtableDemo newContentPane = new JtableDemo();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==nameButton) {
try {
JScrollPane scrollPane = new JScrollPane(jTable);
PreparedStatement orderbystatement = Main.connection.prepareStatement(orderbyname);
//orderbystatement.setString(1,"name");
ResultSet resultSet = orderbystatement.executeQuery();
jTable.setModel(DbUtils.resultSetToTableModel(resultSet));
jTable.setPreferredScrollableViewportSize(new Dimension(500,200));
jTable.setFillsViewportHeight(true);
} catch (SQLException throwables) {
throwables.printStackTrace();
} }
if(e.getSource()==departmentButton) { System.out.println("testdepartmentButton"); }
if(e.getSource()==salaryButton) { System.out.println("testsalaryButton"); }
if(e.getSource()==dateButton) { System.out.println("testdateButton"); }
}
}

refresh a JLabel

This is as the title says, I need your help to refresh the contents of a JLabel.
I explain my worries.
I have a first JFarm or I have a calendar (a DatePicker) which allows me to select a date and a button.
When I click on the button it opens a new window and in this famous window I have my JLabel or I would like to see my date.
In this last window I wrote:
System.out.println(datePicker.getDate());
labelDate.setText(datePicker.getDate());
When I first open my window everything works fine, but if I close it, I change the date in my DatePicker and reopen the window by clicking on my button the date does not change !!!
It always remains on the first date sent.
Yet my:
System.out.println(datePicker.getDate());
Returns the correct date correctly each time.
Do you have an idea ?
Thank you all.
I post my full code but it's very long and not very clean... sorry.
the main window :
public class App extends JFrame{
private JPanel contentPane;
static final int rowMultiplier = 4;
private DatePicker datePicker;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
App frame = new App();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public App() throws SQLException{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
this.setTitle("Absences Management");
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
// =================== PanelTitle ===================================
JPanel panelTitle = new JPanel();
contentPane.add(panelTitle, BorderLayout.NORTH);
JLabel labelTitle = new JLabel("Absence Management");
panelTitle.add(labelTitle);
// ================== PanelMenu =====================================
JPanel panelMenu = new JPanel();
contentPane.add(panelMenu, BorderLayout.WEST);
panelMenu.setLayout(new BoxLayout(panelMenu, BoxLayout.Y_AXIS));
// Border and name for the panel
panelMenu.setBorder(BorderFactory.createTitledBorder(" Menu "));
// create buttons and set the actions for the menu
JButton buttonAddClass = new JButton(new ActionButtonClassManagement(this,"Class management"));
JButton buttonQuit = new JButton(new ActionButtonQuit(this," Quit "));
// add different components in the Panel Menu
panelMenu.add(buttonAddClass);
panelMenu.add(buttonQuit);
// ================= PanelCalendar ==================================
JPanel panelCalendar = new JPanel();
contentPane.add(panelCalendar, BorderLayout.CENTER);
panelCalendar.setAlignmentX(CENTER_ALIGNMENT);
// black border for the panel
panelCalendar.setBorder(BorderFactory.createTitledBorder(" Calendar "));
JLabel labelCalendar = new JLabel("CALENDAR :");
panelCalendar.add(labelCalendar);
// ===== create the calendar
// settings
DatePickerSettings dateSettings = new DatePickerSettings();
dateSettings.setVisibleClearButton(false);
// set the current date by default
dateSettings.setAllowEmptyDates(false);
datePicker = new DatePicker(dateSettings);
// create a icon
URL dateImageURL = FullDemo.class.getResource("/img/calendar20x20.png");
Image calendarImage = Toolkit.getDefaultToolkit().getImage(dateImageURL);
ImageIcon calendarIcon = new ImageIcon(calendarImage);
// create button and set the icon
JButton datePickerButton = datePicker.getComponentToggleCalendarButton();
datePickerButton.setText("");
datePickerButton.setIcon(calendarIcon);
// add the calendar to the PanelCalendar
panelCalendar.add(datePicker);
// create a button Show absences
JButton buttonAbsence = new JButton(new ActionButtonAbsences(this,"Absences", datePicker));
//add the button to the panelCalendar
panelCalendar.add(buttonAbsence);
}
}
The class for my button Absence :
public class ActionButtonAbsences extends AbstractAction{
private App windowAbsence;
private DatePicker datePicker = new DatePicker();
private String dateString = new String();
public ActionButtonAbsences(App app, String textButton, DatePicker datePicker) {
// TODO Auto-generated constructor stub
super(textButton);
this.datePicker = datePicker;
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
dateString = datePicker.getText();
WindowAbsence fen = new WindowAbsence(windowAbsence, datePicker, dateString);
}
}
And the window that opens when I press the button Absence :
public class WindowAbsence extends JDialog implements ActionListener{
private static JPanel panelWindow = new JPanel(new BorderLayout());
private JPanel panelTitle = new JPanel();
private JPanel panelWindowLeft = new JPanel();
private JPanel panelWindowRight = new JPanel();
private JComboBox comboBoxClass;
private JComboBox comboBoxStudent;
private DatePicker datePicker;
private JLabel labelDate = new JLabel();
private String dateString = new String();
private ModelTable modelTableAbsence = new ModelTable();
private JTable tableAbsence = new JTable(modelTableAbsence);
public WindowAbsence(Frame frame, DatePicker datePicker, String date){
//super call the constructor of the main window
// the first argument is the mother window
// the second argument disable this window
super(frame,true);
labelDate.setText(datePicker.getText());
this.dateString = date;
// add BorderLayout in this Window
this.setLayout(new BorderLayout());
// name of the window
this.setTitle("Absences");
// size of the window
this.setSize(700, 600);
// effect for the red cross
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setLocationRelativeTo(null);
this.datePicker = datePicker;
// =================== Data bases connection ============================
/**
* download mysql-connector-java-5.1.40.tar.gz
* https://dev.mysql.com/downloads/file/?id=470332
* Clic droit sur le dossier du projet
* Clic right on the folder of the project
* Build Path
* Add external Archive
*/
DataBase database = new DataBase();
String url = "jdbc:mysql://localhost:3306/AbsenceManagement";
String user = "root";
String pass = "";
String driver = "com.mysql.jdbc.Driver";
try {
database.connectionDataBase(url, user, pass, driver);
// ================== PANEL TITLE ==================================
//JLabel labelDate = new JLabel();
panelTitle.add(labelDate);
//labelDate.setText(datePicker.getText());
date = datePicker.getText();
System.out.println("date: "+date);
labelDate.setText(date);
panelWindow.add(panelTitle, BorderLayout.NORTH);
// ================ PANEL LEFT =====================================
panelWindowLeft.setBorder(BorderFactory.createTitledBorder(" Absences "));
// =========== panelComboBoxLabelClass ======================
JPanel panelLabelComboBoxClass = new JPanel();
panelLabelComboBoxClass.setLayout(new BoxLayout(panelLabelComboBoxClass, BoxLayout.LINE_AXIS));
JLabel labelComboBoxClass = new JLabel("Class :");
comboBoxClass = new JComboBox();
comboBoxClass.addItem("");
panelLabelComboBoxClass.add(labelComboBoxClass);
panelLabelComboBoxClass.add(comboBoxClass);
Statement statementClass = DataBase.connection.createStatement();
ResultSet resultClass = statementClass.executeQuery("SELECT class FROM Class");
//receive the MetaData
ResultSetMetaData resultMetaClass = (ResultSetMetaData) resultClass.getMetaData();
// add the data in the row
while(resultClass.next()){
comboBoxClass.addItem(resultClass.getObject(1));
}
comboBoxClass.addActionListener(this);
resultClass.close();
statementClass.close();
// =========== panelComboBoxLabelStudent ======================
JPanel panelLabelComboBoxStudent = new JPanel();
panelLabelComboBoxStudent.setLayout(new BoxLayout(panelLabelComboBoxStudent, BoxLayout.LINE_AXIS));
JLabel labelComboBoxStudent = new JLabel("Student :");
comboBoxStudent = new JComboBox();
panelLabelComboBoxStudent.add(labelComboBoxStudent);
panelLabelComboBoxStudent.add(comboBoxStudent);
// ========== panelComboBoxHour ===============================
int rowMultiplier = 4;
int row = rowMultiplier;
TimePickerSettings timeSettings = new TimePickerSettings();
timeSettings.setDisplayToggleTimeMenuButton(true);
timeSettings.setDisplaySpinnerButtons(false);
JPanel panelComboBoxHour = new JPanel();
panelComboBoxHour.setLayout(new BoxLayout(panelComboBoxHour, BoxLayout.LINE_AXIS));
JLabel labelComboBoxFrom = new JLabel("From :");
panelComboBoxHour.add(labelComboBoxFrom);
TimePicker timePickerFrom = new TimePicker(timeSettings);
timePickerFrom = new TimePicker();
panelComboBoxHour.add(timePickerFrom, getConstraints(1, (row * rowMultiplier), 1));
//panelComboBoxHour.addLabel(panelComboBoxHour, 1, (row++ * rowMultiplier), "Time 1, Default Settings:");
JLabel labelComboBoxTo = new JLabel("To :");
panelComboBoxHour.add(labelComboBoxTo);
TimePicker timePickerTo = new TimePicker();
timePickerTo = new TimePicker();
panelComboBoxHour.add(timePickerTo, getConstraints(1, (row * rowMultiplier), 1));
// ========== panel button add absence ==============
JPanel panelButtonAddAbsence = new JPanel();
panelButtonAddAbsence.setLayout(new BoxLayout(panelButtonAddAbsence, BoxLayout.LINE_AXIS));
JButton buttonAddAbsence = new JButton("Add Absence");
panelButtonAddAbsence.add(buttonAddAbsence);
// ========================================
panelWindowLeft.setLayout(new BoxLayout(panelWindowLeft, BoxLayout.PAGE_AXIS));
panelWindowLeft.add(panelLabelComboBoxClass);
panelWindowLeft.add(panelLabelComboBoxStudent);
panelWindowLeft.add(panelComboBoxHour);
panelWindowLeft.add(panelButtonAddAbsence);
panelWindow.add(panelWindowLeft, BorderLayout.WEST);
// ====================== PANEL RIGHT ================================
panelWindowRight.setBorder(BorderFactory.createTitledBorder(" Absences "));
//=================== TABLE =======================================
Statement statementAbsence = DataBase.connection.createStatement();
// requet SQL
ResultSet resultAbsence;
ResultSetMetaData resultMetaAbsence;
modelTableAbsence.addColumn("Student");
modelTableAbsence.addColumn("Date");
modelTableAbsence.addColumn("To");
modelTableAbsence.addColumn("From");
// requete SQL
resultAbsence = statementAbsence.executeQuery("SELECT * FROM Absence WHERE `dateAbsence`='"+datePicker.getDate().toString()+"'");
//receive the MetaData
resultMetaAbsence = (ResultSetMetaData) resultAbsence.getMetaData();
modelTableAbsence.fireTableDataChanged();
if(!resultAbsence.next()){
System.out.println("null");
}else{
// add the data in the row
do{
modelTableAbsence.addRow(new Object[]{
resultAbsence.getObject(2).toString(),
resultAbsence.getObject(3).toString(),
resultAbsence.getObject(4).toString(),
resultAbsence.getObject(5).toString()
});
}while(resultAbsence.next());
// close the statementClass
statementAbsence.close();
resultAbsence.close();
// ========= replace id student by firstName and lastName
Statement statementNameStudent = DataBase.connection.createStatement();
ResultSet resultNameStudent = null;
int nbRow = modelTableAbsence.getRowCount();
for(int i = 0; i < nbRow; i++){
resultNameStudent = statementNameStudent.executeQuery("SELECT firstName, lastName FROM Student WHERE `id`='"+modelTableAbsence.getValueAt((i), 0)+"'");
// add the data in the row
while(resultNameStudent.next()){
modelTableAbsence.setValueAt(
(resultNameStudent.getObject(1)+" "+resultNameStudent.getObject(2)),i,0);
}
}
statementNameStudent.close();
resultNameStudent.close();
}
// =================================================================
JScrollPane scrollPane = new JScrollPane(tableAbsence);
panelWindowRight.add(scrollPane);
panelWindow.add(panelWindowRight, BorderLayout.CENTER);
this.setContentPane(panelWindow);
this.setVisible(true);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static GridBagConstraints getConstraints(int gridx, int gridy, int gridwidth) {
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.WEST;
gc.gridx = gridx;
gc.gridy = gridy;
gc.gridwidth = gridwidth;
return gc;
}
// model table for table schedule
public class ModelTableSchedule extends DefaultTableModel {
ModelTableSchedule(Object[][] dataStudent, String[] columnNamesStudent) {
super(dataStudent, columnNamesStudent);
}
// the function return always false, the table is never editable
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
public void actionPerformed(ActionEvent arg0) {
modelTableAbsence.fireTableDataChanged();
// =================== Data bases connection ============================
/**
* download mysql-connector-java-5.1.40.tar.gz
* https://dev.mysql.com/downloads/file/?id=470332
* Clic droit sur le dossier du projet
* Clic right on the folder of the project
* Build Path
* Add external Archive
*/
DataBase database = new DataBase();
String url = "jdbc:mysql://localhost:3306/AbsenceManagement";
String user = "root";
String pass = "";
String driver = "com.mysql.jdbc.Driver";
try {
database.connectionDataBase(url, user, pass, driver);
// add value in ComboBox
Statement statementStudent;
comboBoxStudent.removeAllItems();
statementStudent = DataBase.connection.createStatement();
ResultSet resultStudent = statementStudent.executeQuery("SELECT * FROM `Student` WHERE `class` LIKE '"+comboBoxClass.getSelectedItem().toString()+"'");
//receive the MetaData
ResultSetMetaData resultMetaStudent = (ResultSetMetaData) resultStudent.getMetaData();
// add the data in the row
while(resultStudent.next()){
comboBoxStudent.addItem((resultStudent.getObject(2)+" "+resultStudent.getObject(3)));
}
comboBoxStudent.revalidate();
resultStudent.close();
statementStudent.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thank you for your help.
Again me,
I found my error !
In my WindowAbsence :
private static JPanel panelWindow = new JPanel(new BorderLayout());
The panel it was in static...
i hope will serve for someone !

repaint() method doesn't work more than once

I am currently working on a gui project which is managing a sql database. I am currently adding,deleting logs and showing tables existing in mysql. The problem is my add and delete buttons on my panel are supposed to repaint/refresh the table on that panel as a record is added or deleted however while testing I discovered that repaint method doesn't refresh the table after the first use of the button. What can cause this problem? Thanks in advance..
public JTabbedPane addComponentToPane() {
//Container pane = new Container();
JTabbedPane tabbedPane = new JTabbedPane();
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
JPanel card3 = new JPanel();
JPanel card4 = new JPanel();
JPanel card5 = new JPanel();
JPanel card6 = new JPanel();
JPanel card7 = new JPanel();
JPanel card8 = new JPanel();
card1.setLayout(new BorderLayout());
card2.setLayout(new BorderLayout());
card3.setLayout(new BorderLayout());
card4.setLayout(new BorderLayout());
card5.setLayout(new BorderLayout());
card6.setLayout(new BorderLayout());
card7.setLayout(new BorderLayout());
card8.setLayout(new BorderLayout());
JScrollPane actor = new JScrollPane(createTables("actor"));
card1.add(actor, BorderLayout.CENTER);
card3.add(createTables("address"), BorderLayout.CENTER);
card4.add(createTables("category"), BorderLayout.CENTER);
card5.add(createTables("city"), BorderLayout.CENTER);
card6.add(createTables("country"), BorderLayout.CENTER);
card7.add(createTables("customer"), BorderLayout.CENTER);
card8.add(createTables("film"), BorderLayout.CENTER);
JButton button = new JButton("Yeni Kayıt");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
addRecord("actor");
card1.remove(actor);
card1.add(createTables("actor"), BorderLayout.CENTER);
card1.validate();
card1.repaint();
}
});
JButton delButton = new JButton("Kayıt sil");
delButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
delRecord("actor");
card1.remove(actor);
card1.add(createTables("actor"), BorderLayout.CENTER);
card1.validate();
card1.repaint();
}
});``
card1.add(button, BorderLayout.SOUTH);
card1.add(delButton, BorderLayout.EAST);
tabbedPane.addTab("Şirketler", null, card1, "şirket tanımları");
tabbedPane.addTab("Sorumlular", card2);
tabbedPane.addTab("Varlık Grupları", card3);
tabbedPane.addTab("Bilgi Varlıkları", card4);
tabbedPane.addTab("Varlık Değerleri", card5);
tabbedPane.addTab("Açıklıklar", card6);
tabbedPane.addTab("Tehditler", card7);
tabbedPane.addTab("Ek-A", card8);
//pane.add(tabbedPane, BorderLayout.CENTER);
return tabbedPane;
}
Create tables method creating a Jtable from sql table.
private JScrollPane createTables(String tablename) {
Connection con = null;
Statement statement = null;
ResultSet result = null;
String query;
JScrollPane jsp = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila", "root", "root");
statement = con.createStatement();
query = "select * from " + tablename;
result = statement.executeQuery(query);
ResultSetMetaData rsmt = result.getMetaData();
int columnCount = rsmt.getColumnCount();
Vector column = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
column.add(rsmt.getColumnName(i));
}
Vector data = new Vector();
Vector row = new Vector();
while (result.next()) {
row = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
row.add(result.getString(i));
}
data.add(row);
}
defTableModel = new DefaultTableModel(data, column);
table = new JTable(defTableModel) {
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
;
};
//table.setAutoCreateRowSorter(true);
TableRowFilterSupport.forTable(table).searchable(true).apply();
table.setRowSelectionAllowed(true);
jsp = new JScrollPane(table);
}
catch (Exception e) {
e.printStackTrace();
// JOptionPane.showMessageDialog(null, "ERROR");
}
finally {
try {
statement.close();
result.close();
con.close();
}
catch (Exception e) {
//JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
return jsp;
}
I could see couple of inconsistencies in the code:
The actor variable is not being set to the added component in the action listener.
First time you are adding new JScrollPane(createTables("actor")) and then onwards you only add createTables("actor").
The (1) might be causing the problem.
I think the problem is the reference to the actor:
card1.remove(actor);
card1.add(createTables("actor"), BorderLayout.CENTER);
Here, the variable actor is not more referenced in card1. To not lose this reference you should do something like this, in both actionPerformed methods:
card1.remove(actor);
actor = new JScrollPane(createTables("actor"));
card1.add(actor, BorderLayout.CENTER);

Trying to connect to a sqlite but: SQL error or missing database (no such table: Bank_001)

I don't know what is wrong with this code; the SQL commands and the path looks alright. The connect to the db is ok; but when I try to pass a simple search; it returns that that table doesn't exist.
I tried it (the same code) in a different method to add data and it works fine; so I don't know what I'm doing wrong.
Thanks for your attention.
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
First_GUI frame = new First_GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection conn = null; //Call the Connection Class from JavaSqlite Class
/**
* Create the frame.
*/
public First_GUI() {
conn = Sqlite_Connection.dbconnector(); //call the connection CONN from SQLite class, method DBconnector.
setTitle("First GUI App");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
FlowLayout flowLayout = (FlowLayout) panel.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
contentPane.add(panel, BorderLayout.NORTH);
JLabel lblEnterTheName = new JLabel("Enter the Name :");
lblEnterTheName.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblEnterTheName.setVerticalAlignment(SwingConstants.TOP);
lblEnterTheName.setHorizontalAlignment(SwingConstants.LEFT);
panel.add(lblEnterTheName);
NameField = new JTextField();
panel.add(NameField);
NameField.setColumns(10);
JButton Search = new JButton("Search");
Search.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// ****************************************************************
// Here is the PROBLEM.
String sql = "SELECT * FROM Bank_001 where AccountName like ?";
try {
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, NameField.getText());
ResultSet rs = pst.executeQuery();
rs.close();
pst.close();
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
}
});
panel.add(Search);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextPane textPane = new JTextPane();
textPane.setFont(new Font("Tahoma", Font.PLAIN, 14));
scrollPane.setViewportView(textPane);
}
}
can you show the code for this ?
conn = Sqlite_Connection.dbconnector();
are you using setURL() on a new SQLiteDataSource ?
assuming using setURL, is it constructed correctly ?
Something like:
"jdbc:sqlite:sqlite-test.db"

Categories