Question

Look at the bottom of the code in the spaghettiFrame method. I want my JFrame to start scrolling down as I add more components to the contentPane panel. I know it has something to do with my Layout being set to null(absolute) but whenever I take it out it sets all my components in one horizontal line.

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();
    }
}
Was it helpful?

Solution

JScrollPanes don't behave well with null layout using components, yet another reason to avoid null layouts like the plague. And if you don't use a null layout, your JPanel defaults to a FlowLayout, which is why everything is on one line.

The solution: don't use either but instead use a combination of nested JPanels, each using its own layouts to achieve your design goal.


Edit
For example, please look at these answers:

And this tutorial:


Edit 2
As an aside, I wonder if what you're looking to create is a JTable that is displayed in a JScrollPane. This would hold and display tabular data well, which is what you're after, correct?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top