在Swing中使用具有绝对布局的滚动条

时间:2012-02-27 08:53:11

标签: java swing user-interface layout absolutelayout

我无法在Swing中使用具有绝对布局的滚动条。

我不希望使用此布局,但我必须在单击按钮时在我的面板上显示动态对象并使用setBounds对齐它们,这可以仅使用此布局(我猜)。< / p>

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class clothes2 extends javax.swing.JFrame {

    JTextField n=null;
    JButton m=null;

    public clothes2(){
        initComponents();
    }

    public void initComponents() {
        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());
        final JPanel jp = new JPanel();
        contentPane.setPreferredSize(new Dimension(320,200));
        jp.setLayout(null);
        m=new JButton("add");
        m.setBounds(0,0,50,50);
        jp.add(m);
        m.addMouseListener( new MouseAdapter() {

            int x=0;
            int y=0;

            public void mouseClicked(MouseEvent me){
                x+=100;
                y+=100;
                jp.add(n=new JTextField("Name"));
                n.setBounds(x, y, 50, 50);
                jp.add(n=new JTextField("code"));
                x+=100;
                n.setBounds(x,y, 50, 50);
                jp.revalidate();
                jp.repaint();
                x=0;
            }
        });

        int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
        int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
        JScrollPane jsp = new JScrollPane(jp, v, h);
        contentPane.add(jsp, BorderLayout.CENTER);
    }

    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                JFrame f= new clothes2();
                f.setVisible(true);
                f.setSize(640,320);
            }
        });
    }
}

4 个答案:

答案 0 :(得分:2)

  

显示动态对象..只能使用此布局(我猜)。

你错了。

请参阅this GUI,它不仅可以在运行时更改PLAF,还可以动态添加新组件 1 。点击..

添加另一个标签

  1. 此示例将新标签添加到GridLayout - 但任何布局(或任何组件)的原则都相同。

答案 1 :(得分:1)

设置容器的首选大小。

答案 2 :(得分:1)

JScrollBar使用其中组件的首选大小来确定滚动条应该有多大,以及它们是否应该显示。

通常,布局管理器使用preferredLayoutSize方法处理此问题。可以通过显式设置组件的首选大小来覆盖它。

因此,您必须设置首选大小,或使用自定义布局管理器为您计算。

另见here

可能会帮到你。

答案 3 :(得分:0)

添加布局
jp.setLayout(new FlowLayout());