Items in combobox reduced after adding actionPerformed - java

I want to update my table right after clicking on a diffrent item in combobox. After adding actionPerformed combobox shows only the first item and the arrow doesn't work. I'm updating my table after selecting a diffrent item and clicking a button. Action perform in a button does work. Am I using the actionPerformed incorrectly?
Here is a code how I add items to a combobox.
private void fillComboBox() {
try {
DatabaseMetaData meta = (DatabaseMetaData) conn.getMetaData();
rs = meta.getTables("db", null, null, new String[] {
"TABLE"
});
while (rs.next()) {
ComboBox.addItem(rs.getString("TABLE_NAME"));
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null,e);
}
}
Here is how I fill the table.
private void fillTable()
{
String selectedValue = ComboBox.getSelectedItem().toString();
String sql = "Select * from "+selectedValue;
Statement stmt;
try {
stmt = conn.createStatement(rs.TYPE_SCROLL_INSENSITIVE,rs.CONCUR_UPDATABLE);
rs = stmt.executeQuery(sql);
Table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException ex) {
Logger.getLogger(Welcome.class.getName()).log(Level.SEVERE, null, ex);
}
}
And after clicking a button, I update the table
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
fillTable();
}
Works fine, but I would like to update the table right after clicking on a new item in combobox.
Edit: I fixed it by adding fillComboBox() after fillTable(). But now I have two first items in combobox even after removeAll(). How do I fix it?
public Welcome() {
initComponents();
conn = MySqlConnect.ConnectDB();
fillComboBox();
fillTable();
ComboBox.removeAll();
fillComboBox();
repaint();
}

I always change contents of a ComboBox dynamically by using the underlying Model, not through the actual ComboBox. After your GUI is already shown, I think this matters ... using the model, not the JComboBox itself.
...
final var model = new DefaultComboBoxModel<String>();
while (rs.next()) {
model.addElement(rs.getString("TABLE_NAME"));
}
...
ComboBox.setModel(model);

Related

How to stop mouseClicked?

I have one table where it shows some data from sql server and when I click it it also shows data on text fields that gets it directly from the table. But once I click one row on the table it remains clicked until the frame is closed. How can I disable it? Heres my code on click event.
int rowIndex;
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
rowIndex = jTable1.getSelectedRow();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
if(model.getValueAt(rowIndex, 3).toString().equals("Mashkull "))
{
jRadioButton1_mashkull1.setSelected(true);
jRadioButton2_femer1.setSelected(false);
} else {
jRadioButton2_femer1.setSelected(true);
jRadioButton1_mashkull1.setSelected(false);
}
jTextField1_id1.setText(model.getValueAt(rowIndex, 0).toString());
jTextField1_emri1.setText(model.getValueAt(rowIndex, 1).toString());
jTextField1_mbiemri2.setText(model.getValueAt(rowIndex, 2).toString());
jTextField1_nrtel1.setText(model.getValueAt(rowIndex, 5).toString());
jTextArea1_adresa1.setText(model.getValueAt(rowIndex, 6).toString());
Date bdate;
try {
bdate= new SimpleDateFormat("yyyy-MM-dd").parse(model.getValueAt(rowIndex, 4).toString());
jDateChooser1_data1.setDate(bdate);
} catch (ParseException ex) {
Logger.getLogger(kontrollostudentet.class.getName()).log(Level.SEVERE, null, ex);
}
}
You can make a call to clearSelection() right after getting the row index.
public void clearSelection()
Deselects all selected columns and rows.

Java delete database update panel

