Answers:
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);
}
}
不要使用空布局。了解如何使用LayoutManagers:
http://download.oracle.com/javase/tutorial/uiswing/layout/using.html
LayoutManagers使您能够正确处理窗口大小调整或动态组件计数的事情。乍一看它们似乎令人生畏,但值得您努力学习。
我记得,空布局意味着绝对位置,因此很难为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());
祝好运
首先,您应该认真考虑其他布局管理器,例如BorderLayoutManager(新的JPanel(new BorderLayout()))是一个好的开始。
同样,在设计对话框时,请记住您可以并且应该将布局嵌套:一个JPanel嵌套在另一个JPanel内(例如BorderLayout内的GridLayout)。请注意:“好”对话框应正确调整大小,以便用户调整Frame的大小时,您想要自动扩展信息对象(例如表格),并且不显示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);
}
}
您可以使用以下代码。将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);
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);
试试这个。