I'm having a problem in my project i cant Connect the program with the data Source
So if there's any help plzz assist me
this is the error message and the source code below
I'm in trouble plzzz help meeeeee
//for creating the North Panel
private JPanel northPanel = new JPanel();
//for creating the Center Panel
private JPanel centerPanel = new JPanel();
//for creating the label
private JLabel northLabel = new JLabel("THE LIST FOR THE BOOKS");
//for creating the button
private JButton printButton;
//for creating the table
private JTable table;
//for creating the TableColumn
private TableColumn column = null;
//for creating the JScrollPane
private JScrollPane scrollPane;
//for creating an object for the ResultSetTableModel class
private ResultSetTableModel tableModel;
/***************************************************************************
* for setting the required information for the ResultSetTableModel class. *
***************************************************************************/
private static final String JDBC_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
private static final String DATABASE_URL = "jdbc:odbc:Telecom";
private static final String DEFAULT_QUERY = "SELECT EmployeeID,EmployeeName,ProjectName,JobTitle,MobileNumber,DateOfSim,SimNumber,MCG,Active FROM [Telecom].[dbo].[Employee];";
//constructor of listBooks
public ListBooks() {
//for setting the title for the internal frame
super("Employee", false, true, false, true);
//for setting the icon
setFrameIcon(new ImageIcon(ClassLoader.getSystemResource("images/List16.gif")));
setLocale(new java.util.Locale("ar", "SA", ""));
//for getting the graphical user interface components displaygvk area
Container cp = getContentPane();
//for bassing the required information to the ResultSetTableModel object
try {
tableModel = new ResultSetTableModel(JDBC_DRIVER, DATABASE_URL, DEFAULT_QUERY);
//for setting the Query
try {
tableModel.setQuery(DEFAULT_QUERY);
}
catch (SQLException sqlException) {
}
}
catch (ClassNotFoundException classNotFound) {
System.out.println(classNotFound.toString());
}
catch (SQLException sqlException) {
System.out.println(sqlException.toString());
}
//for setting the table with the information
table = new JTable(tableModel);
//for setting the size for the table
table.setPreferredScrollableViewportSize(new Dimension(990, 200));
//for setting the font
table.setFont(new Font("Tahoma", Font.PLAIN, 12));
//for setting the scrollpane to the table
scrollPane = new JScrollPane(table);
//for setting the size for the table columns
for (int i = 0; i < 9; i++) {
column = table.getColumnModel().getColumn(i);
if (i == 0) //BookID
column.setPreferredWidth(20);
if (i == 1) //Subject
column.setPreferredWidth(100);
if (i == 2) //Title
column.setPreferredWidth(150);
if (i == 3) //Auther
column.setPreferredWidth(50);
if (i == 4) //Publisher
column.setPreferredWidth(70);
if (i == 5) //Copyright
column.setPreferredWidth(40);
if (i == 6) //Edition
column.setPreferredWidth(40);
if (i == 7) //Pages
column.setPreferredWidth(40);
if (i == 8) //NumberOfBooks
column.setPreferredWidth(80);
}
//for setting the font to the label
northLabel.setFont(new Font("Tahoma", Font.BOLD, 14));
//for setting the layout to the panel
northPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
//for adding the label to the panel
northPanel.add(northLabel);
//for adding the panel to the container
cp.add("North", northPanel);
//for setting the layout to the panel
centerPanel.setLayout(new BorderLayout());
//for creating an image for the button
ImageIcon printIcon = new ImageIcon(ClassLoader.getSystemResource("images/Print16.gif"));
//for adding the button to the panel
printButton = new JButton("print the books", printIcon);
//for setting the tip text
printButton.setToolTipText("Print");
//for setting the font to the button
printButton.setFont(new Font("Tahoma", Font.PLAIN, 12));
//for adding the button to the panel
centerPanel.add(printButton, BorderLayout.NORTH);
//for adding the scrollpane to the panel
centerPanel.add(scrollPane, BorderLayout.CENTER);
//for setting the border to the panel
centerPanel.setBorder(BorderFactory.createTitledBorder("Books:"));
//for adding the panel to the container
cp.add("Center", centerPanel);
//for adding the actionListener to the button
printButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Thread runner = new Thread() {
public void run() {
try {
PrinterJob prnJob = PrinterJob.getPrinterJob();
prnJob.setPrintable(new PrintingBooks(DEFAULT_QUERY));
if (!prnJob.printDialog())
return;
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
prnJob.print();
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
catch (PrinterException ex) {
System.out.println("Printing error: " + ex.toString());
}
}
};
runner.start();
}
});
//for setting the visible to true
setVisible(true);
//to show the frame
pack();
}
}
I got the following error
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Invalid string
or buffer length
You should try this
for (int i = 0; i < 9; i++)
column = table.getColumnModel().getColumn(i+1);
instead of this
for (int i = 0; i < 9; i++)
column = table.getColumnModel().getColumn(i);
Maybe it works.
Related
I have created a an jtable in java swing which looks like the following
I have added 6 buttons and 3 of them work fine(add,update,delete). im not worried about random match button but i want "Sort By goals" button to sort out all the records entered by the highest number of goals. same goes for points. I have tried many times but i dont seem to be able to figure out.
Here is the code for my table arrays;
// create JFrame and JTable
JFrame frame = new JFrame();
JTable table = new JTable();
Container c = frame.getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
c.add(table);
// create a table model and set a Column Identifiers to this model
Object[] columns = {"Team name", "Wins", "Losses", "Goals Difference","Points","Matches played"};
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columns);
// set the model to the table
table.setModel(model);
// Change A JTable Background Color, Font Size, Font Color, Row Height
table.setBackground(Color.LIGHT_GRAY);
table.setForeground(Color.black);
Font font = new Font("", 1, 22);
table.setFont(font);
table.setRowHeight(30);
// table.setVisible(true);
Here is my draft for the button;
btnSortPoints.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
Here is my delete button;
btnDelete.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// i = the index of the selected row
int i = table.getSelectedRow();
if(i >= 0){
// remove a row from jtable
model.removeRow(i);
}
else{
System.out.println("Delete Error");
}
}
});
Here is my entire code;
public class table{
public static void main(String[] args) {
// create JFrame and JTable
JFrame frame = new JFrame();
JTable table = new JTable();
Container c = frame.getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
c.add(table);
// create a table model and set a Column Identifiers to this model
Object[] columns = {"Team name", "Wins", "Losses", "Goals Difference","Points","Matches played"};
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columns);
// set the model to the table
table.setModel(model);
// Change A JTable Background Color, Font Size, Font Color, Row Height
table.setBackground(Color.LIGHT_GRAY);
table.setForeground(Color.black);
Font font = new Font("", 1, 22);
table.setFont(font);
table.setRowHeight(30);
// table.setVisible(true);
// create JTextFields
JTextField txtTeamName = new JTextField();
JTextField txtWins = new JTextField();
JTextField txtLosses = new JTextField();
JTextField txtGD = new JTextField();
JTextField txtPoints = new JTextField();
JTextField txtMatches = new JTextField();
JLabel lblTeamName = new JLabel("Team name");
JLabel lblWins = new JLabel("Wins");
JLabel lblLosses = new JLabel("Losses");
JLabel lblGD = new JLabel("Goal difference");
JLabel lblPoints = new JLabel("Points");
JLabel lblMatches = new JLabel("Matches");
// create JButtons
JButton btnAdd = new JButton("Add");
JButton btnDelete = new JButton("Delete");
JButton btnUpdate = new JButton("Update");
JButton btnSortPoints = new JButton("Sort by points");
JButton btnSortGoals = new JButton("Sort by goals");
JButton btnRandomMatch = new JButton("Add a random data");
txtTeamName.setBounds(1200, 230, 100, 25);
txtWins.setBounds(1200, 260, 100, 25);
txtLosses.setBounds(1200, 290, 100, 25);
txtGD.setBounds(1200, 320, 100, 25);
txtMatches.setBounds(1200,350,100,25);
txtPoints.setBounds(1200,380,100,25);
lblTeamName.setBounds(1100,230,100,25);
lblWins.setBounds(1100,260,100,25);
lblLosses.setBounds(1100,290,100,25);
lblGD.setBounds(1100,320,100,25);
lblMatches.setBounds(1100,350,100,25);
lblPoints.setBounds(1100,380,100,25);
btnAdd.setBounds(1150, 20, 200, 50);
btnUpdate.setBounds(1150, 80, 200, 50);
btnDelete.setBounds(1150, 140, 200, 50);
btnSortGoals.setBounds(920,20,200,50);
btnSortPoints.setBounds(920,80,200,50);
btnRandomMatch.setBounds(920,140,200,50);
// create JScrollPane
JScrollPane pane = new JScrollPane(table);
pane.setBounds(0, 0, 880, 400);
frame.setLayout(null);
frame.add(pane);
// add JTextFields to the jframe
frame.add(txtTeamName);
frame.add(txtWins);
frame.add(txtLosses);
frame.add(txtGD);
frame.add(txtMatches);
frame.add(txtPoints);
//Adding the labels to the frame
frame.add(lblTeamName);
frame.add(lblWins);
frame.add(lblLosses);
frame.add(lblGD);
frame.add(lblMatches);
frame.add(lblPoints);
// add JButtons to the jframe
frame.add(btnAdd);
frame.add(btnDelete);
frame.add(btnUpdate);
frame.add(btnSortGoals);
frame.add(btnSortPoints);
frame.add(btnRandomMatch);
// create an array of objects to set the row data
Object[] row = new Object[6];
// button add row
btnAdd.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
row[0] = txtTeamName.getText();
row[1] = txtWins.getText();
row[2] = txtLosses.getText();
row[3] = txtGD.getText();
row[4] = txtMatches.getText();
row[5] = txtPoints.getText();
// add row to the model
model.addRow(row);
}
});
// Event listener for button remove row
btnDelete.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// i = the index of the selected row
int i = table.getSelectedRow();
if(i >= 0){
// remove a row from jtable
model.removeRow(i);
}
else{
System.out.println("Delete Error");
}
}
});
// get selected row data From table to textfields
table.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
// i = the index of the selected row
int i = table.getSelectedRow();
txtTeamName.setText(model.getValueAt(i, 0).toString());
txtWins.setText(model.getValueAt(i, 1).toString());
txtLosses.setText(model.getValueAt(i, 2).toString());
txtGD.setText(model.getValueAt(i, 3).toString());
txtMatches.setText(model.getValueAt(i,4).toString());
txtPoints.setText(model.getValueAt(i,5).toString());
}
});
// button update row
btnUpdate.addActionListener(new ActionListener(){
#Override
public void actionPerformed (ActionEvent e) {
// i = the index of the selected row
int i = table.getSelectedRow();
if(i >= 0)
{
model.setValueAt(txtTeamName.getText(), i, 0);
model.setValueAt(txtWins.getText(), i, 1);
model.setValueAt(txtLosses.getText(), i, 2);
model.setValueAt(txtGD.getText(), i, 3);
model.setValueAt(txtMatches.getText(),i,4);
model.setValueAt(txtPoints.getText(),i,5);
}
else{
System.out.println("Update Error");
}
}
});
btnSortPoints.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
frame.setSize(1400, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
You first need to add sorting support to your JTable. Read the Sorting and Filtering link from the tutorial for information on how to do that.
Once that is done the user will be able to sort any column by clicking on the column header of the column.
Verify the sorting works by manually clicking on the columns headers.
i want "Sort By goals" button to sort out all the records entered by the highest number of goals and points
Now that your JTable supports sorting you can add add an ActionListener to your buttons to do the specific sorting:
btnSortPoints.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Points column in the model is converted to the view column
int viewColumn = table.convertColumnIndexToView(4);
// Set up the columns you want to sort on
List<RowSorter.SortKey> sortKeys = new ArrayList<>();
sortKeys.add(new RowSorter.SortKey(viewColumn, SortOrder.ASCENDING));
// Do the sorting
TableRowSorter sorter = (TableRowSorter)table.getRowSorter();
sorter.setSortKeys(sortKeys);
}
});
`
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 !
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);
Hi guys I built this app to show students how a loop works graphically, that was working although not correctly, but I'll address that in a question later. I'm not sure what I did to the applet but now I get this runtime error. How do I fix this? thanks in advanced!
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import javax.swing.JOptionPane;
public class Checkerboard extends Frame implements ActionListener
{
int[] blocksTextField = new int[15];
Panel blocksPanel = new Panel();
TextArea blocksDisplay[] = new TextArea[16];
TextField start = new TextField (3);
TextField stop = new TextField (3);
TextField step = new TextField (3);
//Colors
Color Red = new Color(255, 90, 90);
Color Green = new Color(140, 215, 40);
Color white = new Color(255,255,255);
//textField ints
int inputStart;
int inputStop;
int inputStep;
//Lables
Label custStartLabel = new Label ("Start : ");
Label custStopLabel = new Label ("Stop : ");
Label custStepLabel = new Label ("Step : ");
//Buttons
Button goButton = new Button("Go");
Button clearButton = new Button("Clear");
//panel for input textFields and lables
Panel textInputPanel = new Panel();
//Panel for buttons
Panel buttonPanel = new Panel();
Checkerboard()
{//constructor method
//set the 3 input textFields to 0
inputStart = 0;
inputStop = 0;
inputStep = 0;
//set Layouts for frame and three panels
this.setLayout(new BorderLayout());
//grid layout (row,col,horgap,vertgap)
blocksPanel.setLayout(new GridLayout(4,4,10,10));
textInputPanel.setLayout(new GridLayout(2,3,20,10));
buttonPanel.setLayout(new FlowLayout());
//setEditable()
//setText()
//add components to blocks panel
for (int i = 0; i<16; i++)
{
blocksDisplay[i] = new TextArea(null,3,5,3);
if(i<6)
blocksDisplay[i].setText(" " +i);
else
blocksDisplay[i].setText(" " +i);
blocksDisplay[i].setEditable(false);
// blocksDisplay[i].setBackground(Red);
blocksPanel.add(blocksDisplay[i]);
}
//add componets to panels
//add text fields
textInputPanel.add(start);
textInputPanel.add(stop);
textInputPanel.add(step);
//add lables
textInputPanel.add(custStartLabel);
textInputPanel.add(custStopLabel);
textInputPanel.add(custStepLabel);
//add button to panel
buttonPanel.add(goButton);
buttonPanel.add(clearButton);
//ADD ACTION LISTENRS TO BUTTONS (!IMPORTANT)
goButton.addActionListener(this);
clearButton.addActionListener(this);
add(blocksPanel, BorderLayout.NORTH);
add(textInputPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
//overridding the windowcClosing() method will allow the user to clisk the Close button
addWindowListener(
new WindowAdapter()
{
public void windowCloseing(WindowEvent e)
{
System.exit(0);
}
}
);
}//end of constructor method
public void actionPerformed(ActionEvent e)
{
//if & else if to see what button clicked and pull user input
if(e.getSource() == goButton) //if go clicked ...
{
System.out.println("go clicked");
try{
String inputStart = start.getText();
int varStart = Integer.parseInt(inputStart);
if (varStart<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("start = " + varStart);
// roomDisplay[available].setBackground(lightRed);
String inputStop = stop.getText();
int varStop = Integer.parseInt(inputStop);
if (varStop<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("stop = " + varStop);
String inputStep = step.getText();
int varStep = Integer.parseInt(inputStep);
if (varStep<=0 || varStep>=15 )throw new NumberFormatException();
System.out.println("step = " + varStep);
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(null, "You must enter a Start, Stop and Step value greater than 0 and less than 15",
"Error",JOptionPane.ERROR_MESSAGE);
}
}
else if(e.getSource() == clearButton ) //else if clear clicked ...
{
System.out.println("clear clicked");
}
//int available = room.bookRoom(smoking.getState());
//if (available > 0)//Rooms is available
}//end action performed method
public static void main(String[]args)
{
Checkerboard frame = new Checkerboard ();
frame.setBounds(50, 100, 300, 410);//changed size to make text feilds full charater size
frame.setTitle("Checkerboarder Array");
frame.setVisible(true);
}//end of main method
}
Make the constructor public.
public Checkerboard() {
...
}
The error appears because the constructor is package-private, e.g. you can't instantiate the class outside it's package.
The scrollPane table isn't refreshing for every time I selected something from the combo. Initially it has data but after I selected something, the data is removed successfully but new data isn't populating in
public void ConsultFrame(String id, String name, String ic){
GenerateMed("dp-000"); // to begin the scrollpane filled with Fever's medicine
JButton proc = new JButton("Proceed");
JButton addmed = new JButton(">>");
selected = new JTable(data, columnNames){
#Override
public boolean isCellEditable(int row,int column){
switch(column){
case 0:
return false;
case 1:
return false;
default: return true;
}
}};
selectedPane = new JScrollPane(selected);
//Dispensary's category combobox related
disp = dbDisp.getDispensary();
final JComboBox cBox = new JComboBox();
for(int count=0; count<disp.size(); count++)
cBox.addItem(disp.get(count).getDSP_desc());
cBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent event) {
for(int count=0; count<disp.size(); count++){
if(cBox.getSelectedItem().equals(disp.get(count).getDSP_desc())){
System.out.println(disp.get(count).getDSP_ID());
GenerateMed(disp.get(count).getDSP_ID());
break;
}
}
}
});
JTextArea tArea = new JTextArea(5, 30);
JScrollPane desc = new JScrollPane(tArea);
tArea.setLineWrap(true);
desc.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );
JPanel info = new JPanel();
info.setLayout(new FlowLayout(FlowLayout.LEFT));
info.add(new JLabel("<html>Patient's ID : " + id + "<br>Patient's Name: " + name + "<br>Patient's IC : " + ic + "<br><br>Medical Description : </html>"));
info.add(desc);
JPanel medSelect = new JPanel();
medSelect.setLayout(new GridLayout(1,2));
medSelect.add(scrollPane);
medSelect.add(selectedPane);
JPanel medic = new JPanel();
medic.setLayout(new BorderLayout());
medic.add(cBox, BorderLayout.NORTH);
medic.add(medSelect, BorderLayout.CENTER);
medic.add(proc, BorderLayout.SOUTH);
JPanel all = new JPanel();
String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm").format(Calendar.getInstance().getTime());
title = BorderFactory.createTitledBorder(timeStamp);
title.setTitleJustification(TitledBorder.RIGHT);
all.setBorder(title);
all.setLayout(new GridLayout(2,1));
all.add(info);
all.add(medic);
JFrame consult = new JFrame();
consult.setTitle(name + "'s consultation");
consult.setResizable(false);
consult.setVisible(true);
consult.setSize(500, 460);
consult.setLocationRelativeTo(null);
consult.add(all);
}
This is where my Combobox's is heading as soon as something is selected and I've tried repaint & revalidate
public void GenerateMed(String dps_id){
if (tModel != null) {
for (int i = tModel.getRowCount() - 1; i > -1; i--)
tModel.removeRow(i);
}
tModel = dbMed.getDPSMedicine(dps_id);
tModel.fireTableDataChanged();
table = new JTable(tModel){
#Override
public boolean isCellEditable(int row,int column){
return false;
}};
table.setShowGrid(false);
table.setShowHorizontalLines(false);
table.setShowVerticalLines(false);
//Table customization
table.getTableHeader().setReorderingAllowed(false);
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.changeSelection(0, 0, false, false);
scrollPane = new JScrollPane(table);
scrollPane.repaint();
scrollPane.revalidate();
}
scrollPane = new JScrollPane(table);
The above line of code creates a new scrollPane, but doesn't add the scrollPane to the frame.
However, there is no need to even create a new JTable or a new JScrollPane. Get rid of all the code.
Instead you just change the model of your JTable by using:
table.setModel( dbMed.getDPSMedicine(dps_id) );
So basically your method becomes one line of code.
Also, use proper method names. Method names should NOT start with an upper case character.