Good afternoon guys, i'm trying to learn java programming and then i'm encountering some problem that i don't know why with my code when I'm learning about JTable.
So, what I'm trying to do is when i double clicked the row in JTable named TableGejala, the row that i double clicked will transfered into the other JTable named TableAturan and after that the row that i double clicked in TableGejala will be removed. For the part of transferring row from TableGejala to TableAturan successfully transferred when i double clicked the row, but it doesn't delete the correct row in TableGejala. Instead of deleting the row that i clicked, it delete the row below it.
For more details, this is my code to create TableGejala :
private void getTableGejala() {
while(tabel2.getRowCount() > 0){
for(int i=0;i < tabel2.getRowCount();i++){
tabel2.removeRow(i);
}
}
tabel2.addColumn("ID Gejala");
tabel2.addColumn("Nama Gejala");
TabelGejala.setModel(tabel2);
TabelGejala.setAutoResizeMode(TabelGejala.AUTO_RESIZE_ALL_COLUMNS);
}
And then this is my code to get data for my table from MySQL :
private void loadDataGejala(Boolean baru){
tabel2.getDataVector().removeAllElements();
try {
java.sql.Connection konek = (Connection) Koneksi.KoneksiDB.getConnection();
java.sql.Statement konek_statement = konek.createStatement();
String query_bukaTabel = "";
if(baru){
query_bukaTabel = "select id_gejala,nama_gejala from gejala";
}
else{
String idPkt = FieldID.getText();
query_bukaTabel = "select gejala.id_gejala,gejala.nama_gejala from gejala where gejala.id_gejala not in(select id_gejala from aturan2 where id_penyakit='"+idPkt+"')";
}
java.sql.ResultSet line_result = konek_statement.executeQuery(query_bukaTabel);
while (line_result.next()) {
Object[] getO = new Object[2];
getO[0] = line_result.getString("id_gejala");
getO[1] = line_result.getString("nama_gejala");
tabel2.addRow(getO);
}
line_result.close();
konek_statement.close();
}catch (Exception e) {}
}
This is my code to transfer the row and delete the row :
private void TabelGejalaMousePressed(java.awt.event.MouseEvent evt) {
if (evt.getClickCount()>=2){
int col = 0;
int row = 0;
row = TabelGejala.rowAtPoint(evt.getPoint());
col = TabelGejala.columnAtPoint(evt.getPoint());
String col1 = (String)TabelGejala.getValueAt(row, 0);
String col2 = (String)TabelGejala.getValueAt(row, 1);
DefaultTableModel model = (DefaultTableModel) TabelAturan.getModel();
DefaultTableModel old = (DefaultTableModel) TabelGejala.getModel();
old.removeRow(row);
model.addRow(new Object[]{col1, col2, 0});
TabelAturan.requestFocus();
TabelAturan.setRowSelectionInterval(TabelAturan.getRowCount()-1,TabelAturan.getRowCount()-1);
TabelAturan.editCellAt(TabelAturan.getRowCount()-1,2);
}
}
And this is the screenshot of my problem :
Before Double Clicked
After Double Clicked
Which part that makes my output get the wrong row to be deleted? please help me, and thank you in advance for any helps, even for reading my question :)
Firstly disable cell editable property in your first table(TabelGejala) to ensure proper deleting of row. I achieved this using the following code :-
//instance table model
DefaultTableModel tableModel = new DefaultTableModel(new Object[][]{},
new String[]{
"ID Gejala", "Nama Gejala"
}) {
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
TabelGejala.setModel(tableModel);
then use jtable.getselectedrow() and jtable.getselectedcolumn() to get values from table. after addition of desired values to second table, simply delete the selected row. here is the code, derived from your code :-
private void TabelGejalaMousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
if (evt.getClickCount() >= 2) {
DefaultTableModel model = (DefaultTableModel) TabelAturan.getModel();
DefaultTableModel old = (DefaultTableModel) TabelGejala.getModel();
model.addRow(new Object[]{TabelGejala.getValueAt(TabelGejala.getSelectedRow(), 0), TabelGejala.getValueAt(TabelGejala.getSelectedRow(), 1), 0});
old.removeRow(TabelGejala.getSelectedRow());
TabelAturan.requestFocus();
TabelAturan.setRowSelectionInterval(TabelAturan.getRowCount() - 1, TabelAturan.getRowCount() - 1);
TabelAturan.editCellAt(TabelAturan.getRowCount() - 1, 2);
}
}
Related
when I Run the project the table rows are displayed correctly except the rank stars the show outside the table and inside the colonne a text appears as displayed in the image :
public ListTasksForm(Form previous) {
SpanLabel sp = new SpanLabel();
sp.setText(ServiceTask.getInstance().getAllArticles().toString());
ArrayList<Articles> articles = ServiceTask.getInstance().getAllArticles();
Object[][] rows = new Object[articles.size()][];
for (int iter = 0; iter < rows.length; iter++) {
rows[iter] = new Object[]{
articles.get(iter).getName(), articles.get(iter).getDescription(), articles.get(iter).getLabel(), articles.get(iter).getQuantity(),
articles.get(iter).getRating(), add(createStarRankSlider(articles.get(iter).getId_article()))
};
}
TableModel model = new DefaultTableModel(new String[]{"name", "description", "label", "quantity", "rating", "rate"}, rows);
Table table = new Table(model);
add(table);
getToolbar().addMaterialCommandToLeftBar("", FontImage.MATERIAL_ARROW_BACK, e -> previous.showBack());
}
});
and this is the function for the star rank creation
private Slider createStarRankSlider(int id) {
Slider starRank = new Slider();
starRank.setEditable(true);
starRank.setMinValue(0);
starRank.setMaxValue(10);
int fontSize = Display.getInstance().convertToPixels(3);
Font fnt = Font.createTrueTypeFont("Handlee", "Handlee-Regular.ttf").
derive(fontSize, Font.STYLE_PLAIN);
Style s = new Style(0xffff33, 0, fnt, (byte) 0);
Image fullStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage();
s.setOpacity(100);
s.setFgColor(0);
Image emptyStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage();
initStarRankStyle(starRank.getSliderEmptySelectedStyle(), emptyStar);
initStarRankStyle(starRank.getSliderEmptyUnselectedStyle(), emptyStar);
initStarRankStyle(starRank.getSliderFullSelectedStyle(), fullStar);
initStarRankStyle(starRank.getSliderFullUnselectedStyle(), fullStar);
starRank.setPreferredSize(new Dimension(fullStar.getWidth() * 5, fullStar.getHeight()));
starRank.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
ServiceTask.getInstance().UpdateRank(id,starRank.getIncrements());
}
});
return starRank;
}
You didn't include the code for the initStarRankStyle but it's pretty obvious what you did here. You just relied on the behavior of the container. Table derives Container so it includes all of its methods e.g. add(Component).
But these methods won't work correctly since a table fetches its data from the model and invokes add internally. So you're logic is conflicting with the table.
You need to derive table and define how you want that data to be rendered. You can do that by overriding the method protected Component createCell(Object value, int row, int column, boolean editable) as explained here.
I have never used tableview before and I am quite new to with Java and JavaFX. I tried to mirror an example but since the data is coming from a db client created in house I couldn't copy it exactly. Anyway, my data is going into the table but its entering as what looks like a csv data and each column is not getting put into its respective column. Here is a screenshot to clarify my question:
Getting columns here
for (Column col : drs.getColumns()){
TableColumn tblCol = new TableColumn(col.getName());
tblCol.setCellValueFactory(new Callback<CellDataFeatures<ObservableList,String>,ObservableValue<String>>(){
public ObservableValue<String> call(CellDataFeatures<ObservableList, String> p) {
return new SimpleStringProperty(p.getValue().toString());
}
});
table.getColumns().addAll(tblCol);
}
Getting the rows here:
while (drs.hasNextRow()) {
ObservableList<String> row = FXCollections.observableArrayList();
for (int i = 0; i < drs.getColumns().length; i++) {
row.add(drs.getNextRow().getItem(i) + "");
}
data.add(row);
}
And here is where I fail at sending the data to the table.
table.setItems(data);
System.out.println("dis is data: " +data);
the data prints like so:
dis is data: [[data, data, data....], [data, data, data....], [data, data, data....]]
It takes each [row] and puts it into each column for each record. I am assuming I need the data to look like:
[[data], [data], [data]....[data]], [[data], [data], [data]....[data]], [[data], [data], [data]....[data]]
} catch(Exception e){
e.printStackTrace();
System.out.println("everything is broken");
}
}
So, I am lost. I don't know what I am doing and I'd appreciate any help that you can offer me.
In TableView all the data in a row is associated with a item. The TableColumn.cellValueFactory is used to select the "part" of a item that should be shown in the column. Therefore you should use it to select the value:
TableView<ObservableList<String>> table = ...
int index = 0;
for (Column col : drs.getColumns()) {
final int columnIndex = index++;
TableColumn<ObservableList<String>, String> tblCol = new TableColumn(col.getName());
tblCol.setCellValueFactory(new Callback<CellDataFeatures<ObservableList<String>, String>, ObservableValue<String>>(){
public ObservableValue<String> call(CellDataFeatures<ObservableList, String> p) {
return Bindings.stringValueAt(p.getValue(), columnIndex);
}
});
table.getColumns().add(tblCol);
}
Here the Bindings.stringValueAt is used to select the element form the ObservableList.
Also you need to use one row per row:
while (drs.hasNextRow()) {
ObservableList<String> row = FXCollections.observableArrayList();
Row sourceRow = drs.getNextRow();
for (int i = 0; i < drs.getColumns().length; i++) {
row.add(Objects.toString(sourceRow.getItem(i)));
}
data.add(row);
}
I am having a small problem of showing results from my database to a JTable. It displays all of the data correctly, but at the moment it is showing "true" or "false" for boolean.
I know it must be because I am using getString, but does anyone know what to use in order to change it to a checkbox instead?
Current JTable:
My Database:
Code:
connection con=new connection();
Connection getcon=null;
Vector col = new Vector();
Vector dat= new Vector();
ResultSet rs = null;
try{
getcon = con.creatConnection();
col.add("Fanta");
col.add("Crisps");
col.add("Beer");
col.add("Wine");// create income table default colum names and sore it
col.add("Water");
col.add("Seat Row");
col.add("Seat");
col.add("Total Cost");
rs=getcon.createStatement().executeQuery("select*from orders"); //getting all the information from the table
dat.clear();
while(rs.next()){// if record source avilable
Vector v =new Vector();
v.add(rs.getString("Fanta").trim());
v.add(rs.getString("Crisps").trim());
v.add(rs.getString("Beer").trim());
v.add(rs.getString("Wine").trim());// getting income values from database and store in dat
v.add(rs.getString("Water").trim());
v.add(rs.getString("SeatRow").trim());
v.add(rs.getString("Seat").trim());
v.add(rs.getString("TotalCost").trim());
dat.add(v);
}
orderResults.setModel(new DefaultTableModel(dat, col));
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
First you have to save data as a Boolean in your model. So you should use this rs.getBoolean("Fanta") instead of rs.getString("Fanta").trim().
Second, you have to override a public Class getColumnClass(int column) method from your JTable. Your code could look like this:
JTable orderResults = new JTable() {
#Override
public Class getColumnClass(int column) {
// first 5 columns will be represented as an checkbox
if(column <= 4){
return Boolean.class;
}
// rest of them as a text
return String.class;
}
};
I have a jtable I populated from a database , but I want to enable or gray out some of this jtable lines ( lines that exist in another table of the same database) for the user cannot check the checkbox of these lines, but the rest of the lines ( lines that do not exist in this table ) can always be checked.
for (int m = 0; m < tb_doublon.getRowCount(); m++) {
Statement statdouble=null;
ResultSet rsdouble=null;
//I get the value of the cell of the column 1 :id, line : i
String id = (String)tb_doublon.getValueAt(m, 1);
String cli = (String)tb_doublon.getValueAt(m, 2);
//i browse the other table to enable or gray out the lines existing in that table with th id
String doubleexistant ="select * from doublon where id='"+id+"' and cli='"+cli+"'" ;
statdouble = conn.createStatement();
rsdouble = statdouble.executeQuery(doubleexistant);
while (rsdouble.next()) {
//i think this is here that i must enable or gray out the lines but i don't know how !!!!<br>
}
}
sir, you can create your checkboxes in an array for accessing them easier.
JCheckBox [] checkboxes= new JCheckBox[WIDTH];
if you found 2nd index to be duplicate you can simply disable the 2nd checkbox in your array
checkboxes[1].setEnabled(false);
Coloring a row can be perform using a modified TableCellRenderer. I have created a customized TableCellRenderer as follows.
ColorTableRenderer.java
It can add rows to be mark as gray, and clear all marked rows.
public class ColorTableRenderer extends DefaultTableCellRenderer {
//contains row indexes which need to color
private final List<Integer> colorIndexes = new ArrayList<>();
//add new index to show as color
public void addColorIndex(Integer index) {
colorIndexes.add(index);
}
//clear all color indexes
public void clearColorIndexes() {
colorIndexes.clear();
}
private boolean isColorIndex(Integer index) {
return colorIndexes.contains(index);
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component component = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (isColorIndex(row)) {//check if marked as colored
component.setBackground(Color.LIGHT_GRAY);//highlight color
} else {
component.setBackground(Color.WHITE);//other color
}
return component;
}
}
Using the ColorTableRenderer
Set the ColorTableRenderer to the table using one of following methods.
ColorTableRenderer renderer = new ColorTableRenderer();
//set TableCellRenderer into a specified JTable column class
table.setDefaultRenderer(String[].class, renderer);
//or, set TableCellRenderer into a specified JTable column
table.getColumnModel().getColumn(columnIndex).setCellRenderer(renderer);
Considering your code, you can add following modifications to make selected row color.
renderer.clearColorIndexes();
for (int m = 0; m < tb_doublon.getRowCount(); m++) {
Statement statdouble = null;
ResultSet rsdouble = null;
//I get the value of the cell of the column 1 :id, line : i
String id = (String) tb_doublon.getValueAt(m, 1);
String cli = (String) tb_doublon.getValueAt(m, 2);
//i browse the other table to enable or gray out the lines existing in that table with th id
String doubleexistant = "select * from doublon where id='" + id + "' and cli='" + cli + "'";
statdouble = conn.createStatement();
rsdouble = statdouble.executeQuery(doubleexistant);
while (rsdouble.next()) {
renderer.addColorIndex(m);
}
}
This is my tested screen-shot
Since the program is too large I'll just paste the important parts of code. Here's the problem:
I have two JTables. First one collects data from DB and displays the list of all invoices stored in DB. The purpose of the second table is when you click on one row from the table, event handler needs to collect integer from column ID. Using this ID the second table will then display all the contest of that invoice (all the products stored in it).
First and second table work perfectly. The problem is that I have no idea how can I collect certain data (I basically just need ID column) from a selected row and then through a method I already made update the second JTable with new info. Here's my code if it helps:
(PS: once I learn how to do that, will the list on the left change every time by default when I select different row, or do I need to use validate/revalidate methods?)
public JPanel tabInvoices() {
JPanel panel = new JPanel(new MigLayout("", "20 [grow, fill] 10 [grow, fill] 20", "20 [] 10 [] 20"));
/** Labels and buttons **/
JLabel labelInv = new JLabel("List of all invoices");
JLabel labelPro = new JLabel("List of all products in this invoice");
/** TABLE: Invoices **/
String[] tableInvTitle = new String[] {"ID", "Date"};
String[][] tableInvData = null;
DefaultTableModel model1 = new DefaultTableModel(tableInvData, tableInvTitle);
JTable tableInv = null;
/** Disable editing of the cell **/
tableInv = new JTable(model1){
public boolean isCellEditable(int r, int c) {
return false;
}
};
/** Load the invoices from DB **/
List<Invoice> listInv = is.getAllInvoices();
for (int i = 0; i < listInv.size(); i++) {
model1.insertRow(i, new Object[] {
listInv.get(i).getID(),
listInv.get(i).getDate()
});
}
/** TABLE: Invoice Info **/
String[] tableInfTitle = new String[] {"ID", "Name", "Type", "Price", "Quantity"};
String[][] tableInfData = null;
DefaultTableModel model2 = new DefaultTableModel(tableInfData, tableInfTitle);
JTable tableInf = null;
/** Disable editing of the cell **/
tableInf = new JTable(model2){
public boolean isCellEditable(int r, int c) {
return false;
}
};
/** Load the products from DB belonging to this invoice **/
List<Product> listPro = is.getInvoiceInfo(1); // Here's where I need the ID fetched from selected row. For now default is 1.
for (int i = 0; i < listPro.size(); i++) {
model2.insertRow(i, new Object[] {
listPro.get(i).getID(),
listPro.get(i).getName(),
listPro.get(i).getType(),
listPro.get(i).getPrice(),
listPro.get(i).getQuantity()
});
}
/** Scroll Panes **/
JScrollPane scrollInv = new JScrollPane(tableInv);
JScrollPane scrollPro = new JScrollPane(tableInf);
panel.add(labelInv);
panel.add(labelPro, "wrap");
panel.add(scrollInv);
panel.add(scrollPro);
return panel;
}
For now, the right table only displays content of the first invoice:
With the help of following code you can get the value of selected clicked cell, so you just have to click on ID cell value (the Invoicee ID whose Products you want to see in second table) and with the help of following event handler you will get the value and then you can get data based on that ID and set to second table. (In the code below, table is the object of your first table)
(Off-course you will have to apply some validation too, to check that the selected (and clicked) cell is ID not the DATE)
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
int row = table.rowAtPoint(e.getPoint());
int col = table.columnAtPoint(e.getPoint());
Object selectedObj = table.getValueAt(row, col);
JOptionPane.showMessageDialog(null, "Selected ID is " + selectedObj);
}
});