JTable not showing column titles - java

This is my first time working with GUI, so I'm not exactly sure what is causing the problem. I have an assignment from my Uni. The project is to make a sort of "Product management" program for various purposes. The whole thing is done except the GUI, and this is where I just don't get it why this JTable won't display column titles. Here's the code (btw, using MIGLayout)
package sepm.s2012.e0727422.gui;
import sepm.s2012.e0727422.service.*;
import java.awt.*;
import javax.swing.*;
import net.miginfocom.swing.MigLayout;
public class MainFrame {
/** Start all services **/
// IProductService ps = new ProductService();
// IInvoiceService is = new InvoiceService();
// IOrderService os = new OrderService();
/** Frame **/
private JFrame frame;
private JTabbedPane tab;
public static void main(String[] args) {
new MainFrame();
}
public MainFrame() {
frame = new JFrame("Product control and management system");
frame.setVisible(true);
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/** TABBED PANE options and parameters **/
tab = new JTabbedPane();
ImageIcon icon = null; // TODO
tab.addTab("Products", icon, tabProducts(), "Add/Update/Delete products");
tab.addTab("Invoices", icon, tabInvoices(), "Overview of invoices");
tab.addTab("Cart", icon, tabCart(), "Order new products");
tab.setSelectedIndex(0);
frame.add(tab, BorderLayout.CENTER);
}
/**
* Products Panel tab
* #return panel
*/
public JPanel tabProducts() {
JPanel panel = new JPanel(new MigLayout("","20 [] 20", "10 [] 10 [] 10 [] 10"));
JLabel label = new JLabel("List of all available products");
JButton add = new JButton("Add product");
JButton update = new JButton("Update product");
// Below is a test table, will be replace by products in DB
String[] tableTitle = new String[] {"ID", "Name", "Type", "Price", "In stock"};
String[][] tableData = new String[][] {{"1", "Item 1", "Type 1", "0.00", "0"}, {"2", "Item 2", "Type 2", "0.00", "0"},
{"3", "Item 3", "Type 3", "0.00", "0"}, {"4", "Item 4", "Type 4", "0.00", "0"}};
JTable table = new JTable(tableData, tableTitle);
panel.add(label, "wrap, span");
panel.add(table, "wrap, span");
panel.add(add);
panel.add(update);
return panel;
}
public JPanel tabInvoices() {
JPanel panel = new JPanel(new MigLayout());
return panel;
}
public JPanel tabCart() {
JPanel panel = new JPanel(new MigLayout());
return panel;
}
}

Add the table to a JScrollPane
The docs for JTable state:
.. Note that if you wish to use a JTable in a standalone view (outside of a JScrollPane) and want the header displayed, you can get it using getTableHeader() and display it separately.

At first add your table to a JScrollPane:
JScrollPane scrollpane = new JScrollPane(table);
then add the scrollpane to your layout :
panel.add(scrollpane, "wrap, span");
Secondly, add all your components to the frame and make it visible at the end of your method:
//...
frame.add(tab, BorderLayout.CENTER);
frame.validate();
frame.setVisible(true);

For miglayout I use this:
JPanel panel = new JPanel(new MigLayout("wrap 1, gapy 0"));
table = CreateParametersTable();
panel.add(table.getTableHeader(), "width 100%");
panel.add(table, "width 100%");
For removing vertical gaps read this How to remove vertical gap between two cells in MigLayout?

Related

How to Maximize and Minimize a JTable which is inside a JPanel in Swing?

