JTable appearing blank - java

I will only post the part that matters.
I have created a JFrame with a JPanel in it, that contains some JTextFields, JTextAreas and a JList. I know want to add a JTable to show some results, but it will appear blank. I tried checking out some posts, but I wasn't able to fix it.
I entered 2 rows manually, but they wouldn't appear. Nor would the column names. Please help!
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class GUI_Automata_Ex_1 extends JFrame {
public static int ScreenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
public static int ScreenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
public static int WindowWidth = ScreenWidth*3/4;
public static int WindowHeight = WindowWidth*9/16;
public static int unit = WindowWidth/160;
// tables used
static String[] columnNames = {"word", "length", "result"};
static Object[][] data = {{"abbaa", new Integer (5), "belongs"}, {"baabbb", new Integer (6), "does not belong"}};
public static JTable table_saved_words = new JTable(data, columnNames);
public static DefaultTableModel dtm_saved_words = new DefaultTableModel();
public static JScrollPane sp_saved_words;
public GUI_Automata_Ex_1 () {
// this will only run on ultrawide screens (e.g. 21:9 or 32:9) because the window is 16:9 optimized
if (ScreenWidth/2 > ScreenHeight) {
WindowHeight = ScreenHeight*3/4;
WindowWidth = WindowHeight*16/9;
unit = WindowWidth/160;
}
this.setTitle("Automata Theory 1st Excercise");
this.setBounds(ScreenWidth/2-WindowWidth/2,ScreenHeight/2-WindowHeight/2,WindowWidth,WindowHeight);
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBackground(colorBG);
Board board = new Board();
this.setContentPane(board);
this.setLayout(null);
// TABLES
// settings for table_saved_words
table_saved_words.setBackground(Color.white);
table_saved_words.setFont(fontM);
table_saved_words.setModel(dtm_saved_words);
table_saved_words.setPreferredScrollableViewportSize(new Dimension(unit*86, unit*50));
table_saved_words.setFillsViewportHeight(true);
sp_saved_words = new JScrollPane(table_saved_words);
board.add(sp_saved_words);
sp_saved_words.setBounds(unit*68, unit*32, unit*86, unit*50);
sp_saved_words.setWheelScrollingEnabled(true);
sp_saved_words.setViewportView(table_saved_words);
sp_saved_words.setVisible(false);
dtm_saved_words.addRow(new Object[]{"aabbbbaa", 5, "belongs"});
}
public class Board extends JPanel {
public void paintComponent (Graphics g) {
}
}
}
}
Here is a screenshot:
https://i.stack.imgur.com/AHtLf.png
The JTable is on the bottom-right. I did not include the code part for the other J-components.
What I want to do after I get the lists to show is simply add some rows as the window runs (words that the user enters and either belong to a dictionary or not and their length), but the part I'm stuck on is getting the JTable to show the columns and data.

Your table model has no columns, so it never shows the data you add to it.
From the documentation for the zero-argument DefaultTableModel constructor
Constructs a default DefaultTableModel which is a table of zero columns and zero rows.
Initially, your table has a valid table model created automatically:
JTable table_saved_words = new JTable(data, columnNames);
But then you create a new model, with no columns:
DefaultTableModel dtm_saved_words = new DefaultTableModel();

Related

How to Verify Required Fields in JTable

