Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

StringSet.java Can you please help me the JAVA program? Write a WidgetView appli

ID: 3775794 • Letter: S

Question

StringSet.java

Can you please help me the JAVA program?

Write a WidgetView application.

Create a class StringAnalysis. This class has an event handler inner class extending WidgetViewActionEvent

StringSet sSet

JTextField inputStr

JLabel numStr

JLabel numChar

create a WidgetView object

create sSet

create a local variable JLabel prompt initialized to "Enter a String"

create inputStr with some number of columns

create a local variable JButton pushMe initialized to "Push to include String"

create numStr initialized to "Number of Strings: 0"

create numChar initalized to "Number of Characters: 0"

create an event handler object and add it as a listener to pushMe

add prompt, inputStr, pushMe, numStr and numChar to your WidgetView object.

------------------------------------------------------

Here is OLD requirement. https://www.chegg.com/homework-help/questions-and-answers/stringsetjava-please-help-java-program--please-show-output-also-q15958409

------------------------------------------------------

WidgetView.java from instructor.

import java.awt.event.ActionListener;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.swing.AbstractButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
* A really simple class to display Swing widgets in a FlowLayout GUI.
* <p>
*
* @author parks
*/
public class WidgetView {
  
   public static final int DEFAULT_X_SIZE = 600;
   public static final int DEFAULT_Y_SIZE = 400;

private JFrame jframe;
private JPanel anchor;
private boolean userClicked = false;

private Lock lock;
private Condition waitingForUser;

private JComponent userInputComponent = null;
private ActionListener eventHandler;

/**
* Default constructor will display an empty JFrame that has a Flow layout
* JPanel as its content pane and initialize the frame to a default size.
*/
public WidgetView() {
   this(DEFAULT_X_SIZE, DEFAULT_Y_SIZE);
}
  
/**
* Constructor will display an empty JFrame that has a Flow layout
* JPanel as its content pane and initialize the frame to a given size.
*/
public WidgetView(int pixelSizeInX, int pixelSizeInY) {
lock = new ReentrantLock();
waitingForUser = lock.newCondition();
// lambda expression requires Java 8
eventHandler = e -> {
if (e.getSource() != userInputComponent) {
return;
}
lock.lock();
userClicked = true;
waitingForUser.signalAll();
lock.unlock();
};

/* java 7 solution
* eventHandler = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() != userInputComponent) {
return;
}
lock.lock();
userClicked = true;
waitingForUser.signalAll();
lock.unlock();
}
};
*/

jframe = new JFrame();
anchor = new JPanel();
jframe.setContentPane(anchor);
jframe.setSize(pixelSizeInX, pixelSizeInY);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setVisible(true);
}

/**
* Add a Swing widget to the GUI.
*
* @param jcomp Swing widget (subclasses of JComponent--like JLabel and
* JTextField) to be added to the JFrame
*/
public void add(JComponent jcomp) {
anchor.add(jcomp);
jframe.setContentPane(anchor);
}

/**
* Add an Abstract Button (like a JButton) to the JFrame. Create an action
* listener to wait (suspend the caller) until it is clicked.
*
* @param absButton Button (like a JButton) to add to the JFrame
*/
public void addAndWait(AbstractButton absButton) {
userInputComponent = absButton;
absButton.addActionListener(eventHandler);

addWait(absButton);
}

/**
* Add a JTextField to the JFrame, and wait for the user to put the cursor
* in the field and click Enter. The caller is suspended until enter is
* clicked.
*
* @param jTextField Field to add to the JFrame
*/
public void addAndWait(JTextField jTextField) {
userInputComponent = jTextField;
jTextField.addActionListener(eventHandler);

addWait(jTextField);
}

private void addWait(JComponent jcomp) {
add(jcomp);
lock.lock();
try {
while (!userClicked) {
waitingForUser.await();
}
}
catch (InterruptedException e1) {
System.err.println("WidgetView reports that something really bad just happened");
e1.printStackTrace();
System.exit(0);
}
userClicked = false;
waitingForUser.signalAll();
lock.unlock();
}
}

