0

我试图通过点击我的 JButton 从我的 JTextField 中获取一个 int,但我不知道该怎么做。我正在尝试获取 int 并将其设置为一个变量,以便我可以在我的程序中进一步使用它。

这是代码(这是整个方法):

    JFrame presets = new JFrame("Presets");
    presets.setVisible(true);
    presets.setSize(500, 500);

    JPanel gui = new JPanel(new BorderLayout(2,2));

    JPanel labelFields = new JPanel(new BorderLayout(2,2));
    labelFields.setBorder(new TitledBorder("Presets"));

    JPanel labels = new JPanel(new GridLayout(0,1,1,1));

    JPanel fields = new JPanel(new GridLayout(0,1,1,1));

    labels.add(new JLabel("Place values on Cat.2/Cat.3 at"));
    JTextField f1 = new JTextField(10);
    String text = f1.getText();
    int first = Integer.parseInt(text);
    labels.add(new JLabel("and place follow up value at"));
    fields.add(new JTextField(10));


    labelFields.add(labels, BorderLayout.CENTER);
    labelFields.add(fields, BorderLayout.EAST);

    JPanel guiCenter = new JPanel(new BorderLayout(2,2));

    JPanel submit = new JPanel(new FlowLayout(FlowLayout.CENTER));

    submit.add( new JButton("Submit") );
    guiCenter.add( submit, BorderLayout.NORTH );

    gui.add(labelFields, BorderLayout.NORTH);
    gui.add(guiCenter, BorderLayout.CENTER);

    JOptionPane.showMessageDialog(null, gui);
4

3 回答 3

3

尝试这个,

      String getText()

      Returns the text contained in this TextComponent.

因此,将您的字符串转换为整数:

try {
    int integerValue = Integer.parseInt(jTextField.getText());
}
catch(NumberFormatException ex)
{
    System.out.println("Exception : "+ex);
}
于 2013-07-29T02:01:39.697 回答
2

可能您希望输入的数据为int. 写在按钮动作中

JButton button = new JButton("Submit");
button.addActionListener(new ActionListener() {
  @Override
  public void actionPerformed(ActionEvent arg0) {
    try {
      int myInt=Integer.parseInt(jtextfield.getText());
      System.out.println("Integer is: "+myInt);
      //do some stuff
    }
    catch (NumberFormatException ex) {
      System.out.println("Not a number");
      //do you want
   }
  }
});

记住必须接住的Integer.parseInt投掷。NumberFormatException参见java 文档

于 2013-07-29T03:09:20.317 回答
2

如果您想在提交按下时获取 f1 文本,请使用以下代码:

   .
   .
   .
    JPanel submit = new JPanel(new FlowLayout(FlowLayout.CENTER));
    JButton button = new JButton("Submit");
    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            int first = Integer.parseInt(f1.getText().trim());
        }
    });
    submit.add(button);
    guiCenter.add(submit, BorderLayout.NORTH);
      .
      .
      .
于 2013-07-29T02:28:44.960 回答