我想将滚动条添加到我的文本区域,以便如果用户输入大于 20 的数字,则文本应该有滚动条。 基本上我正在尝试制作一个应用程序,其中用户输入他想要的乘法表的数字,并且输入他想要显示的表格的数字。但是我的应用程序显示最多 20 个表格,例如 12 X 20 = 240。其余部分被隐藏。
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");
}
}
}
最佳答案
您应该将 answer
对象放入新的 JScrollPane 中对象,并将滚动 Pane 添加
到您的LayoutM
。
因此,您应该在您的字段中添加:
private JScrollPane scroll;
而不是使用
add(answer,BorderLayout.SOUTH);
你应该使用
add(scroll,BorderLayout.SOUTH);
在您的 actionPerformed()
方法中,您应该根据从用户那里获得的行数来更改行数。将其放在 for
循环之前:
if ( num22 > 20 ) {
answer.setRows(num22);
} else {
answer.setRows(20);
}
关于Java滚动条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26904516/