I have a JTable and I need to verify the input of 2 columns. That is 2 specific columns need to contain proper values in every cell. If they do then I want to enable a button. I know how to enable a button but I don't know where/how to verify those 2 columns. What table model method would be the appropriate place to verify those cells and enable the button, if any? I'm thinking I need a listener for those cells and process them in loseFocus(). The only issue is if the user leaves the cursor in one of those cells so it never loses focus even though the entry is valid. This must be a relatively common practice so there must be a best programming practice to accomplish it. TIA.
A TableModelListener added to the table's model will notify you of any change in the model's data. Within the listener, you can iterate through the rows, extracting column data with getValueAt(...) method, and then enable/disable your JButton or its Action accordingly.
For example, in the following code there are two columns of integers. The ints in the B column must be greater than the A column for the data to be valid. If this is not the case (or if any value is null), the button is disabled:
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
public class TableFun extends JPanel {
private Integer[][] DATA = {{1, 2}, {3, 4}, {5, 6}};
private String[] COL_NAMES = {"A", "B"};
private DefaultTableModel model = new DefaultTableModel(DATA, COL_NAMES) {
public java.lang.Class<?> getColumnClass(int columnIndex) {
return Integer.class;
};
};
private JTable table = new JTable(model);
private JButton myButton = new JButton("My Button");
public TableFun() {
model.addTableModelListener(new TableModelListener() {
#Override
public void tableChanged(TableModelEvent e) {
boolean valid = true;
for (int row = 0; row < model.getRowCount(); row++) {
Integer valueA = (Integer) model.getValueAt(row, 0);
Integer valueB = (Integer) model.getValueAt(row, 1);
if (valueA == null || valueB == null || valueA.compareTo(valueB) > 0) {
valid = false;
}
}
myButton.setEnabled(valid);
}
});
JPanel panel = new JPanel();
panel.add(myButton);
setLayout(new BorderLayout());
add(new JScrollPane(table));
add(panel, BorderLayout.PAGE_END);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
TableFun mainPanel = new TableFun();
JFrame frame = new JFrame("TableFun");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}

From JTable to Histogram - Swing

I have a JTable with three columns. For each rows I have a word, its type and the number of occurrences; for example in the next picture, the String "Rosing Prize" is present two times.
Starting from this JTable I want to build an histogram that takes as input the first and the last column. The first column is the name of bars and the last is its height; when the user selects some rows, they are represent in the histogram.
For example in this situation I have 4 rows selected:
The output are four J-Frames: the first with just one bar (that represents the first row); in the second J-Frame I have two bars (first and second row); in the third JFrame there are 3 bars for first, second and third row and, finally in the forth and last JFrame I have the correct output:
I thought about two possibilities to fix this problem:
to add a Jbutton and after one presses it the selected rows are drawn in the histogram
to add all JFrame to an ArrayList and to print only the last.
Are there better solutions?
I added a ListSelectionListener listener to my table model.
In your ListSelectionListener, update the chart's dataset only when getValueIsAdjusting() is false. This will defer updates until the selection is stable.
If I understand your question right, ListSelectionListener will solve your problem.
Define a selection listener first:
class MySelectionListener implements ListSelectionListener {
Then add it to your table's selection model:
MySelectionListener selectionListener = new MySelectionListener();
table.getSelectionModel().addListSelectionListener(selectionListener);
Edit:
Create a MouseListener. Then add it to your table. Here is a working sample code:
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JTable;
public class TableTest {
JFrame window = new JFrame();
private TableTest() {
createWindow();
}
public void createWindow() {
Object rowData[][] = { { "Row1-Column1", "Row1-Column2", "Row1-Column3" },
{ "Row2-Column1", "Row2-Column2", "Row2-Column3" },
{ "Row3-Column1", "Row3-Column2", "Row3-Column3" } };
Object columnNames[] = { "Column One", "Column Two", "Column Three" };
JTable table = new JTable(rowData, columnNames);
table.addMouseListener(new SelectionListener(table));
window.add(table);
window.pack();
window.setVisible(true);
}
public static void main(String[] args) {
new TableTest().createWindow();
}
}
class SelectionListener extends MouseAdapter {
JTable table;
public SelectionListener(JTable table) {
this.table = table;
}
#Override
public void mouseReleased(MouseEvent e) {
int[] rows = table.getSelectedRows();
for (int i = 0; i < rows.length; i++) {
System.out.println(rows[i]);
}
}
}

Preferred height of JPanel is lower then combined height of its children in table renderer

I have a JTable for which the renderer returns a JPanel composed of multiple JLabel instances. One of those JLabels can contain HTML used among other things to split the output over multiple lines using <br/> tags.
To show the multiple lines in the table, the renderer calls in the getTableCellRendererComponent method
table.setRowHeight(row, componentToReturn.getPreferredSize().height);
to dynamically update the row height, based on the contents. This only works correctly if componentToReturn indicates a correct preferred size.
It looks however that the getPreferredSize returns bogus values. The preferred height of the returned component is smaller than the sum of the heights of the labels inside the component.
Here is a little program illustrating this behaviour (without using a JTable)
import java.awt.*;
import javax.swing.*;
public class SwingLabelTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
LabelPanel renderer = new LabelPanel();
Component component = renderer.getComponent(false);
//asking for a bigger component will not
//update the preferred size of the returned component
component = renderer.getComponent(true);
}
});
}
private static class LabelPanel {
private final JPanel compositePanel;
private final JLabel titleLabel = new JLabel();
private final JLabel propertyLabel = new JLabel();
public LabelPanel() {
JPanel labelPanel = new JPanel();
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.PAGE_AXIS));
labelPanel.add(titleLabel);
labelPanel.add(propertyLabel);
compositePanel = new JPanel(new BorderLayout());
//normally it contains more components,
//but that is not needed to illustrate the problem
compositePanel.add(labelPanel, BorderLayout.CENTER);
}
public Component getComponent( boolean aMultiLineProperty ) {
titleLabel.setText("Title");
if ( aMultiLineProperty ){
propertyLabel.setText("<html>First line<br/>Property: value</html>");
} else {
propertyLabel.setText("Property: value");
}
int titleLabelHeight = titleLabel.getPreferredSize().height;
int propertyLabelHeight = propertyLabel.getPreferredSize().height;
int compositePanelHeight = compositePanel.getPreferredSize().height;
if ( compositePanelHeight < titleLabelHeight + propertyLabelHeight){
throw new RuntimeException("Preferred size of the component returned "
+ "by the renderer is incorrect");
}
return compositePanel;
}
}
}
As I am aware that the previous example is a bit far-fetched, here an example which includes a JTable
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class SwingTableTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
DefaultTableModel tableModel = new DefaultTableModel(0, 1);
JTable table = new JTable(tableModel);
table.setDefaultRenderer(Object.class, new DataResultRenderer());
tableModel.addRow(new Object[]{new Object()});
tableModel.addRow(new Object[]{new Object()});
tableModel.addRow(new Object[]{new Object()});
JFrame testFrame = new JFrame("TestFrame");
testFrame.getContentPane().add(new JScrollPane(table));
testFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
testFrame.setSize(new Dimension(300, testFrame.getPreferredSize().height));
testFrame.setVisible(true);
}
});
}
private static class DataResultRenderer implements TableCellRenderer {
private final JPanel compositePanel;
private final JLabel titleLabel = new JLabel();
private final JLabel propertyLabel = new JLabel();
public DataResultRenderer() {
JPanel labelPanel = new JPanel();
labelPanel.setOpaque(false);
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.PAGE_AXIS));
labelPanel.add(titleLabel);
labelPanel.add(propertyLabel);
compositePanel = new JPanel(new BorderLayout());
//normally it contains more components,
//but that is not needed to illustrate the problem
compositePanel.add(labelPanel, BorderLayout.CENTER);
}
#Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
titleLabel.setText("Title");
if ( row == 2 ){
propertyLabel.setText("<html>Single property: value</html>");
} else {
String text = "<html>";
text += "First property<br/>";
text += "Second property<br/>";
text += "Third property:value";
text += "</html>";
propertyLabel.setText(text);
}
int titleLabelHeight = titleLabel.getPreferredSize().height;
int propertyLabelHeight = propertyLabel.getPreferredSize().height;
int compositePanelHeight = compositePanel.getPreferredSize().height;
if ( compositePanelHeight < titleLabelHeight + propertyLabelHeight){
throw new RuntimeException("Preferred size of the component returned "
+ "by the renderer is incorrect");
}
table.setRowHeight(row, compositePanel.getPreferredSize().height);
return compositePanel;
}
}
}
I am looking for a way to update the row height of the table to ensure that the multi-line content is completely visible, without knowing up front how many lines each row will contain.
So either I need a solution to retrieve the correct preferred size, or my approach is completely wrong and then I need a better one.
Note that the above examples are simplified. In the real code, the "renderer" (the code responsible for creating the component) is decorated a few times. This means that the outer renderer is the only with access to the JTable, and it has no knowledge about what kind of Component the inner code returns.
Because setRowHeight() "Sets the height, in pixels, of all cells to rowHeight, revalidates, and repaints," the approach is unsound. Absent throwing an exception, profiling shows 100% CPU usage as an endless cascade of repaints tries to change the row height repeatedly. Moreover, row selection becomes unreliable.
Some alternatives include these:
Use TablePopupEditor to display multi-line content on request from a TableCellEditor.
Update an adjacent multi-line panel from a TableModelListener, as shown here.

