Hot questions for Using Applets in input

Question:

Hi i am using Jsch to run my shell command. I want to make it interactive .I am using java textarea to display the output of a script.This script requires some user inputs also. How i can i make this textarea to accept user input and run the commands.

public void init(){
try{
  JSch jsch=new JSch();

  Panel panel = new Panel();
  TextArea log = new TextArea();
  panel.add(log);
  add(panel);
  PrintStream printStream = new PrintStream(new CustomOutputStream(log));
  System.setOut(printStream);
  System.setErr(printStream);

  Session session=jsch.getSession("akumar", "banas", 22);
  String passwd = "*****";
  Properties config = new Properties(); 
  config.put("StrictHostKeyChecking", "no");
  session.setConfig(config);
  session.setPassword(passwd);
  session.connect(30000);   // making a connection with timeout.

  Channel channel=session.openChannel("shell");
  channel.setInputStream(System.in);
  channel.setOutputStream(System.out);
  channel.connect(3*1000);

  printStream.println("sftp akumar@banas");

  printStream.flush();

}
catch(Exception e){
  System.out.println(e);
}
  }

// This is the code for making textarea as output stream

 public class CustomOutputStream extends OutputStream {
    private TextArea textArea;

    public CustomOutputStream(TextArea textArea) {
        this.textArea = textArea;
    }

    @Override
    public void write(int b) throws IOException {
        // redirects data to the text area
        textArea.append(String.valueOf((char)b));
        // scrolls the text area to the end of data
        textArea.setCaretPosition(textArea.getText().length());
    }
}

Answer:

Here is an approach using a BlockingQueue to pass data from a JTextField's actionListener to the CustomInputStream.

public class Main extends JFrame {

    public Main() {
        init();
    }