------------------------------------------------------

Here is the code from OLD requirement:

class StringSet
{
//An instance variable of type String[]
String[] set;
//An int instance variable that indicates the number of String objects that the StringSet currently contains.
int numOfStrings;
//A no argument constructor.
public StringSet()
{
numOfStrings = 0;
set = new String[10];
}
//A mutator that adds a String newStr to the StringSet object.
void add(String newStr)
{
set[numOfStrings++] = newStr;
}
//An accessor that returns the number of String objects that have been added to this StringSet object.
int size()
{
return numOfStrings;
}
//An accessor that returns the total number of characters in all of the Strings that have been added to this StringSet object.
int numChars()
{
int sum = 0;
for(int i = 0; i < numOfStrings; i++)
sum += set[i].length();
return sum;
}
//An accessor that returns the number of Strings in the StringSet object that have exactly len characters.
int countStrings(int len)
{
int count = 0;
for(int i = 0; i < numOfStrings; i++)
if(set[i].length() == len)
count++;
return count;
}
}

And the code for StringSetTester.java is:

import java.util.*;
class StringSetTester
{
public static void main(String[] args)
{
Scanner kybd = new Scanner(System.in);
System.out.print("How many strings will you enter? ");
int numStr = kybd.nextInt();
kybd.nextLine();
StringSet ss = new StringSet();
for(int i = 0; i < numStr; i++)
{
System.out.print("Enter string " + (i+1) + ": ");
String temp = kybd.nextLine();
ss.add(temp);
}
System.out.println("The size of the StringSet is: " + ss.size());
System.out.println("The number of characters in StringSet is: " + ss.numChars());
System.out.println("The number of strings of length 5 are: " + ss.countStrings(5));
System.out.println("The number of strings of length 7 are: " + ss.countStrings(7));
}
}

============================================================================

Output shoud look like this:

0-InitialWindow

4-ThirdStringEntered

Enter a String Push to include string Number of Strings: 0 Number of Characters: 0

Explanation / Answer

package lu.fisch.canze.widgets;

import android.content.Context;

import android.content.Intent;

import android.content.res.TypedArray;

import android.graphics.Canvas;

import android.graphics.Paint;

import android.graphics.PaintFlagsDrawFilter;

import android.graphics.Point;

import android.os.Handler;

import android.os.Message;

import android.util.AttributeSet;

import android.view.Display;

import android.view.MotionEvent;

import android.view.SurfaceHolder;

import android.view.SurfaceView;

import android.view.View;

import android.view.WindowManager;

import java.lang.reflect.Constructor;

import lu.fisch.awt.Color;

import lu.fisch.awt.Graphics;

import lu.fisch.canze.actors.Field;

import lu.fisch.canze.classes.ColorRanges;

import lu.fisch.canze.classes.Intervals;

import lu.fisch.canze.interfaces.DrawSurfaceInterface;

import lu.fisch.canze.activities.MainActivity;

import lu.fisch.canze.R;

import lu.fisch.canze.activities.WidgetActivity;

public class WidgetView extends SurfaceView implements DrawSurfaceInterface, SurfaceHolder.Callback, View.OnTouchListener {

private DrawThread drawThread = null;

private Drawable drawable = null;

    private String fieldSID = "";

    private boolean clickable = true;

    protected boolean landscape = true;

    public static Drawable selectedDrawable = null;

public void setDrawable(Drawable drawable)

    {

        this.drawable=drawable;

        drawable.setDrawSurface(this);

        repaint();

    }

public Drawable getDrawable()

{

return drawable;

}

public WidgetView(Context context) {

super(context);

init(context, null);

        setOnTouchListener(this);

}

public WidgetView(Context context, AttributeSet attrs) {

super(context, attrs);

init(context, attrs);

        setOnTouchListener(this);

}

public WidgetView(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

init(context,attrs);

        setOnTouchListener(this);

}

