How to build a dynamic graphic with JFreeChart? - java

Actually im trying this:
public static DefaultCategoryDataset dataset = new DefaultCategoryDataset();;
public void atualizaDataset(int humano, int zumbi, int rodada){
final String series1 = "Humano";
final String series2 = "Zumbi";
dataset.addValue(humano, series1, (Comparable)rodada);
dataset.addValue(zumbi, series2, (Comparable)rodada);
}
and in the main
public Grafico g = new Grafico("Grafico");
public void verGrafico(){
g.atualizaDataset(qtdHumanos, qtdZumbis, nroJogada);
g.pack();
g.setVisible(true);
g.repaint();
}
but when i send the values to ´atualizaDataset´ he add them to the graphic but do not save this dataset to concatenate with the new values that are coming..

Related

How would i add textures to textButtons in libgdx

I'm new to libGDX I've been trying to follow tutorials on how to create buttons and add textures to them however I am really struggling with it. How would I add textures to the continue and back buttons? I only have the png image and a .pack file for the textures
Also if anyone would be able to suggest some ways I can change the font of the labels I have for my buttons e.g. lbl_ip
Any help would be really appreciated.
public class MenuScreen implements Screen {
private Viewport viewport;
private Stage stage;
#SuppressWarnings("unused")
private MainGame game;
private Label lbl_ip;
private Label lbl_name;
private Label lbl_back;
private LabelStyle lbl_style;
private Skin txt_skin;
private TextButtonStyle btn_style;
private TextField txt_ip;
private TextField txt_name;
//private TextField txt_back;
private Button btn_confirm;
private Button btn_back;
public static String ip = "localhost"; // change with user input
public static String name = "Player 1";
public static String back = "<---";
public MenuScreen(MainGame game) {
this.game = game;
viewport = new FitViewport(MainGame.V_WIDTH/6, MainGame.V_HEIGHT/6, new OrthographicCamera());
stage = new Stage(viewport, ((MainGame) game).batch);
lbl_style = new Label.LabelStyle();
lbl_style.font = new BitmapFont();
txt_skin = new Skin(Gdx.files.internal("uiskin.json"));
btn_style = new TextButton.TextButtonStyle();
btn_style.font = new BitmapFont();
Table table = new Table();
table.top();
table.setFillParent(true);
lbl_ip = new Label("please enter an IP address:" , lbl_style);
lbl_name = new Label("enter your name: " , lbl_style);
lbl_back = new Label("Return to Main Menue", lbl_style);
txt_ip = new TextField(ip, txt_skin);
txt_name = new TextField(name, txt_skin);
//txt_back = new TextField(back, txt_skin);
btn_confirm = new TextButton("confirm", btn_style);
btn_back = new TextButton("<--", btn_style);
table.add(lbl_ip).expandX();
table.add(txt_ip).width(200);
table.row();
table.add(lbl_name).expandX();
table.add(txt_name).width(200);
table.row();
//table.add(lbl_back).expandX();
table.add(btn_back);
//table.add(txt_back).width(200);
table.row();
table.add(btn_confirm);
table.row();
stage.addActor(table);
Gdx.input.setInputProcessor(stage);
}
private void buttonHandler() {
if(Gdx.input.isKeyPressed(Input.Keys.ENTER)) {
/*
game.setScreen(new PlayScreen(game));
*/
txt_ip.setTextFieldListener(new TextField.TextFieldListener() {
#Override
public void keyTyped(TextField textField, char c) {
ip = textField.getText();
}
});
txt_name.setTextFieldListener(new TextField.TextFieldListener() {
#Override
public void keyTyped(TextField textField, char c) {
name = textField.getText();
}
});
new MPClient(txt_ip.getText(), txt_name.getText(), game);
dispose();
}
}
#Override
public void show() {
// TODO Auto-generated method stub
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0 , 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.draw();
stage.act(delta);
buttonHandler();
}
#Override
public void dispose() {
stage.dispose();
}
}
You need to use ImageTextButton for that. You need to provide it with ImageTextButtonStyle, which is easy to create (you need to assign its imageUp property, other properties can be null).
As far as label font goes, you need to create a new LabelStyle and assign it a new BitmapFont. An example:
Label lab = new Label("This is the text", new LabelStyle(myFont, Color.RED));
"myfont" is a BitmapFont.
Here is a real-world example how to create a BitmapFont:
FreeTypeFontGenerator generator;
FreeTypeFontParameter parameter;
generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/nidsans-webfont.ttf"));
parameter = new FreeTypeFontParameter();
parameter.size = 12;
parameter.minFilter = TextureFilter.Linear;
parameter.magFilter = TextureFilter.Linear;
myfont = generator.generateFont(parameter);
You need to change the -style- associated with the widget. And you may want to make a new style per widget rather than sharing a style across all (because that would update all widgets with the new background)
LabelStyle newLabelStyle = new LabelStyle(originalLabel.getStyle());
tobeChangedLabel.setStyle(newLabelStyle);
newLabelStyle.background = new Image( //however you like to make the image
Changing the font is somewhat tricky... as the fonts are baked into the style as bitmaps (for rendering speed). You may find that given you don't like the background of your style, or even the font, that you might want to use a different skin. You can make your own or use one from here.
https://github.com/czyzby/gdx-skins
If you have to dynamically choose font you can dynamically build your bitmaps of rendered fonts with gdx-freetype-font-manager
https://jitpack.io/p/1nt3g3r/gdx-freetype-font-manager

How to display bar labels in HorizontalBarChart?

I have a HorizontalBarChart from MPAndroidChart library (version v3.0.0-beta1) in which I display the monthly spending of the user's accounts.
So i implemented this method:
List<Account> accounts = getAccounts();
final ArrayList<BarEntry> entries = new ArrayList<>();
Float count = 0F;
for (Account account : accounts) {
entries.add(new BarEntry(count++, new float[]{Float.valueOf(account.getBalance())}, account.getName()));
}
BarDataSet dataset = new BarDataSet(entries, " ");
dataset.setColors(ColorTemplate.PASTEL_COLORS);
dataset.setValueTextSize(10F);
BarData data = new BarData(dataset);
horizontalBarChartMonthlySpending.setData(data);
horizontalBarChartMonthlySpending.setDescription("Gastos por conta neste mês!");
horizontalBarChartMonthlySpending.getAxisLeft().setDrawLabels(false);
horizontalBarChartMonthlySpending.getAxisRight().setDrawLabels(false);
horizontalBarChartMonthlySpending.setFitBars(true);
horizontalBarChartMonthlySpending.setTouchEnabled(false);
And this is what i got:
What i want is, beside every bar, put the description of the related account. I tried to do this in line 6 with the account.getName() but it didn't appear anywhere in the report.
Is there a way to do it?
I had this problem and correct putting this code:
horizontalBarChartMonthlySpending.getXAxis().setValueFormatter(new AxisValueFormatter() {
#Override
public String getFormattedValue(float value, AxisBase axis) {
return entries.get((int) value).getData().toString();
}
#Override
public int getDecimalDigits() {
return 0;
}
});
XAxis xAxis = horizontalBarChartMonthlySpending.getXAxis();
xAxis.setGranularity(1f);
xAxis.setGranularityEnabled(true);

JavaFX moving along the Axis of a line chart

So I have a javafx line chart in my program. The program generates a random value from 1-6 every second and plots it on the graph. So the X axis represents the time in seconds and the Y axis represents the random value chosen. How would I go about moving the graph on the x axis as time goes by? i.e animating the graph going in the right direction.
public class MainDisplayController implements Initializable {
LineChart<String,Number> lineChart;
Timer timer = new Timer();
TimerTask task;
Random dice = new Random();
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
XYChart.Series<String,Number> series = new XYChart.Series<String,Number>();
series.getData().add(new XYChart.Data<String,Number>("1",0));
lineChart.getData().add(series);
task = new TimerTask(){
int secondsPassed = 0;
#Override
public void run() {
secondsPassed++;
System.out.println(secondsPassed);
int number;
number = 1+dice.nextInt(6);
series.getData().add(new XYChart.Data<String,Number>(String.valueOf(secondsPassed),number));
}
};
timer.scheduleAtFixedRate(task, 1000, 1000);
}
}
I think you should try setting:
xAxis.setForceZeroInRange(false);
And then remove data indexed 0 (first one) from your series when certain condition is met.
Here is some code that does something similar, I hope it helps.
public class PointEverySecondLineChart extends Application {
private BorderPane root = new BorderPane();
private Scene scene = new Scene(root,800,600);
private Random rand = new Random();
private SimpleIntegerProperty
lastX = new SimpleIntegerProperty(0);
private XYChart.Series <Integer,Integer> mySeries;
private NumberAxis
xAxis = new NumberAxis(),
yAxis = new NumberAxis();
private LineChart lineChart = new LineChart<>(xAxis,yAxis);
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Timeline addPointEverySecond = new Timeline(new KeyFrame(Duration.millis(500),event->{
lastX.set(lastX.add(1).get());
mySeries.getData().add(new XYChart.Data<>(lastX.get(), rand.nextInt(100)));
if (mySeries.getData().size()>10) mySeries.getData().remove(0);
}));
addPointEverySecond.setCycleCount(Timeline.INDEFINITE);
ObservableList <XYChart.Series<Integer,Integer>> data = FXCollections.observableArrayList();
LineChart<Integer,Integer> chart = makeLineChart(data);
chart.setPrefWidth(600);
chart.setPrefHeight(600);
root.setCenter(chart);
Button btGo = new Button("GO!");
btGo.setOnAction(action -> {
mySeries = new XYChart.Series<>();
data.add(mySeries);
lastX.set(0);
addPointEverySecond.playFromStart();
});
btGo.disableProperty().bind(addPointEverySecond.statusProperty().isEqualTo(Animation.Status.RUNNING));
root.setBottom(btGo);
primaryStage.setScene(scene);
primaryStage.show();
}
LineChart<Integer, Integer> makeLineChart(ObservableList <XYChart.Series<Integer,Integer>> series) {
xAxis.setForceZeroInRange(false);
lineChart.setCreateSymbols(false);
lineChart.setData(series);
return lineChart;
}
}