    public void init() {
        try {
            JSch jsch = new JSch();

            JPanel panel = new JPanel();
            panel.setPreferredSize(new Dimension(200, 200));
            JTextArea log = new JTextArea();
            JTextField cmd = new JTextField();
            panel.setLayout(new BorderLayout());
            JScrollPane scrollPane = new JScrollPane(log);
            panel.add(scrollPane, BorderLayout.CENTER);
            panel.add(cmd, BorderLayout.SOUTH);
            add(panel);

            Session session = jsch.getSession("akumar", "banas", 22);
            String passwd = "******";
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.setPassword(passwd);
            session.connect(30000);   // making a connection with timeout.

            Channel channel = session.openChannel("shell");
            channel.setInputStream(new CustomInputStream(cmd));
            channel.setOutputStream(new CustomOutputStream(log));
            channel.connect(3 * 1000);
            pack();

        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public class CustomInputStream extends InputStream implements ActionListener {

        final JTextField field;
        final BlockingQueue<String> q;

        public CustomInputStream(JTextField field) {
            this.field = field;
            q = new LinkedBlockingQueue<>();
            field.addActionListener(this);
        }

        private String s;
        int pos;

        @Override
        public int read() throws IOException {
            while (null == s || s.length() <= pos) {
                try {
                    s = q.take();
                    pos = 0;
                } catch (InterruptedException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            int ret = (int) s.charAt(pos);
            pos++;
            return ret;
        }

        @Override
        public boolean markSupported() {
            return false;
        }

        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            int bytes_copied = 0;
            while (bytes_copied < 1) {
                while (null == s || s.length() <= pos) {
                    try {
                        s = q.take();
                        System.out.println("s = " + s);
                        pos = 0;
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                int bytes_to_copy = len < s.length()-pos ? len : s.length()-pos;
                System.arraycopy(s.getBytes(), pos, b, off, bytes_to_copy);
                pos += bytes_to_copy;
                bytes_copied += bytes_to_copy;
            }
            return bytes_copied;
        }

        @Override
        public int read(byte[] b) throws IOException {
            return read(b, 0, b.length); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            q.add(field.getText() + "\r\n");
            field.setText("");
        }

    }

// This is the code for making textarea as output stream
    public class CustomOutputStream extends OutputStream {

        private JTextArea textArea;

        public CustomOutputStream(JTextArea textArea) {
            this.textArea = textArea;
        }

        @Override
        public void write(int b) throws IOException {
            // redirects data to the text area
            textArea.append(String.valueOf((char) b));
            // scrolls the text area to the end of data
            textArea.setCaretPosition(textArea.getText().length());
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            String s = new String(b,off,len);
            textArea.append(s);
            textArea.setCaretPosition(textArea.getText().length());
        }

        @Override
        public void write(byte[] b) throws IOException {
            this.write(b, 0, b.length);
        }
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(() -> {
            new Main().setVisible(true);
        });
    }
}

Question:

here is what I wanted to do. There is a textfield and user enters what he wants. For example "Rectangle" or "rectangle", "circle" or "CIRCLE" like that. And then the user presses the button. After that program draws the shape that user wrote down below. I couldn't use the "paint" function itself. It got worse somehow. So I used "paintRec" etc. But I think that's not true according to OOP. So please show me the legit way to solve this question. There are a lot of wrong coding down there. That's for sure. Show me how can I do this. Where am I doing wrong. Thanks.

public class extends Applet implements ActionListener{
TextField tf;
Button draw;

public void init(){
    tf = new TextField(10);
    draw = new Button("Draw");
    draw.addActionListener(this);
    add(tf);
    add(draw);
}

public void actionPerformed(ActionEvent e) {
    String shape = tf.getText();
    if (shape.equals("rectangle") || shape.equals("RECTANGLE"))
    {
        paintRec(null);
    }
    if (shape.equals("circle") || shape.equals("CIRCLE"))
    {
        paintCirc(null);
    }
}

public void paintRec(Graphics g){
    g.drawRect(30,30,50,60);
}
public void paintCirc(Graphics g){
    g.drawOval(30, 30, 50, 60);
}
}

Answer:

The problem lies at here:

public void actionPerformed(ActionEvent e) {
  String shape = tf.getText();
  if (shape.equals("rectangle") || shape.equals("RECTANGLE"))
  {
    paintRec(null);//passing null value to a method which has Graphics class instance and using it for drawing
  }
  if (shape.equals("circle") || shape.equals("CIRCLE"))
  {
      paintCirc(null);//same here
  }
}

The better way is always use paint() method and call repaint() method. Use the below code:

import java.applet.Applet;
import java.awt.event.*;
import java.awt.*;

/*
<applet code = "Demo.class" width = 400 height = 200> </applet>
*/

public class Demo extends Applet implements ActionListener{
  TextField tf;
  Button draw;
  String shape = "rectangle";//drawing rectangle by default

  public void init(){
    tf = new TextField(10);
    draw = new Button("Draw");
    draw.addActionListener(this);
    add(tf);
    add(draw);
  }

  public void actionPerformed(ActionEvent e) {
    shape = tf.getText();
    repaint();
  }

  public void paint(Graphics g){
    super.paint(g);
    if (shape.equals("rectangle") || shape.equals("RECTANGLE"))
    {
      g.drawRect(30,30,50,60);
    }
    if (shape.equals("circle") || shape.equals("CIRCLE"))
    {
      g.drawOval(30, 30, 50, 60);
    }
    else
    {
      //notify to enter the correct input
    }
  }
}

Question:

I am back with a new question about the same code as last time. I took a lot of the suggestions that were given, and changed a few things. The program compiles, but no rectangle appears with any input. People in the last thread said that the code would work with the issues fixed, but this doesn't seem to work. I don't know if it a problem with the graphics (I think someone else suggested to do what I did in the code I have now) or with the way I am accepting key inputs.

Anyways, the program below is supposed to have a rectangle drawn, and for that rectangle be moved one coordinate to the right or left depending on if you press the <- or -> key on your keyboard. However, no rectangle appears with any input.

import java.awt.*;
import java.net.*;
import java.util.*;
import java.applet.Applet;


public class game extends Applet
{
    Thread loopThread;
    boolean left  = false;
    boolean right = false;
    int platPos = 50;


    public void run() 
    { 
        Graphics g = null;

        int i, j;
        long startTime;

        if (loopThread == null) 
        {
            loopThread = new Thread();
            loopThread.start();
        }

        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        startTime = System.currentTimeMillis();
        while(Thread.currentThread() == loopThread) 
        {
            updatePlatter(g);
        }

    }


     public void updatePlatter(Graphics g) 
    {

         if(left)
         {
             g.setColor(new Color(255,255,255)); //sets color to white
             g.fillRect(50+platPos, 200, 100, 20); //draws over whatever existing rectangle there is with white
             platPos--; 
             g.setColor(new Color(100,100,100)); //sets new color
             g.fillRect(50+platPos,200, 100,20); //draws new rectangle 
             left = false; 
         }

         if(right)
         {
             g.setColor(new Color(255,255,255));
             g.fillRect(50+platPos,200,100,20);
             platPos++;
             g.setColor(new Color(100,100,100));
             g.fillRect(50+platPos,200,100,20);
             right = false;
         }

    }

    public boolean keyDown(Event e, int key) 
    {
            if (key == Event.LEFT)
            left = true;

            if (key == Event.RIGHT)
            right = true;

            return true;
     }
}

Also I want to use applet, not JFrame. Just a personal preference. Thanks for any help! ^.^


Answer:

First of all the graphics is provided to your applet. It's an abstract class and when you use the applet Java provides you with the proper implementation. You cannot just instance it. There are methods which take care of painting / repainting the applet. So I would suggest using the paint method for initial painting of the rectangle and then calling repaint in your loop. By the way using thread for a loop like that is not readable code (and it doesn't work). You don't even need run() method ;) When you create the applet it starts working.

So we can do it like that:

import java.applet.Applet;
import java.awt.Color;
import java.awt.Event;
import java.awt.Graphics;


public class Game extends Applet
{
    boolean left  = false;
    boolean right = false;
    int platPos = 0;


    @Override
     public void paint(Graphics g) 
    {
         g.fillRect(50+platPos, 0, 100, 20); 
         System.out.println("repaint");
         if(left)
         {

             g.setColor(new Color(255,255,255)); //sets color to white
             g.fillRect(50+platPos, 0, 100, 20); //draws over whatever existing rectangle there is with white
             platPos--; 
             g.setColor(new Color(100,100,100)); //sets new color
             g.fillRect(50+platPos,0, 100,20); //draws new rectangle 
             left = false; 
         }

         if(right)
         {
             g.setColor(new Color(255,255,255));
             g.fillRect(50+platPos,200,100,20);
             platPos++;
             g.setColor(new Color(100,100,100));
             g.fillRect(50+platPos,200,100,20);
             right = false;
         }

    }
    @Override
    public boolean keyDown(Event e, int key) 
    {
             if (key == Event.LEFT) {
                left = true;
             }

            if (key == Event.RIGHT) {
                right = true;
            }

            repaint();
            return true;
     }
}

Question:

I am trying to show the list of words which start with the letter specified by the user input.

So for example if I add three words to my list, cat, corn and dog, and the user inputs the letter c, the output on the Java applet should be cat, corn.

However, I have no idea on how to go about this.

public void actionPerformed(ActionEvent e){
    if (e.getSource() == b1 ){
        x = textf.getText();
        wordList.add(x);
        textf.setText(null);
    } 

    if (e.getSource() == b2 ){
    }
}

b1 is adding all the user input into a secretly stored list, and I now want to make another button when pressed to show the words that start with the specified letter by the user.

textf = my text field
wordList = my list I created
x = string I previously defined 

Answer:

You could loop through all the possible indices, check if the element at that index starts with the letter, and print it if it does.

ALTERNATIVE (and probably better) code (I was going to put this after, but since its better it deserves to be first. Taken form @larsmans's answer here.

//given wordList as the word list
//given startChar as the character to search for in the form of a *String* not char
for (String element : wordList){
    if (element.startsWith(startChar)){
        System.out.println(element);
    }
}

DISCLAIMER: This code is untested, I don't have much experience with ArrayList, and Java is more of a quaternary programming language for me. Hope it works :)

//given same variables as before
for (int i = 0; i < wordList.size(); i++){
    String element = wordList.get(i);
    //you could remove the temporary variable and replace element with
    //  wordList.get(i)
    if (element.startsWith(startChar){
        System.out.println(element);
    }
}

Question:

I'm writing a Java applet for a programming class to calculate tuition. I think (no, I know) I've outkicked my coverage trying to get the ActionListener to get the input value and then use that value to perform the calculation. Code is below. This is homework, so I'm not looking for a bunch of code - I would just like to get pointed in the right direction for how to get the value a user would input into the "numCredits" text field incorporated into the tuition calculation formula. Thanks!

/**
 * Calculate tuition at NHCC based on 
 * number of credits and instruction type.
 * 
 * by Jodi Rehlander
 * version 1.0, 9/7/15 for CSci1130-51
 */

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

public class Tuition4 extends JApplet implements ActionListener
{
Image nhccImg;
ImageIcon nhccIcon;
JLabel credits, cType, nhcc, title; 
JTextField numCredits;
JButton online, standard, nursing;
JTextArea tType;
String inputCredits;
int numCreditsInt = 0;
double totalOnline;
double totalStandard;
double totalNursing;


    //define buttons, add listeners, display the buttons in the applet
    public void init( )
    {
        getContentPane( ).setBackground( Color.WHITE );

        setLayout( new BorderLayout( ) );

        nhccImg = getImage( getCodeBase( ), "NHCCLOGO.png" );
        nhccIcon = new ImageIcon( nhccImg );
        nhcc = new JLabel (nhccIcon);
        credits = new JLabel( "How many credits?" );
        cType = new JLabel( "\n What kind of classes?" );
        online = new JButton( "Online" );
        standard = new JButton( "Standard" );
        nursing = new JButton( "Nursing" );
        numCredits = new JTextField( "",3 );
        inputCredits = numCredits.getText( );
        tType = new JTextArea( 12,14 );
        tType.setEditable(false);
        addListeners( );
        add( nhcc, BorderLayout.WEST );
        JPanel pane = new JPanel( new FlowLayout( ) );
        pane.add( credits );
        pane.add( numCredits );
        pane.add( cType );
        pane.add( online );    
        pane.add( standard );     
        pane.add( nursing );
        pane.add( tType );
        add( pane, BorderLayout.CENTER );
    }


     public void addListeners( )
    {
        numCredits.addActionListener( this );
        online.addActionListener( this );
        standard.addActionListener( this );
        nursing.addActionListener( this );
    }



    public void actionPerformed( ActionEvent ae)
    {
        Object obj = ae.getSource( );
            if( obj == online )
            {
                numCreditsInt = Integer.parseInt(numCredits.getText( ) );
                tType.setText( "\n \n Tuition type: Online \n \n Cost/Credit: $177.96 \n Fees: $14.35 \n Textbooks: $250.00 \n \n Total Cost: " + "$"+( totalOnline ) );
            }
            else if ( obj == standard )
            {
                tType.setText( "Tuition type: Standard \n Cost/Credit: $165.08 \n Fees: $14.35 \n Parking: $3.20 \n Textbooks: $350.00 \n Total Costs: $xxx.xx \n" );
            }
            else if ( obj == nursing )
            {
               tType.setText( "Tuition type: Standard \n Cost/Credit: $189.78 \n Fees: $14.35 \n Parking: $3.20 \n Textbooks: $600.00 \n Total Costs: $xxx.xx \n" );
            }
            revalidate( );
            repaint( );
    }

    public double calculateOnlineTuition(int numCredits, double rate, double tuition, double fees, 
       double textbooks)
    {
        //calculate online tuition
        //numCredits = Integer.parseInt(inputCredits);
        rate = 177.96;
        fees = 14.35;
        textbooks = 275.00;
        tuition = numCreditsInt*rate;
        totalOnline = tuition + fees + textbooks;
        return totalOnline;

        //calculate Standard and Nursing rates once Online works
    }


    public void paint(Graphics g)
    {
        super.paint (g);

        Font heading = new Font( "Monospaced", Font.BOLD, 14 );
        Font small = new Font( "Monospaced", Font.PLAIN, 12 );
        Font smallItalic = new Font( "Monospaced", Font.ITALIC, 12 );


        g.setFont( heading );
        g.drawString("FEE BREAKDOWN:", 272, 375);
        g.setFont( small );
        g.drawString("Technology Fee    $8.00", 272, 390);
        g.drawString("Student Life Fee  $5.00", 272, 405);
        g.drawString("MSCSA Fee         $0.35", 272, 420);
        g.drawString("Health Svcs Fee   $1.00", 272, 435);
        g.drawString("*Parking          $3.20", 272, 450);
        g.setFont( smallItalic );
        g.drawString("*Parking not included", 280,485 );
        g.drawString("in online rate", 300,501);

    }
}

Answer:

First, check to see if the numCredits field has a value or not, no point in making any calculations without out.

Next gather the require parameters for the calculateOnlineTuition method (FYI this smacks of a dedicated class by the way) based on the selected action.

There is no need for numCredits to have a ActionListener, as only the buttons have any meaning. Also, it's pointless passing tuition to calculateOnlineTuition as this is the value you are trying to calculate, better to let the method simply return the value you're after

As an example:

public void actionPerformed(ActionEvent ae) {
    Object obj = ae.getSource();

    if (!numCredits.getText().trim().isEmpty()) {
        numCreditsInt = Integer.parseInt(numCredits.getText());
        double rate = 0;
        double fees = 0;
        double books = 0;
        if (obj == online) {
            rate = 177.96;
            fees = 14.35;
            books = 250.0;
            tType.setText("\n \n Tuition type: Online \n \n Cost/Credit: $177.96 \n Fees: $14.35 \n Textbooks: $250.00 \n \n Total Cost: ");
        } else if (obj == standard) {
            rate = 165.08 + 3.20; //?
            fees = 14.35;
            books = 350.0;
            tType.setText("Tuition type: Standard \n Cost/Credit: $165.08 \n Fees: $14.35 \n Parking: $3.20 \n Textbooks: $350.00 \n Total Costs: ");
        } else if (obj == nursing) {
            rate = 189.78 + 3.20; //?
            fees = 14.35;
            books = 600.0;
            tType.setText("Tuition type: Standard \n Cost/Credit: $189.78 \n Fees: $14.35 \n Parking: $3.20 \n Textbooks: $600.00 \n Total Costs: ");
        }

        double total = calculateOnlineTuition(numCreditsInt, rate, fees, books);
        tType.append(NumberFormat.getCurrencyInstance().format(total) + "\n");

    }

    revalidate();
    repaint();
}

public double calculateOnlineTuition(int numCredits, double rate, double fees,
                double textbooks) {
    //calculate online tuition
    //numCredits = Integer.parseInt(inputCredits);
    rate = 177.96;
    fees = 14.35;
    textbooks = 275.00;
    double tuition = numCreditsInt * rate;
    totalOnline = tuition + fees + textbooks;
    return totalOnline;

    //calculate Standard and Nursing rates once Online works
}

Question:

I am in need of assistance, (Using NetBeans 7.4)

I am creating a Programming applet, and I want the end user to answer some questions I will have in the applet.

Is there any way I can have the users inputted "code" (answer to the question) compiled and printed out through the GUI. (User inputs answer, submits, it compiles, and my application prints out if it is right or wrong)

Example: The user needs to answer

How do I print out "Hello" in java?

and they would have to put

"System.out.println("Hello");"

Any help would be fantastic,

Thank you in advance,


Answer:

Well it's possible, but you need to define the set of valid answers for each question, for example you point

System.out.println("Hello");

as valid answer, but

System.out.print("Hello");

or

System.out.printf("%s", "Hello");

just to mention a few, are also valid from a code compilation point of view.

Also you need to clearly define what is a right or a wrong answer, for example should the output have a new line at the end or not, i.e. println vs. print.

Those are only a few questions who complex and broad the problem is. Not to mention the human understanding of what a correct answer is.

To minimize all this complexity I would suggest to ask precise questions and when code is submitted compile and run it and compare with the expected result. To take your example I would ask

How do I print out "Hello" to standard output in java?

Then you will have to run the code in separate process, given it compiles correctly, and read the stdout of that process. After that you may choose to trim the result and compare with the expected result. If matched then the use did input 'a code' which produces to a valid output.

This way your program will validate all above print statements as correct.

To compile user entered code you may use the Interface to invoke Java™ programming language compilers from programs.

To compile other code than java you will need the their compiles installed too which you can also run from java program, if you want to validate C code you will need for example GCC installed.

Question:

I'm learning how to make an Applet using Java in the form of a game. In the game, I have a character sprite drawn at the center and moves when the player presses w a s d.

It goes like this:

public game extends applet implements KeyListener {
    int x, y;
    URL url;
    Image image;
    public void init() {
        x = getSize().width/2;
        y = getSize().height/2;
        url = new URL(getCodeBase());
        image = getImage(url, "player.gif"); //take note that this is a still image
        addKeyListener(this);
    }
    public void paint(Graphics g) {
        g.drawImage(image, x, y, 32, 32, this); //the size of the image is 32x32
    }
    public void KeyPressed(arg0) {
    char c = arg0.getKeyChar();
    switch(c) {
        case 'w':  
            y -= 10;
            break; 
        /*And so on. You guys know how it works.*/      
    }
    repaint();
}

My problem is, the character sprite seems dull when the user doesn't press anything. What I want to do is to make the Image an array of images and put a simple image animation by looping the array in paint like so:

public void paint(Graphics g) {
    for(int i = 0; ; i++) {
        g.drawImage(image[i], x, y, 32, 32, this);
        if(i == image.size() - 1) { i = 0;}
    }
}

However, if I do this, I won't be able to get anymore KeyEvents that would activate when the user wants to move. My question is this: How will I make it so that my character does an animation when the program is "idle" (i.e. the user isn't pressing anything) while still maintaining the capability to take in KeyEvents (e.g. moving when the player types in w, a, s, or d, and then continuing the idle animation after repainting)?

Thanks in advance.

PS. I'm still quite a beginner in Java so sorry if my code is not very nice. Any advice is welcome.


Answer:

You need to make your application multithreaded so that the painting runs in a separate thread.

Otherwise you will have the painting blocked while waiting for the next key.

This is not a trivial change to your code though.