ScrollPane和面板布局

时间:2014-03-16 03:45:57

标签: java swing layout jpanel jscrollpane

查看spaghettiFrame方法中代码的底部。我希望我的JFrame开始向下滚动,因为我向contentPane面板添加了更多组件。我知道它与我的布局被设置为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();
    }
}

1 个答案:

答案 0 :(得分:3)

JScrollPanes使用组件的null布局表现不佳,这是避免像瘟疫这样的空布局的另一个原因。如果你不使用null布局,你的JPanel默认为FlowLayout,这就是为什么一切都在一行上。

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


修改
例如,请查看以下答案:

本教程:


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