How to combine the GUI class and the scanner class?

青春壹個敷衍的年華 提交于 2019-12-10 12:05:18

问题


I'm new in java and well I'm trying to create a program that will first ask the user to for some number and will output a volume, area and so on. Also I want to display a rectangle I don't know how that can be done because my program runs fine it just won't display the rectangle. What can I do?

package testchap3;

import java.util.*;
import javax.swing.JApplet;
import java.awt.*;

public class Chapter_3 extends JApplet
{
    public void paint(Graphics page)
    {
        page.drawRect(50,50,60,60);
    }

    public static void main(String[] args)
    {
        int lenght,width,height,volume,Area,Perimeter;

        Scanner scan = new Scanner(System.in);

        System.out.println("What is the lenght:");
        lenght = scan.nextInt();

        System.out.println("What is the height:");
        height = scan.nextInt();

        System.out.println("What is the width:");
        width= scan.nextInt();

        volume = (lenght*height*width);
        Area= volume/height;
        Perimeter= lenght+width+lenght+width;   

        System.out.println("Your volume is:"+volume);
        System.out.println("Your Area is:"+ Area);
        System.out.println("Your perimeter is:"+Perimeter);

     }
}

回答1:


Your question:

How to combine the GUI class and the scanner class?

Short answer: don't.

Longer answer: At least don't try to combine a GUI with a Scanner tied to System.in/console as that leads to the attempt to mesh two diametrically opposed ways of getting user input: linear console input vs event-driven GUI interaction. Instead, why not let users enter information via the GUI in an event-driven manner? Else you lose all the advantages of using a GUI in the first place and risk tying up your GUI's event thread for console input.

In your case, I'd have three JTextFields or JFormattedTextFields or JSpinners that the user can enter in data, and then I'd display the results in another text component or JLabel, after a JButton has been pressed and its Action initiated.

Other problems: your GUI is a JApplet, and yet you've given it a main method and run its main method which is never going to work and won't display the GUI. Please read the GUI tutorials which you can find here. Instead display a JFrame, not an applet, override a JPanel and draw in its paintComponent method (as per the tutorials), and again get rid of all the Scanner code.



来源:https://stackoverflow.com/questions/26246308/how-to-combine-the-gui-class-and-the-scanner-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!