I am making a Swing GUI. I am not getting how to max and min the JTable which is inside a JPanel.
Edit From comments
You comment said I want to make the table "full screen". If by full screen you mean, the size of the container, you can simply do.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.BorderLayout;
public class JTableExample {
public static void main(String[] args) {
JPanel borderLayoutPanel = new JPanel(new BorderLayout());
String[] headers = {"Header 1", "Header 2", "etc..."};
String[][] data = {{"Some data", "some more data", "etc..."},
{"Some data 1", "some more data 3", "etc..."},
{"Some data 2", "some more data 4", "etc..."}};
JTable table = new JTable(data, headers);
JScrollPane scrollableTable = new JScrollPane(table);
borderLayoutPanel.add(scrollableTable, BorderLayout.CENTER);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(borderLayoutPanel);
frame.setSize(800, 800);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
If you actually want a full screen window, look at this.
There are a few ways to do it.
I recommend you read this question as it will help explain why null layouts are bad.
The TLDR is basically use a layout manager. My preferred layout manager is MigLayout as it is simple to use and understand but full of features. If you can't use MigLayout as it is a 3rd party library, then use something like GridBagLayout
MigLayout Website and MigLayout Download Page.
My Preferred Layout Manager
If you are willing to use a third part layout manager, then I think MigLayout is the way to go. It provides more control and I think is easier to use than most layout managers.
private JPanel createMigPanel() {
String layoutConstraints = "fillx, filly";
String columnAndRowConstraints = "fill, grow, center";
JPanel migPanel = new JPanel(new MigLayout(layoutConstraints, columnAndRowConstraints, columnAndRowConstraints));
String[] headers = {"Header 1", "Header 2", "etc..."};
String[][] data = {{"Some data", "some more data", "etc..."},
{"Some data 1", "some more data 3", "etc..."},
{"Some data 2", "some more data 4", "etc..."}};
JTable table = new JTable(data, headers);
JScrollPane scrollableTable = new JScrollPane(table);
migPanel.add(new JScrollPane(table), "width 400:500:800, height 400:500:800");
return migPanel;
}
The Bad Way
If you must use a null layout in a JPanel, which is not recommended at all, then you can use two buttons to set the table to its min / max size.
// Not recommended
private JPanel createNullPanel() {
JPanel nullPanel = new JPanel(null);
String[] headers = {"Header 1", "Header 2", "etc..."};
String[][] data = {{"Some data", "some more data", "etc..."},
{"Some data 1", "some more data 3", "etc..."},
{"Some data 2", "some more data 4", "etc..."}};
JTable table = new JTable(data, headers);
JScrollPane scrollableTable = new JScrollPane(table);
scrollableTable.setMinimumSize(new Dimension(100, 100));
scrollableTable.setMaximumSize(new Dimension(500, 500));
JButton minButton = new JButton("Min");
minButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
scrollableTable.setSize(scrollableTable.getMinimumSize());
}
});
minButton.setBounds(10, 10, 50, 25);
nullPanel.add(minButton);
JButton maxButton = new JButton("Min");
maxButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
scrollableTable.setSize(scrollableTable.getMaximumSize());
}
});
maxButton.setBounds(70, 10, 50, 25);
nullPanel.add(maxButton);
nullPanel.add(scrollableTable);
scrollableTable.setBounds(10, 45, 300, 300);
return nullPanel;
}
Inbuilt Layout Manager
But, you can use a layout manager. One that is a bit complicated but provides some more control than most is the GridBagLayout.
private JPanel createGridBagPanel() {
JPanel gridBagPanel = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.weightx = 1;
constraints.weighty = 1;
constraints.fill = GridBagConstraints.BOTH;
constraints.insets = new Insets(10, 10, 10, 10);
String[] headers = {"Header 1", "Header 2", "etc..."};
String[][] data = {{"Some data", "some more data", "etc..."},
{"Some data 1", "some more data 3", "etc..."},
{"Some data 2", "some more data 4", "etc..."}};
JTable table = new JTable(data, headers);
JScrollPane scrollableTable = new JScrollPane(table);
scrollableTable.setMinimumSize(new Dimension(400, 400));
scrollableTable.setPreferredSize(new Dimension(500, 500));
scrollableTable.setMaximumSize(new Dimension(800, 800));
// Nasty work around to support min and max size
// https://stackoverflow.com/questions/15161332/setting-up-a-maximum-component-size-when-using-gridbaglayout-in-java
JPanel wrappingPanel = new JPanel(null);
wrappingPanel.setLayout(new BoxLayout(wrappingPanel, BoxLayout.LINE_AXIS));
wrappingPanel.add(scrollableTable);
gridBagPanel.add(wrappingPanel, constraints);
return gridBagPanel;
}
Complete code sample
import net.miginfocom.swing.MigLayout;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JTableExample {
private void run() {
setUpWindow();
}
private void setUpWindow() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.getContentPane().add(createNullPanel());
// frame.getContentPane().add(createGridBagPanel());
frame.getContentPane().add(createMigPanel());
// If using null layout manager
// frame.setSize(800, 800);
// If using a none null layout manager
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// Not recommended
private JPanel createNullPanel() {
JPanel nullPanel = new JPanel(null);
String[] headers = {"Header 1", "Header 2", "etc..."};
String[][] data = {{"Some data", "some more data", "etc..."},
{"Some data 1", "some more data 3", "etc..."},
{"Some data 2", "some more data 4", "etc..."}};
JTable table = new JTable(data, headers);
JScrollPane scrollableTable = new JScrollPane(table);
scrollableTable.setMinimumSize(new Dimension(100, 100));
scrollableTable.setMaximumSize(new Dimension(500, 500));
JButton minButton = new JButton("Min");
minButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
scrollableTable.setSize(scrollableTable.getMinimumSize());
}
});
minButton.setBounds(10, 10, 50, 25);
nullPanel.add(minButton);
JButton maxButton = new JButton("Min");
maxButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
scrollableTable.setSize(scrollableTable.getMaximumSize());
}
});
maxButton.setBounds(70, 10, 50, 25);
nullPanel.add(maxButton);
nullPanel.add(scrollableTable);
scrollableTable.setBounds(10, 45, 300, 300);
return nullPanel;
}
private JPanel createGridBagPanel() {
JPanel gridBagPanel = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.weightx = 1;
constraints.weighty = 1;
constraints.fill = GridBagConstraints.BOTH;
constraints.insets = new Insets(10, 10, 10, 10);
String[] headers = {"Header 1", "Header 2", "etc..."};
String[][] data = {{"Some data", "some more data", "etc..."},
{"Some data 1", "some more data 3", "etc..."},
{"Some data 2", "some more data 4", "etc..."}};
JTable table = new JTable(data, headers);
JScrollPane scrollableTable = new JScrollPane(table);
scrollableTable.setMinimumSize(new Dimension(400, 400));
scrollableTable.setPreferredSize(new Dimension(500, 500));
scrollableTable.setMaximumSize(new Dimension(800, 800));
// Nasty work around to support min and max size
// https://stackoverflow.com/questions/15161332/setting-up-a-maximum-component-size-when-using-gridbaglayout-in-java
JPanel wrappingPanel = new JPanel(null);
wrappingPanel.setLayout(new BoxLayout(wrappingPanel, BoxLayout.LINE_AXIS));
wrappingPanel.add(scrollableTable);
gridBagPanel.add(wrappingPanel, constraints);
return gridBagPanel;
}
private JPanel createMigPanel() {
String layoutConstraints = "fillx, filly";
String columnAndRowConstraints = "fill, grow, center";
JPanel migPanel = new JPanel(new MigLayout(layoutConstraints, columnAndRowConstraints, columnAndRowConstraints));
String[] headers = {"Header 1", "Header 2", "etc..."};
String[][] data = {{"Some data", "some more data", "etc..."},
{"Some data 1", "some more data 3", "etc..."},
{"Some data 2", "some more data 4", "etc..."}};
JTable table = new JTable(data, headers);
JScrollPane scrollableTable = new JScrollPane(table);
migPanel.add(new JScrollPane(table), "width 400:500:800, height 400:500:800");
return migPanel;
}
public static void main(String[] args) {
JTableExample example = new JTableExample();
example.run();
}
}