Save/Load jFreechart TimeSeriesCollection chart from XML

I'm working with this exemple wich put rondom dynamic data into a TimeSeriesCollection chart.
My problem is that i can't find how to :
1- Make a track of the old data (of the last hour) when they pass the left boundary (because the data points move from the right to the left ) of the view area just by implementing a horizontal scroll bar.
2- Is XML a good choice to save my data into when i want to have all the history of the data?
public class DynamicDataDemo extends ApplicationFrame {
/** The time series data. */
private TimeSeries series;
/** The most recent value added. */
private double lastValue = 100.0;
public DynamicDataDemo(final String title) {
super(title);
this.series = new TimeSeries("Random Data", Millisecond.class);
final TimeSeriesCollection dataset = new TimeSeriesCollection(this.series);
final JFreeChart chart = createChart(dataset);
final ChartPanel chartPanel = new ChartPanel(chart);
final JPanel content = new JPanel(new BorderLayout());
content.add(chartPanel);
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
setContentPane(content);
}
private JFreeChart createChart(final XYDataset dataset) {
final JFreeChart result = ChartFactory.createTimeSeriesChart(
"Dynamic Data Demo",
"Time",
"Value",
dataset,
true,
true,
false
);
final XYPlot plot = result.getXYPlot();
ValueAxis axis = plot.getDomainAxis();
axis.setAutoRange(true);
axis.setFixedAutoRange(60000.0); // 60 seconds
axis = plot.getRangeAxis();
axis.setRange(0.0, 200.0);
return result;
}
public void go() {
final double factor = 0.90 + 0.2 * Math.random();
this.lastValue = this.lastValue * factor;
final Millisecond now = new Millisecond();
System.out.println("Now = " + now.toString());
this.series.add(new Millisecond(), this.lastValue);
}
public static void main(final String[] args) throws InterruptedException {
final DynamicDataDemo demo = new DynamicDataDemo("Dynamic Data Demo");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
while(true){
demo.go();
Thread.currentThread().sleep(1000);
}
}
}
The example uses the default values specified in TimeSeries for the maximum item age and count. You'll want to change them to suit your requirements.
XML is fine, but it's voluminous for high rates; plan accordingly.
See also this example that uses javax.swing.Timer to avoid blocking the event dispatch thread.

