只需要一些帮助将文本打印到类项目的TextArea。我有一种方法可以生成 5-0 之间的 100 个随机数,并希望它打印到 TextArea,但我不确定如何做到这一点。(现在我只有 Syste.out.println 作为占位符,但我想删除它)
public class Interface
{
public Interface()
{
}
public static void randomNumber()
{
Random randomNumber = new Random();
System.out.println("Generating 5 Random Numbers.");
for (int randomNum = 1; randomNum <= 5; ++randomNum)
{
int randomInt = randomNumber.nextInt(5);
System.out.println("Random Number: " + randomInt);
}
System.out.println("Done.");
}
}
public class InterfacePanel extends JPanel
{
private InterfaceController baseController;
private SpringLayout baseLayout;
private JButton buttonOne;
private JButton buttonTwo;
private JButton buttonThree;
private JButton buttonFour;
private JLabel lableOne;
private JLabel lableTwo;
private JLabel lableThree;
private JLabel lableFour;
private TextArea textField;
public InterfacePanel(InterfaceController baseController)
{
setBackground(Color.DARK_GRAY);
this.baseController = baseController;
buttonOne = new JButton("Random Numbers");
buttonTwo = new JButton("Two");
buttonThree = new JButton("Three");
buttonFour = new JButton("Four");
lableOne = new JLabel("5 Random Numbers");
lableTwo = new JLabel("Two");
lableThree = new JLabel("Three");
lableFour = new JLabel("Four");
baseLayout = new SpringLayout();
textField = new TextArea();
setupPanel();
setupLayout();
setupListeners();
}
private void setupPanel()
{
this.setLayout(baseLayout);
this.add(lableOne);
this.add(buttonOne);
this.add(buttonTwo);
this.add(buttonThree);
this.add(buttonFour);
this.add(lableTwo);
this.add(lableThree);
this.add(lableFour);
this.add(textField);
}
private void setupLayout()
private void setupListeners()
{
buttonOne.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent click)
{
Interface.randomNumber();
}
});
buttonTwo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent click)
{
}
});
buttonThree.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent click)
{
}
});
buttonFour.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent click)
{
}
});
}
}
在方法
中添加参数 JTextArea
randomNumber()
。
public static void randomNumber(JTextArea myText){
Random randomNumber = new Random();
System.out.println("Generating 5 Random Numbers.");
for (int randomNum = 1; randomNum <= 5; ++randomNum)
{
int randomInt = randomNumber.nextInt(5);
myText.setText(myText.getText() + randomInt + "n");
}
System.out.println("Done.");
}
并以这种方式调用InterfacePanel
类中的randomNumber()
方法
Interface.randomNumber(textField);