Everytime I delete something from my JButton it deletes in the database but my jpanel wont update...
I wonder if there is an easy fix for this?
private void DeleteActionPerformed(java.awt.event.ActionEvent evt) {
infLabel.setText(inform[2]);
Connection connection = FlatFinder.getConnection();
Statement selectStmt = null;
try {
selectStmt = connection.createStatement();
Flat activeFlat = (Flat) AdminAll.getSelectedValue();
String sql = String.format(
"DELETE FROM `flats` WHERE flat_id = %d",
activeFlat.getId()
);
selectStmt.executeUpdate(sql);
} catch (SQLException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
this.repaint();
}
This is my current code. Is there any easy solution to update the jpanel when I press the delete button?

Garbage value in jtable after adding row dynamically

I have JTable which has few columns.In that I have JComboBox. At program start I want them to be empty.I have one JButton on click action of button i have the code to add row dynamically in table.
But after adding the row i get garbage value in the cell having JComboBox. As shown in below figure :
And here is the code :
Code to add JComboBox in table
// Create columns names
String columnNames[] = { "Item", "Sun Item", "Required Quantity","Price","Gross Amount" };
// Create some data
final String dataValues[][] =
{
{ "", "", "","","", },
};
tableModel = new DefaultTableModel(dataValues, columnNames);
// Create a new table instance
table = new JTable( tableModel );
updateItemCombo();
TableColumn itemColumn = table.getColumnModel().getColumn(0);
itemColumn.setCellEditor(new DefaultCellEditor(comboItem));
public void updateItemCombo(){
Vector<String> s = new Vector<String>();
try{
setConnectin();
String str = "select * from ItemTable";
stmt = conn.createStatement();
rs = stmt.executeQuery(str);
while(rs.next())
{
String nm = rs.getString("Item_Name");
s.add(nm);
}
conn.close();
}catch(Exception e2){
e2.printStackTrace();
}
DefaultComboBoxModel<String> modelData = new DefaultComboBoxModel<String>(s);
comboItem.setModel(modelData);
}
Code to add row dynamically on button click :
btnAddOrder.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
tableModel.addRow(dataValues);
tableModel.fireTableDataChanged();
}
});
What should i do to remove this garbage value from table? Please help
The addRow(...) method takes a 1-Dimensional array as a parameter. You are attempting to add a 2-Dimensional array.
Also, do not use:
tableModel.fireTableDataChanged();
it is the job of the TableModel to invoke the appropriate fireXXX() method, which by the way in this case would be fireTableRowsInserted(...).

TableModel, causing duplicate Database Info in a Java JFrame

I have this method setup in a JFrame to be called when the user presses a button to "Load File"; however, when the user presses the button a second time . . . they get another table underneath the first table so all the information gets duplicated and it expands beyond my "non-resizable" frame.
How can I get it to only load the one table no matter how many times the user presses the button?
JButton btnLoad = new JButton("Load File")
private void GetAction()
{
ActionHandler handler = new ActionHandler();
btnLoad.addActionListener(handler);
}
private class ActionHandler implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
String incmd = evt.getActionCommand();
if (incmd.equals("Load File")) // If Load File button is pressed
DatabaseLoad();
else if (incmd.equals("Exit")) // If Exit button is pressed
System.exit(0);
}
}
private void DatabaseLoad()
{
try
{
// The driver allows you to query the database with Java
// forName dynamically loads the class for you
Class.forName("com.mysql.jdbc.Driver");
// DriverManager is used to handle a set of JDBC drivers
// getConnection establishes a connection to the database
// You must also pass the userid and password for the database
String url = "jdbc:mysql://localhost:3306/charity";
conn = DriverManager.getConnection (url,"root","password");
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement sqlState = conn.createStatement();
// This is the query I'm sending to the database
String selectStuff = "SELECT `name`, `charity`, `amount` FROM `charity`.`donations` ";
// A ResultSet contains a table of data representing the
// results of the query. It can not be changed and can
// only be read in one direction
rows = sqlState.executeQuery(selectStuff);
// Temporarily holds the row results
Object[] tempRow;
// next is used to iterate through the results of a query
while(rows.next()){
// Gets the column values based on class type expected
tempRow = new Object[]{rows.getString(1), rows.getString(2), rows.getDouble(3) };
// Adds the row of data to the end of the model
dTableModel.addRow(tempRow);
}
// Successfully loaded, message the user
message1.setText("<html><font color='red'>Database Info Loaded</font>");
message2.setText("");
}
catch (SQLException ex)
{
// String describing the error
System.out.println("SQLException: " + ex.getMessage());
// Vendor specific error code
System.out.println("VendorError: " + ex.getErrorCode());
}
catch (ClassNotFoundException e)
{
// Executes if the driver can't be found
System.out.println("Driver Cannot be found");
e.printStackTrace();
}
// Create a JTable using the custom DefaultTableModel
JTable table = new JTable(dTableModel);
// Increase the font size for the cells in the table
table.setFont(new Font("Serif", Font.PLAIN, 16));
// Increase the size of the cells to allow for bigger fonts
table.setRowHeight(table.getRowHeight()+5);
// Allows the user to sort the data
table.setAutoCreateRowSorter(true);
// right justify amount column
TableColumn tc = table.getColumn("amount");
RightTableCellRenderer rightRenderer = new RightTableCellRenderer();
tc.setCellRenderer(rightRenderer);
// Disable auto resizing
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// Set the width for the columns
TableColumn col1 = table.getColumnModel().getColumn(0);
col1.setPreferredWidth(200);
TableColumn col2 = table.getColumnModel().getColumn(1);
col2.setPreferredWidth(275);
TableColumn col3 = table.getColumnModel().getColumn(2);
col3.setPreferredWidth(75);
// Put the table in a scrollpane and add scrollpane to the frame
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(552, 400));
this.add(scrollPane, BorderLayout.CENTER);
}
// To change justification to the right
class RightTableCellRenderer extends DefaultTableCellRenderer {
public RightTableCellRenderer() {
setHorizontalAlignment(JLabel.RIGHT);
}
}
How can I get it to only load the one table no matter how many times the user presses the button?
The table and scrollpane should only be created once when you build the GUI components. Then when you want to change the data you just change the model of the existing table:
table.setModel( updatedModel );

