I have looked and found that many people weren't putting their table into a scrollPane. Even though I nest my table into a scrollPane then into the frame it still fails to show the header. Is there something else I'm missing ? Thanks
public class Gui extends JFrame {
AbstractTableModel model;
JTable table;
public void start(AbstractTableModel model) {
this.model = model;
table=new JTable(model){
#Override
public boolean isCellEditable(int arg0, int arg1) {
return false;
}
};
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumn column = null;
for (int i = 0; i < model.getColumnCount(); i++) {
column = table.getColumnModel().getColumn(i);
column.setPreferredWidth(120);
column.setMaxWidth(300);
column.setMinWidth(50);
}
JScrollPane pane = new JScrollPane(table);
pane.setPreferredSize(new Dimension(900,900));
add(pane);
setLayout(new FlowLayout());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
}
Based on your code and then having to add the missing functionality, you code works...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class Gui extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
Gui frame = new Gui();
frame.start(new DefaultTableModel(new Object[]{"A", "B", "C"}, 10));
}
});
}
AbstractTableModel model;
JTable table;
public void start(AbstractTableModel model) {
this.model = model;
table = new JTable(model) {
#Override
public boolean isCellEditable(int arg0, int arg1) {
return false;
}
};
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumn column = null;
for (int i = 0; i < model.getColumnCount(); i++) {
column = table.getColumnModel().getColumn(i);
column.setPreferredWidth(120);
column.setMaxWidth(300);
column.setMinWidth(50);
}
JScrollPane pane = new JScrollPane(table);
pane.setPreferredSize(new Dimension(900, 900));
add(pane);
setLayout(new FlowLayout());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
}
}
This then leads to two broad assumptions...
You're TableModel doesn't have any columns
You're TableModel doesn't have any column names...
For example, a TableModel with no column names...
Personally...
I wouldn't use FlowLayout for this, BorderLayout will give better results
pack the frame before you make it visible
Set the layout before you add components as sometimes, things can get messed up...
For example...
setLayout(new FlowLayout()); // But I'd use a `BorderLayout`
add(pane);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
Related
When the jlist only has a couple rows in it, I don't want the scroll bar to be able to scroll down because there is no need. Also, I am able to click on the empty rows, which highlights the row, even though it is empty. How can I disable the ability to highlight the row?
public ProductApplication()
{
//WEST PANEL
JPanel west = new JPanel(new BorderLayout());
west.setBorder(BorderFactory.createMatteBorder(
5, 5, 5, 5, Color.blue));
west.add(new JTextField("Products"),
BorderLayout.NORTH);
pList = new JList(product);
pList.setFixedCellHeight(20);
pList.setFixedCellWidth(100);
west.add(pList, BorderLayout.CENTER);
scrollpane = new JScrollPane(pList);
west.add(scrollpane, BorderLayout.WEST);
add(west, BorderLayout.WEST);
1) If you needn't to show JScrollBar just create JScrollPane like next :
JScrollPane jScrollPane = new JScrollPane(list);
jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
2) You can manage highlight ability with help of ListCellRenderer.
Try next example:
import java.awt.Component;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
public class TestFrame extends JFrame {
public TestFrame(){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
});
}
private void init() {
DefaultListModel<String> model;
JList<String> l = new JList<>(model = new DefaultListModel<>());
l.setFixedCellHeight(20);
l.setFixedCellWidth(100);
model.addElement("");
for(int i=0;i<5;i++){
model.addElement(i+"");
}
model.addElement("");
model.addElement("5");
l.setCellRenderer(getRenderer());
JScrollPane jScrollPane = new JScrollPane(l);
jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
add(jScrollPane);
}
private ListCellRenderer<? super String> getRenderer() {
return new DefaultListCellRenderer(){
#Override
public Component getListCellRendererComponent(JList<?> list,Object value, int index, boolean isSelected,boolean cellHasFocus) {
Component listCellRendererComponent = super.getListCellRendererComponent(list, value, index, isSelected,cellHasFocus);
if((value == null || value.toString().isEmpty()) && isSelected){
listCellRendererComponent.setBackground(list.getBackground());
((JComponent)listCellRendererComponent).setBorder(null);
}
return listCellRendererComponent;
}
};
}
public static void main(String... s){
new TestFrame();
}
}
I am working on a the GUI of a piece of code that I have been patching together. I am stuck at this part of the program where I would like a datafile the user chooses to be displayed in a JTable in a preview manner (i.e. the user should not be able to edit the data on the table).
With a button click from Experiment Parameters tab (see screenshot below), I create and run a "PreviewAction" which creates a new tab, and fills it up with the necessary components. Below is the code for DataPreviewAction. EDIT: I also posted a self-contained, minimal version of this that mimics the conditions in the real project, and exhibits the same behaviour.
import java.awt.BorderLayout;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class MyFrame extends JFrame {
private JPanel panel1;
private JTabbedPane tabs;
private JButton runButton;
public MyFrame() {
tabs = new JTabbedPane();
panel1 = new JPanel();
runButton = new JButton("go!");
runButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
runButtonActionPerformed(evt);
}
});
panel1.add(runButton);
tabs.addTab("first tab", panel1);
this.add(tabs);
pack();
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
MyFrame frame = new MyFrame();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {
/*
* Normally there is more stuff happening here but this much will do for
* the sake of example
*/
List<String[]> data = new LinkedList<String[]>();
for (int i = 1; i < 1000; i++)
data.add(new String[] { "entry1", "value1", "value2", "value3" });
SwingUtilities.invokeLater(new DataPreviewAction(data, tabs));
}
public class DataPreviewAction implements Runnable {
private JTabbedPane contentHolder;
private List<String[]> data;
public DataPreviewAction(List<String[]> data, JTabbedPane comp) {
this.contentHolder = comp;
this.data = data;
}
#Override
public void run() {
DefaultTableModel previewModel = new DefaultTableModel() {
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
for (String[] datarow : data) {
previewModel.addRow(Arrays.copyOf(datarow, datarow.length,
Object[].class));
}
JTable table = new JTable(previewModel);
JPanel buttonPanel = new JPanel();
buttonPanel.add(new JButton("A button"));
buttonPanel.add(new JLabel(
"Some description for the awesome table below "));
buttonPanel.add(new JButton("another button"));
JScrollPane tablePanel = new JScrollPane(table);
JPanel container = new JPanel();
container.setLayout(new BorderLayout());
container.add(buttonPanel, BorderLayout.NORTH);
container.add(tablePanel, BorderLayout.CENTER);
contentHolder.addTab("Preview", container);
contentHolder.validate();
contentHolder.repaint();
}
}
}
There are at least two problems here:
The JTable (or the JScrollPane) does not render at all
The JScrollPane is not as wide as the frame itself, I have no idea why
I am not all that good in Swing so I might be missing something fundamental. I have checked that the datafile is read properly, and the data model contains the right amount of rows (1000+). SO the table should not be empty.
Suggestions?
JPanel buttonPanel = new JPanel();
buttonPanel.add(new JButton("A button"));
buttonPanel.add(new JLabel("Some description for the awesome table below "));
buttonPanel.add(new JButton("another button"));
JScrollPane tablePanel = new JScrollPane(table);
JPanel container = new JPanel();
container.add(buttonPanel,BorderLayout.NORTH);
container.add(tablePanel,BorderLayout.SOUTH);
contentHolder.addTab("Preview", container);
//contentHolder.validate(); <- NO good
//contentHolder.repaint(); <- --"---
}
JPanel uses FlowLayout (implemented in API, acceptiong only PreferredSize, by default isn't resizable), correct output as is demonstrated in attn image, you have to change default LayoutManager for JPanel to BorderLayout, then code lines
.
container.add(buttonPanel,BorderLayout.NORTH);
container.add(tablePanel,BorderLayout.SOUTH);
will expands JComponents and can be works as you expecting, but I think tablePanel should be placed in CENTER area
EDIT:
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class MyFrame extends JFrame {
private JPanel panel1;
private JTabbedPane tabs;
private JButton runButton;
private JFrame frame = new JFrame();
private String[] columnNames = {"Nama", "Nim", "IP", "Hapus Baris ke"};
private Object[][] data = {
{"igor", "B01_125-358", "1.124.01.125", true},
{"lenka", "B21_002-242", "21.124.01.002", true},
{"peter", "B99_001-358", "99.124.01.001", false},
{"zuza", "B12_100-242", "12.124.01.100", true},
{"jozo", "BUS_011-358", "99.124.01.011", false},
{"nora", "B09_154-358", "9.124.01.154", false},
{"xantipa", "B01_001-358", "1.124.01.001", false},};
private DefaultTableModel model = new DefaultTableModel(data, columnNames) {
private static final long serialVersionUID = 1L;
#Override
public boolean isCellEditable(int row, int column) {
switch (column) {
case 3:
return true;
default:
return false;
}
}
#Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
public MyFrame() {
tabs = new JTabbedPane();
panel1 = new JPanel();
runButton = new JButton("go!");
runButton.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
//
}
});
panel1.add(runButton);
tabs.addTab("first tab", panel1);
JTable table = new JTable(model);
JPanel buttonPanel = new JPanel();
buttonPanel.add(new JButton("A button"));
buttonPanel.add(new JLabel("Some description for the awesome table below "));
buttonPanel.add(new JButton("another button"));
JScrollPane tablePanel = new JScrollPane(table);
JPanel container = new JPanel();
container.setLayout(new BorderLayout());
container.add(buttonPanel, BorderLayout.NORTH);
container.add(tablePanel, BorderLayout.CENTER);
tabs.addTab("Preview", container);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(tabs);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MyFrame frame = new MyFrame();
}
});
}
}
EDIT 2nd. e.g.
from code (included your idea about to fill data to model)
import java.awt.BorderLayout;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class MyFrame extends JFrame {
private JPanel panel1;
private JTabbedPane tabs;
private JButton runButton;
private JFrame frame = new JFrame();
private String[] columnNames = {"Nama", "Nim", "IP", "Hapus Baris ke"};
private Object[][] data = {
{"igor", "B01_125-358", "1.124.01.125", "true"},
{"lenka", "B21_002-242", "21.124.01.002", "true"},
{"peter", "B99_001-358", "99.124.01.001", "false"},
{"zuza", "B12_100-242", "12.124.01.100", "true"},
{"jozo", "BUS_011-358", "99.124.01.011", "false"},
{"nora", "B09_154-358", "9.124.01.154", "false"},
{"xantipa", "B01_001-358", "1.124.01.001", "false"},};
private DefaultTableModel model = new DefaultTableModel(data, columnNames) {
private static final long serialVersionUID = 1L;
#Override
public boolean isCellEditable(int row, int column) {
switch (column) {
case 3:
return true;
default:
return false;
}
}
#Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
public MyFrame() {
tabs = new JTabbedPane();
panel1 = new JPanel();
runButton = new JButton("go!");
runButton.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
List<String[]> data = new LinkedList<String[]>();
for (int i = 1; i < 10; i++) {
data.add(new String[]{"entry1", "value1", "value2", "value3"});
}
for (String[] datarow : data) {
model.addRow(Arrays.copyOf(datarow, datarow.length, Object[].class));
}
}
});
panel1.add(runButton);
tabs.addTab("first tab", panel1);
JTable table = new JTable(model);
JPanel buttonPanel = new JPanel();
buttonPanel.add(new JButton("A button"));
buttonPanel.add(new JLabel("Some description for the awesome table below "));
buttonPanel.add(new JButton("another button"));
JScrollPane tablePanel = new JScrollPane(table);
JPanel container = new JPanel();
container.setLayout(new BorderLayout());
container.add(buttonPanel, BorderLayout.NORTH);
container.add(tablePanel, BorderLayout.CENTER);
tabs.addTab("Preview", container);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(tabs);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MyFrame frame = new MyFrame();
}
});
}
}
Following the footsteps of mKorbel I ended up doing some debugging. I am providing it here in case others run into the same problem.
It felt quite odd that the table looked OK when the underlying DataModel was supplied a data matrix upon initialisation
private DefaultTableModel model = new DefaultTableModel(data, columnNames)
but it would not show up properly when created with the empty constructor
private DefaultTableModel model = new DefaultTableModel()
and adding rows later with model.addRow(Object[] row);
I started look through the source code, and it turns out with the empty constructor the number of rows and columns for the model (private fields) is initiated to 0 and not updated properly afterwards. I noticed this while debugging since my tables had the dimension of 1370 x 0, which of course does not display properly.
Since I do not want to hardcode the number of rows/cols in advance the best course of action was to convert my "rows" to a matrix and provide the data to the model via constructor (much like mKorbel did). Here comes the fun part, if you want to supply the data then you need to supply the column names as well. THe fact that you have to have column names is counter-intuitive (IMHO), what happens if you dont have/need headers? The data is already in a table form, so I dont understand why column names is so important.
At any rate the following code renders the table at least:
String[] colNames = new String[data[1].length];
for(int i=0; i<colNames.length; i++)
colNames[i] = "C" + i;
DefaultTableModel model = new DefaultTableModel(data,colNames){
#Override
public boolean isCellEditable(int row, int column){
return false;
}};
I am accepting this because it points to the origin of the problem, but I would not be able to pinpoint the problem without mKorbel's answer, so give the upvote to his/her answer :)
I have a jTable which is populating according to my requirement . I want to add two comboboxes into all the cells in one column. So can anyone help me on this... ![here is my table ][1]
[1]: http://i.stack.imgur.com/nC9RL.jpg I need to add two comboboxes into all the rows of 1 st column. I did my coding into CREATE TABLE button which u can see in the image. here is my code so far : | |
int row=0;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
row=Integer.parseInt(jTextField2.getText());
row=row-1;
DefaultTableModel dtm =(DefaultTableModel) jTable1.getModel();
TableColumn sportColumn = jTable1.getColumnModel().getColumn(1);
JComboBox subject= new JComboBox();
box.addItem("DDD");
box.addItem("CCC");
JComboBox teacher= new JComboBox();
box1.addItem("AAA");
box1.addItem("FFF");
JPanel jPanel = new JPanel();
GroupLayout gl= new GroupLayout(jPanel);
jPanel.setLayout(gl);
jPanel.add(box);
jPanel.add(box1);
dtm.setRowCount(0);
dtm.setRowCount(Integer.parseInt(jTextField1.getText()));
for (int i = 0; i < dtm.getRowCount(); i++) {
row++;
dtm.setValueAt(String.valueOf(row), i, 0);
sportColumn.setCellRenderer(
(TableCellRenderer) new DefaultTableCellRenderer()
.getTableCellRendererComponent(
jTable1, jPanel, true, true, i, 1));
}
}
jButton1===> create table Button / jTextField2===> number starts with / jTextField1===>number of rows
Caverts:
I think this is a crazy idea, personally. If your cell represents a compound object, then I'd be thinking about using a dialog or some other means, but that's me.
Personally, I think this is going to blow up in your face...
Example
The concepts presented are all based on the information from How to use Tables
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.AbstractCellEditor;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
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;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumnModel;
public class Enrolement {
public static void main(String[] args) {
new Enrolement();
}
public Enrolement() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
DefaultTableModel model = new DefaultTableModel(new Object[]{"Subject"}, 10);
JTable tbl = new JTable(model);
TableColumnModel columnModel = tbl.getColumnModel();
columnModel.getColumn(0).setCellEditor(new SubjectTableCellEditor());
tbl.setRowHeight(columnModel.getColumn(0).getCellEditor().getTableCellEditorComponent(tbl, "Astronomy/Aurora Sinistra", true, 0, 0).getPreferredSize().height);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(tbl));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class SubjectTableCellEditor extends AbstractCellEditor implements TableCellEditor {
private JComboBox subject;
private JComboBox teacher;
private JPanel editor;
private Map<String, String[]> subjectTeachers = new HashMap<>(25);
public SubjectTableCellEditor() {
subjectTeachers.put("Astronomy", new String[]{"Aurora Sinistra"});
subjectTeachers.put("Charms", new String[]{"Filius Flitwick"});
subjectTeachers.put("Dark Arts", new String[]{"Igor Karkaroff", "Amycus Carrow"});
subjectTeachers.put("Defence Against the Dark Arts", new String[]{"Defence Against the Dark Arts",
"Quirinus Quirrell",
"Gilderoy Lockhart",
"Remus Lupin",
"Bartemius Crouch Jr.",
"Dolores Umbridge",
"Severus Snape",
"Amycus Carrow"});
subjectTeachers.put("Flying", new String[]{"Rolanda Hooch"});
subjectTeachers.put("Herbology", new String[]{"Herbert Beery",
"Pomona Sprout",
"Neville Longbottom"});
subjectTeachers.put("History of Magic", new String[]{"Professor Cuthbert Binns"});
subjectTeachers.put("Potions", new String[]{"Severus Snape",
"Horace Slughorn"});
subjectTeachers.put("Transfiguration", new String[]{"Minerva McGonagall",
"Albus Dumbledore"});
subject = new JComboBox(new String[]{
"Astronomy",
"Charms",
"Dark Arts",
"Defence Against the Dark Arts",
"Flying",
"Herbology",
"History of Magic",
"Potions",
"Transfiguration"
});
teacher = new JComboBox();
editor = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
editor.add(subject, gbc);
editor.add(teacher, gbc);
subject.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
teacher.setModel(new DefaultComboBoxModel(subjectTeachers.get(subject.getSelectedItem())));
}
});
}
#Override
public Object getCellEditorValue() {
return subject.getSelectedItem() + "/" + teacher.getSelectedItem();
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if (value instanceof String) {
String parts[] = value.toString().split("/");
subject.setSelectedItem(parts[0]);
teacher.setSelectedItem(parts[1]);
}
editor.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
return editor;
}
}
}
Here is an example table of what I have been using:
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane);
table = new JTable();
DefaultTableModel tableModel = new DefaultTableModel(new Object[]{"Row 1","Row 2"},0);
table.setModel(tableModel);
scrollPane.setViewportView(table);
I've attempted to use the following autoscrolling methods both with the same result.
// Method 1
JScrollBar vertical = scrollPane.getVerticalScrollBar();
vertical.setValue(vertical.getMaximum());
// Method 2
table.scrollRectToVisible(table.getCellRect(table.getRowCount(), 0, true));
Both examples go to the near-bottom of the table, up until the last (bottom) row that the user has to scroll down to see, only to happen again when another row is added.
EDIT: Example code to replicate the problem
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
public class ScrollTableEx extends JFrame {
private static final long serialVersionUID = 1L;
public int i = 100;
public JScrollPane scrollPane;
public JPanel contentPane;
public JTable table;
public JButton add;
public DefaultTableModel model = new DefaultTableModel(new Object[] { "Int (+)", "Int (-)" }, 0);
public static void main(String[] args) {
ScrollTableEx frame = new ScrollTableEx();
frame.setVisible(true);
}
public ScrollTableEx() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setSize(500,400);
scrollPane = new JScrollPane();
table = new JTable();
table.setCellSelectionEnabled(true);
table.setModel(model);
scrollPane.setViewportView(table);
for (int i = 0; i < 100; i++) {
model.addRow(new Object[] { i, i * -1 });
Rectangle goodRect = table.getCellRect(model.getRowCount() - 1, 0, true);
table.scrollRectToVisible(goodRect);
}
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Rectangle goodRect = table.getCellRect(model.getRowCount() - 1, 0, true);
table.scrollRectToVisible(goodRect);
model.addRow(new Object[] { i, i * -1 });
i++;
}
});
add(add, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
}
}
The problem is, JTable and TableModel are both 0 indexed. That is, the last value is actually rowCount - 1.
So when you use table.getCellRect(table.getRowCount(), 0, true), it's actually returning a Rectangle of the right position, just with a 0 height, because the row doesn't actually exist.
Instead you want to use table.getCellRect(table.getRowCount() - 1, 0, true)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Rectangle;
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.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class ScrollTable {
public static void main(String[] args) {
new ScrollTable();
}
public ScrollTable() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final DefaultTableModel model = new DefaultTableModel(new Object[]{"Test"}, 0);
for (int index = 0; index < 100; index++) {
model.addRow(new Object[]{index});
}
final JTable table = new JTable(model);
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.addRow(new Object[]{model.getRowCount()});
Rectangle badRect = table.getCellRect(model.getRowCount(), 0, true);
Rectangle goodRect = table.getCellRect(model.getRowCount() - 1, 0, true);
System.out.println("bad = " + badRect);
System.out.println("goodRect = " + goodRect);
table.scrollRectToVisible(goodRect);
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(table));
frame.add(add, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
I would avoid using .setBounds where possible. It does not take into consideration the variety of differences that exist between different computers and OS's and while it might look perfectly fine when you are developing, when you move it another system, it could produce undeseriable results - IMHO
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;