JTable width layout

I'm creating a GUI interface to interact with the database of a warehouse. The application needs to add items to the database, update them and show them. I have some tables in the database and for each table, I want to create a JPanel, and put them in a cardlayout, so I can navigate between them with JMenu items. Each JPanel has the same form. In the top, there is a box with textfields, comboboxes etc. to add an item in the table. Under the box, I have a JTable with 1 row and under that, I have a JTable in a JScrollPane to show the content of the table. Each column needs to have a width of 150, except the last one (width=100, it will contain a JButton for modifications). I use the first JTable as a filter (for example if the first column contains '1', then the second JTable will only show items with an ID starting by '1'). I don't know how to choose correct layouts for different JPanels. For the moment, each JPanel has a BorderLayout and each component is placed in the center. But the problem is that I can't choose the width of each column.
Well, finally I've solved my own problem. Actually, I need to put the JTable in a JPanel, and the JPanel in a JScrollPane. Here is the code :
public class Brouillon extends JFrame {
public Brouillon() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jpContent = new JPanel();
JPanel jpCards = new JPanel();
jpContent.setLayout(new BoxLayout(jpContent, BoxLayout.PAGE_AXIS));
CardLayout clSelect = new CardLayout();
jpCards.setLayout(clSelect);
JButton jbTest = new JButton();
jbTest.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
clSelect.next(jpCards);
}
});
jpContent.add(jbTest);
JPanel jpContainer1 = new JPanel();
JTable jtData1 = new JTable(new Object[2][3], new String[] {"1", "2", "3"});
jtData1.getColumnModel().getColumn(0).setPreferredWidth(150);
jtData1.getColumnModel().getColumn(1).setPreferredWidth(150);
jtData1.getColumnModel().getColumn(2).setPreferredWidth(50);
JPanel jpTemp1 = new JPanel();
jpTemp1.setLayout(new BorderLayout());
jpTemp1.add(jtData1.getTableHeader(), BorderLayout.NORTH);
jpTemp1.add(jtData1, BorderLayout.CENTER);
JScrollPane jspData1 = new JScrollPane(jpTemp1);
jpContainer1.add(jspData1);
JPanel jpContainer2 = new JPanel();
JTable jtData2 = new JTable(new Object[2][7], new String[] {"1", "2", "3", "4", "5", "6", "7"});
jtData2.getColumnModel().getColumn(0).setPreferredWidth(150);
jtData2.getColumnModel().getColumn(1).setPreferredWidth(150);
jtData2.getColumnModel().getColumn(2).setPreferredWidth(150);
jtData2.getColumnModel().getColumn(3).setPreferredWidth(150);
jtData2.getColumnModel().getColumn(4).setPreferredWidth(150);
jtData2.getColumnModel().getColumn(5).setPreferredWidth(150);
jtData2.getColumnModel().getColumn(6).setPreferredWidth(50);
JPanel jpTemp2 = new JPanel();
jpTemp2.setLayout(new BorderLayout());
jpTemp2.add(jtData2, BorderLayout.CENTER);
jpTemp2.add(jtData2.getTableHeader(), BorderLayout.NORTH);
JScrollPane jspData2 = new JScrollPane(jpTemp2);
jpContainer2.add(jspData2);
jpCards.add(jpContainer2);
jpCards.add(jpContainer1);
jpContent.add(jpCards);
this.getContentPane().add(jpContent);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
new Brouillon();
}
}
For jTable, you can set the column size.
Possibly the below example may help. Please let me know if this is what you are looking for!
TableColumn column = null;
for (int i = 0; i < 3; i++) {
column = table.getColumnModel().getColumn(i);
if (i == 2) {
column.setPreferredWidth(100); //sport column is bigger
} else {
column.setPreferredWidth(50);
}
}

