如何使用JButton从JTextField获取int

时间:2013-07-29 01:58:28

标签: java swing jbutton jtextfield

我试图通过点击我的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);

3 个答案:

答案 0 :(得分:3)

试试这个,

      String getText()

      Returns the text contained in this TextComponent.

因此,将String转换为Integer为:

try {
    int integerValue = Integer.parseInt(jTextField.getText());
}
catch(NumberFormatException ex)
{
    System.out.println("Exception : "+ex);
}

答案 1 :(得分: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);
      .
      .
      .

答案 2 :(得分: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 docs