Names of my JTable columns not showing - java

I created a JFrame with Java Swing using a BorderLayout. Both east and west layout are fixed with some components, while BorderLayout at the center can change depending on what the user does. At the beginning there is a picture,
panelDinamycCenter = new JPanel ();
JScrollPane = new JScrollPane (panelDinamycCenter);
panelDinamycCenter.add (new JLabel ( "", new Imagelcon ( "......."), JLabel.CENTER));
jFrame.getContentPane (). add (JScrollPane, BorderLayout.CENTER);
Then a data entry screen, for which I used a GridBagLayout. In order to remove the picture and to insert the new screen I used this:
panelDinamycCenter.removeAll (),
then I add the various components. After
setVisible (true);
I have now created a JTable, to be included in panelDinamycCenter,
panelDinamycCenter.removeAll ();
String [] [] matrixValori = new String [arrayOggCreaJTableDeroghe.length] [arrayJTableNomeColumnDeroghe.length];
for (int i = 0; i <arrayOggCreaJTableDeroghe.length; i ++) {
matrixValori [i] = arrayOggCreaJTableDeroghe [i] .creaArrayString ();
}
DefaultTableModel model = new DefaultTableModel (matrixValori, arrayJTableNomeColumnDeroghe);
JTable JTable = new JTable (model);
jTable.setAutoResizeMode (JTable.AUTO_RESIZE_OFF);
panelDinamycCenter.add (JTable);
jFrame.setVisible (true);
All right, but I can not see the names of the columns. Why?

As shown in How to Use Tables: Adding a Table to a Container, "The scroll pane automatically places the table header at the top of the viewport." At a minimum, you need to replace the JScrollPane removed by removeAll():
JTable jTable = new JTable(model);
panelDinamycCenter.add(new JScrollPane(jTable));
Among alternatives, consider these:
Add the table header to PAGE_START, as suggested here.
Instead of removing and restoring, use CardLayout to switch between views.

Related

Java swing JTable doesn't show scroll bar when using JScrollPane