Unable to get column name in JTable in Swing

JTable table = new JTable(data,columnNames);
JScrollPane pane = new JScrollPane(table);
this.add(pane);
this.add(table);
My data is showing but column name is not showing on top.
A component can only have a single parent.
JScrollPane pane = new JScrollPane(table);
this.add(pane);
this.add(table);
First you add the table to the viewport of the scrollpane, which is good as this will cause the table header to automatically be displayed when the GUI is made visible.
But then you add the table directly to the frame, which is bad because it can no longer be displayed in the scrollpane.
Get rid of:
//this.add(table);
and then the scrollpane containing the table will be displayed properly on the frame.
Have a look at this example
import java.awt.Color;
import javax.swing.*;
public class table extends JFrame{
public table() {
setSize(600, 300);
String[] columnNames = {"A", "B", "C"};
Object[][] data = {
{"Moni", "adsad", 2},
{"Jhon", "ewrewr", 4},
{"Max", "zxczxc", 6}
};
JTable table = new JTable(data, columnNames);
JScrollPane tableSP = new JScrollPane(table);
JPanel tablePanel = new JPanel();
tablePanel.add(tableSP);
tablePanel.setBackground(Color.red);
add(tablePanel);
setTitle("Marks");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
table ex = new table();
ex.setVisible(true);
}
});
}
}

