Here is my code.
It got problem on while you selete from left to right..
import javax.swing.*;
import javax.swing.event.*;
public class swingex7 extends JFrame{
swingex7(){
JFrame f = new JFrame("Table Example");
String row[][]= {{"101","Hein Htet","10000000"},{"102","Hein Htet1","20000000"},{"103","Hein
Htet2","30000000"}};
String column[]= {"Id","Name","Salary"};
final JTable jt = new JTable(row,column);
jt.setCellSelectionEnabled(true);
ListSelectionModel lsm = jt.getSelectionModel();
lsm.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lsm.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
String data=null;
int[] rows=jt.getSelectedRows();
int[] columns = jt.getSelectedColumns();
for(int i=0;i<rows.length;i++) {
for(int j=0;j<columns.length;j++) {
data = (String)jt.getValueAt(rows[i], columns[j]);
}
}
System.out.println("Table element seleted is "+data);
}
});
JScrollPane js = new JScrollPane(jt);
f.add(js);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 400);
f.setVisible(true);
}
public static void main (String[]args) {
new swingex7();
}
}
It got problem on while you Selete from left to right.
I also want to output only once per action.
There are 2 problems in the code.
1.
First problem is ListSelectionListener is called 2 times when mouse is clicked and when mouse is released. But instead of that if you can add MouseListener to your JTable as below.
MouseListener tableMouseListener = new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
String data = null;
int[] rows = jt.getSelectedRows();
int[] columns = jt.getSelectedColumns();
for (int i = 0; i < rows.length; i++) {
for (int j = 0; j < columns.length; j++) {
data = (String) jt.getValueAt(rows[i], columns[j]);
System.out.println("Table element selected is " + data);
}
}
}
};
jt.addMouseListener(tableMouseListener);
2.
Second issue is the place where you printed the data. It should be inside the for loop. Otherwise the data will be rewritten in each iteration in the loop and only last value will be printed.
for (int i = 0; i < rows.length; i++) {
for (int j = 0; j < columns.length; j++) {
data = (String) jt.getValueAt(rows[i], columns[j]);
System.out.println("Table element selected is " + data);
}
}
Related
Ok so I am trying to make a chess game in swing. I have a program that creates a 2d array of JButton's 8x8. I then create them all in a loop doing stuff like going back and forth between white/black and adding an action event. The problem i am having is that each button has the same action event and it is the event that is created last I.E. button on Row 8 column H is the action listener for all of the buttons in the array. Here is a snippet of code that is where I am creating the buttons and adding them.
I also have an Enum Columns that just goes from int to character 1 to H for example. selectPosition and targetPosition are objects that have two members columns and rows.
public void initializeGui(boolean isWhite) {
boolean shouldBeWhite = true;
for(int i = 0; i< 8; i++){
for(int j = 0; j < 8; j++){
column = i+1;
row = j+1;
JButton square = new JButton();
square.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
final int thisRow = row;
final int thisColumn = column;
selectPosition.setColumn(Columns.getColumnsFromInt(thisColumn));
selectPosition.setRow(thisRow);
if(isSelecting){
System.out.print("Selecting square to move. Row: " + thisRow + " Column: " + Columns.getColumnsFromInt(thisColumn));
selectPosition.setColumn(Columns.getColumnsFromInt(thisColumn));
selectPosition.setRow(thisRow);
} else{
System.out.print("Targeting square to move to. Row: " + thisRow + " Column: " + Columns.getColumnsFromInt(thisColumn) + "\n");
targetPosition.setColumn(Columns.getColumnsFromInt(thisColumn));
targetPosition.setRow(thisRow);
}
System.out.println("");
isSelecting = !isSelecting;
}
});
if(shouldBeWhite){
square.setBackground(Color.WHITE);
shouldBeWhite = false;
}else{
square.setBackground(Color.BLACK);
shouldBeWhite = true;
}
if (j == 7){
shouldBeWhite = !shouldBeWhite;
}
chessBoardSquares[i][j] = square;
gui.add(chessBoardSquares[i][j]);
}
}
if(isWhite){
setInitialPiecesWhiteStart();
}else{
setInitialPiecesBlackStart();
}
}
Further up as a member of this class are the following:
int column = 0, row = 0;
When I click on any of these buttons i see printed
Selecting square to move. Row: 8 Column: H
Targeting square to move to. Row: 8 Column: H
Selecting square to move. Row: 8 Column: H
Targeting square to move to. Row: 8 Column: H
and so on. My question is why are these buttons all given the same action event? My logic walk through would be something like create the first button set column = i+1 and row = j+1 then add an action listener with an action event that sets the current row/column values to the inner final variables and then prints out the thisRow and thisColumn associated with that action event. Am i overriding the values at the end or do i have the scope wrong? Basically how am i creating these buttons actions listeners incorrectly?
You could...
Use the actionCommand API to pass information between the button and the ActionListener...
JButton btn = new JButton();
btn.setActionCommand(row + "x" + column);
btn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
//...
}
});
The problem here is you're relying on String parsing to extract the values, which can get messy quickly
You could...
Create a custom ActionListener which takes the values you want to use...
public class SquareActionListener implements ActionListener {
private int column;
private int row;
public SquareActionListener(int row, int column) {
this.row = row;
this.column = column;
}
#Override
public void actionPerformed(ActionEvent e) {
//...
}
}
This de-couples the ActionListener from the rest of the code and provides you the information you need, although, you may need to pass additional information (such as the model) as well for it to work
You could...
Make use of the Action API which is designed to be provide self contained units of work, it's generally a more re-usable solution, but might be a little beyond what you need right now
public class SquareAction extends AbstractAction {
private int column;
private int row;
public SquareAction(int row, int column) {
this.row = row;
this.column = column;
}
#Override
public void actionPerformed(ActionEvent e) {
//...
}
}
This looks alot like the last suggestion, but instead of adding it as the button's ActionListener, you actually apply it to the button directly...
JButton btn = new JButton(new SquareAction(row, column));
The button then uses other properties (which I've not set) to set itself up
I had the same issue when making a tic-tac-toe game. I used each button's hashcode to trace back which button was actually pushed. This is what my button setup looked like:
hashcodes= new ArrayList<Integer>();
for (int i=1;i<=9;i++) {
JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setHash(button.hashCode());
testWinner();
testDraw();
}
});
hashcodes.add(button.hashCode());
panel.add(button);
}
}
private void setHash(int hashcode) {
for (int h:hashcodes) {
if (h==hashcode) {
//do stuff
}
}
}
This is my Test class, and it works perfectly.
public class Test extends javax.swing.JFrame {
private javax.swing.JButton[][] buttons;
private final int ROW = 8;
private final int COLUMN = 8;
public Test() {
initComponents();
}
private void initComponents() {
this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH);
this.buttons = new javax.swing.JButton[ROW][COLUMN];
this.setLayout(new java.awt.GridLayout(ROW, COLUMN));
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COLUMN; j++) {
final int row = i;
final int column = j;
buttons[i][j] = new javax.swing.JButton(
String.format("Button %d-%d", i, j));
buttons[i][j].addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
// System.out.println(
// String.format("You have just pressed the button at row %d and column %d", row, column));
javax.swing.JOptionPane.showMessageDialog(
Test.this, String.format("You have just pressed the button at row %d and column %d", row, column));
}
});
this.add(buttons[i][j]);
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new Test().setVisible(true);
}
}
I have a problem with my JTable. Firstly I selected some entries in my table. However when I deselect some of them, the table could not understand it.
Example scenario: I select job1 and 2 for the testing after that I change my mind and de-select job2. But in the result I saw job1 job1 and job2 ( job 1 seen 2 times and even though I dis-select job 2 I saw them.) Or after selected all the jobs ( choose all button) I want to deselect all of them (Clear button) when I click clear all the table seems empty. It is good but somehow the background of the program still protect the all old selection. How can I solve this?
Try:
I created the row of my table by read csv file.
public class JobSelectionListPanel extends JPanel {
private static final long serialVersionUID = 5198916547962359735L;
private static JobSelectionListPanel INSTANCE = new JobSelectionListPanel();
public static JobSelectionListPanel getInstance() {
return INSTANCE;
}
private JTable table;
private JButton next, back, btnClear, btnNewButton, btnChooseAll;
private JobList fnnJobList = new JobList();
private JobSelectionListPanel() {
table = new JTable();
JScrollPane scrollPane = new JScrollPane(table);
table.setBorder(new CompoundBorder());
// Read all FNN jobs from file
try {
fnnJobList.readFromFile("rules.csv");
} catch (IOException e1) {
System.out.println("You are not able to read the rules.csv file");
}
// Create ArrayList of JobNames
Object[][] initialData = new Object[fnnJobList.size()][1];
int i = 0;
for (Job jobDes : fnnJobList) {
initialData[i][0] = (Object) jobDes.getJobname();
i++;
}
String[] columnNames = new String[] { "", "Your preferences" };
table.setModel(new DefaultTableModel(initialData, columnNames) {
private static final long serialVersionUID = 1L;
#SuppressWarnings("rawtypes")
Class[] columnTypes = new Class[] { Object.class, Boolean.class };
#SuppressWarnings({ "unchecked", "rawtypes" })
public Class getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
});
table.getColumnModel().getColumn(1).setPreferredWidth(80);
table.getColumnModel().getColumn(1).setMinWidth(40);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setCellSelectionEnabled(true);
I user want to choose all rows then I implemented this.
btnChooseAll = new JButton("Choose all");
btnChooseAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel chooseAllData = (DefaultTableModel) table.getModel();
if (DeviceGroups.DeviceAList.size() == 0 || DeviceGroups.DeviceBList.size() == 0
|| DeviceGroups.DeviceCList.size() == 0 || DeviceGroups.DeviceDList.size() == 0)
JOptionPane.showMessageDialog(null,
"You should choose at least 1 device for each test device to apply this test case", "Invalid OPTION",
JOptionPane.ERROR_MESSAGE);
else
for (int i = 0; i < chooseAllData.getRowCount(); i++) {
for (int j = 1; j < chooseAllData.getColumnCount(); j++) {
chooseAllData.setValueAt(true, i, j);
}
}
}
});
For clear all preferences :
btnClear = new JButton("Clear all");
// Clear button create a model of JTable and delete all the rows of table!!
btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel clearTableData = (DefaultTableModel) table.getModel();
for (int i = 0; i < clearTableData.getRowCount(); i++) {
for (int j = 1; j < clearTableData.getColumnCount(); j++) {
clearTableData.setValueAt(null, i, j);
}
}
}
});
I see the following problem in your code: mixing up view indexes and model indexes. This is the offending snippet:
for (int i = 0; i < table.getRowCount(); i++) {
if (table.getValueAt(i, 1) != null) {
if (((Boolean) table.getValueAt(i, 1)).booleanValue()) {
String jobName = (((DefaultTableModel) table.getModel()).getValueAt(i, 0).toString());
You are using the i variable to denote view row indices, since you are checking values in this statement: table.getValueAt(i, 1) != null.
But then a bit further you are using i to index the model:
String jobName = ((DefaultTableModel) table.getModel()).getValueAt(i, 0).toString();
If i is to be a view index, you need to convert it to a model index before indexing the model:
String jobName = ((DefaultTableModel) table.getModel()).getValueAt(table.convertRowIndexToModel(i), 0).toString();
Also, when columns would be switched around in the view (ie on screen in your GUI), the following will probably not work as intended:
table.getValueAt(i, 1) != null
You most likely mean to say, get the second column value in the model, not the view. Best rewrite then as
table.getValueAt(i, table.convertColumnIndexToView(1)) != null
I've got a form with gridLayout which contains 15 JButtons and one JLabel. Every button has an action and when it's fired It should show clicked!, perform some operation and show in console its position.
But it shows position in console only once - when I press any button first time. After that only clicked text appears in console.
What's the problem?
public class PuzzleUI extends JFrame {
private static final long serialVersionUID = 1L;
private int gap = 2;
private Puzzle puzzle;
private JComponent[][] itemGrid;
private JPanel controls;
public PuzzleUI(String title, int puzzles, int empty_cell) {
super(title);
puzzle = new Puzzle(puzzles, empty_cell);
itemGrid = new JComponent[puzzle.getRowSize()][puzzle.getRowSize()];
controls = new JPanel();
controls.setLayout(new GridLayout(puzzle.getRowSize(), puzzle
.getRowSize(), gap, gap));
init(this.getContentPane());
}
public void init(final Container pane) {
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Object ob = e.getSource();
boolean finished = false;
if (ob instanceof JButton) {
System.out.println("Clicked!");
int cnt = 0;
label: for (int i = 0; i < itemGrid.length; i++)
for (int j = 0; j < itemGrid[i].length; j++) {
if (itemGrid[i][j] == (JButton) ob) {
System.out.println(i + "-" + j); // appeared only once
finished = puzzle.swap(cnt);
break label;
}
cnt++;
}
PuzzleUI.this.init(PuzzleUI.this.getContentPane());
PuzzleUI.this.controls.repaint();
if (finished == true)
JOptionPane.showMessageDialog(
PuzzleUI.this,
"FINISHED WITH MOVE: "
+ PuzzleUI.this.puzzle.getMoves());
}
}
};
int cnt = 0;
for (int i = 0; i < itemGrid.length; i++)
for (int j = 0; j < itemGrid[i].length; j++) {
int value = puzzle.getListItem(cnt);
if (value == puzzle.getEmptyFlag())
itemGrid[i][j] = new JLabel("");
else {
JButton jb = new JButton(String.valueOf(value));
jb.addActionListener(al);
itemGrid[i][j] = jb;
}
controls.add(itemGrid[i][j]);
cnt++;
}
pane.add(controls);
}
}
I'm making a multiplication table using swing.Its basically made up of JButtons. The table is formed from input from the user. The user selects the size of the table by entering a number. The last thing i need to do with this is create a heading that displays the numbers of the table created. Here is my sample code, if you run it, you'll see that its done for the vertical numbers. How can i get the numbers above and properly formatted to represent each column. Thank you.
package lab7;
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GUIMultiplicationTable{
JFrame theFrame;
int number = 0;
JPanel panel, answerPanel, topPanel, leftPanel;
JLabel answerLabel, topLabel, leftLabel;
private void createAndShowGui(){
String x;
do{
x = JOptionPane.showInputDialog(null, "Enter the number");
number = Integer.parseInt(x);
}while (number <= 0);
theFrame = new JFrame("Multiplication Table");
panel = new JPanel(new GridLayout(number, number));
answerPanel = new JPanel();
answerLabel = new JLabel();
topPanel = new JPanel();
topLabel = new JLabel();
leftPanel = new JPanel();
leftLabel = new JLabel();
for (int i = 0; i < number; i++){
JLabel blah = new JLabel(Integer.toString(i + 1));
panel.add(blah);//add center to label
for (int j = 0; j < number; j++){
JButton button = new JButton();
if (i == 0){
button.setText(String.valueOf(j + 1));
}
if (j == 0){
button.setText(String.valueOf(i + 1));
}
for (int k = 1; k < number; k++)
{
if (i == k)
{
button.setText(String.valueOf((j + 1) * (k + 1)));
}
}
button.addActionListener(new ButtonsTableActionListener(i, j));
panel.add(button);
}
}
answerPanel.add(answerLabel);
theFrame.add(answerPanel, BorderLayout.SOUTH);
topPanel.add(topLabel);
theFrame.add(topPanel, BorderLayout.NORTH);
theFrame.add(panel);
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theFrame.pack();
theFrame.setLocationRelativeTo(null);
theFrame.setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
GUIMultiplicationTable h = new GUIMultiplicationTable();
h.createAndShowGui();
}
});
}
private class ButtonsTableActionListener implements ActionListener{
private int theRow, theColumn;
public ButtonsTableActionListener(int row, int column){
theRow = row;
theColumn = column;
}
#Override
public void actionPerformed(ActionEvent e){
int value = (theRow + 1) * (theColumn + 1);
answerLabel.setText("The value is: " + value + ".\nI got that by multiplying \n" + (theRow + 1) + "x" + (theColumn + 1));
}
};
}
An easy way to do this is to store the position of the button in the ActionListener, you can accomplish this by making your own class extending ActionListener, instead of doing an anonymous class. This way the code executed by the button will already have the information it needs to accomplish whatever you want.
Also you don't need the array of buttons, just add a button in the panel at a time, and at the same time add the actionListener.
This is your code cleaned up and working properly. Now, instead of showing a dialog do whatever you want to do.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GUIMultiplicationTable
{
JFrame theFrame;
int number = 0;
JPanel panel;
private void createAndShowGui()
{
String x;
do
{
x = JOptionPane.showInputDialog(null, "Enter the number");
number = Integer.parseInt(x);
} while (number <= 0);
theFrame = new JFrame("Multiplication Table");
panel = new JPanel(new GridLayout(number, number));
for (int i = 0; i < number; i++)
{
for (int j = 0; j < number; j++)
{
JButton button = new JButton();
if (i == 0)
{
button.setText(String.valueOf(j + 1));
}
if (j == 0)
{
button.setText(String.valueOf(i + 1));
}
for (int k = 1; k < number; k++)
{
if (i == k)
{
button.setText(String.valueOf((j + 1) * (k + 1)));
}
}
button.addActionListener(new ButtonsTableActionListener(i, j));
panel.add(button);
}
}
theFrame.add(panel);
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theFrame.pack();
theFrame.setLocationRelativeTo(null);
theFrame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
GUIMultiplicationTable h = new GUIMultiplicationTable();
h.createAndShowGui();
}
});
}
private class ButtonsTableActionListener implements ActionListener
{
private int _row, _column;
public ButtonsTableActionListener(int row, int column)
{
_row = row;
_column = column;
}
#Override
public void actionPerformed(ActionEvent e)
{
// /do something
int value = (_row + 1) * (_column + 1);
String message = "I'm the button in the position (" + _row + ", " + _column + ")\nMy value is " + value + " = " + (_row + 1) + "*" + (_column + 1);
JOptionPane.showMessageDialog(theFrame, message);
}
};
}
Everything you need to do is just putting a JLabel somewhere.
final JLabel resultLabel = new JLabel("Select a button!");
Note that it should be final to be able to use it in the ActionListener. In the ActionListener you already had the right way, just look at these few lines to make it happen:
ActionListener first = new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < number; i++){
for(int j = 0; j < number; j++){
if(buttons[i][j] == e.getSource()){
// write the equation to the label
resultLabel.setText(buttons[i][j].getText()
+ " = " + (i+1) + " * "
+ (j+1));
// since you found the button you can now break
break;
}
}
}
}
};
Note the i+1 and j+1. The buttons are indexed from 0 to number-1, so the button at (0,0) actually shows the result of 1*1.
This is also important for your next two lines of code:
// you used i=1 and j=1, but you have to start with 0 to make it work for all buttons
for(int i = 0; i < number; i++){
for(int j = 0; j < number; j++){
buttons[i][j].addActionListener(first);
}
}
At a last step you also have to show the the label. If you just add it to the frame, as you do with the panel, you will see that you will not see it.
theFrame.add(resultLabel);
theFrame.add(panel);
The problem is that theFrame doesn't have a layoutmanager yet. So use a new Layout here as well:
theFrame.setLayout(new GridLayout(2,1));
Of course there will be better choices or some nice tweeks to make the layout more beautiful.
So as in sum how to change your code from top to bottom:
set a Layout for theFrame
create a new JLabel for the result of the click, make it final
set the label's text in the actionPerformed() method
add the label to theFrame
You can also consider putting the Label into a new JPanel and add that Panel to theFrame.
The loop in your actionListener is not required, the source of the event is the button that triggered it, so you can simply do...
JButton source = (JButton) e.getSource();
JOptionPane.showMessageDialog(theFrame, source.getText());
Instead.
Now having said that, I would, personally, use some kind of Map to link the JButton to the value, removing the need to have to try and cast the text of the button back to a numeric value (which I believe would be your next step), or store other information you might need to work with for the button (such as the values required to produce the answer)...
private Map<JButton, int[]> answers = new HashMap<JButton, int[]>(25);
//...
for(int i = 0; i < number; i++){
for(int j = 0; j < number; j++){
buttons[i][j] = new JButton();
if(i == 0) {
buttons[i][j].setText(String.valueOf(j+1));
}
if(j == 0) {
buttons[i][j].setText(String.valueOf(i+1));
}
for(int k = 1; k < number; k++){
if(i == k){
buttons[i][j].setText(String.valueOf((j+1) * (k+1)));
}
}
panel.add(buttons[i][j]);
// Store the answer here...
answers.put(buttons[i][j], new int[]{i, j});
}
}
//...
public void actionPerformed(ActionEvent evt) {
JButton source = (JButton) e.getSource();
int[] answer = answers.get(source);
JPanel panel = new JPanel();
JTextField[] fields = new JTextField[]{
new JTextField(2),
new JTextField(2)
};
panel.add(fields[0]);
panel.add(new JLabel("x"));
panel.add(fields[1]);
panel.add(new JLabel(" = " + source.getText()));
JOptionPane.showMessageDialog(theFrame, panel);
// check the values of the fields against the
// values of the answer
}
I have a query ... code is running fine, but am not able to get value of last cell of last row and last column. Below is the code... pls guide
with this code am adding rows dynamically to JTable :
if(e.getSource()==addb)
{
model.addRow(new Object[3]);
repaint();
}
Below is the code for getting values from JTable row wise and later on instead of System.out.println() am going to send data to database...
if(e.getSource()==submit)
{
int j = table.getRowCount();
for(int row=1;row<j;row++)
{
for(int column=0;column<3;column++)
{
System.out.println("row "+row+" Column is "+column);
System.out.println(model.getValueAt(row, column));
}
}
}
Something like this :
int i= table1.getRowCount()-1;
int j= table1.getColumnCount();
Object [] value = new Object[j];
for(int k = 0 ; k<j ; k++)
{
value[k] = model.getValueAt(i,k);
}
Also see this little example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TableTest extends JFrame implements ActionListener{
JTable table ;
JButton button;
public TableTest(){
String []colNames = {"Subject","lecturer"};
String [][] rowDatas = { {"Java Programming","Jon"},
{"C++ Programming","Nuhara"},
{"Mathematicz","Mike"},
{"Database","Saran"}
};
table = new JTable(rowDatas,colNames);
button = new JButton("Show Last Record");
button.addActionListener(this);
this.add(table);
this.add(button);
this.setVisible(true);
this.setSize(300,200);
this.setDefaultCloseOperation(3);
this.setLayout(new FlowLayout());
}
#Override
public void actionPerformed(ActionEvent e) {
int i= table.getRowCount()-1;
int j= table.getColumnCount();
Object [] value = new Object[j];
for(int k = 0 ; k<j ; k++)
{
//value[k] = table.getValueAt(i,k);
System.out.println(table.getValueAt(i, k));
}
}
public static void main(String...ag){
new TableTest();
}
}
Making a wild guess that you are editing the last cell when you click on the "Submit" button.
If so then see: Table Stop Editing.
Thanks Azad,
Its working superb now...
I have a edited the code little bit to get data from all the rows...
int i= table.getRowCount()-1;
int j= table.getColumnCount();
for (int d=1;d<i+1;d++){ // will provide row wise data
for(int k = 0 ; k<j ; k++) // will provide column wise data
{
System.out.println("row num "+d+" "+model.getValueAt(d,k));
} }