Creating a custom TableModel with multiple column headers and row headers

I'm attempting to create a JTable that looks like the mockup below:
The green corner is basically buffer-space for the red column and row headers. The cells don't need to be rendered in the colours pictured; however they need to be distinguishable from the rest of the 'white' cells in the table.
This table also is not editable or selectable; it's merely viewed by a user whilst it is updated.
I know this can be achieved using a DefaultTableModel with custom renders for rows 1,2 && cols 1,2 and adding +2 when setting and getting table values (accounting for the rows and columns that are being used as headers).
My questions are as follows:
Is there a cleaner way of doing this without polluting my table model with these static values used in headers?
I've read about extending table models but I'm not sure which class should I extend (DefaultTableModel, AbstractTableModel) and what methods I should override.
Input is limited to 20x20 so including the headers that's 22x22.
Also consider a JScrollPane containing a JPanel having GridLayout and containing 22x22 instances JLabel, or a suitable subclass. This scales easily to several thousand cells.
Addendum: If the need arises, CellRendererPane makes a good flyweight renderer, as suggested here.
If you go with JTable for rendering scalability,
This is no abuse; it is exactly how TableModel is intended to be used. TableModel models a rectangular matrix of whatever you decide. JTable is just an (efficiently rendered) view of that model.
I prefer AbstractTableModel, shown here, because Vector is rarely the desired data structure. Use whatever container makes your indexing most convenient. DefaultTableModel is handy and serves as a guide to extending AbstractTableModel. In particular, you'll need a setValueAt().
#Override
public void setValueAt(Object aValue, int row, int col) {
... // update your data structure
this.fireTableCellUpdated(row, col); // notify the view
}
longer comment, everything depends
1) if is possible for Columns
resize
reordering
2) if is possible for Columns
filtering
sorting
a. then you have look at two JTables, first JTable only with TableHeader, simple with removed rows and second full sized JTable with TableHeader and Columns and rows,
b. for interactions betweens two JTableHeader is there
TableColumnModelListener#columnMarginChanged(ChangeEvent e) and columnMoved(TableColumnModelEvent e)
c. everyting put to one JPanel inside JScrollPane
d. if you'll change numbers of rows or colums (or filtering / sorting) then you have to notified JPanel for rezize JTable#getPreferredScrollableViewportSize() + Dimension for ontop JTable only with TableHeader
very similair way as there (is everything that you needed)
(endless kudos for Rob)
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class TableFilterRow extends JFrame implements TableColumnModelListener {
private static final long serialVersionUID = 1L;
private JTable table;
private JPanel filterRow;
public TableFilterRow() {
table = new JTable(3, 5);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
table.getColumnModel().addColumnModelListener(this);
// Panel for text fields
filterRow = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
for (int i = 0; i < table.getColumnCount(); i++) {
filterRow.add(new JTextField(" Sum at - " + i));
}
columnMarginChanged(new ChangeEvent(table.getColumnModel()));
getContentPane().add(filterRow, BorderLayout.SOUTH);
}
// Implement TableColumnModelListener methods
// (Note: instead of implementing a listener you should be able to
// override the columnMarginChanged and columMoved methods of JTable)
#Override
public void columnMarginChanged(ChangeEvent e) {
TableColumnModel tcm = table.getColumnModel();
int columns = tcm.getColumnCount();
for (int i = 0; i < columns; i++) {
JTextField textField = (JTextField) filterRow.getComponent(i);
Dimension d = textField.getPreferredSize();
d.width = tcm.getColumn(i).getWidth();
textField.setPreferredSize(d);
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
filterRow.revalidate();
}
});
}
#Override
public void columnMoved(TableColumnModelEvent e) {
Component moved = filterRow.getComponent(e.getFromIndex());
filterRow.remove(e.getFromIndex());
filterRow.add(moved, e.getToIndex());
filterRow.validate();
}
#Override
public void columnAdded(TableColumnModelEvent e) {
}
#Override
public void columnRemoved(TableColumnModelEvent e) {
}
#Override
public void columnSelectionChanged(ListSelectionEvent e) {
}
public static void main(String[] args) {
JFrame frame = new TableFilterRow();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
3) otherwise look How to Use Raised Borders in the prepareRederer
4) this question has nothing to do with type of TableModel

