I have a JTable that contains one row. I'am using multiple selection interval as a selection mode, besides a new row will be inserted on top of the table after 5 seconds from execution. My problem is: When I run the code and select the first row, after 5 seconds a new row is added (this is OK) but I got two selected rows which I do not want because I need to preserve the old selection,that means after adding the new row only the second row is selected. How to resolve this problem using multiple selection interval mode? Here is my code:
public static void main(String args[]) {
Object[][] rowData = { { "Hello", "World" }, { "By By", "World" } };
Object[] columnNames = { "A", "B" };
JFrame frame = new JFrame("Selecting JTable");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final DefaultTableModel model = new DefaultTableModel(rowData,columnNames);
JTable jtable = new JTable(model);
jtable.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JScrollPane scrollPane1 = new JScrollPane(jtable);
frame.add(scrollPane1, BorderLayout.CENTER);
frame.setSize(640, 300);
frame.setVisible(true);
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
model.insertRow(0, rowData[0]);
}
You can call removeRowSelectionInterval method right after you insert the row.
Something like:
int newRowIndex = 0;
model.insertRow(newRowIndex, rowData[0]);
jtable.removeRowSelectionInterval(newRowIndex, newRowIndex);
Related
i'm trying to place a loop inside a TableModel to loop all the articles inside an arraylist to insert all the rows inside the table so i can add it to the form and show all the articles to the user
public class ListArticlesForm extends Form {
public ListArticlesForm(Form previous) {
setTitle("List all articles");
SpanLabel sp = new SpanLabel();
sp.setText(ServiceTask.getInstance().getAllArticles().toString());
ArrayList<Articles> articles = ServiceTask.getInstance().getAllArticles();
TableModel model = new DefaultTableModel(new String[]{"name", "description", "label", "quantity", "rating", "rate"},
new Object[][]{
{
// I WANT TO PLACE A FOR HERE (this is showing only the first row !
articles.get(0).getName(), articles.get(0).getDescription(), articles.get(0).getLabel(), articles.get(0).getQuantity(), articles.get(0).getRating(), add(createStarRankSlider())
},});
Table table = new Table(model);
add(table);
getToolbar().addMaterialCommandToLeftBar("", FontImage.MATERIAL_ARROW_BACK, e -> previous.showBack());
}
}
You can't create an array as a for loop inside the array. You need to do it a line sooner.
Object[][] rows = new Object[articles.size()][];
for(int iter = 0 ; iter < rows.length ; iter++) {
rows[iter] = new Object[] {
articles.get(iter).getName(), articles.get(0).getDescription(), articles.get(0).getLabel(), articles.get(0).getQuantity(), articles.get(0).getRating(), add(createStarRankSlider())
};
}
TableModel model = new DefaultTableModel(new String[]{"name", "description", "label", "quantity", "rating", "rate"}, rows);
now after 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:
the function for the star rank creation is :
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());
Dialog.show("Success","thank you for rating our product",new Command("OK"));
}
});
return starRank;
}
I have created a jtable that hosts a cell that is a combobox I can get the combobox to populate the jtable but once I restart the program the cells become completely empty. I need a way to save the changes so that once the program is restarted the changes made will remain.( Noted: I have searched solutions for this but to no advance.)
String path ="C:\\Users\\GrantAJ\\Documents\\Comment Matrix";
File folder = new File(path);'File[] listOfFiles= folder.listFiles();
////// filters file objects in java to populate jcombobox with just the name /////
List<String> fileNames = new ArrayList<String>();
for(File files1: listOfFiles){
if(files1.isFile()){
fileNames.add(files1.getName());
}else if (files1.isDirectory())
{ System.out.print("Directory : );
}
final JComboBox jList1 = new JComboBox(listOfFiles);
jList1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
JOptionPane.showMessageDialog(null, files1.getName());
}
});
TableColumn col = jTable_Files_Name.getColumnModel().getColumn(4);
col.setCellEditor(new DefaultCellEditor(jList1));
}
Object[] row = new Object[6];
// fill the rows and columns
row[0] = file.getName();
row[1] = file.getAbsolutePath();
row[2]= dt;
row[3]=sb.toString();
row[4]=files1.getName();
row[5]=hostname;
model.addRow(new Object []{row[0],row[1],row[2],row[3],"",row[5]});
}
}catch(Exception e){e.printStackTrace();}
Try to build an "AbstractTableModel".
This table model will contains your data and could be saved.
To load your model, call new JTable(your_model).
You can look here for more help : http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#data
Good luck.
I have a JTable filled with data about students (student id, name...), and when I select a row from a table, the form opens and its field need to be filled with same values (eg. if Johny Bravo was selected from the table.
Then his name should be shown in text filed Name on the form, I did like this txtfieldName.setText(student.getName).
My question is how do I set my Radio button automatically (my radio button is Male or Female) when I clicked the field.
enter code here
tableGuest.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try{
int row = tableGuest.getSelectedRow();
String guestEdit=(tableGuest.getModel().getValueAt(row, 0).toString());
String query = "Select guest_id,guest_fname,guest_lname,guest_contact,guest_age,guest_gender,guest_address,guest_email from guest_tbl where guest_id= '"+guestEdit+"'";
PreparedStatement pst = con.prepareStatement(query);
ResultSet rs = pst.executeQuery();
buttonGroupEdit.add(rdbtnMaleEdit);
buttonGroupEdit.add(rdbtnFemaleEdit);
while(rs.next())
{
String genderEdit=rs.getString("guest_gender");
if(genderEdit.equals("Male"))
{
rdbtnMaleEdit.setSelected(true);
}
else if(genderEdit.equals("Female"))
{
rdbtnFemaleEdit.setSelected(true);
}
else
{
JOptionPane.showMessageDialog(null, "error !");
}
tfEditFname.setText(rs.getString("guest_fname"));
tfEditLname.setText(rs.getString("guest_lname"));
tfEditEmail.setText(rs.getString("guest_email"));
tfEditContact.setText(rs.getString("guest_contact"))
}
pst.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
});
String gender = "male"
// this comes from db - since we don't know the structure this is a plain guess.
if (gender.equals("male") {
rbtMale.setSelected(true);
} else {
rbtFemale.setSelected(true);
}
And like MadProgrammer said, you will need a ButtonGroup and add all relevant buttons to it.
private final ButtonGroup genderButtons = new ButtonGroup();
genderButtons.add(rbtMale);
genderButtons.add(rbtFemale);
I've worked with same kinda solution in my work I am generating radiobutton with database values and showing them in java dialog.
We have a values from database stored in list like below:
List Titles; //This is a list containing your database values
First count the values of this list elements:
int list_count=Titles.size();
Now to proceed with radio function first we need to convert list elements into array like below:
String[] col = new String[list_count]; //created an array with limit of list count values
for(int i=0; i < list_count; i++){
col[i]=Titles.get(i).toString(); // add values of list into array with loop
}
Below is the function that is creating radio buttons with database array we created above:
public String get_key(int list_count, String[] col){
JRadioButton jb[] = new JRadioButton[col.length]; //Create Radion button array
ButtonGroup rb = new ButtonGroup(); //Group Radio Button
JPanel panel = new JPanel( new GridLayout(0, 1) ); //Set layout of radion button to display each after other
JScrollPane sp = new JScrollPane(panel); // Create a scrollpane to put all these radio button on that
GridBagLayout gridbag = new GridBagLayout(); //Layout for scrollpane
sp.setViewportBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); //bordre for scrollpane
List<Component> q = new ArrayList<>(); // q is a component to store and display each radio button
JLabel h1=new JLabel("Select a value"); //put a heading on top of jpanel before radio button
h1.setFont(new Font("Serif", Font.BOLD, 18)); // set heading text
panel.add(h1); //add heading on top of jpanel
panel.setBorder(new EmptyBorder(10, 10, 10, 10)); //set panel border to padding each radio button
for(int i=0; i < list_count; i++){
jb[i]=new JRadioButton(col[i]); //create radion button dynamacially "col[i]" is the value of each radio
rb.add(jb[i]); //it is important also to put all radio in a group we created so only one element should be selected
panel.add(jb[i]); // add all radio on jpanel
}
sp.setPreferredSize( new Dimension( 350, 300 ) ); //set size of scrollpane
int act=JOptionPane.showConfirmDialog(null, sp, "Select Primary Key",JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE); //add and show scrollpane in dialog
}
Calling this function with parameter values we created first "list_count" & "col":
get_key(list_count, col);
Create a Student.java class to get particular table value from database.
In the current form AddStudent create a function call as getStudentList to fill the GUI form with database data to particular id.
public ArrayList<Student> getStudentList() {
ArrayList<Student> studentList = new ArrayList<>();
conn = DbConnection.ConnectDb();
String selectQuery = "SELECT * FROM student";
try {
PreparedStatement pst = conn.prepareStatement();
ResultSet rs = pst.executeQuery();
Donor donor;
while(rs.next()) {
student = new Student(rs.getString("id"),
rs.getString("gender"));
studentList.add(student);
}
} catch (SQLException ex) {
Logger.getLogger(Student.class.getName()).log(Level.SEVERE, null, ex);
}
return studentList;
}
After create a function called showStudent to show the particular data value to called id.(In below code male,female are the checkbox values)
public void showStudent(int index) throws ParseException {
if(getStudentList().get(index).getGender().equals("male")) {
male.setSelected(true);
female.setSelected(false);
gender = "male";
}
else {
female.setSelected(true);
male.setSelected(false);
gender = "female";
}
}
Set action to the jbutton, When get value id from jtextfield then fill the checkbox in particular gender value.
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);
}
});
I am trying to add values to a Jtable, the values are fetched from arrayList,
How do you do that
I tried making Object[][] data; and the populate it inside a loop, but it does not work, How do you fix this?
String[] columns = {"Field String","Field Double"," Field Double"};
Object[][] data;
Iterator<Node> itr = arrayList.iterator();
while (itr.hasNext()) {
Node el = itr.next();
double a = el.getval();
data[i][1] = el.getstring();
data[i][2] = a;
data[i][3] = a*4;
i++;
}
JFrame frame = new JFrame("Title ");
JTable tablE = new JTable(data, columnas);
JPanel panel = new JPanel();
panel.add(table);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
How do you populate "data" inside a while loop?
Use a DefaultTableModel and add rows of data using its addRow(Object[]) or addRow(Vector) method. Set this as your JTable's model. The API and the JTable tutorial can get you started.
For e.g.,
ArrayList arrayList = new ArrayList();
String[] columns = {"Field String","Field Double"," Field Double"};
DefaultTableModel model = new DefaultTableModel(columns, 0);
for (Object item : arrayList) {
Object[] row = new Object[3];
//... fill in row with info from item
model.addRow(row);
}
JTable table = new JTable(model);
This demonstrates doing it with a for loop, but a while loop would be similar.