How to add JTable in JPanel with null layout?

I want to add JTable into JPanel whose layout is null. JPanel contains other components. I have to add JTable at proper position.
Nested/Combination Layout Example
The Java Tutorial has comprehensive information on using layout managers. See the Laying Out Components Within a Container lesson for further details.
One aspect of layouts that is not covered well by the tutorial is that of nested layouts, putting one layout inside another to get complex effects.
The following code puts a variety of components into a frame to demonstrate how to use nested layouts. All the layouts that are explicitly set are shown as a titled-border for the panel on which they are used.
Notable aspects of the code are:
There is a combo-box to change PLAF (Pluggable Look and Feel) at run-time.
The GUI is expandable to the user's need.
The image in the bottom of the split-pane is centered in the scroll-pane.
The label instances on the left are dynamically added using the button.
Nimbus PLAF
NestedLayoutExample.java
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.border.TitledBorder;
/** A short example of a nested layout that can change PLAF at runtime.
The TitledBorder of each JPanel shows the layouts explicitly set.
#author Andrew Thompson
#version 2011-04-12 */
class NestedLayoutExample {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
final JFrame frame = new JFrame("Nested Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel gui = new JPanel(new BorderLayout(5,5));
gui.setBorder( new TitledBorder("BorderLayout(5,5)") );
//JToolBar tb = new JToolBar();
JPanel plafComponents = new JPanel(
new FlowLayout(FlowLayout.RIGHT, 3,3));
plafComponents.setBorder(
new TitledBorder("FlowLayout(FlowLayout.RIGHT, 3,3)") );
final UIManager.LookAndFeelInfo[] plafInfos =
UIManager.getInstalledLookAndFeels();
String[] plafNames = new String[plafInfos.length];
for (int ii=0; ii<plafInfos.length; ii++) {
plafNames[ii] = plafInfos[ii].getName();
}
final JComboBox plafChooser = new JComboBox(plafNames);
plafComponents.add(plafChooser);
final JCheckBox pack = new JCheckBox("Pack on PLAF change", true);
plafComponents.add(pack);
plafChooser.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae) {
int index = plafChooser.getSelectedIndex();
try {
UIManager.setLookAndFeel(
plafInfos[index].getClassName() );
SwingUtilities.updateComponentTreeUI(frame);
if (pack.isSelected()) {
frame.pack();
frame.setMinimumSize(frame.getSize());
}
} catch(Exception e) {
e.printStackTrace();
}
}
} );
gui.add(plafComponents, BorderLayout.NORTH);
JPanel dynamicLabels = new JPanel(new BorderLayout(4,4));
dynamicLabels.setBorder(
new TitledBorder("BorderLayout(4,4)") );
gui.add(dynamicLabels, BorderLayout.WEST);
final JPanel labels = new JPanel(new GridLayout(0,2,3,3));
labels.setBorder(
new TitledBorder("GridLayout(0,2,3,3)") );
JButton addNew = new JButton("Add Another Label");
dynamicLabels.add( addNew, BorderLayout.NORTH );
addNew.addActionListener( new ActionListener(){
private int labelCount = 0;
public void actionPerformed(ActionEvent ae) {
labels.add( new JLabel("Label " + ++labelCount) );
frame.validate();
}
} );
dynamicLabels.add( new JScrollPane(labels), BorderLayout.CENTER );
String[] header = {"Name", "Value"};
String[] a = new String[0];
String[] names = System.getProperties().
stringPropertyNames().toArray(a);
String[][] data = new String[names.length][2];
for (int ii=0; ii<names.length; ii++) {
data[ii][0] = names[ii];
data[ii][1] = System.getProperty(names[ii]);
}
DefaultTableModel model = new DefaultTableModel(data, header);
JTable table = new JTable(model);
try {
// 1.6+
table.setAutoCreateRowSorter(true);
} catch(Exception continuewithNoSort) {
}
JScrollPane tableScroll = new JScrollPane(table);
Dimension tablePreferred = tableScroll.getPreferredSize();
tableScroll.setPreferredSize(
new Dimension(tablePreferred.width, tablePreferred.height/3) );
JPanel imagePanel = new JPanel(new GridBagLayout());
imagePanel.setBorder(
new TitledBorder("GridBagLayout()") );
BufferedImage bi = new BufferedImage(
200,200,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
GradientPaint gp = new GradientPaint(
20f,20f,Color.red, 180f,180f,Color.yellow);
g.setPaint(gp);
g.fillRect(0,0,200,200);
ImageIcon ii = new ImageIcon(bi);
JLabel imageLabel = new JLabel(ii);
imagePanel.add( imageLabel, null );
JSplitPane splitPane = new JSplitPane(
JSplitPane.VERTICAL_SPLIT,
tableScroll,
new JScrollPane(imagePanel));
gui.add( splitPane, BorderLayout.CENTER );
frame.setContentPane(gui);
frame.pack();
frame.setLocationRelativeTo(null);
try {
// 1.6+
frame.setLocationByPlatform(true);
frame.setMinimumSize(frame.getSize());
} catch(Throwable ignoreAndContinue) {
}
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
Other Screen Shots
Windows PLAF
Mac OS X Aqua PLAF
Ubuntu GTK+ PLAF
Don't use a null layout. Learn to use LayoutManagers:
http://download.oracle.com/javase/tutorial/uiswing/layout/using.html
LayoutManagers allow you to properly handle things window resizing or dynamic component counts. They might seem intimidating at first, but they are worth the effort to learn.
As I can remember, the null layout means an absolute position so it will be pretty hard you to count the X point for your JTable left upper corner location. But if you just want to have all panel components one by one you can use FlowLayout() manager as
JPanel panel=new JPanel(new FlowLayout());
panel.add(new aComponent());
panel.add(new bComponent());
panel.add(new JTable());
or if you need to fill the panel you should use GridLayout() as...
int x=2,y=2;
JPanel panel=new JPanel(new GridLayout(y,x));
panel.add(new aComponent());
panel.add(new bComponent());
panel.add(new JTable());
Good luck
If you are using null layout manager you always need to set the bounds of a component.
That is the problem in your case.
You should do what everyone suggest here and go and use some layout manager believe they save time.
Go and check out the tutorial in #jzd's post.
Enjoy, Boro.
JTable should be added into the JScrollPane which actually should be added into the JPanel.
The JPanel should have some layout manager.
If you don't care about the precision of components size you can use pure BorderLayout and combine it with FlowLayout and GridLayout. if you need precision - use jgoodies FormLayout.
The FormLayout is really tricky one, but you can play a little with WindowBuilder (which is embedded into Eclipse) and a look at the code it generates. It may look complicated but it is just an ignorance.
Good luck.
First, you should seriously consider other Layout managers, for example the BorderLayoutManager (new JPanel(new BorderLayout())) is a good start.
Also when designing your dialog, remember that you can and should nest your layouts: one JPanel inside another JPanel (e.g. a GridLayout inside a BorderLayout). Please note: a 'good' dialog should resize properly, so that if the user resizes your Frame, you want to automatically extend your information objects such as your table, and not show large areas of JPanel background. That's something you cannot achieve with a NullLayout.
But there are probably cases - somewhere in this big world - where a NullLayout is just the thing. So here's an example:
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class JTableInNullLayout
{
public static void main(String[] argv) throws Exception {
DefaultTableModel model = new DefaultTableModel(
new String[][] { { "a", "123"} , {"b", "456"} },
new String[] { "name", "value" } );
JTable t = new JTable(model);
JPanel panel = new JPanel(null);
JScrollPane scroll = new JScrollPane(t);
scroll.setBounds( 0, 20, 150, 100 ); // x, y, width, height
panel.add(scroll);
JFrame frame = new JFrame();
frame.add(panel);
frame.setPreferredSize( new Dimension(200,200));
frame.pack();
frame.setVisible(true);
}
}
When a component have a "null" layout, you have to manage the layout by yourself, that means you have to calculate the dimensions and locations for the children of the component to decide where they are drawn. Quite tedious unless it is absolutely necessary.
If you really want that fine-grained control, maybe try GridBagLayout first before going mudding with the UI arrangement.
JPanel panel = new JPanel();
JTable table = new JTable(rowData, colData);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane, BorderLayout.CENTER);
panel.setSize(800, 150);
panel.add(table);
panel.setLocationRelativeTo(null);
panel.setVisible(true);
Hope this helps.
JFrame frame = new JFrame("Sample Frame");
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
DefaultTableModel dfm = new DefaultTableModel(data, columnNames);
JTable table = new JTable(dfm);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane);
frame.add(panel);
frame.setVisible(true);
table model depends on your requirement
this.setTitle("Sample");
JPanel p = new JPanel(new BorderLayout());
WindowEvent we = new WindowEvent(this, WindowEvent.WINDOW_CLOSED);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
// Create columns names
String columnNames[] = { "FirstCol", "SecondCol",
"ThirdCol", "FourthCol" };
dataModel = new DefaultTableModel();
for (int col = 0; col < columnNames.length; col++) {
dataModel.addColumn(columnNames[col]);
}
// Create a new table instance
table = new JTable(dataModel);
table.setPreferredScrollableViewportSize(new Dimension(200, 120));
table.setFillsViewportHeight(true);
table.setShowGrid(true);
table.setAutoscrolls(true);
// Add the table to a scrolling pane
scrollPane = new JScrollPane(table,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(700, 700));
JPanel jpResultPanel = new JPanel();
jpResultPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Result",
TitledBorder.CENTER, TitledBorder.TOP));
jpResultPanel.add(scrollPane);
add(jpResultPanel);
pack();
setSize(720, 720);
setVisible(true);
Try this.
You can make use of the following code. To add JTable to JPanel.
JPanel panel = new JPanel();
this.setContentPane(panel);
panel.setLayout(null);
String data[][] = {{"1.", "ABC"}, {"2.", "DEF"}, {"3.", "GHI" }};
String col[] = {"Sr. No", "Name"};
JTable table = new JTable(data,col);
table.setBounds(100, 100, 100, 80);
panel.add(table);
setVisible(true);
setSize(300,300);

