如何在JPanel中添加带有null布局的JTable?

Sag*_*gar 232 java layout jtable layout-manager null-layout-manager

我想添加JTableJPanel其布局中null. JPanel包含其他组件.我必须添加JTable适当的位置.

And*_*son 178

嵌套/组合布局示例

Java Tutorial提供了有关使用布局管理器的全面信息.有关详细信息,请参阅" 在容器中布置组件"课程.

本教程未能很好地介绍布局的一个方面是嵌套布局,将一个布局放在另一个布局中以获得复杂的效果.

以下代码将各种组件放入框架中,以演示如何使用嵌套布局.显式设置的所有布局都显示为使用它们的面板的标题边框.

代码的显着方面是:

  • 有一个组合框可以在运行时更改PLAF(Pluggable Look and Feel).
  • GUI可根据用户的需要进行扩展.
  • 拆分窗格底部的图像位于滚动窗格的中心.
  • 左侧的标签实例使用按钮动态添加.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

其他屏幕截图

Windows PLAF

Mac OS X Aqua PLAF

Ubuntu GTK + PLAF


jzd*_*jzd 49

不要使用null布局.学习使用LayoutManagers:

http://download.oracle.com/javase/tutorial/uiswing/layout/using.html

LayoutManagers允许您正确处理窗口大小调整或动态组件计数.起初他们可能看起来很吓人,但他们值得学习.


use*_*704 19

我记得,null布局意味着一个绝对的位置,所以你很难计算你的JTable左上角位置的X点.但是,如果您只想逐个使用所有面板组件,可以使用FlowLayout()管理器作为

JPanel panel=new JPanel(new FlowLayout());
panel.add(new aComponent());
panel.add(new bComponent());
panel.add(new JTable());
Run Code Online (Sandbox Code Playgroud)

或者如果你需要填充面板,你应该使用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());
Run Code Online (Sandbox Code Playgroud)

祝好运


Bor*_*oro 16

如果使用null布局管理器,则始终需要设置组件的边界.这就是你的问题.

您应该按照每个人的建议去做,然后使用一些布局经理相信他们可以节省时间.去查看@jzd帖子中的教程.

享受,博罗.


ser*_*ank 12

JTable应该添加到JScrollPane实际应该添加到的内容中JPanel.

JPanel应该有一些布局管理器.

如果您不关心组件尺寸的精度,您可以使用纯净BorderLayout并将其与FlowLayout和组合GridLayout.如果你需要精确 - 使用jgoodies FormLayout.

FormLayout是非常棘手的,但你可以玩一点WindowBuilder(嵌入到Eclipse中)并查看它生成的代码.它可能看起来很复杂,但这只是一种无知.

祝好运.


Axe*_*ehl 6

首先,您应该认真考虑其他布局管理器,例如BorderLayoutManager(新的JPanel(新的BorderLayout()))是一个好的开始.

在设计对话框时,请记住您可以并且应该嵌套布局:一个JPanel在另一个JPanel中(例如BorderLayout中的GridLayout).请注意:" 正确 "对话框应正确调整大小,以便在用户调整框架大小时,您希望自动扩展信息对象(如表格),而不显示大面积的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);
  }
}
Run Code Online (Sandbox Code Playgroud)