I've populated JTable from database. But the table is not appearing. I can not figure out the problem with the code. I can not understand whether the problem is with layout or the code block retrieving data from database. Also I am not getting any Exception message. I've added frame.getContentPane().add(scroll, BorderLayout.CENTER); in the code, still can not the table. Please see the attached image what I am getting.
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import controller.DB_con;
public class Jtable {
private JFrame frame;
private JTable table;
String[] columnNames = {"ID", "name", "username", "contact", "GENDER"};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Jtable window = new Jtable();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.toString());
}
}
});
}
/**
* Create the application.
*/
public Jtable() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
table = new JTable();
frame.getContentPane().add(table, BorderLayout.CENTER);
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
frame.getContentPane().add(scroll, BorderLayout.CENTER);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
try
{
Connection sqlCon = DB_con.getSQLConnection();
PreparedStatement ps = sqlCon.prepareStatement("select id,name,username,contact,gender from temp_tbl");
int i = 0;
ResultSet rs = ps.executeQuery();
while(rs.next())
{
String id = rs.getString("id");
String name = rs.getString("name");
String username = rs.getString("username");
String contact = rs.getString("contact");
String gender = rs.getString("gender");
model.addRow(new Object[]{id, name, username, contact, gender});
i++;
}
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
}
You add the JTable to the frame, you then add it to the JScrollPane but never add the JScrollPane to the anything ...
A component can only reside within a single container, so when you do JScrollPane scroll = new JScrollPane(table);, you are removing the JTable from the frame.
Add frame.getContentPane().add(scroll, BorderLayout.CENTER); after you've created the JScrollPane
You also never apply the TableModel to the JTable
table.setModel(model);
frame.getContentPane().add(scroll, BorderLayout.CENTER);
Related
My GUI application is Connecting to the DB and I have managed to add a product from the DB to my JTable on the GUI. When I click a second button it overwrites the first. I do not want this as it is an order till system and I want whatever I click to appear on the table as it is clicked. Is there any way to append onto the table rather than overwriting the values every time. Here is my code.
americanoSmall.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try {
String query = "select ProductName, Price from product where ProductID = 24";
java.sql.PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e1)
{
e1.printStackTrace();
}
}
});
Don't change the table model whenever the model changes. Instead, use the addRow method of the TableModel. Here's a minimal, complete and verifiable example.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
Container cont = frame.getContentPane();
cont.setLayout(new BorderLayout());
DefaultTableModel dtm = new DefaultTableModel(new Object[]{"Column 1","Column 2"}, 0);
JTable table = new JTable(dtm);
JScrollPane scroll = new JScrollPane(table);
cont.add(scroll, BorderLayout.CENTER);
dtm.addRow(new Object[]{"Value 1", "Value 2"});
JButton add = new JButton("Add");
cont.add(add, BorderLayout.NORTH);
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dtm.addRow(new Object[]{"Another value", "Another value"});
}
});
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
I'm trying to display a JscrollPane using this code. but it's displaying a blank frame with just the "close" button displayed. Can't figure out why it wouldn't display. Any help would be greatly appreciated! :)
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.table.DefaultTableModel;
import edu.pitt.bank.Account;
import edu.pitt.bank.Transaction;
import edu.pitt.utilities.DbUtilities;
import edu.pitt.utilities.MySqlUtilities;
public class TransactionUI {
private JFrame frame;
private JScrollPane transactionPane;
private JTable tblTransactions;
public TransactionUI(Account userAccount) {
frame = new JFrame();
frame.setTitle("Account Transactions");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
transactionPane = new JScrollPane();
frame.getContentPane().add(transactionPane);
DbUtilities db = new MySqlUtilities();
String [] cols = {"Type", "Amount", "Date"};
String sql = "SELECT type, amount, transactionDate FROM srp63_bank1017.transaction;";
try {
System.out.println("use getDataTable()");
DefaultTableModel transactionList = db.getDataTable(sql, cols);
System.out.println("getDataTable() used");
tblTransactions = new JTable(transactionList);
tblTransactions.setFillsViewportHeight(true);
tblTransactions.setShowGrid(true);
tblTransactions.setGridColor(Color.BLACK);
transactionPane.getViewport().add(tblTransactions);
} catch (SQLException e) {
e.printStackTrace();
}
JButton btnClose = new JButton("Close");
btnClose.setBounds(323, 212, 89, 23);
btnClose.setBounds(284, 214, 73, 23);
frame.getContentPane().add(btnClose);
}
public JFrame getFrame() {
return frame;
}
}
I use this to call the above frame from another class:
public void actionPerformed(ActionEvent arg0) {
if(userAccount.getAccountID() != null){
TransactionUI tUI = new TransactionUI(userAccount);
tUI.getFrame().setVisible(true);
} else {
System.out.println("Account object must not be null");
}
}
});
Here is the getDataTable method...
public DefaultTableModel getDataTable(String sqlQuery, String[] customColumnNames) throws SQLException{
ResultSet rs = getResultSet(sqlQuery);
/* Metadata object contains additional information about a ResulSet,
* such as database column names, data types, etc...
*/
ResultSetMetaData metaData = rs.getMetaData();
// Get column names from the metadata object and store them in a Vector variable
Vector<String> columnNames = new Vector<String>();
for(int column = 0; column < customColumnNames.length; column++){
columnNames.add(customColumnNames[column]);
}
// Create a nested Vector containing an entire table from the ResultSet
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while(rs.next()){
Vector<Object> vector = new Vector<Object>();
for(int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++){
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
I received no errors
Problem #1
frame.getContentPane().setLayout(null);
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
See Laying Out Components Within a Container for more details
Problem #2
transactionPane.getViewport().add(tblTransactions);
Don't use ad with JScrollPane or JViewport, use
transactionPane.getViewport().setView(tblTransactions);
or
transactionPane.setViewportView(tblTransactions);
instead
See
How to Use Scroll Panes for more details
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JTable table = new JTable(new DefaultTableModel(100, 100));
table.setGridColor(Color.LIGHT_GRAY);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(table);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Problem #3
The use of multiple windows, see The Use of Multiple JFrames, Good/Bad Practice? for a more in-depth discussion
I think what you really want is some kind of modal dialog. See How to Make Dialogs for more details
Your code without modifications
(Except removing the database code)
This is how your code looks on my PC, take a good hard look at the button...
Your code modified to use layout managers...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
TransactionUI ui = new TransactionUI();
JFrame frame = ui.getFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TransactionUI {
private JFrame frame;
private JScrollPane transactionPane;
private JTable tblTransactions;
public TransactionUI() {
frame = new JFrame();
frame.setTitle("Account Transactions");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
transactionPane = new JScrollPane();
frame.getContentPane().add(transactionPane);
String[] cols = {"Type", "Amount", "Date"};
String sql = "SELECT type, amount, transactionDate FROM srp63_bank1017.transaction;";
System.out.println("use getDataTable()");
DefaultTableModel transactionList = new DefaultTableModel(100, 100);
System.out.println("getDataTable() used");
tblTransactions = new JTable(transactionList);
tblTransactions.setFillsViewportHeight(true);
tblTransactions.setShowGrid(true);
tblTransactions.setGridColor(Color.BLACK);
transactionPane.setViewportView(tblTransactions);
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JButton btnClose = new JButton("Close");
buttons.add(btnClose);
frame.getContentPane().add(buttons, BorderLayout.SOUTH);
}
public JFrame getFrame() {
return frame;
}
}
}
Im having an issue with JTable columns. I create the JTable but the columns wont show up.And yes, I tried the previously asked question about this issue saying about adding a JScrollPane but putting the ScrollPane inside destroyed completely my Table and the Table wasn't visible.
I tried frame.getContentPane.add(new JScrollPane(table)) from this link (JTable won't show column headers) but didnt have any effect as I said above.
Im not using a layout manager.
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=12345");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id");
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
String[] cols = new String[columnCount];
for (i=1;i<= columnCount;i++)
{
cols[i-1] = md.getColumnName(i);
}
DefaultTableModel model = new DefaultTableModel(cols,0);
while (rs.next())
{
Object[] row = new Object[columnCount];
for (i = 1 ; i <= columnCount ; i++)
{
row[i-1] = rs.getObject(i);
}
model.addRow(row);
}
JTable table = new JTable(model);
model.fireTableDataChanged();
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true);
table.setFillsViewportHeight(true);
table.setSurrendersFocusOnKeystroke(true);
table.setBounds(146,59,763,360);
frame.getContentPane().add((table));
model.fireTableDataChanged();
}
JTable is designed to work with JScrollPane, it will automatically add the TableHeader to the scroll pane, for example
Instead of
frame.getContentPane().add((table));
Try using...
frame.getContentPane().add(new JScrollPane(table));
See How to Use Tables for more details
Beware, you should avoid using setBounds and instead use an appropriate layout manager, you should also void using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
Updated...
You should never need to call fireTableDataChanged or any other event methods on a model, they are not meant for your use, but for use within the model.
Before adding the table/scroll pane to the content pane, try this...
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new JScrollPane(table));
Let me demonstrate...
With a layout manager...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class TableExample {
public static void main(String[] args) {
new TableExample();
}
public TableExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
int columnCount = 10;
String[] cols = new String[columnCount];
for (int i = 1; i <= columnCount; i++) {
cols[i - 1] = Integer.toString(i);
}
DefaultTableModel model = new DefaultTableModel(cols, 0);
JTable table = new JTable(model);
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true);
table.setFillsViewportHeight(true);
table.setSurrendersFocusOnKeystroke(true);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Without a layout manager...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class TableExample {
public static void main(String[] args) {
new TableExample();
}
public TableExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
int columnCount = 10;
String[] cols = new String[columnCount];
for (int i = 1; i <= columnCount; i++) {
cols[i - 1] = Integer.toString(i);
}
DefaultTableModel model = new DefaultTableModel(cols, 0);
JTable table = new JTable(model);
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true);
table.setFillsViewportHeight(true);
table.setSurrendersFocusOnKeystroke(true);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
The problem isn't with the code you've shown us, the problem is with your choice to do away with one of the core concepts upon which the Swing API is built on...the layout manager
You can try to get the TableHeader from the Table and add this to the ContentPane:
JTableHeader tableHeader = table.getTableHeader();
frame.getContentPane().add(tableHeader);
Either you have to wrap your table in a JScrollPane like this:
frame.getContentPane().add(new JScrollPane(table));
Or you have to add the table header separatly:
frame.getContentPane().add(table.getTableHeader, BorderLayout.NORTH);
frame.getContentPane().add(table); // By default this adds to CENTER
This assumes the layout manager of the content pane is the default BorderLayout.
I want to display the JTable each time a row is added.
The code that i write below add a new row to table , then display the jtable for 2 seconds ,then add another row , then display the table. But the jtable is not displaying ,
It only display after adding all rows
Vector<Object> rowVector = null;
while(rs.next()){
rowVector = new Vector<Object>();
for(int i=1;i<=columnCount;i++){
rowVector.add(rs.getString(i));
//System.out.print(rs.getString(i));
}
System.out.println(rowVector.toString());
//data.add(rowVector);
model.addRow(rowVector);
JTable table1 = new JTable(model);
JTableHeader header1 = table1.getTableHeader();
table1.setEnabled(false);
header1.setResizingAllowed(false);
header1.setReorderingAllowed(false);
header1.setForeground(Color.white);
header1.setBackground(Color.black);
jpanedisplay.setViewportView(table1);
jpanedisplay.getViewport().setBackground(Color.white);
jpanedisplay.setBorder(BorderFactory.createLineBorder(Color.black));
Thread.sleep(3000);
}
You're creating a new JTable in each iteration, you don't need to do that. Add the model to the table before the loop. And just add rows to the model in the loop
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(model);
table.setEnabled(false);
JTableHeader header1 = table.getTableHeader();
header1.setResizingAllowed(false);
header1.setReorderingAllowed(false);
header1.setForeground(Color.white);
header1.setBackground(Color.black);
jpanedisplay.setViewportView(table1);
jpanedisplay.getViewport().setBackground(Color.white);
jpanedisplay.setBorder(BorderFactory.createLineBorder(Color.black));
...
while(rs.next()){
Vector<Object> rowVector = new Vector<Object>();
for(int i=1;i<=columnCount;i++){
rowVector.add(rs.getString(i));
//System.out.print(rs.getString(i));
}
model.addRow(rowVector);
// DON'T CALL Thread.sleep();
}
UPDATE
If you dont want the table added until the database task is finished, just use a method
private JTable createTable(ResultSet rs) {
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(model);
table.setEnabled(false);
JTableHeader header1 = table.getTableHeader();
header1.setResizingAllowed(false);
header1.setReorderingAllowed(false);
header1.setForeground(Color.white);
header1.setBackground(Color.black);
while(rs.next()){
Vector<Object> rowVector = new Vector<Object>();
for(int i=1;i<=columnCount;i++){
rowVector.add(rs.getString(i));
}
model.addRow(rowVector);
}
return table;
}
Then you can just add it to what ever panel
panel.add(new JScrollPane(createTable(rs));
UPDATE #2 after Op explained that they were trying to get a dynamic look the rows being added, instead of all at One time.
I used a java.swing.Timer to add the rows.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.table.DefaultTableModel;
public class TestTimerTable {
String[] cols = {"ID", "Name", "Country Code", "District", "Population"};
DefaultTableModel model = new DefaultTableModel(cols, 0);
JTable table = new JTable(model);
ResultSet rs = null;
JButton start = new JButton("Start");
Timer timer = new Timer(0, null);
public TestTimerTable() {
initDB();
JScrollPane scroll = new JScrollPane(table);
scroll.setViewportView(table);
JFrame frame = new JFrame("Test Timer Table");
frame.add(scroll);
frame.add(start, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
timer = new Timer(200, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
if (rs.next()) {
String s1 = rs.getString(1);
String s2 = rs.getString(2);
String s3 = rs.getString(3);
String s4 = rs.getString(4);
String s5 = rs.getString(5);
model.addRow(new Object[]{s1, s2, s3, s4, s5});
} else {
((Timer) e.getSource()).stop();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
});
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
}
});
}
private void initDB() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/...", "...", "...");
PreparedStatement ps = conn.prepareStatement("SELECT * FROM city");
rs = ps.executeQuery();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestTimerTable();
}
});
}
}
I would like the JTable to autoscroll to the bottom whenever I add a new column and show the last 10 rows. However, I have the option of scrolling to anywhere I want (mouse listener?). Do you know how to do that? Here's the code I have so far. It builds a JTable and adds a new row for every mouse click on the JButton.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class sampleGUI extends JFrame implements ActionListener {
private JButton incrementButton;
private JTable table;
private DefaultTableModel model;
private int count;
private JScrollPane scroll;
public sampleGUI() {
JFrame frame = new JFrame("sample frame");
frame.setLayout(new BorderLayout());
incrementButton = new JButton("Increase the count!");
model = new DefaultTableModel();
model.addColumn("column 1");
table = new JTable(model);
frame.add(incrementButton, BorderLayout.NORTH);
scroll = new JScrollPane(table)
frame.add(scroll, BorderLayout.CENTER);
count = 0;
incrementButton.addActionListener(this);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public synchronized void actionPerformed(ActionEvent e) {
if (e.getSource() == incrementButton) {
count++;
model.addRow(new Object[] { count });
}
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
sampleGUI gui = new sampleGUI();
}
});
}
}
Thanks!
Required to change selection in JTable, add code line
table.changeSelection(table.getRowCount() - 1, 0, false, false);
to
public (synchronized) void actionPerformed(ActionEvent e) {
I would like the JTable to autoscroll to the bottom whenever I add a new column
I assume you mean scroll to the bottom when you add a new row?
model.addRow(new Object[] { count });
table.scrollRectToVisible(...);
You forget add JScrollPane to the table :
//...
frame.add(new JScrollPane(table), BorderLayout.CENTER);
//...
and don't forget
import javax.swing.JScrollPane;