Java 滚动窗格和面板布局

Java 滚动窗格和面板布局,java,swing,layout,jpanel,jscrollpane,Java,Swing,Layout,Jpanel,Jscrollpane,查看spaghettiFrame方法中代码的底部。我希望在向contentPane面板添加更多组件时,JFrame开始向下滚动。我知道这与我的布局被设置为null(绝对)有关,但每当我取出它时,它就会将我的所有组件设置在一条水平线上 public class SpaghettiFrame extends JFrame{ private static final AutoCompletion AutoCompletion = null; private AutoCompletio

查看spaghettiFrame方法中代码的底部。我希望在向contentPane面板添加更多组件时,JFrame开始向下滚动。我知道这与我的布局被设置为null(绝对)有关,但每当我取出它时,它就会将我的所有组件设置在一条水平线上

public class SpaghettiFrame extends JFrame{

    private static final AutoCompletion AutoCompletion = null;
    private AutoCompletion beta;
    private JSpinner Quantity_1;
    private JComboBox Part_1;
    private JPanel contentPane =  new JPanel();
    private JScrollPane jsp = new JScrollPane(contentPane);
    private JTextField Price_1;
    private JTextField Total;
    private JLabel lblTotal;
    private JTextField Building_1;
    private String value = "0";
    private String totalvalue = "0";
    private int loc = 1;
    private static String[] pricedatabase;
    private static String[] partdatabase;
    private static File pricefile = new File("DataBase/Price DataBase.txt");
    private static File partfile = new File("DataBase/Part DataBase.txt");
    private static DateFormat dateFormat = new SimpleDateFormat("MM_dd_yyyy");
    private static Date date = new Date();
    private static File file = new File("Reports/" + (dateFormat.format(date)) + "Report.txt");
    private static PrintWriter info;
    ArrayList<JComboBox> part;
    ArrayList<JSpinner> quantity;
    ArrayList<JTextField> price;
    ArrayList<JComponent> next;
    ArrayList<JTextField> building;

    public static void main(String[] args) throws Exception {
        scanData();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    SpaghettiFrame frame = new SpaghettiFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static void scanData() throws Exception{

        Scanner sc = new Scanner(partfile);
        List<String> lines = new ArrayList<String>();
        while (sc.hasNextLine()) {
          lines.add(sc.nextLine());
        }
        partdatabase = lines.toArray(new String[lines.size()]);

        Scanner scc = new Scanner(pricefile);
        List<String> numbers = new ArrayList<String>();
        while (scc.hasNextLine()) {
          numbers.add(scc.nextLine());
        }
        pricedatabase = numbers.toArray(new String[numbers.size()]);
    }

    public void addComponent(AutoCompletion beta){

        Part_1 = new JComboBox();
        Part_1.setBounds(50, 28 + loc*40, 178, 20);
        for(int i=0; i <= partdatabase.length -1; i++){
            Part_1.addItem(partdatabase[i]);
        }
        part.add(Part_1);
        //AutoCompletion.enable(Part_1);
        Part_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {    
                    totalvalue = "0";
                    for(int i=0;i<part.size();i++){
                        value = String.valueOf(Integer.valueOf(pricedatabase[part.get(i).getSelectedIndex()]) * (Integer)quantity.get(i).getValue());
                        totalvalue = String.valueOf(Integer.valueOf(totalvalue) + Integer.valueOf(value));
                        price.get(i).setText(value);
                        Total.setText(totalvalue);
                    }
            }
        });

        Quantity_1 = new JSpinner();
        Quantity_1.setBounds(287, 28 + loc*40, 41, 20);
        quantity.add(Quantity_1);
        Quantity_1.addChangeListener(new ChangeListener() {      
              @Override
              public void stateChanged(ChangeEvent e) {
                  totalvalue = "0";
                    for(int i=0;i<part.size();i++){
                        value = String.valueOf(Integer.valueOf(pricedatabase[part.get(i).getSelectedIndex()]) * (Integer)quantity.get(i).getValue());
                        totalvalue = String.valueOf(Integer.valueOf(totalvalue) + Integer.valueOf(value));
                        price.get(i).setText(value);
                        Total.setText(totalvalue);
                    }
              }
            });

        Price_1 = new JTextField();
        Price_1.setBounds(390, 28 + loc*40, 86, 20);
        Price_1.setText("");
        Price_1.setEditable(false);
        Price_1.setColumns(10);
        price.add(Price_1);

        Building_1 = new JTextField();
        Building_1.setBounds(5, 28 + loc*40, 35, 20);
        Building_1.setText("");
        Building_1.setEditable(true);
        Building_1.setColumns(10);
        building.add(Building_1);

        Total.setBounds(390, 68 + loc*40, 86, 20);
        lblTotal.setBounds(320, 68 + loc*40, 86, 20);

        update();
        loc++;
    }

    public void update(){
        for(JComponent j: part){
            contentPane.add(j);
        }
        for(JComponent j: quantity){
            contentPane.add(j);
        }
        for(JComponent j: price){
            contentPane.add(j);
        }
        for(JComponent j: building){
            contentPane.add(j);
        }

        contentPane.updateUI();
        contentPane.repaint();
    }

    public SpaghettiFrame() throws Exception {
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 492, 651);
        setContentPane(jsp);
        jsp.setViewportView(contentPane);
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
        contentPane.setLayout(null);


        part = new ArrayList<JComboBox>();
        quantity = new ArrayList<JSpinner>();
        price = new ArrayList<JTextField>();
        building = new ArrayList<JTextField>();


        JLabel lblBalanceCalculator = new JLabel("Balance Calculator");
        lblBalanceCalculator.setFont(new Font("Times New Roman", Font.BOLD, 16));
        lblBalanceCalculator.setHorizontalAlignment(SwingConstants.CENTER);
        lblBalanceCalculator.setBounds(31, 11, 411, 14);
        contentPane.add(lblBalanceCalculator);

        Total = new JTextField();
        Total.setBounds(390, 68 + loc*40, 86, 20);
        Total.setEditable(false);
        Total.setColumns(10);
        Total.setText(totalvalue);
        contentPane.add(Total);

        lblTotal = new JLabel("Total:");
        lblTotal.setFont(new Font("Times New Roman", Font.BOLD, 12));
        lblTotal.setHorizontalAlignment(SwingConstants.CENTER);
        lblTotal.setBounds(320, 68 + loc*40, 86, 20);
        contentPane.add(lblTotal);

        JButton btnPrint = new JButton("Print");
        btnPrint.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    info = new PrintWriter(file);
                } catch (FileNotFoundException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                file.getParentFile().mkdirs();
                info.println("BALANCE CALCULATOR                " + (dateFormat.format(date)));
                info.println("");
                for(int i=0;i<=part.size()-1; i++){
                    info.println(String.valueOf(part.get(i).getSelectedItem()) + "  x  " + quantity.get(i).getValue() + "  =  " + price.get(i).getText());
                    info.println("");
                }
                info.print("Total: " + totalvalue);
                info.close();
            }
        });
        btnPrint.setBounds(43, 589, 89, 23);
        contentPane.add(btnPrint);


        JButton btnNext = new JButton("Next");
        btnNext.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                    totalvalue = "0";
                    for(int i=0;i<part.size();i++){
                        value = String.valueOf(Integer.valueOf(pricedatabase[part.get(i).getSelectedIndex()]) * (Integer)quantity.get(i).getValue());
                        totalvalue = String.valueOf(Integer.valueOf(totalvalue) + Integer.valueOf(value));
                        price.get(i).setText(value);
                        Total.setText(totalvalue);
                    }
                addComponent(AutoCompletion);
            }
        });
        btnNext.setBounds(353, 589, 89, 23);
        contentPane.add(btnNext);

        addComponent(AutoCompletion);
        update();
    }
}
公共类SpaghettiFrame扩展JFrame{
私有静态最终自动完成自动完成=空;
私有自动完成beta;
私有JSpinner数量_1;
私人JComboBox第1部分;
private JPanel contentPane=new JPanel();
私有JScrollPane jsp=newjscrollpane(contentPane);
私人JTextField价格_1;
私有JTextField总数;
私人JLabel lblTotal;
私人JTextField大厦1号;
私有字符串值=“0”;
私有字符串totalvalue=“0”;
私有int loc=1;
私有静态字符串[]数据库;
私有静态字符串[]partdatabase;
私有静态文件pricefile=new文件(“DataBase/Price DataBase.txt”);
私有静态文件partfile=new文件(“DataBase/Part DataBase.txt”);
私有静态DateFormat DateFormat=新的SimpleDateFormat(“MM_dd_yyyy”);
私有静态日期=新日期();
私有静态文件File=new文件(“Reports/”+(dateFormat.format(date))+“Report.txt”);
私有静态PrintWriter信息;
阵列列表部分;
数组列表数量;
ArrayList价格;
ArrayList下一步;
ArrayList大厦;
公共静态void main(字符串[]args)引发异常{
斯堪的纳维亚();
invokeLater(新的Runnable(){
公开募捐{
试一试{
SpaghettiFrame=新的SpaghettiFrame();
frame.setVisible(true);
}捕获(例外e){
e、 printStackTrace();
}
}
});
}
public static void scanda()引发异常{
扫描仪sc=新扫描仪(零件文件);
列表行=新的ArrayList();
while(sc.hasNextLine()){
line.add(sc.nextLine());
}
partdatabase=lines.toArray(新字符串[lines.size()]);
扫描仪scc=新扫描仪(价格文件);
列表编号=新的ArrayList();
而(scc.hasNextLine()){
add(scc.nextLine());
}
pricedatabase=numbers.toArray(新字符串[numbers.size()]);
}
公共无效添加组件(自动完成测试版){
第1部分=新的JComboBox();
第1部分立根(50,28+loc*40178,20);

例如(int i=0;iJScrollPanes在使用组件的空布局时表现不好,这是避免像瘟疫一样使用空布局的另一个原因。如果不使用空布局,您的JPanel默认为FlowLayout,这就是为什么所有内容都在一行上

解决方案:不要使用任何一种,而是使用嵌套JPanel的组合,每个都使用自己的布局来实现您的设计目标


编辑
例如,请看以下答案:

本教程:


编辑2

顺便说一句,我想知道您想要创建的是一个显示在JScrollPane中的JTable。这将很好地保存和显示表格数据,这就是您所追求的,对吗?

您有这样的例子吗?@lavascre:我有很多这样的例子。搜索我的Swing答案,您会发现许多使用这种技术的GUIhnique。也可以在谷歌上搜索Swing布局管理器教程并浏览。@lavascrpe:不客气。请同时查看“编辑”中的链接以回答问题。