【问题标题】:Return Value from one method to another从一种方法返回值到另一种方法
【发布时间】:2015-02-12 15:08:38
【问题描述】:

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

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!

【问题讨论】:

标签: java methods return frame


【解决方案1】:

有多种方法可以做到这一点,但从代码的外观来看,您只需要显示一个值(因为您没有循环)。您可以将此值放入 JLabel 并调用函数来更新 JLabel 的文本。

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

如果这太简单,请查看 cmets 中建议的事件监听器

【讨论】:

    【解决方案2】:

    标签更新示例:

    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()));
    }
    

    【讨论】:

      【解决方案3】:

      您可以从下面给出的示例中实现类似的效果 , 只要用户输入 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");
      
         }
      

      【讨论】:

        猜你喜欢
        • 2017-03-19
        • 1970-01-01
        • 1970-01-01
        • 2022-11-29
        • 2018-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多