MPAndroidChart I want to change dot color if the value over the constant - mpandroidchart

I want to make a linechart that
for many values, if there are values that over constant,
its dot color changed to another color
How to change dot colors if value is higher than constant in MPAndroidChart
I read this and try to follow this, but it changed bar not dots
what can i do?
here's my code
private void setData(int count, int range)
ArrayList<Integer> color = new ArrayList<>();
ArrayList<Entry> yVals1 = new ArrayList<>();
for (int i=0; i<count; i++)
{
float val = (float) (Math.random()*range);
if (val > 50){
//color.add(Color.RED);
//color.add(ColorTemplate.rgb("ff0000"));
yVals1.add(new Entry(i, val));
} else {
//color.add(Color.BLACK);
// color.add(ColorTemplate.rgb("000000"));
yVals1.add(new Entry(i, val));
}
}

First replace following line:
color.add(Color.RED);
with:
color.add(context.getResources().getColor(R.color.your_defined_color_in_colors_xml));
then after your code you need to add following line:
dataSet.setCircleColors(color);

Related

my code is only drawing a straight line no matter how many sides i input in the pSides JTextFields

When I input a digit in the JTextfields it should pass through my actionListener to store all the values (ID, number of sides, length of sides and color) into an arraylist. It should then be used in my polygonContainer class that goes through a for loop and a polygon formula, then prints it out. However what comes out all the time is a straight line.
This is the code i tried:
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
public class ContainerFrame extends JFrame{
ArrayList<PolygonContainer> polygons = new ArrayList<>();
// JTextFields for the number of sides, side length, color, and ID
public JTextField pSides, pSidesLengths, pColor, pID;
// Button for submission
public JButton submitButton;
public void createComponents() {
// Initialize the JTextFields
pSides = new JTextField();
pSidesLengths = new JTextField();
pColor = new JTextField();
pID = new JTextField();
submitButton = new JButton("Submit");
submitButton.addActionListener(new ContainerButtonHandler(this));
JPanel textFieldsPanel = new JPanel();
// uses a gridlayout to organise the textfields then sets it as north
textFieldsPanel.setLayout(new GridLayout(5, 2));
textFieldsPanel.add(new JLabel("Sides:"));
textFieldsPanel.add(pSides);
textFieldsPanel.add(new JLabel("Sides Length:"));
textFieldsPanel.add(pSidesLengths);
textFieldsPanel.add(new JLabel("Color:"));
textFieldsPanel.add(pColor);
textFieldsPanel.add(new JLabel("ID:"));
textFieldsPanel.add(pID);
add(textFieldsPanel, BorderLayout.NORTH);
add(submitButton, BorderLayout.SOUTH);
JPanel drawPanel = new ContainerPanel(this);
add(drawPanel, BorderLayout.CENTER);
setSize(1600, 900);
setVisible(true);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); // Close action.
}
public static void main(String[] args) {
ContainerFrame cFrame = new ContainerFrame();
cFrame.createComponents();
}
}
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
class ContainerButtonHandler implements ActionListener {
ContainerFrame theApp; // Reference to ContainerFrame object
// ButtonHandler constructor
ContainerButtonHandler(ContainerFrame app) {
theApp = app;
}
public void actionPerformed(ActionEvent e) {
// Get the text from the JTextFields using the getText method
String sides = theApp.pSides.getText();
String sidesLengths = theApp.pSidesLengths.getText();
String id = theApp.pID.getText();
//parse the values as integers
int intSides = Integer.parseInt(sides);
int intSidesLength = Integer.parseInt(sidesLengths);
int intId = Integer.parseInt(id);
//does the input validation where sides, sides length and id needs to be positive integers
if (intId >= 100000 && intId <= 999999 && intSides >= 0 && intSidesLength >= 0) {
// The inputs are valid
String color = theApp.pColor.getText();
// Store the values in an arraylist or other data structure
ArrayList<String> polygonArray = new ArrayList<String>();
polygonArray.add(sides);
polygonArray.add(sidesLengths);
polygonArray.add(color);
polygonArray.add(id);
PolygonContainer polygon = new PolygonContainer(polygonArray);
theApp.polygons.add(polygon);
theApp.repaint();
JOptionPane.showMessageDialog(theApp, "Polygon" + id + "was added to the list.", "Success", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(theApp, "The Polygon" + id + "was not added to the list as a valid Id was not provided.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
public class PolygonContainer implements Comparable<PolygonContainer>{
Color pColor = Color.BLACK; // Colour of the polygon, set to a Colour object, default set to black
int pId = 000000; // Polygon ID should be a six digit non-negative integer
int pSides; // Number of sides of the polygon, should be non-negative value
int pSideLengths; // Length of each side in pixels of the polygon, should be non-negative value
int polyCenX; // x value of centre point (pixel) of polygon when drawn on the panel
int polyCenY; // y value of centre point (pixel of polygon when drawn on the panel
int [] pointsX; // int array containing x values of each vertex (corner point) of the polygon
int [] pointsY; // int array containing y values of each vertex (corner point) of the polygon
// Constructor currently set the number of sides and the equal length of each side of the Polygon
//Constructor that takes the values from the array
public PolygonContainer(ArrayList<String> values){
this.pSides = Integer.parseInt(values.get(0));
this.pSideLengths = Integer.parseInt(values.get(1));
this.pColor = Color.getColor(values.get(2));
this.pId = Integer.parseInt(values.get(3));
pointsX = new int[pSides];
pointsY = new int[pSides];
}
// Used to populate the points array with the vertices corners (points) and construct a polygon with the
// number of sides defined by pSides and the length of each side defined by pSideLength.
// Dimension object that is passed in as an argument is used to get the width and height of the ContainerPanel
// and used to determine the x and y values of its centre point that will be used to position the drawn Polygon.
public Polygon getPolygonPoints(Dimension dim) {
polyCenX = dim.width / 2; // x value of centre point of the polygon
polyCenY = dim.height / 2; // y value of centre point of the polygon
Polygon p = new Polygon();
for (int i = 0; i < pSides; i++) {
// Calculate the x and y coordinates of the ith point of the polygon
int x = polyCenX + pSideLengths * (int) Math.cos(2.0 * Math.PI * i / pSides);
int y = polyCenY + pSideLengths * (int) Math.sin(2.0 * Math.PI * i / pSides);
// Add the x and y coordinates to the pointsX and pointsY arrays
pointsX[i] = x;
pointsY[i] = y;
// Add the point to the polygon object using the addPoint method
p.addPoint(x, y);
}
return p;
}
// You will need to modify this method to set the colour of the Polygon to be drawn
// Remember that Graphics2D has a setColor() method available for this purpose
public void drawPolygon(Graphics2D g, Dimension d) {
//Set color of polygon
g.setColor(pColor);
Polygon p = getPolygonPoints(d);
g.draw(p);
//this creates a bounding box around the polygon
Rectangle2D bounds = p.getBounds2D();
g.draw(bounds);
}
// gets a stored ID
public int getID() {
return pId;
}
#Override
// method used for comparing PolygonContainer objects based on stored ids, you need to complete the method
public int compareTo(PolygonContainer o) {
return 0;
}
// outputs a string representation of the PolygonContainer object, you need to complete this to use for testing
public String toString()
{
return "";
}
}
import javax.swing.JPanel;
import java.awt.*;
public class ContainerPanel extends JPanel{
ContainerFrame conFrame;
public ContainerPanel(ContainerFrame cf) {
conFrame = cf; // reference to ContainerFrame object
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D comp = (Graphics2D)g; // You will need to use a Graphics2D objects for this
Dimension size = getSize(); // You will need to use this Dimension object to get
// the width / height of the JPanel in which the
// Polygon is going to be drawn
for (PolygonContainer polygon : conFrame.polygons) {
polygon.drawPolygon(comp, size);
}
}
}
JFrame

mpandroidchart I want to get 3rd value

I am using mpandroidchart and i have a problem now
I set 3 values into the array likes this
(index, values, and another value)
ArrayList<Entry> value1 = new ArrayList<>();
for (int i = 0; i < 10; i++) {
float y = (float) Math.random();
float h = (float) Math.random();
value1.add(new Entry(i, y, h));
}
I want to get h values to use this h
but i cant' find the way
How can i get h value?
Thanks for reading
*Edited *
enter image description here
This is the image i want to make
* Edited2 *
ArrayList<Integer> color;
ArrayList<Entry> value1 = new ArrayList<>();
for (int i = 0; i < 10; i++) {
float y = (float) Math.random();
value1.add(new Entry(i, y));
if(y>10)
{
color.add(context.getResources().getColor(R.color.colorPrimary));
}
else
color.add(context.getResources().getColor(R.color.colorAccent));
}
dataSet.setColors(color);
Dear M.Saad Lakhan
You suggested like upper code, But there are some ploblems.
ArrayList color;
-> "variable 'color' might not have been initiallized
color.add(context.getResources().getColor(R.color.colorPrimary)
-> cannot resolve symbol 'context'
ArrayList dataSets = new ArrayList<>(); //this is my code
dataSets.setColors(color);
-> there is no setColors in my datasets
What are these problem?
You need to create:
ArrayList<Integer> colors = new ArrayList<>();
After that you need to add values for each entry which color you want to show, you need to modify your code as:
ArrayList<Entry> value1 = new ArrayList<>();
for (int i = 0; i < 10; i++)
{
float y = (float) Math.random();
value1.add(new Entry(i, y));
// add your condition here
if(y>10)
{
color.add(getContext().getResources().getColor(R.color.colorPrimary));
}
else
color.add(getContext().getResources().getColor(R.color.colorAccent));
}
When you complete your colors arraylist then you can set colors as:
dataSet.setColors(color);

How to remove all punctuation from a ArrayList<String>? Meaning "," and "."

I have an ArrayList that has numbers in it in a form of Strings, that are taken from a WebElement List (Copied into it).
I have 2 of these and I would like to compare between them, But because they have some "," and "." in these numbers I have difficulty to do that.
I have tried to look into similar questions such as
How can I remove punctuation from input text in Java?
But have failed to implement it on my arrayList.
The lists in the code can be easily located as :
/ / ***** LIST #1 - NEED TO IGNORE ALL NON_NUMERIC CHARACTERS *****///
and
***** LIST #1 - NEED TO IGNORE ALL NON_NUMERIC CHARACTERS *****///
public static void WatchlistInstrumentsList(WebDriver driver, boolean finalstatus) throws InterruptedException
{
List<Integer> memoryOfSelectedi = new ArrayList<Integer>(); // Remembering the 'Clock = Green' instruments
int size = 2;
int forCounter1=0;
for (int i = 1; i < size ; i++) {
forCounter1=i;
// The selector of "Last" price = Streamer
listOfLastPrice1= driver.findElements(By.cssSelector("[data-column-name='last'][class*='pid']"));
// ***** LIST #1 - NEED TO IGNORE ALL NON_NUMERIC CHARACTERS *****///
ArrayList<String> listCopyLastPrice1 = new ArrayList<String>();
for (WebElement element : listOfLastPrice1) {
listCopyLastPrice1.add(element.getText());
}
System.out.println("Number of Open stocks out of the list is: " +memoryOfSelectedi.size());
WatchlistCheckSocket(driver, listCopyLastPrice1, memoryOfSelectedi,listOfLastPrice1, forCounter1) ;
finalstatus = true;
}
public static void WatchlistCheckSocket(WebDriver driver,List listCopyLastPrice1,
List<Integer> memoryOfSelectedi, List<WebElement> listOfLastPrice1, int forCounter1) throws InterruptedException
{
// ******** CHANGE LATTER TO 180000 ******///
Thread.sleep(60000);
List<WebElement> listOfLastPrice2=null;
int size = 2;
int forCounter2;
for (int z = 0; z < size ; z++) {
listOfLastPrice2= driver.findElements(By.cssSelector("[data-column-name='last'][class*='pid']"));
size = listOfLastPrice2.size();
String NewPrice = listOfLastPrice2.get(z).getText();
System.out.println("Last Price is: " +listOfLastPrice2.get(z).getText());
}
// LIST #2 - NEED TO IGNORE ALL NON_NUMERIC CHARACTERS ///
// Put all Values of WebElement listOfLastPrice2 List, into a String array list //
ArrayList<String> listCopyLastPrice2 = new ArrayList<String>();
for (WebElement element : listOfLastPrice2) {
listCopyLastPrice2.add(element.getText());
}
// ****** COMPARE GREEN INSTRUMENTS, LIST1_Price VS LIST2_Price ****//
int sizeList=0;
while (sizeList<memoryOfSelectedi.size())
{
if (listCopyLastPrice1.get(memoryOfSelectedi.get(sizeList)) != listOfLastPrice2.get(memoryOfSelectedi.get(sizeList)).getText())
{
System.out.println("First price was: " +listCopyLastPrice1.get(memoryOfSelectedi.get(sizeList)));
System.out.println("Second price was: " +listCopyLastPrice2.get(memoryOfSelectedi.get(sizeList)));
}
sizeList++;
}}}
If I'll modify my list's syntax to that, would this help?
listCopyLastPrice2.add(element.getText().replaceAll("[^A-Za-z0-9]", ""));

Two colors in one text field using Actionscript 2

I'm trying to get realtime rainbow text in a single word and reset to red when I space to the next word to create another rainbow word.
For instance, if I want to type the string, "his forgiveness", I want "h" to be red, "i" to be orange, "s" to be yellow, "f" to be red, "o" to be orange, "r" to be yellow, "g" to be green, "i" to be blue, "v" to be indigo, "e" to be violet. The remaining, "ness" can all be violet, I don't care. I just need the original concept down.
So far, I'm only able to change the color of the whole text area on a keypress(s) and not a single string character.
To fast forward to where I am, follow this quick 4 point process:
(1/4)Paste the following code on the stage.
counter = -1;
var key:Object = {onKeyDown:function () {
counter = counter+1;
if (counter == 1) {
inp.textColor = 0xFF0000;
}
if (counter == 2) {
inp.textColor = 0xFF9900;
}
if (counter == 3) {
inp.textColor = 0xFFFF00;
}
}};
Key.addListener(key);
(2/4)Make an input box with the instance name, "inp"
(3/4)Test the movie.
(4/4)Select the textbox and start typing in it.
I only have it changing the whole text box from your default color to red then orange than yellow. Getting a true rainbow code will be what I've long waited for if you can help.
In order to implement different colors on a single textfield you must use this properties on your textfield:
myTextField.html = true
myTextField.htmlText = 'bli bli bli<font color="#0000FF">bla bla bla/font>'
or you can use the TextFormat class to do so.
Here is how you can do.
tField.text = "bli bli bli";
var tFormat:TextFormat = new TextFormat();
tFormat.color = 0xff0000;
tField.setTextFormat(0,5,tFormat);
tFormat.color = 0x33cc33;
tField.setTextFormat(5,9,tFormat);
and in order to get the colors as you type use this class:
package {
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.events.KeyboardEvent;
import flash.events.Event;
public class ColorTextField extends TextField{
var tf:TextFormat = new TextFormat();
var ar:Array = new Array(0xFF0000,0x00FF00,0x0000FF,0x123456);
public function ColorTextField() {
// constructor code
this.type = TextFieldType.INPUT;
tf.size = 33;
this.defaultTextFormat = tf;
this.addEventListener(KeyboardEvent.KEY_UP,onKeyUp);
}
private function onKeyUp(event:KeyboardEvent):void{
var index:int = 0;
var colorIndex:int = 0;
while (index < this.text.length){
var char:String = this.text.substr(index,1);
if(char == " "){
colorIndex = 0;
}else{
tf.color = ar[colorIndex];
trace(index + "-" +ar[colorIndex]);
this.setTextFormat(tf,index,index+1);
colorIndex++;
if(colorIndex > ar.length-1){
colorIndex = ar.length-1;
}
}
index++;
}
}
}
}
this how you implement it.Create a new AS3 Fla and assign this as base class:
package {
import flash.display.MovieClip;
import flash.text.TextField;
import flash.text.TextFieldType;
public class MyClass extends MovieClip {
var tf:ColorTextField = new ColorTextField();
public function MyClass() {
// constructor code
tf.width = 500;
tf.text = "12345";
this.addChild(tf);
}
}
}
does not matter where you input the new text

How to pass variables as parameters

I have two bits of code
Tree tree;
void setup() {
int SZ = 512; // screen size
int d = 2;
int x = SZ/2;
int y = SZ;
size(SZ,SZ);
background(255);
noLoop();
tree = new Tree(d, x, y);
}
void draw() {
tree.draw();
}
and also
class Tree {
// member variables
int m_lineLength; // turtle line length
int m_x; // initial x position
int m_y; // initial y position
float m_branchAngle; // turtle rotation at branch
float m_initOrientation; // initial orientation
String m_state; // initial state
float m_scaleFactor; // branch scale factor
String m_F_rule; // F-rule substitution
String m_H_rule; // H-rule substitution
String m_f_rule; // f-rule substitution
int m_numIterations; // number of times to substitute
// constructor
// (d = line length, x & y = start position of drawing)
Tree(int d, int x, int y) {
m_lineLength = d;
m_x = x;
m_y = y;
m_branchAngle = (25.7/180.0)*PI;
m_initOrientation = -HALF_PI;
m_scaleFactor = 1;
m_state = "F";
m_F_rule = "F[+F]F[-F]F";
m_H_rule = "";
m_f_rule = "";
m_numIterations = 5;
// Perform L rounds of substitutions on the initial state
for (int k=0; k < m_numIterations; k++) {
m_state = substitute(m_state);
}
}
void draw() {
pushMatrix();
pushStyle();
stroke(0);
translate(m_x, m_y); // initial position
rotate(m_initOrientation); // initial rotation
// now walk along the state string, executing the
// corresponding turtle command for each character
for (int i=0; i < m_state.length(); i++) {
turtle(m_state.charAt(i));
}
popStyle();
popMatrix();
}
// Turtle command definitions for each character in our alphabet
void turtle(char c) {
switch(c) {
case 'F': // drop through to next case
case 'H':
line(0, 0, m_lineLength, 0);
translate(m_lineLength, 0);
break;
case 'f':
translate(m_lineLength, 0);
break;
case 's':
scale(m_scaleFactor);
break;
case '-':
rotate(m_branchAngle);
break;
case '+':
rotate(-m_branchAngle);
break;
case '[':
pushMatrix();
break;
case ']':
popMatrix();
break;
default:
println("Bad character: " + c);
exit();
}
}
// apply substitution rules to string s and return the resulting string
String substitute(String s) {
String newState = new String();
for (int j=0; j < s.length(); j++) {
switch (s.charAt(j)) {
case 'F':
newState += m_F_rule;
break;
case 'H':
newState += m_F_rule;
break;
case 'f':
newState += m_f_rule;
break;
default:
newState += s.charAt(j);
}
}
return newState;
}
}
This isn't assessed homework, it's an end of chapter exercise but I'm very stuck.
I want to "extend the Tree constructor so that values for all of the Tree member variables can be passed in as parameters."
Whilst I understand what variables and parameters are, I'm very stuck as to what to begin reading / where to begin editing the code.
One thing that has confused me and made me question my understanding is that, if I change the constructor values, (for example m_numiterations = 10;), the output when the code is run is the same.
Any pointers in the right direction would be greatly appreciated.
You already have everything in there to add more stuff to your Tree.
You see, in your setup(), you call:
tree = new Tree(d, x, y);
Now, that line, is actually calling the contructor implemented here:
Tree(int d, int x, int y) {
m_lineLength = d;
m_x = x;
etc....
So, if you want you can change that constructor to accept any variable that you want to pass from setup()
For instance, Tree(int d, int x, int y, String word, float number, double bigNumber)
Try experimenting with that. If you have any questions, PM me
EDIT
Let me add a little more flavor to it:
You see constructors are the way to initialize your class. It does not matter the access level (protected, public, private) or the number of constructors.
So, for example, Let's say you have this class with two public fields:
public class Book
{
public String Author;
public String Title;
public Book(String title, String author)
{
this.Title = title;
this.Author = author;
}
public Book()
{
this("Any title");//default title
}
}
Here, you can create books with both author and title OR only title! isn't that great? You can create things that are not inclusively attached to other things!
I hope you understand this. But, basically the idea is to encapsulate everything that matters to a certain topic to its own class.
NEW EDIT
Mike, you see, according to your comment you added this line:
int m_numIterations = 25;
The thing is that what you just did was only create a variable. A variable holds the information that you eventually want to use in the program. Let's say you are in high school physics trying to solve a basic free fall problem. You have to state the gravity, don't you?
So, in your notebook, you would go:
g = 9.8 m/s^2
right? it is a constant. But, a variable that you will use in your problem.
Well, the same thing applies in programming.
You added the line. That means that now, you can use it in your problem.
Now, go to this line,
tree = new Tree(d, x, y);
and change it to:
tree = new Tree(d, x, y, m_numIterations);
As you can see, now you are ready to "use" your variable in your tree. However! you are not done yet. You have to update as well your constructor because if not, the compiler will complain!
Go to this line now,
Tree(int d, int x, int y) {
m_lineLength = d;
m_x = x;
....
And change it to:
Tree(int d, int x, int y, int iterations) {
m_lineLength = d;
m_x = x;
....
You, see, now, you are telling your tree to accept a new variable call iterations that you are setting from somewhere else.
However! Be warned! There is a little problem with this :(
You don't have any code regarding the use of that variable. So, if you are expecting to actually see something different in the Tree, it won't happen! You need to find a use to the variable within the scope of the Tree (the one that I called iterations). So, first, find a use for it! or post any more code that you have to help you solve it. If you are calling a variable iterations, it is because you are planning to use a loop somewhere, amirite? Take care man. Little steps. Be patient. I added a little more to the Books example. I forgot to explain it yesterday :p