我想添加JTable
到JPanel
谁的布局是null
. JPanel
包含其他组件。我必须JTable
在适当的位置添加。
11 回答
嵌套/组合布局示例
Java 教程包含有关使用布局管理器的全面信息。有关详细信息,请参阅在容器中布置组件课程。
本教程没有很好地介绍布局的一个方面是嵌套布局,将一个布局放在另一个布局中以获得复杂的效果。
以下代码将各种组件放入一个框架中,以演示如何使用嵌套布局。所有明确设置的布局都显示为使用它们的面板的标题边框。
代码的显着方面是:
- 有一个组合框可以在运行时更改 PLAF(可插拔外观)。
- GUI 可根据用户的需要进行扩展。
- 拆分窗格底部的图像在滚动窗格中居中。
- 左侧的标签实例是使用按钮动态添加的。
光轮解放军
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);
}
}
其他屏幕截图
视窗解放军
Mac OS X Aqua PLAF
Ubuntu GTK+ PLAF
不要使用空布局。学习使用 LayoutManagers:
http://download.oracle.com/javase/tutorial/uiswing/layout/using.html
LayoutManagers 允许您正确处理窗口大小调整或动态组件计数。起初它们可能看起来很吓人,但它们值得努力学习。
我记得,null布局意味着绝对位置,因此您很难计算 JTable 左上角位置的 X 点。但是,如果您只想一一拥有所有面板组件,则可以将 FlowLayout() 管理器用作
JPanel panel=new JPanel(new FlowLayout());
panel.add(new aComponent());
panel.add(new bComponent());
panel.add(new JTable());
或者如果您需要填充面板,您应该使用 GridLayout() 作为...
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());
祝你好运
如果您使用的是空布局管理器,则始终需要设置组件的边界。这就是你的问题。
你应该按照每个人的建议去做,然后去使用一些布局管理器,相信它们可以节省时间。去查看@jzd 帖子中的教程。
享受吧,博罗。
JTable
应该添加到JScrollPane
其中实际上应该添加到JPanel
.
JPanel
应该有一些布局管理器。
如果您不关心组件尺寸的精度,您可以使用 pureBorderLayout
并将其与FlowLayout
and结合使用GridLayout
。如果您需要精确使用 jgoodies FormLayout
。
这FormLayout
真的很棘手,但是您可以玩一点WindowBuilder
(嵌入到 Eclipse 中)并查看它生成的代码。它可能看起来很复杂,但这只是一种无知。
祝你好运。
首先,您应该认真考虑其他布局管理器,例如 BorderLayoutManager (new JPanel(new BorderLayout())) 是一个好的开始。
此外,在设计对话框时,请记住您可以并且应该嵌套布局:一个 JPanel 位于另一个 JPanel 中(例如,GridLayout 位于 BorderLayout 中)。请注意:一个“好的”对话框应该适当调整大小,这样如果用户调整您的框架大小,您希望自动扩展您的信息对象,例如您的表格,而不是显示大面积的 JPanel 背景。这是使用 NullLayout 无法实现的。
但可能有一些情况——在这个大世界的某个地方——NullLayout 就是这样。所以这里有一个例子:
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);
}
}
当组件具有“空”布局时,您必须自己管理布局,这意味着您必须计算组件子级的尺寸和位置来决定它们的绘制位置。除非绝对必要,否则相当乏味。
如果你真的想要那种细粒度的控制,也许在弄乱 UI 安排之前先试试 GridBagLayout。
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);
希望这可以帮助。
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);
表模型取决于您的要求
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);
尝试这个。
您可以使用以下代码。将 JTable 添加到 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);