I have two tables and I need to add the value from specific cell in table_3 to table_4 .. but its not working. Any help please?
Code :
JTable table_3 = new JTable(TableModel2);
final JTable table_4 = new JTable(TableModel3);
JButton btnAdd = new JButton("add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table_3.getSelectedRow();
int column = table_3.getSelectedColumn();
Object selectedPlanet = TableModel2.getValueAt(row, column);
int columnContainingPlanets = 0;
for (int index = columnContainingPlanets; index < TableModel3.getRowCount();index ++){
Object value = TableModel3.getValueAt(index, columnContainingPlanets) ;
if (value == selectedPlanet) {
JOptionPane.showMessageDialog(panel_10,"This item was selected ,Please select another item");
return; }}
TableModel3.addRow(new Object[] { selectedPlanet });
}
});
Still waiting for your Minimal, Complete, and Verifiable Example(MCVE). What makes you think the problem is in the code you posted? Until a problem is solved every question should have a simple example demonstrating the problem which proves that you tried to simplify problem to better debug it.
What is the point of posting the error message without indicating the line of code causing the problem? Again another reason to post the MCVE. You don't know until the question is answered what information is needed to solve the problem.
Without all the information all we can do is guess.
As a newbie to the forum you get one guess. Future questions will require an MCVE
My guess is that the "tableModel3" doesn't have any columns, so you can't add a row to the model containing a single column of data.
So the model should be created with code something like:
String[] columnNames = { "Planets" };
DefaultTableModel tableModel3 = new DefaultTableMNodel(columnNames, 0);
Related
I have a problem since yesterday.
I'v created a jTable with the WindowBuilder in Eclipse and currently are trying to get the number of the selected row, by using the .getSelectedRow() function, but it is always returning -1 (no row selected), even when I have selected something.
This is my current code for testing the output:
public void checkActiveItem() {
System.out.println(tableBills.getSelectedRow());
}
I try to let it run this way trough a timer and at least that seems working:
Timer time = new Timer();
time.schedule(new TimerTask() {
public void run() {
Frontend f = new Frontend();
f.checkActiveBill();
f.checkActiveItem();
}
}, 250, 250 );
The table currently has just one entry, but even the first row dosn't get returned on selection.
I can create new rows by clicking add (and name them by entering a name in the textfield next to the add button before)
To create a new row I use this code, maybe there is the problem?
public void addBill() {
//maybe need this value somewhere else to, so let -1 and +1 as it is
int numbersOfBills = tableBills.getRowCount() - 1;
Bill newBill = new Bill(txtBillName.getText(), numbersOfBills + 1);
DefaultTableModel billModel2 = (DefaultTableModel) tableBills.getModel();
int billNb = numbersOfBills + 1;
billModel2.addRow(new Object[] {newBill.getBillNr(),newBill.getBillName(), newBill.getItemsInBill()});
}
The reason why you are getting -1 from getSelectedRow() even though you seem to have "added a row" is, because the Frontend object you are calling checkActiveItem() on is a completely different Frontend object than the one you are seeing.
The issue is here, inside of your Timers run():
Frontend f = new Frontend();
You create a new Frontend object for each timer iteration. And you call checkActiveItem() on exactly this object, not on the frontend you are seeing and pressing buttons on. Hence, the incorrect output.
As a solution, don't create new Frontends, instead, call checkActiveItem() on your original frontend object, which you made visible.
I asked a question related to the issue I was having before, but a new one arose. Originally, I wanted the capability of highlighting a row in my table with a single click, and editing a cell with a double click. greg-449 gave me the solution to the problem (getting rid of the FocusCellManager and simply using EditingSupport along with the other classes I had, and setting the editorActivationStrategy to have the MOUSE_DOUBLE_CLICK_SELECTION bit. However, now when I type text into a cell, the text is not saved into my model. On the other hand, when I use the FocusCellManager, the text is indeed saved.
Now, I have to use CellEditors, as there is already a very long list of CellEditors set up for the specific columns. I am not sure if it is possible to use EditingSupport along with CellEditors, or if it necessary at all. I am attaching some snippets.
Relevant Section of DatumTableViewer.java:
FocusCellOwnerDrawHighlighter drawHighlighter = new FocusCellOwnerDrawHighlighter(this); //removed this to fix the highlighting issue
final TableViewerFocusCellManager mgr = new TableViewerFocusCellManager(this, drawHighlighter); //removed this to fix the highlighting issue.
final ColumnViewerEditorActivationStrategy editorActivationSupport = getEditorActivationStrategy();
int tableKeyboardTraversalFeature = getKeyboardTraversalFeature();
TableViewerEditor.create(this, mgr, editorActivationSupport, tableKeyboardActivationFeature);
DatumColumnEmnum[] tableColumnsAsArray = getTableColumnsAsArray();
createTable(this.getTable(), tableColumnsAsArray);
setColumnProperties(properties.getPresentedColumnNames); //properties is passed into constructor
setCellEditors(tableColumnsAsArray); //I think this doesn't work properly without FocusCellManager
DatumCellModifier modifier = new DatumCellModifier(this, properties, myExpressionDataProvider); // myExpressionDataProvider is passed into constructor)
setCellModifier(modifier);
setContentProvider(contentProvider);
setInput(_myDatumList); // myDatumList set before this snippet
}
setCellEditors:
private void setCellEditors(DatumColumnEnum[] columns)
{
cellEditor[] editors = new CellEditor[columns.length];
for(int i = 0; i < columns.length; i++){
DatumColumnEnum columnID = columns[i];
switch(columnID) // cases have been trimmed to shorten this snippet
{
case DATUM_ID_COLUMN:
case DATUM_NUMBER_COLUMN:
case DATUM_NAME_COLUMN:
editors[i] = new TextCellEditor(this.getTable());
((Text) editors[i].getControl()).setTextLimit(60);
break;
}
}
this.setCellEditors(editors);
}
I suspect these snippets contain the problem, but if not, then please let me know and I'll add the other functions as well.
I have an array of question, an array of possible answers and an array of properties I want to find out by answering the questions
String[] questions = new String[]{"Question1", "Question2", "Question3"};
String[] possibleAnswers = new String[]{"yes,no", "yes,no", "big,small"};
String[] properties = new String[]{"", "", ""};
I created a label for every question and JRadioButtons for every answer for that question by using split on the corresponding element in the possibleAnswers array.
for (int i = 0; i < questions.length; i++) {
//label that holds the current question
JLabel questionLabel = new JLabel(questions[i]);
questionPanel.add(questionLabel);
// string that holds answers for current question i.e. {yes, no}
String[] currentQuestionAnswers = possibleAnswers[i].split(",");
ButtonGroup buttonGroup = new ButtonGroup();
for (int j = 0; j < currentQuestionAnswers.length; j++) {
JRadioButton btnRadio = new JRadioButton(currentQuestionAnswers[j]);
// action listener that will store the selected answer and the question
btnRadio.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
answer = btnRadio.getText();
// some code that moves answer at the right index in the properties array
}
});
buttonGroup.add(btnRadio);
questionPanel.add(btnRadio);
}
}
This image shows what I want it to look like.
For each question I want to find a property. Let's say {Question1, Question2, Question3} are actually these questions {"talks?", "expensive?", "dimension?"}. When I get the text from the selected buttons, I'll have talks -> yes, expensive -> no, dimension -> big, so the properties array will become {"yes", "no", "big"}.
I know how to get the selected answer, but I can't figure out how to find the question that corresponds to that answer. I thounght I can somehow use the button groups I created, but I don't know how.
I hope this makes sense and someone can help. Thank you.
One way to do it would be to extend JRadioButton and add a simple ID field (a tag). I can't test this code right now but I think
it should work.
class MyRadioButton extends JRadioButton{
private int tag;
public getTag(){ return tag;}
public setTag(int val){ tag = val}
}
And then in the actionPerfomed method, just check this tag and take an appropriate action based on it.
int tag = 0;
btnRadio.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
answer = btnRadio.getText();
switch(btnRadio.getTag()){
case 0:
//do some action
break;
case 1:
....
}
// some code that moves answer at the right index in the properties array
}
});
btnRadio.setTag(tag++);//this will set a unique tag for each radio button
buttonGroup.add(btnRadio);
Alternatively, if you don't want to extend JRadioButton,which arguably might be overkill for your use case, you can use RadioButton.setActionCommand and ActionEvent.getActionCommand
btnRadio.setActionCommand("some_unique_string")
and then just check this command string in actionPerformed
if("some_unique_string".equals(ae.getActionCommand())
//do something
well i am making this system that has a table, and i have to put buttons in the last column. i've been researching but all the codes i saw are really confusing. there is one tho, but there are still some parts that i didn't understand. here's the site where i got it http://www.javaquery.com/2013/05/how-to-implement-jbutton-in-jtable.html
String[] InvoiceArray = new String[20];
//Declare above variable globally. Used by two-three methods. Change variable name as per your need.
/*
* import the ButtonColumn class if you are not working in IDE
* I used formWindowOpened event to load content in Jtable but you can use other event.
* All you need is put the code with in that event.
*/
private void formWindowOpened(java.awt.event.WindowEvent evt) {
Object[][] rowData = new Object[4][2]; // 4: is number of row ; 2: is number of column
Object columnNames[] = {"Invoice No", "View Report"}; // Name of columns
for (int i = 0; i < 4; i++) {
InvoiceArray[i] = i + "-2345";
rowData[i][0] = i + "-2345";
rowData[i][1] = "View Order " + i; // Can change the text of button.
}
DefaultTableModel tm = new DefaultTableModel(rowData, columnNames);
jTable1.setModel(tm);
ButtonColumn buttonColumn = new ButtonColumn(jTable1, showOrder, 1); // 1: is column number. column count starts with 0,1,2...
}
what's the InvoiceArray for? and should i make the showOrder from the last line? and also, i didn't understand the code he posted on how to make a listener on it. here it is:
Action showOrder = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
//JTable table = (JTable) e.getSource(); // If you have multiple component following the ActionEvent
int modelRow = Integer.valueOf(e.getActionCommand());
if (InvoiceArray[modelRow] != null) {
/* We are placing invoice no in array
* And track the button click index
* And fetch index in invoice no
*/
System.out.println("Your Invoice No:" + InvoiceArray[modelRow]);
} else {
JOptionPane.showMessageDialog(rootPane, "No records found!");
}
}
};
i know there are some explanations already. i understand some of them but not all. just a simplier way to add jbutton on jtable and also listeners for the jbutton. thank you so much
just a simplier way to add jbutton on jtable and also listeners for the jbutton.
There is no simple way. You need to understand how renderers and editors work in a JTable. Read the section from the Swing tutorial on Concepts: Renderers and Editors for the basics.
Then you can check out Table Button Column which does the hard work for you. You only need to provide the Action to be invoked when you click on the button.
what's the InvoiceArray for?
It is used to load data into the JTable. This is basic usage of a JTable and has absolutely nothing to do with adding a button to a column of the table.
After the data is loaded you should forget about the invoiceArray. The Action you write should access the data via the TableModel or the JTable.
I am finding hard to clear the table contents in my table. I have tried this code.
for ( int i = 0; i<resultTable.getItems().size(); i++) {
resultTable.getItems().clear();
}
To clarify my question, the problem I am having is that i want to delete the values in my table. This was the first code i used;
public void removeRow(){
allFiles = table.getItems(); fileSelected = table.getSelectionModel().getSelectedItems();
fileSelected.forEach(allFiles :: remove);
}
But it only removes a particular selected row. I want to clear all the rows and leave the table empty at once, without having to select any row. I tried to use this code;
public void removeAllRows(){
for ( int i = 0; i<resultTable.getItems().size(); i++) {
resultTable.getItems().clear();
}
}
but it does not clear all the rows in the table
My plan is to use this method as an action for a button.
e.g
Button btn = new ("Clear Table");
btn..setOnAction(e->{removeAllRows();});
When this button is clicked, it should delete all rows in the table at once.
tableView.getItems().clear()
Will do the trick
Try using the following: Name "tableView" to whatever your FXMLtable is called
for ( int i = 0; i<tableView.getItems().size(); i++) {
tableView.getItems().clear();
}