Java 从一个方法返回值到另一个方法
如何从main方法到creategui方法获取输入值。我创建了一个框架,让用户在我的main方法中输入一个值。我现在希望用户输入的值显示在框架上Java 从一个方法返回值到另一个方法,java,methods,return,frame,Java,Methods,Return,Frame,如何从main方法到creategui方法获取输入值。我创建了一个框架,让用户在我的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 JFra
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!
有多种方法可以做到这一点,但是从代码的外观来看,您只需要显示一个值(因为您没有循环)。您可以将此值放入JLabel并调用函数来更新JLabel的文本
public void showValue(int a){
label.setText(Integer.toString(a));
}
如果这太简单,请查看注释示例中建议的事件侦听器,以更新标签:
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()));
}
您可以通过下面给出的示例实现类似的功能 ,一旦用户输入
值
,文本就会显示在GUI中:标签
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");
}
阅读事件侦听器