how do I send colors to an ArrayList?

I am working on an assignment for school (mobile device applications programming) and I've run into an issue. Part of the assignment is to create an ArrayList of colors and then use a random number generator to randomly select a color set (for both text and background color) and apply it to the TextView. I am not sure I am populating the array properly. The parameters are set in a class called Colors_Class() I will include the class code as well as the method for populating the array here. I appreciate any and all help. thanks
here is the code for the Class
public class Color_Class
{
private int backgroundColor;
private int textColor;
public Color_Class(int color, int background)
{
textColor = color;
backgroundColor = background;
}
public int Get_Background_Color()
{
return backgroundColor;
}
public int Get_Text_Color()
{
return textColor;
}
}
Here is the method code
private void Create_Color_Objects()
{
Color_Class color1 = new Color_Class(Color.parseColor("#FF0000"), Color.parseColor("#FFFFFF"));
colorObjectList.add(color1);
Color_Class color2 = new Color_Class(Color.parseColor("#000000"), Color.parseColor("#FFe4c4"));
colorObjectList.add(color2);
Color_Class color3 = new Color_Class(Color.parseColor("#0000FF"), Color.parseColor("#SF9EA0"));
colorObjectList.add(color3);
Color_Class color4 = new Color_Class(Color.parseColor("#FFFFFF"), Color.parseColor("#8A2BE2"));
colorObjectList.add(color4);
Color_Class color5 = new Color_Class(Color.parseColor("#FF7F24"), Color.parseColor("#7FFF00"));
colorObjectList.add(color5);
Color_Class color6 = new Color_Class(Color.parseColor("#FFFFFF"), Color.parseColor("#DC143C"));
colorObjectList.add(color6);
Color_Class color7 = new Color_Class(Color.parseColor("#00008B"), Color.parseColor("#00FFFF"));
colorObjectList.add(color7);
Color_Class color8 = new Color_Class(Color.parseColor("#8B6508"), Color.parseColor("#A9A9A9"));
colorObjectList.add(color8);
Color_Class color9 = new Color_Class(Color.parseColor("#FFFFFF"), Color.parseColor("#8B0000"));
colorObjectList.add(color9);
Color_Class color10 = new Color_Class(Color.parseColor("#FFFFFF"), Color.parseColor("#8B3A3A"));
colorObjectList.add(color10);
}
Your code looks good, it would be better if you can use a generic version of your array list:
ArrayList<Color_Class> colorObjectList = new ArrayList<Color_Class>();

Categories