    @Override

    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {

        super.onLayout(changed, left, top, right, bottom);

        landscape = (right-left)>(bottom-top);

        if(changed) drawable.onLayout(landscape);

    }

    public void reset()

    {

        drawable.reset();

        repaint();

    }

    public void init(final Context context, AttributeSet attrs)

{

        SurfaceHolder holder = getHolder();

        holder.addCallback(this);

        setFocusable(true);

     WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

     Display display = wm.getDefaultDisplay();

     Point size = new Point();

     display.getSize(size);

        if(attrs!=null)

        {

            try

            {

                String[] widgets = {"Tacho","Kompass", "Bar","BatteryBar","Plotter","Label","Timeplot","BarGraph"};

                TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.WidgetView, 0, 0);

                int widgetIndex = attributes.getInt(R.styleable.WidgetView_widget, 0);

                if(widgetIndex<widgets.length)

                {

                    String widget = widgets[widgetIndex];

                    //MainActivity.debug("WidgetView: I am a "+widget);

                    Class clazz = Class.forName("lu.fisch.canze.widgets." + widget);

                    Constructor<?> constructor = clazz.getConstructor(null);

                    drawable = (Drawable) constructor.newInstance();

                    drawable.setDrawSurface(WidgetView.this);

                    drawable.setMin(attributes.getInt(R.styleable.WidgetView_min, 0));

                    drawable.setMax(attributes.getInt(R.styleable.WidgetView_max, 0));

                    drawable.setMajorTicks(attributes.getInt(R.styleable.WidgetView_majorTicks, 0));

                    drawable.setMinorTicks(attributes.getInt(R.styleable.WidgetView_minorTicks, 0));

                   drawable.setTitle(attributes.getString(R.styleable.WidgetView_text));

                    drawable.setShowLabels(attributes.getBoolean(R.styleable.WidgetView_showLabels, true));

                    drawable.setShowValue(attributes.getBoolean(R.styleable.WidgetView_showValue, true));

                    drawable.setInverted(attributes.getBoolean(R.styleable.WidgetView_isInverted, false));

                    String colorRangesJson =attributes.getString(R.styleable.WidgetView_colorRanges);

                    if(colorRangesJson!=null && !colorRangesJson.trim().isEmpty())

                        drawable.setColorRanges(new ColorRanges(colorRangesJson.replace("'", """)));

                    String foreground =attributes.getString(R.styleable.WidgetView_foregroundColor);

                    if(foreground!=null && !foreground.isEmpty())

                        drawable.setForeground(Color.decode(foreground));

                    String background =attributes.getString(R.styleable.WidgetView_backgroundColor);

                    if(background!=null && !background.isEmpty())

                        drawable.setBackground(Color.decode(background));

                    String intermediate =attributes.getString(R.styleable.WidgetView_intermediateColor);

                    if(intermediate!=null && !intermediate.isEmpty())

                        drawable.setIntermediate(Color.decode(intermediate));

                    String titleColor =attributes.getString(R.styleable.WidgetView_titleColor);

                    if(titleColor!=null && !titleColor.isEmpty())

                        drawable.setTitleColor(Color.decode(titleColor));

                    String intervalJson =attributes.getString(R.styleable.WidgetView_intervals);

                    if(intervalJson!=null && !intervalJson.trim().isEmpty())

                        drawable.setIntervals(new Intervals(intervalJson.replace("'", """)));

                    fieldSID = attributes.getString(R.styleable.WidgetView_fieldSID);

                    String[] sids = fieldSID.split(",");

                    for(int s=0; s<sids.length; s++) {

                        Field field = MainActivity.fields.getBySID(sids[s]);

                        if (field == null) {

                            MainActivity.debug("!!! >> Field with following SID <" + sids[s] + "> not found!");

                        }

                        else {

                            drawable.addField(field.getSID());

                            field.addListener(drawable);

                            int interval = drawable.getIntervals().getInterval(field.getSID());

                            if(interval==-1)

                                MainActivity.device.addActivityField(field);

                            else

                                MainActivity.device.addActivityField(field,interval);

                        }

                    }

                    if(MainActivity.milesMode) drawable.setTitle(drawable.getTitle().replace("km","mi"));

                }

                else

                {

                    MainActivity.debug("WidgetIndex "+widgetIndex+" is wrong!? Not registered in <WidgetView>?");

                }

            }

            catch(Exception e)

            {

                e.printStackTrace();

            }

        }

}

    private boolean motionDown = false;

    private boolean motionMove = false;

    private float downX, downY;

    @Override

    public boolean onTouch(View v, MotionEvent event)

    {

     int pointerIndex = event.getActionIndex();

     int pointerId = event.getPointerId(pointerIndex);

     int maskedAction = event.getActionMasked();

        MainActivity.debug("WidgetView: maskedAction = "+maskedAction);

     switch (maskedAction) {

      case MotionEvent.ACTION_DOWN:

      case MotionEvent.ACTION_POINTER_DOWN:{

                motionDown=true;

                downX=event.getX();

                downY=event.getY();

                break;

            }

      case MotionEvent.ACTION_MOVE: {

                motionMove=true;

       break;

      }

      case MotionEvent.ACTION_UP:

      case MotionEvent.ACTION_POINTER_UP:

            {

                if(!motionMove && clickable && MainActivity.isSafe()) {

                    Intent intent = new Intent(this.getContext(), WidgetActivity.class);

                    selectedDrawable = this.getDrawable();

                    this.getContext().startActivity(intent);

                }

                motionDown=false;

                motionMove=false;

                break;

            }

      case MotionEvent.ACTION_CANCEL: {

       break;

      }

     }

     invalidate();

     return true;

    }

