返回值从一种方法到另一种方法

时间:2015-02-12 15:08:38

标签: java methods return frame

如何将输入的值从main方法获取到create GUI方法。我已经创建了一个框架,我让用户在我的main方法中输入一个值。我现在想要用户输入的值显示在框架上

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Scanner;

/**
* This program displays an empty frame.
*/
public class SimpleFrame extends JFrame
{

 /**
 * The main launcher method
 */
 public static void main(String[] args)
 {
 SimpleFrame frame = new SimpleFrame();



    final int FRAME_WIDTH = 240;
    final int FRAME_HEIGHT = 360;
    final int FRAME_X = 150;
    final int FRAME_Y = 245;



    frame.setLocation(FRAME_X, FRAME_Y);
    frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
    frame.setTitle("New Frame Title");

    frame.createGUI();
    frame.setVisible(true);

    Scanner scan = new Scanner(System.in);
    System.out.println("Enter an integer");

    int a = scan.nextInt();


    System.out.println(a);



}

/**
 * This method sets up the graphical user interface.
 */
private void createGUI()
{
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Container window = getContentPane();
    window.setLayout(new FlowLayout());

    int a;

    // Nothing in the window yet!

3 个答案:

答案 0 :(得分:0)

您可以通过各种方式执行此操作,但通过代码的外观,您只需要显示一个值(因为您没有循环)。您可以将此值放入JLabel并调用函数来更新JLabel的文本。

public void showValue(int a){
    label.setText(Integer.toString(a));
}

如果这太简单了,请按照评论

中的建议查看事件监听器

答案 1 :(得分:0)

更新标签的示例:

public static void main(String[] args) {
    JFrame frame = new JFrame();
    JLabel label = new JLabel();
    frame.getContentPane().add(label, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);

    Scanner scan = new Scanner(System.in);
    System.out.println("Enter an integer");
    label.setText(String.valueOf(scan.nextInt()));
}

答案 2 :(得分:0)

您可以从下面给出的示例中获得类似的结果 ,一旦用户输入Value,GUI中显示的文本显示为label

 Scanner scan = new Scanner(System.in);
    System.out.println("Enter an integer");
    while(youWantToTakeTheInput){  //Break this on some condtion of your choice
               int a = scan.nextInt();
               System.out.println(a);

              // Now call the below method with the reference of label 

               displayInputIntoMyGUI(label,a);
   }
   public void displayInputIntoMyGUI(label,a){
       label.setText(a); // This will replace the previous text
      // If you want to Append the Text then this is the way ,
       label.setText(label.getText() + "text u want to append");

   }