adding a JList to a table and adding the table to a scroll pane

I have created a JList and I want to add it to the table and then add the table to the scroll pane so that both of them will be contained in the scroll pane.
import model.*;
import java.awt. *;
import java.text.*;
import javax.swing.*;
import javax.swing.table.TableColumn;
public class ScrollPanel extends JPanel implements View
{
private Prison prison;
private String[] cells = new String[20];
private JList list = new JList(cells);
public ScrollPanel(Prison prison)
{
this.prison = prison;
prison.attach(this);
setup();
build(prison);
}
public void setup()
{
}
public void build(Prison prison)
{
int rows = 20;
int columns = 2;
for (int i = 0; i < 20; i++)
{
cells[i] = prison.cells().get(i).id();
}
JTable table = new JTable(rows, columns);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumn column = null;
column = table.getColumnModel().getColumn(0);
column.setPreferredWidth(91);
column = table.getColumnModel().getColumn(1);
column.setPreferredWidth(91);
table.add(list);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(220, 150));
add(scrollPane);
}
public void update()
{ }
}
This is how my program looks when I did the code I pasted above, which is adding the list to the table.
alt text http://img21.imageshack.us/img21/3237/11834317.jpg
When I added the table to the list and then to the scroll pane, this is how it looked. How do I add them both to the scroll pane with both of them showing?
alt text http://img27.imageshack.us/img27/3678/94687555.jpg
This is what it should look like..
alt text http://img21.imageshack.us/img21/1343/90528093.jpg
What do you want to achieve by adding a JList to a table? It's a fundamentally wrong thing to do - JTables aren't intended to have components added to them at all. If you want the table to display the items in the list, you need an implementation of the TableModel interface, not a JList.
Edit:
If you want the JList and the JTable to be displayed next to each other, you have to addthem both to a JPanel before adding that to the ScrollPane. But this is a rather unusualy thing to do; normally, a table is in a ScrollPane of its own. You could have a separate ScrollPane each for the table and the list. Or you could simply put the list items in the first column of the table. Which is better depends on your requirements.
I'm not sure what you are trying to achieve, if you just want to have the first column in the table show values for a row id like 1.1,1.2,1.3, etc, you could just add those to the first column of the jtable, you could even style that column different w/ Renderers. If that will not work then you could try and set the JList on the rowHeader of the scrollpane, similiar to the below. You will need to adjust the row height to accomodate the list height, or vice-versa. But this will achieve what you want and allow the list to scroll w/ the table. Good Luck!
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Scroll {
public static final void main(String[] args){
JFrame f = new JFrame();
f.setSize(new Dimension(400,400));
JList list = new JList(new Object[]{"1.1","1.2","1.3","1.4","1.5","1.6","1.7","1.8","1.9","1.10","1.11"});
JTable table = new JTable(11,10);
JScrollPane sp = new JScrollPane(table);
sp.setRowHeaderView(list);
f.getContentPane().add(sp);
f.setVisible(true);
}
}
Maybe you could add a "Details" button to each row of the table. If, so then the TableButtonColumn will help you out.

Categories