Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
727 views
in Technique[技术] by (71.8m points)

java - How to combine the GUI class and the scanner class?

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

     }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...