Harpreet Singh Saini
Harpreet Singh Saini

Reputation: 159

Java Scroll bar

I want to add scroll bar to my text area so that if the user inputs a number greater than 20 the text are should have a scroll bar. Basically I am trying to make a application where user inputs a number he wants the multiplication table and also he inputs up to what number he wants the table to be displayed.But my application show table up to 20 e.g 12 X 20 = 240. and the rest is hidden.

public class LayoutM extends JFrame implements ActionListener {

    private JTextField num1;
    private JTextField num2;
    private JTextArea answer;
    private JButton go;
    private int num11;
    private int num22;



    public LayoutM(){

        super("Multiplication");
        setLayout(new FlowLayout());

        Dimension numDim = new Dimension(60,20);
        Dimension ansDim = new Dimension(200,300);
        Dimension goDim = new Dimension(60,20);

        num1 = new JTextField("Number");
        num1.setPreferredSize(numDim);

        num2 = new JTextField("Upto");
        num2.setPreferredSize(numDim);

        go = new JButton("GO"); 
        num2.setPreferredSize(goDim);

        answer = new JTextArea(20,20);
        answer.setPreferredSize(ansDim);
        answer.setEditable(false);



        add(num1, BorderLayout.CENTER);
        add(num2,BorderLayout.CENTER);
        add(go,BorderLayout.CENTER);
        add(answer,BorderLayout.SOUTH);


        go.addActionListener(this);

    }

    public static void main(String[] args){
        LayoutM ob = new LayoutM();
        ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ob.setVisible(true);
        ob.setSize(300,400);
        ob.setResizable(false);
        ob.setLocationRelativeTo(null);
    }


    public void actionPerformed(ActionEvent event){
        try{

         answer.setText(" ");   
         num11 = Integer.parseInt(num1.getText());
         num22 = Integer.parseInt(num2.getText());

        for(int count = 1; count < num22+1;count++){
            answer.append(num11+ " X "+ count+" = " + num11*count+" \n");

        }
     }catch(Exception e){
         JOptionPane.showMessageDialog(null, "No decimals allowed");
     }  
    }

}

Upvotes: 0

Views: 196

Answers (1)

RealSkeptic
RealSkeptic

Reputation: 34628

You should put the answer object into a new JScrollPane object, and add the scroll pane to your LayoutM.

So, in your fields you should add:

    private JScrollPane scroll;

Instead of using

    add(answer,BorderLayout.SOUTH);

You should use

    add(scroll,BorderLayout.SOUTH);

And in your actionPerformed() method, you should change the number of rows according to the number you got from the user. Put this before the for loop:

     if ( num22 > 20 ) {
         answer.setRows(num22);
     } else {
         answer.setRows(20);
     }

Upvotes: 1

Related Questions