show data from jTable in jFrame

I have jFrame2 which contains jTable with 4 columns (the jTable taking data from table in database which contain 20 columns)
Also I have jFrame1 which I have used it to fill database.
What I want to do that when I select row in jTable and click jButton, it must open jframe1 showing all data for that row.
i will clear what i want in points
*i want open jframe1 from jframe2 via jbutton(this task is done and this is the code)
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jButton2){
jframe2 regFace =new jframe2();
regFace.setVisible(true);
}}
*once jframe1 opened by jbutton in jframe2 it must show in it fields all data of selected row in jframe2>>this point mean
........-sql query executed once jfram1 opened by Jbutton in jframe2
.........-showing data in jtextfield taking from database by query i mentioned in line above (this task is done and this is the code but not completed)
try {
dbconnect = new myDbConnection();
ResultSet resultSet =null;
resultSet = dbconnect.excuteQuery("SELECT id, area,location, status1 FROM pledges where id='17'");
while (resultSet.next()){
id.setText(resultSet.getString(1));
area.setText(resultSet.getString(2));
location.setText(resultSet.getString(3));
status.setText(resultSet.getString(4));
// i = Long.parseLong(rs1.getString(1));
}
*in brief i want understand jframe1 that please if you opened by jframe2 execute a query and fill text fields by that query
*this is picture would clear better
here
It sounds like the part you are having trouble with is how to get the selected data from the table into the fields in jframe1.
A lot of this depends on the TableModel that is used in your JTable. Assuming you just used a DefaultTableModel, you can get the selected row data like this:
#Override
public void actionPerformed(ActionEvent e) {
int viewRow = myJTable.getSelectedRow();
int modelRow = myJTable.convertRowIndexToModel(viewRow);
DefaultTableModel model = (DefaultTableModel) myJTable.getModel();
// You will get a compiler warning on the following line, but there's not much you can do about it beside suppress it
Vector<Object> rowVector = (Vector<Object>) model.getDataVector().get(modelRow);
jframe2 regFace =new jframe2();
regFace.setSelectedRow(rowVector);
regFace.setVisible(true);
}
And you would have the following method in your jframe2 class:
public void setSelectedRow(Vector<Object> row ) {
id.setText(row.get(0).toString());
area.setText(row.get(1).toString());
location.setText(row.get(2).toString());
status.setText(row.get(3).toString());
// continue for all columns
}
before i put the answer i would thank #wolfcastle such a nice person.He almost answer the question and i'm just modify it to adapt it with sql query and database.
this is the code for jfrme2
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jButton2){
int viewRow = jTable1.getSelectedRow();
int modelRow = jTable1.convertRowIndexToModel(viewRow);
Object oc= jTable1.getModel().getValueAt(modelRow, 0);
String vv=oc.toString();
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
jframe1 regFace =new jframe1();
try {
regFace.setSelectedRow(vv);
} catch (SQLException ex) {
Logger.getLogger(showp1.class.getName()).log(Level.SEVERE, null, ex);
}
regFace.setVisible(true);
}
}
and the the code for jframe1
public void setSelectedRow(String row ) throws SQLException {
dbconnect = new myDbConnection();
ResultSet resultSet =null;
System.out.print(row);
resultSet = dbconnect.excuteQuery("SELECT id, area,location, status1 ,date1,insname,oname,bname,street,junction,INSPSITION,recname1 FROM pledges where id='"+row+"'");
while (resultSet.next()){
id.setText(resultSet.getString(1));
area.setText(resultSet.getString(2));
location.setText(resultSet.getString(3));
status.setText(resultSet.getString(4));
date.setText(resultSet.getString(5));
insname.setText(resultSet.getString(6));
oname.setText(resultSet.getString(7));
bname.setText(resultSet.getString(8));
street.setText(resultSet.getString(9));
junction.setText(resultSet.getString(10));
insposition.setText(resultSet.getString(11));
recname.setText(resultSet.getString(12));
}
}

Categories