Creating Java dialogs

What would be the easiest way for creating a dialog:
in one window I'm giving data for envelope addressing, also set font type from list of sizes
when clicked OK, in the same window or in next window I get preview of how the envelope would look like with the given names, and used selected font size
It should look similarly to:
alt text http://img15.imageshack.us/img15/7355/lab10aa.gif
Should I use Jdialog? Or will JOptionPane will be enough? The next step will be to choose color of font and background so I must keep that in mind.
This should get you going.
class TestDialog extends JDialog {
private JButton okButton = new JButton(new AbstractAction("ok") {
public void actionPerformed(ActionEvent e) {
System.err.println("User clicked ok");
// SHOW THE PREVIEW...
setVisible(false);
}
});
private JButton cancelButton = new JButton(new AbstractAction("cancel") {
public void actionPerformed(ActionEvent e) {
System.err.println("User clicked cancel");
setVisible(false);
}
});
private JTextField nameField = new JTextField(20);
private JTextField surnameField = new JTextField();
private JTextField addr1Field = new JTextField();
private JTextField addr2Field = new JTextField();
private JComboBox sizes = new JComboBox(new String[] { "small", "large" });
public TestDialog(JFrame frame, boolean modal, String myMessage) {
super(frame, "Envelope addressing", modal);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
getContentPane().add(mainPanel);
JPanel addrPanel = new JPanel(new GridLayout(0, 1));
addrPanel.setBorder(BorderFactory.createTitledBorder("Receiver"));
addrPanel.add(new JLabel("Name"));
addrPanel.add(nameField);
addrPanel.add(new JLabel("Surname"));
addrPanel.add(surnameField);
addrPanel.add(new JLabel("Address 1"));
addrPanel.add(addr1Field);
addrPanel.add(new JLabel("Address 2"));
addrPanel.add(addr2Field);
mainPanel.add(addrPanel);
mainPanel.add(new JLabel(" "));
mainPanel.add(sizes);
JPanel buttons = new JPanel(new FlowLayout());
buttons.add(okButton);
buttons.add(cancelButton);
mainPanel.add(buttons);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
public String getAddr1() {
return addr1Field.getText();
}
// ...
}
Result:
If you need to use JOptionPane :
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame {
private static JTextField nameField = new JTextField(20);
private static JTextField surnameField = new JTextField();
private static JTextField addr1Field = new JTextField();
private static JTextField addr2Field = new JTextField();
private static JComboBox sizes = new JComboBox(new String[] { "small", "medium", "large", "extra-large" });
public Main(){
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
getContentPane().add(mainPanel);
JPanel addrPanel = new JPanel(new GridLayout(0, 1));
addrPanel.setBorder(BorderFactory.createTitledBorder("Receiver"));
addrPanel.add(new JLabel("Name"));
addrPanel.add(nameField);
addrPanel.add(new JLabel("Surname"));
addrPanel.add(surnameField);
addrPanel.add(new JLabel("Address 1"));
addrPanel.add(addr1Field);
addrPanel.add(new JLabel("Address 2"));
addrPanel.add(addr2Field);
mainPanel.add(addrPanel);
mainPanel.add(new JLabel(" "));
mainPanel.add(sizes);
String[] buttons = { "OK", "Cancel"};
int c = JOptionPane.showOptionDialog(
null,
mainPanel,
"My Panel",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
buttons,
buttons[0]
);
if(c ==0){
new Envelope(nameField.getText(), surnameField.getText(), addr1Field.getText()
, addr2Field.getText(), sizes.getSelectedIndex());
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
You will need to use JDialog. No point messing about with JOptoinPane - it's not meant for gathering more than a simple string. Additionally, use either MigLayout, TableLayout, or JGoodies forms - it will help you get a nice layout that's easy to code.
If it is allowed to use a GUI builder I would recommend you IntelliJ IDEA's
You can create something like that in about 5 - 10 mins.
If that's not possible ( maybe you want to practice-learn-or-something-else ) I would use a JFrame instead ) with CardLayout
Shouldn't be that hard to do.
You can use JOptionPane. You can add any Swing component to it.
Create a panel with all the components you need except for the buttons and then add the panel to the option pane. The only problem with this approach is that focus will be on the buttons by default. To solve this problem see the solution presented by Dialog Focus.

Categories

Resources