I've created a JTable using following way. This table has 5 columns and 4 rows.
All 4 rows are empty in this status.
String[] columns = {"Emplotee ID","Name","Address","City","Salary"};
//Table that already have 4 empty rows
DefaultTableModel model = new DefaultTableModel(columns,4);
JTable detail = new JTable(model);
JScrollPane scroll = new JScrollPane(detail);
Now I want to add values into those empty rows using String array.
The GUI of this program has 5 JTextFields to get user input. When I enter values into JTextFileds and click Add button, all JTextFiled values get by String array named values.
String[] values = new String[6];
//When click addButton all textFiled data should go into table
addButton.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent evt){
values[0] = idField.getText(); //get JTextFields data into array
values[1] = nameField.getText();
values[2] = addressField.getText();
values[3] = cityField.getText();
values[4] = salaryField.getText();
//What now?
}
});
I know I can use this to add new row into the table. But this is not the feature what I want.
DefaultTableModel newModel = (DefaultTableModel)detail.getModel();
newModel.addRow(values);
Set contents of an existing table row with:
int row;
....
// make sure row is set to index of the table row
// you want to populate
for (int c=0; c<values.length; ++c)
detail.setValueAt(values[c], row, c);
TableModel also has setValueAt method, if you prefer.
Related
I was trying to write the GUI for my program. I have a Product class in which I store price and names of the products in an arraylist. I also have an Order arraylist which consists of the orders given to each waiter.I put all my products in a JComboBox and added an action listener to each to show the price of each product when clicked by updating the text of a JLable. Then there is a JSpinner to get the quantity of the products selected. And lastly there is an "Add" button that I wanted to use to update the Jtable with product name and its quantity and its total price while also adding that product to the arraylist of Orders. I have no idea how populate JTable and couldn't understand much from other answers because they were using netbeans. I thought of just using a simple JLabe but also I couldn't understand how to update the text and add a new line to the label after I select and add each product. Can you explain how I can achieve this? part of my code looks like this
box1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Product prod = (Product) box1.getSelectedItem();
price.setText(String.valueOf(prod.getSellingPrice()));
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int numbs = (Integer) spinner.getValue();
for (int i = 0; i <= numbs; i++) {
order.addProduct(prod);
}
JLabel label = new JLabel();
lists.add(label);
label.setText(prod.getName() + " " + numbs + " " + numbs * prod.getSellingPrice());
}
});
}
});
If I understand your question correctly, you want a JTable in your gui, which shows the orders (or other data possibly) if a button is clicked.
Firstable, I would advise you to check out
https://docs.oracle.com/javase/tutorial/uiswing/components/table.html
as they explain the use of the JTable very well.
Anyway, to answer your question:
Firstable, you have to create a table and add it to your gui:
//creating a new JTable without any data and one column 'Orders'
//you might wanna declare the JTable before that, since it will be referred to in the refresh() method
JTable table = new JTable(new String[][]{{""}}, new String[]{"Orders"});
//creating a scrollpane to put the table in, in case the table data exeeds the table
JScrollPane scrollPane = new JScrollPane();
//here you would e.g. set the bounds of the scrollpane etc
scrollPane.setBounds(x,y,w,h)
//setting the table in the scrollpane
scrollPane.setViewportView(table);
//adding the scrollpane to your contentPane
contentPane.add(scrollPane);
Now you want to refresh the table, if a button is pressed, so I would put a reference to the following method in the actionlistener of the button:
//the method to refresh the table containing the orders (or possibly other data)
void refresh(List<String> orders) {
//creating a new TableModel for the table
DefaultTableModel model = new DefaultTableModel();
//set the data in the model to the data that was given, new Object[]{0} points to the 1st column
model.setDataVector(getDataVector(data), new Object[]{"Orders});
//set the model of the table to the model we just created
table.setModel(model);
}
Since model.setDataVecor() takes rows and not columns as its first parameter, you have to make the list of data fitting as a data vector, for example with the following method:
Object[][] getDataVector(List<String> data){
Object[][] vector = new Object[data.size()][1];
for(int i=0; i<data.size(); i++){
vector[i][0] = data.get(i);
}
return vector;
}
I have a Swing program with a JTable, and there are two columns: one for names, and one for phone numbers associated with those names. Currently, the program allows for selection of rows, which causes data in both columns to become selected. I want selected data to be output to an array of strings, but only the data from within a certain column (that with phone numbers), no matter how many rows are selected. How would I go about this?
I was thinking of changing setColumnSelectionAllowed(false) to setColumnSelectionAllowed(true) and allowing a JHeader to be clicked to select an entire row, or somehow allowing for getValueAt(int row, int column) to be put into an array and only allow for reading of the phone numbers column.
Code for initializing table:
// Initializing the JTable
String[] columns = {"Student", "Phone"};
students = new JTable(data, columns);
students.setGridColor(Color.lightGray);
students.setPreferredScrollableViewportSize(new Dimension(500, 400));
TableColumnModel columnModel = students.getColumnModel();
columnModel.getColumn(0).setPreferredWidth(100);
columnModel.getColumn(1).setPreferredWidth(100);
students.setRowHeight(25);
students.setFillsViewportHeight(true);
students.setRowSelectionAllowed(true);
students.setColumnSelectionAllowed(false);
students.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
Table is made from CSV file as an array:
String[][] myNewArray1 = new String[30][30]; //creates an array
Scanner myScanner1 = new Scanner(filePath1); //creates a scanner which uses the text file
int k = 0;
while (myScanner1.hasNext()) {
myNewArray1[k] = myScanner1.nextLine().split(",");
k++;
}
return (myNewArray1);
}
// Driver method
public static void main(String[] args) throws Exception {
File filePath1 = new File("C:\\Users\\cmorl\\IdeaProjects\\CompSciIA\\src\\CompSciIA.csv"); //file path
String[][] data1;
data1 = makeArrayFromTxt(filePath1);
new Database(data1);
}
TableModel model = table.getModel();
List <String> data = new ArrayList();
for (int count = 0; count < model.getRowCount(); count++){
data.add(model.getValueAt(count, 0).toString()); //Change 0 with 1 if you want column 2
}
I have a table with some data. I want to select a couple of rows which I want to monitor (I will then display these rows in a new JFrame with its own table) - let's call this monitored records.
I have this piece of code I found that does this exactly, but it creates the new table with the same number of rows as the original table. It however does show the new selected rows successfully but it populates the new table from the bottom going up.
For instance my original table has 10 rows, I select 3, the new table will have 10 rows in total, but only 8, 9 and 10 are populated with the selected data and rows 1 to 7 just have empty cells.
How do I make it only show the selected data and not the empty rows?
public void exportSelectedRows(ActionEvent actionEvent) {
TableModel tableModel = patientTable.getModel();
int[] index = patientTable.getSelectedRows();
Object[] row = new Object[10]; //problem is here that object has size 10 hence the 10 rows?
monitoredPatients = new MonitoredPatients();
monitoredPatients.monitoredPatientsTable = new JTable(row.length, columnNames.length);
DefaultTableModel defaultTableModel = (DefaultTableModel) monitoredPatients.monitoredPatientsTable.getModel();
for (int value : index) {
row[0] = tableModel.getValueAt(value, 0);
row[1] = tableModel.getValueAt(value, 1);
row[2] = tableModel.getValueAt(value, 2);
row[3] = tableModel.getValueAt(value, 3);
row[4] = tableModel.getValueAt(value, 4);
row[5] = tableModel.getValueAt(value, 5);
defaultTableModel.addRow(row);
}
monitoredPatients.add(new JScrollPane(monitoredPatients.monitoredPatientsTable));
}
I expect the new table to only show the selected records with no empty rows.
row = new Object[10]; //problem is here that object has size 10 hence the 10 rows?
..
monitoredPatients.monitoredPatientsTable = new JTable(row.length, columnNames.length);
Well you have a couple of problems:
Why would you create the row Array with a value of 10? The row array represents the data for each row. You only copy 6 columns of data, so the size of the array should only be 6.
The value for the number of rows should be 0, since you are starting with an empty DefaulotTableModel. You then use the addRow(...) method to add a new row of data. This makes the size of your TableModel dynamic.
So the code should be:
monitoredPatients.monitoredPatientsTable = new JTable(0, columnNames.length);
Or better yet, why don't you create the TableModel with the array containing the name of the columns? I'm sure you don't want to see "A, B, C, D, E, F", which will be the default if you just specify the number of columns. Read the DefaultTableModel API for the appropriate constructor to use.
I have a jtable.
Some of the cells contain very long strings and trying to scroll left and right through it is difficult. My question is whether it is possible to show a row from a JTable in a pop-up eg showDialog type box (ie where the selected row is organised as a column).
Even a link to a tutorial would do.
I have scoured the internet but I don't think I'm really using the correct keywords as I get a lot of right-click options.
If this is not possible are there any other suggestions for how to do this?
As shown here, the JOptionPane factory methods will display the Object passed in the message parameter. If that message is a one column JTable, you can recycle any custom renderers and editors that were applied to the original table.
In outline,
Add a ListSelectionListener to your table and get the selectedRow.
Iterate through the table's model and construct a newModel whose rows are the columns of the selectedRow.
Create a JTable newTable = new JTable(newModel).
Apply any non-default renderers and editors.
Pass a new JScrollPane(newTable) as the message parameter to your chosen JOptionPane method.
Starting from this example, the following listener displays the dialog pictured.
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
int selectedRow = table.convertRowIndexToModel(table.getSelectedRow());
if (selectedRow > -1) {
DefaultTableModel newModel = new DefaultTableModel();
String rowName = "Row: " + selectedRow;
newModel.setColumnIdentifiers(new Object[]{rowName});
for (int i = 0; i < model.getColumnCount(); i++) {
newModel.addRow(new Object[]{model.getValueAt(selectedRow, i)});
}
JTable newTable = new JTable(newModel) {
#Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(140, 240);
}
};
// Apply any custom renderers and editors
JOptionPane.showMessageDialog(f, new JScrollPane(newTable),
rowName, JOptionPane.PLAIN_MESSAGE);
}
}
});
I want to show all the values in the row, each in their cel, organised vertically- that's what I meant by 'in a column'.
That should be in the question, not in the comment.
There is no default functionality for this but you can do it yourself.
You could create a JPanel (maybe using a GridBagLayout), with two labels in a row to represent the data in a column of the selected row of the table.
For the data in the first label you would use the getColumnName(...) method of the TableModel.
For the data in the second label you would use the getValueAt(...) method of the TableModel.
Another option is to simply display a tool tip for the cell. See the section from the Swing tutorial on Specifying ToolTips For Cells for more information.
You may use the following ListSelectionListener:
final JTable dialogTable =new JTable();
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent event) {
int selectedRow = table.getSelectedRow();
if (selectedRow > -1) {
int columnCount = table.getModel().getColumnCount();
Object[] column = new Object[]{"Row "+(selectedRow+1)};
Object[][] data = new Object[columnCount][1];
for (int i = 0; i < columnCount; i++) {
Object obj = table.getModel().getValueAt(selectedRow, i);
data[i][0] = obj;
}
dialogTable.setModel(new DefaultTableModel(data, column));
JOptionPane.showMessageDialog(null, new JScrollPane(dialogTable));
}
}
});
This is going to show a message dialog which contains a JTable with data that is derived from the selected row. Hope this helps you.
I want to print only selected rows in a JTable.
My approach is to make a new TableModel, copy the selected rows there, add the tableModel to a new JTable and then print this new Table.
My Problem: It doesnt work as expected, I just see a black line with the height of the rows, if i select lesser rows the line is smaller) but no content. But the content is in the table model, i can see it when i do system.out...
this is my code:
QueryTableModel tempModel = new QueryTableModel(String[] tableheaders);
JTable tempTable = new JTable();
for(int i : table.getSelectedRows())
tempModel.addRow(((QueryTableModel)table.getModel()).getRowAt(i));
System.out.println(tempModel.getRowCount());
tempTable.setModel(tempModel);
tempTable.print(JTable.PrintMode.FIT_WIDTH, header, null);