I have a tablePanel which is a JScrollPane,and initialized with a JTable, the JTable initialized with a defaultTableModel.When I trying to add some rows to the table, but didn't see the scroll bar, appriciated for any reply.
JFrame jFrame = new JFrame();
//rows will be added dynamically.
DefaultTableModel defautTableModel = new DefaultTableModel(null,columnNames){
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
JTable jTable = new JTable(defautTableModel);
jTable.setLocation(20,60);
jTable.setSize(950,450);
jTable.setRowHeight(25);
jTable.getColumn("No.").setMaxWidth(45);
jTable.getColumn("position").setMaxWidth(45);
...
JTableHeader jTableHeader = jTable.getTableHeader();
jTableHeader.setLocation(20,30);
jTableHeader.setSize(950,30);
jTableHeader.setFont(new Font(null, Font.BOLD, 16));
jTableHeader.setResizingAllowed(true);
jTableHeader.setReorderingAllowed(true);
JScrollPane tablePanel = new JScrollPane(jTable);
tablePanel.setLayout(null);
tablePanel.add(jTableHeader);
tablePanel.add(jTable);
jFrame.setContentPane(tablePanel);
tablePanel.setLayout(null); is the primary cause of your problem. A JScrollPane has its own layout manager which is used to manage the scrollbars, view port and headers.
tablePanel.add is your next problem, as you shouldn't be adding components to the JScrollPane. Instead, you should be setting the JScrollPane's JViewPort.
But, since you're using JScrollPane tablePanel = new JScrollPane(jTable);, there's actually no need for the three lines which follow it.
I would highly recommend that you take a closer look at:
How to us tables
How to use scroll panes
Laying Out Components Within a Container
Now, before you tell me how nothing I've suggested actually works, go and re-read Laying Out Components Within a Container - this is the corner stone concept you will need to understand and master before Swing really begins to work for you
JScrollPane tablePanel = new JScrollPane(jTable);
// No need for the below code
/*tablePanel.setLayout(null);
tablePanel.add(jTableHeader);
tablePanel.add(jTable);*/
jFrame.setContentPane(tablePanel);

Delete/Hide margins of a Jtable

I have used a JTable only for the alignement of the values I want to display.
So far I my table looks like this:
What I want is to delete the margin of the table, so it can't be noticed that it is a table. Is there a way to make this possible?
My code:
displayNames = new ArrayList<String>();
displayClasses = new ArrayList<String>();
for (int i=0; i<displayName.size(); i++) {
displayNames.add(displayName.get(i));
displayClasses.add(classes.get(i));
}
Object rowData[][] = { displayNames.toArray(), displayClasses.toArray() };
Object columnNames[] = displayNames.toArray();
JTable table = new JTable(rowData, columnNames);
table.setTableHeader(null);
table.setShowGrid(false);
table.setBackground(Color.LIGHT_GRAY);
tablePane = new JScrollPane(table);
tablePane.setPreferredSize(new Dimension(765,40));
tablePane.setBackground(Color.LIGHT_GRAY);
rightPanel.removeAll();
rightPanel.updateUI();
rightPanel.add(tablePane);
public void showGUI() {
JFrame frame = new JFrame();
frame.add(leftPanel,BorderLayout.EAST);
frame.add(listScrollPane,BorderLayout.WEST);
frame.add(rightPanel);
frame.setSize(1000,500);
frame.setLocation(200,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
It sounds like you want to use setBorder on the JScrollPane
tablePane.setBorder(BorderFactory.createEmptyBorder());
Answered in more detail here.
tablepane.setBorder(BorderFactory.createEmptyBorder());
The margin (and border) are showing because you place your table in a JScrollPane.
If you use rightPanel.add(**table**), the margin is gone.
If still want the border, you can manually add a border to the table using table.setBorder(...).
By not using the JScrollPane, you obviously will also lose the ability to scroll... I'm not sure if this is a problem for you.
I also agree with Andrew: you shouldn't use a table for this, use GridBagLayout instead.

Adding JScrollPane to JTable doesn't show up

I'm pretty new to Javas swings, so sorry if this is something trivial. This is the constructor, I excluded unnecessary form items. (I tried running the code as short as this, but the problem still appears)
//This just opens a connection to MySQL server, this doesn't create any problems.
bp = BazaPodataka.getBaza();
//Forming the main frame..
JFrame frame = new JFrame();
{
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
frame.setBounds(d.width/2 - sirina/2, d.height/2 - visina/2, sirina, visina);
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
//Adding a layered pane so I can place items inside the form more 'freely'
JLayeredPane layeredPane = new JLayeredPane();
frame.getContentPane().add(layeredPane, BorderLayout.CENTER);
//Adding a table
JTable table = new JTable();
String[] rowData = {"Name:", "Price:", "Cathegory:", "Sum:"};
DefaultTableModel model = new DefaultTableModel(rowData, 0);
JScrollPane skrol = new JScrollPane(table);
table.setModel(model);
//The 2 lines below work as intended
ResultSet rs = (ResultSet) bp.query("SELECT * FROM table"); //This calls a query
popuniTabelu(rs, model); //This populates the table.
table.setBounds(10, 110, 500, 350);
table.setEnabled(false);
table.setShowHorizontalLines(false);
layeredPane.add(table);
Populating the table and displaying it isn't the problem, there's enough information inside the table 'table' that the user even needs to scroll down.
But that's where the problem begins, the scroll doesn't show up. How do I implement it from here. I tried following solutions I found on google, but they pretty much sum up on:
JScrollPane scroll = new JScrollPane(table);
Which simply doesn't work in my case.
The problem may be trivial, if it is, I'm sorry, I'm still learning swing. Also, sorry for my bad english, it's not my native language. :)
Also, if there's something I forgot to include, please let me know.
Thank you!
You add your table to 2 components :
JScrollPane skrol = new JScrollPane(table);
and
layeredPane.add(table);
Because of Swing component can have just one parent component second statment override first, so your JScrollPane is empty. Seems you need to remove layeredPane.add(table);
As mentioned here
Each GUI component can be contained only once. If a component is already in a container and you try to add it to another container, the component will be removed from the first container and then added to the second.

JTable Not Showing Up In JPanel

I'm trying to create a JTable with the column headers defined in colName using a DefaultTableModel, then adding the table to a JScrollPane then to a JPanel. However, when I add the panel to my JFrame, only the panel shows up, not the table. I am using similar code in another table, and that one shows up fine, only difference being the number of columns and variable names.
What am I missing?
My code :
//Column Names
final String[] colNames = {"Item", "Count"};
DefaultTableModel dtm = new DefaultTableModel(0, colNames.length);
//Panel to hold Table
JPanel j = new JPanel(new BorderLayout());
j.setBounds(9, 78, 267, 254);
//Colored to see if the panel has been added
j.setBackground(Color.RED);
//Set Column Headers
dtm.setColumnIdentifiers(colNames);
//Jtable with model
JTable t = new JTable(dtm);
t.setBackground(Color.GREEN);
t.getTableHeader().setReorderingAllowed(false);
t.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
t.getColumnModel().getColumn(0).setPreferredWidth(113);
t.doLayout();
j.add(new JScrollPane(t), BorderLayout.CENTER);
I would suggest that the column's are being overridden by those reported back by the table model. You could instead use...
String[] colNames = {"Item", "Count"};
DefaultTableModel dtm = new DefaultTableModel(colNames, 0);
JPanel j = new JPanel(new BorderLayout());
JTable t = new JTable(dtm);
t.setBackground(Color.GREEN);
t.getTableHeader().setReorderingAllowed(false);
t.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
t.getColumnModel().getColumn(0).setPreferredWidth(113);
j.add(new JScrollPane(t), BorderLayout.CENTER);
Instead...
Without seeing the code you're using to put the table on the frame, it's difficult to comment further, however...
Avoid using setBounds, it's pointless in this context any way.
The background color will actually be defined more by the view port then the table or panel until the table is either configured to fill the empty space or has enough rows to fill the empty space

Fit JTable to fill the JPanel

Hi here are my codes for my table settings:
String [] column = {"MacAddress","PcName","OperatingSystem","IpAddress","Port","Status"};
model = new DefaultTableModel(0,column.length);
model.setColumnIdentifiers(column);
mainTable = new JTable(model);
mainTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for(int i=0;i<=column.length-1;i++){
mainTable.getColumnModel().getColumn(i).setPreferredWidth(300);
}
pane = new JScrollPane(mainTable);
pnlTabel = new JPanel();
pnlTabel.setBorder(BorderFactory.createTitledBorder(""));
pnlTabel.setPreferredSize(new Dimension(dim.width*70/100, dim.height*60/100));
pnlTabel.add(pane);
addMainPanel(pnlTabel);
Here is my addMainPanel() function:
public void addMainPanel(Component pnl){
mainPanel.add(pnl);
mainPanel.revalidate();
}
And here is my code for my mainPanel:
mainPanel = new JPanel();
mainPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
add(mainPanel,"Center");
and I'm using border layout for my frame:
setLayout(new BorderLayout(0,0));
My problem is that, even i use this set of code to set my JTable to fit but it seems to fail all the this, this code:
mainTable.setAutoResizeMode(JTa![enter image description here][1]ble.AUTO_RESIZE_OFF);
for(int i=0;i<=column.length-1;i++){
mainTable.getColumnModel().getColumn(i).setPreferredWidth(300);
}
When is use that code, my jtable does not resize but only add on a horizontal scroll bar at the bottom.
No offense meant but .. your code and consequently your question is a mess ;-) Plus you don't explain what exactly you want to achieve.
Trying to detangle, taking the nested layouts/resizing characteristics (as seen in the snippets, might not be complete):
frame // BorderLayout
mainPanel // FlowLayout
pnlTabel // FlowLayout, hard-coded prefSize
pane // scrollPane
mainTable // auto-resize-off
Aside: intentionally kept untelling names to demonstrate how mixing naming schemes tend to contribute to overall confusion :-) Doesn't really matter whether you decide for pre or postFixing some type-related marker, but if you do be consistent.
In that hierarchy, there are two levels of FlowLayout which basically will layout their children at their respective prefs and adjusting their own pref accordingly, lest the pref were hard-coded on the level of the pnlTable: however the table's pref will be changed (by changing the column prefs) it cannot bubble further up because ... hard-coding the pref leads not calculating its size (neither by layoutManager and nor uiDelegate, both never get a chance to do it)
Another issue - the more interesting one :-) - is that the JScrollPane is somewhat special in
calculating its own prefSize from its view's pref/scrollablePrefViewportSize depending on whether or not the view implements Scrollable (JTable does so, though in a crappy way)
being a validationRoot: invalidating the view (or any children) doesn't bubble further up the hierarchy
Assuming that you want the table's scrollPane to grow if the prefWidts of the columns change, there are two thingies to tweak:
implement table's getPreferredScrollableWidth to return a value calculated based on the prefWidth of the columns
revalidate a container higher up in the hierarchy
Some code to play with:
final JTable table = new JTable(50, 10) {
// properties to base a reasonable prefScrollable size
int visibleColumns = 3;
int visibleRows = 10;
// hard-coded default in super
Dimension dummySuper = new Dimension(450, 400);
#Override
public Dimension getPreferredScrollableViewportSize() {
Dimension dim = super.getPreferredScrollableViewportSize();
if (!dummySuper.equals(dim)) return dim;
dim = new Dimension();
for (int column = 0; column < Math.min(visibleColumns, getColumnCount()); column++) {
dim.width += getColumnModel().getColumn(column).getPreferredWidth();
}
dim.height = visibleRows * getRowHeight();
return dim;
}
};
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for (int i = 0; i < table.getRowCount(); i++) {
table.setValueAt("row: " + i, i, 0);
}
JComponent tablePanel = new JPanel();
tablePanel.add(new JScrollPane(table));
Action sizeColumns = new AbstractAction("size columns") {
int prefWidth = 75;
#Override
public void actionPerformed(ActionEvent e) {
int newWidth = prefWidth + 15;
for (int i = 0; i < table.getColumnCount(); i++) {
if (table.getColumnModel().getColumn(i).getPreferredWidth() == prefWidth)
table.getColumnModel().getColumn(i).setPreferredWidth(newWidth);
}
prefWidth = newWidth;
// revalidate "higher up" than the table itself
frame.revalidate();
}
};
frame.add(new JButton(sizeColumns), BorderLayout.SOUTH);
If you want a JTable to fill the available space, you should put it inside a JPanel which has a BorderLayout layout manager. Also don't forget about the JScrollPane which ensures that if the table doesn't fit into the view (e.g. too many rows), scrollbars will appear:
JFrame frame = new JFrame();
// set up frame
JTable table = new JTable();
// Set up table, add data
// Frame has a content pane with BorderLayout by default
frame.getContentPane().add( new JScrollPane( table ), BorderLayout.CENTER );
If you have other content you wish to display besides the table, you can add those to the NORTH, SOUTH, EAST, WEST parts of the content panel (which can be wrapped into other panels if more components are to be placed there).

Categories

Resources