@Override

public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {

}

@Override

public void surfaceCreated(SurfaceHolder arg0)

{

        (new Thread(new Runnable() {

            @Override

            public void run() {

                drawable.loadValuesFromDatabase();

                repaint();

            }

        })).start();

}

    public void repaint2() {

        Canvas c = null;

        try {

            c = getHolder().lockCanvas();

            if (c != null) {

                c.setDrawFilter(new PaintFlagsDrawFilter(1, Paint.ANTI_ALIAS_FLAG));

                Paint paint = new Paint();

                paint.setColor(drawable.getBackground().getAndroidColor());

                c.drawRect(0, 0, c.getWidth(), c.getHeight(), paint);

                drawable.setWidth(getWidth());

                drawable.setHeight(getHeight());

                drawable.draw(new Graphics(c));

            }

        }

        catch(Exception e)

        {

        }

        finally

        {

            if (c != null) {

                getHolder().unlockCanvasAndPost(c);

            }

        }

    }

public void repaint()

{

        if(drawThread==null || !drawThread.isRunning())

        {

            System.gc();

            this.post(new Runnable() {

                @Override

                public void run() {

                    drawThread = new DrawThread(getHolder(), getContext(), new Handler() {

                        @Override

                        public void handleMessage(Message m) {

                        }

                    });

                    if (drawable != null) {

                        drawable.setWidth(getWidth());

                        drawable.setHeight(getHeight());

                       drawThread.setDrawable(drawable);

                    }

                    drawThread.start();

                }

            });

        }

}

@Override

public void surfaceDestroyed(SurfaceHolder arg0)

{

        boolean retry = true;

        while (retry)

        {

            try

            {

                if(drawThread!=null && drawThread.isRunning())

                 drawThread.join();

                retry = false;

            }

            catch (InterruptedException e)

            {

                e.printStackTrace();

            }

        }

        drawThread=null;

}

    public String getFieldSID()

    {

        return fieldSID;

    }

    @Override

    public boolean isClickable() {

        return clickable;

    }

    @Override

    public void setClickable(boolean clickable) {

        this.clickable = clickable;

    }

    public void setFieldSID(String fieldSID) {

        this.fieldSID = fieldSID;

    }

}