I face a problem with getting data from CandleStickChart and adding this into LineChart.
Ok, so look at this method. I got data from CandleStick and configure data to LineChart. Everything work perfectly. I have generated 2 chars like you guys see on Image:
But the problem is when i trying to add dynamicData to chars. My method only add data to CandleStickChart.
Here is method to setData on LineChart, here CandleEntry lastEntry = set1.getEntryForIndex(i); i know what value is on bars.
private void setData() {
int prog = 50;
for (int i = 0; i < prog; i++) {
CandleEntry lastEntry = set1.getEntryForIndex(i);
float lastOpenCloseMax = Math.max(lastEntry.getOpen(), lastEntry.getClose());
entries.add(new Entry(i, lastOpenCloseMax));
}
XAxis xAxis = lineChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setTextColor(Color.TRANSPARENT);
xAxis.setDrawGridLines(false);
YAxis leftAxis = lineChart.getAxisLeft();
leftAxis.setLabelCount(12, false);
leftAxis.setDrawGridLines(false);
leftAxis.setAxisMaximum(1.6f);
leftAxis.setAxisMinimum(0.4f);
leftAxis.setDrawAxisLine(true);
leftAxis.setTextColor(Color.TRANSPARENT);
YAxis rightAxis = lineChart.getAxisRight();
rightAxis.setEnabled(false);
Collections.sort(entries, new EntryXComparator());
lineDataSet = new LineDataSet(entries, "# of Calls");
lineData = new LineData(lineDataSet);
lineDataSet.setColor(Color.GRAY);
lineDataSet.setDrawCircles(false);
// dataset.setDrawFilled(true);
lineData.setValueTextColor(Color.TRANSPARENT);
lineChart.getLegend().setEnabled(false);
lineChart.getDescription().setEnabled(false);
lineChart.setBackgroundColor(Color.TRANSPARENT);
lineChart.setData(lineData);
lineChart.animateX(4000);
}
Here i addLineEntry, but this not work and i dont know why, do you guys have any idea?
private void addLineEntry() {
lineData = lineChart.getData();
if (lineDataSet == null) {
lineDataSet = createLineSet();
lineData.addDataSet(lineDataSet);
}
int prog = 1;
for (int i = 0; i < prog; i++) {
CandleEntry lastEntry = set1.getEntryForIndex(yVals1.size() - 1);
float lastOpenCloseMax = Math.max(lastEntry.getOpen(), lastEntry.getClose());
entries.add(new Entry(lineDataSet.getXMax() +1, lastOpenCloseMax));
}
lineDataSet.notifyDataSetChanged();
lineChart.notifyDataSetChanged();
lineChart.invalidate();
mChart.moveViewTo(mChart.getXChartMax(), 2f, YAxis.AxisDependency.RIGHT);
}
And the last is similar method from CandleStickChart to addEntry.
private void addEntry(boolean start) {
data = mChart.getData();
if (set1 == null) {
set1 = createSet();
data.addDataSet(set1);
}
float highmax = 1.0700f;
float highlow = 1.1700f;
float lowmax = 0.5700f;
float lowlow = 0.63000f;
int prog = 1;
int xMax = (int) set1.getXMax();
CandleEntry lastEntry = set1.getEntryForIndex(yVals1.size() - 1);
for (int i = 0; i < prog; i++) {
float open = highlow + new Random().nextFloat() * (highmax - highlow);
float close = lowlow + new Random().nextFloat() * (lowmax - lowlow);
float lastOpenCloseMax = Math.max(lastEntry.getOpen(), lastEntry.getClose());
float currentOpenCloseMax = Math.max(open, close);
float currentOpenCloseMin = Math.min(open, close);
float high = open + 0.3f;
float low = close - 0.3f;
if (currentOpenCloseMax < lastOpenCloseMax) {
yVals1.add(new CandleEntry(xMax + 1, high, low, currentOpenCloseMax, currentOpenCloseMin));
} else {
yVals1.add(new CandleEntry(xMax + 1, high, low, currentOpenCloseMin, currentOpenCloseMax));
}
mChart.notifyDataSetChanged();
mChart.invalidate();
mChart.moveViewTo(mChart.getXChartMax(), 2f, YAxis.AxisDependency.RIGHT);
}
}
And here is method to remove Entry from CandleStickChart and LineChart, and this work good.
private void removeLastEntry() {
CandleData data = mChart.getData();
if (data != null) {
ICandleDataSet set = data.getDataSetByIndex(0);
if (set != null) {
set.removeFirst();
data.notifyDataChanged();
mChart.notifyDataSetChanged();
mChart.invalidate();
}
}
LineData lineData = lineChart.getData();
if (lineData != null) {
ILineDataSet set = lineData.getDataSetByIndex(0);
if (set != null) {
set.removeFirst();
data.notifyDataChanged();
lineChart.notifyDataSetChanged();
lineChart.invalidate();
}
}
Do you guys have any idea whats wrong?
I started a bounty:
Here isfull class:
public class MainGameFragment extends Fragment {
#BindView(R.id.spinner_money)
Spinner spinnerData;
#BindView(R.id.text_profit_ill)
TextView text_profit;
#BindView(R.id.button_cash)
Button btnCashCurrency;
#BindView(R.id.restart_game)
Button restartGame;
#BindView(R.id.butonCurrency)
Button buttonCurrency;
#BindView(R.id.chart)
CandleStickChart mChart;
#BindView(R.id.progress_bar)
ProgressBar progress;
#BindView(R.id.btn_buy)
Button btnBuy;
#BindView(R.id.btn_sell)
Button btnSell;
#BindView(R.id.drawer_settings)
ImageButton openDrawerSettings;
#BindView(R.id.chartLine)
LineChart lineChart;
public static ArrayList<String> HISTORYTRANSACTION = new ArrayList<>();
public static ArrayList<String> LEADERBOARDUSER = new ArrayList<>();
public static String userNameAndScore;
private Handler handler;
private Handler handlerLast;
private String buttonPosition;
int pos = 0;
LostDialogFragment lostFragment = LostDialogFragment.newInstance(1);
WinDialogFragment winFragment = WinDialogFragment.newInstance(1);
SettingsFragment settingsFragment = SettingsFragment.newInstance(1);
String DIALOG_WIN = "WinDialogFragment";
String DIALOG_LOST = "LostDialogFragment";
String DIALOG_SETTINGS = "settingsFragment";
private CandleData data;
private LineData lineData;
private LineDataSet lineDataSet;
private CandleDataSet set1;
private Drawer result;
public static StorageReference storageReference;
private Runnable r;
private Runnable rLast;
ArrayList<CandleEntry> yVals1 = new ArrayList<>();
ArrayList<Entry> entries = new ArrayList<>();
public MainGameFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
buttonPosition = getArguments().getString("button_position", "value");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main_game, container, false);
ButterKnife.bind(this, view);
setText();
configureSpinnerDataAndLogic();
configureChart();
configureColorProgresBar();
openDrawer();
configureDrawer();
welcomeMessage();
configureHandler(5000);
storageReference = FirebaseStorage.getInstance().getReference();
setData();
return view;
}
private void setData() {
int prog = 50;
for (int i = 0; i < prog; i++) {
CandleEntry lastEntry = set1.getEntryForIndex(i);
float lastOpenCloseMax = Math.max(lastEntry.getOpen(), lastEntry.getClose());
entries.add(new Entry(i, lastOpenCloseMax));
}
XAxis xAxis = lineChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setTextColor(Color.TRANSPARENT);
xAxis.setDrawGridLines(false);
YAxis leftAxis = lineChart.getAxisLeft();
leftAxis.setLabelCount(12, false);
leftAxis.setDrawGridLines(false);
leftAxis.setAxisMaximum(1.6f);
leftAxis.setAxisMinimum(0.4f);
leftAxis.setDrawAxisLine(true);
leftAxis.setTextColor(Color.TRANSPARENT);
YAxis rightAxis = lineChart.getAxisRight();
rightAxis.setEnabled(false);
Collections.sort(entries, new EntryXComparator());
lineDataSet = new LineDataSet(entries, "# of Calls");
lineData = new LineData(lineDataSet);
lineDataSet.setColor(Color.GRAY);
lineDataSet.setDrawCircles(false);
// dataset.setDrawFilled(true);
lineData.setValueTextColor(Color.TRANSPARENT);
lineChart.getLegend().setEnabled(false);
lineChart.getDescription().setEnabled(false);
lineChart.setBackgroundColor(Color.TRANSPARENT);
lineChart.setData(lineData);
lineChart.animateX(4000);
}
private void welcomeMessage() {
Toast.makeText(getContext(), "Welcome " + MainActivity.getUsername(getContext()).trim() + "!"
+ " Getting data from last hour..",
Toast.LENGTH_LONG).show();
}
private void configureDrawer() {
AccountHeader headerResult = new AccountHeaderBuilder()
.withActivity(getActivity())
.withProfileImagesClickable(false)
.withHeaderBackground(R.drawable.logo_white)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
#Override
public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {
return false;
}
})
.build();
result = new DrawerBuilder()
.withSliderBackgroundColor(Color.GRAY)
.withAccountHeader(headerResult)
.withActivity(getActivity())
.withDisplayBelowStatusBar(false)
.withDrawerGravity(Gravity.LEFT)
.withHeaderPadding(true)
.addDrawerItems(
new SectionDrawerItem().withName("Options"),
new PrimaryDrawerItem().withName("Trading History").withIcon(R.drawable.trading_history).withIdentifier(2),
new PrimaryDrawerItem().withName("Leader Board").withIcon(R.drawable.leade_board).withIdentifier(3),
new PrimaryDrawerItem().withName("Special offer").withIcon(R.drawable.special_icon).withIdentifier(4),
new PrimaryDrawerItem().withName("Video tutorials").withIcon(R.drawable.video_tutorials).withIdentifier(5),
new PrimaryDrawerItem().withName("FAQ").withIcon(R.drawable.faq_icon).withIdentifier(6),
new PrimaryDrawerItem().withName("CONTACT").withIcon(R.drawable.contact_icon).withIdentifier(7)
)
.buildForFragment();
result.setOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.addToBackStack(null);
SettingsFragment.POSITION = position;
result.closeDrawer();
if (settingsFragment != null) {
settingsFragment.show(ft, DIALOG_SETTINGS);
}
return true;
}
});
result.getDrawerLayout().setFitsSystemWindows(false);
result.getSlider().setFitsSystemWindows(false);
}
private CandleDataSet createSet() {
set1 = new CandleDataSet(null, "DataSet 1");
set1.setColor(Color.rgb(240, 99, 99));
set1.setHighLightColor(Color.rgb(190, 190, 190));
set1.setAxisDependency(YAxis.AxisDependency.LEFT);
set1.setValueTextSize(10f);
return set1;
}
private LineDataSet createLineSet() {
lineDataSet = new LineDataSet(null, "DataSet 1");
lineDataSet.setColor(Color.rgb(240, 99, 99));
lineDataSet.setHighLightColor(Color.rgb(190, 190, 190));
lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
lineDataSet.setValueTextSize(10f);
return lineDataSet;
}
public void openDrawer() {
openDrawerSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.openDrawer();
}
});
}
private void addLineEntry() {
lineData = lineChart.getData();
if (lineDataSet == null) {
lineDataSet = createLineSet();
lineData.addDataSet(lineDataSet);
}
int prog = 1;
int xMax = (int) set1.getXMax();
for (int i = 0; i < prog; i++) {
CandleEntry lastEntry = set1.getEntryForIndex(xMax -1);
float lastOpenCloseMax = Math.max(lastEntry.getOpen(), lastEntry.getClose());
entries.add(new Entry(lineData.getDataSetCount() +1, lastOpenCloseMax));
}
lineDataSet.notifyDataSetChanged();
lineChart.notifyDataSetChanged();
lineChart.invalidate();
lineChart.moveViewTo(lineChart.getXChartMax(), 2f, YAxis.AxisDependency.RIGHT);
}
private void addEntry(boolean start) {
data = mChart.getData();
if (set1 == null) {
set1 = createSet();
data.addDataSet(set1);
}
float highmax = 1.0700f;
float highlow = 1.1700f;
float lowmax = 0.5700f;
float lowlow = 0.63000f;
int prog = 1;
int xMax = (int) set1.getXMax();
CandleEntry lastEntry = set1.getEntryForIndex(yVals1.size() - 1);
for (int i = 0; i < prog; i++) {
float open = highlow + new Random().nextFloat() * (highmax - highlow);
float close = lowlow + new Random().nextFloat() * (lowmax - lowlow);
float lastOpenCloseMax = Math.max(lastEntry.getOpen(), lastEntry.getClose());
float currentOpenCloseMax = Math.max(open, close);
float currentOpenCloseMin = Math.min(open, close);
float high = open + 0.3f;
float low = close - 0.3f;
if (currentOpenCloseMax < lastOpenCloseMax) {
yVals1.add(new CandleEntry(xMax + 1, high, low, currentOpenCloseMax, currentOpenCloseMin));
} else {
yVals1.add(new CandleEntry(xMax + 1, high, low, currentOpenCloseMin, currentOpenCloseMax));
}
mChart.notifyDataSetChanged();
mChart.invalidate();
mChart.moveViewTo(mChart.getXChartMax(), 2f, YAxis.AxisDependency.RIGHT);
}
}
private void removeLastEntry() {
CandleData data = mChart.getData();
if (data != null) {
ICandleDataSet set = data.getDataSetByIndex(0);
if (set != null) {
set.removeFirst();
data.notifyDataChanged();
mChart.notifyDataSetChanged();
mChart.invalidate();
}
}
LineData lineData = lineChart.getData();
if (lineData != null) {
ILineDataSet set = lineData.getDataSetByIndex(0);
if (set != null) {
set.removeFirst();
data.notifyDataChanged();
lineChart.notifyDataSetChanged();
lineChart.invalidate();
}
}
}
public String getUserInfoAndSave() {
userNameAndScore = MainActivity.getUsername(getContext()).trim() + ": "
+ btnCashCurrency.getText().toString().trim();
return userNameAndScore;
}
private void configureHandlerWithoutRemoveLastEntry(final int time) {
handlerLast = new Handler();
rLast = new Runnable() {
public void run() {
// removeLastEntry();
addEntry(true);
handler.postDelayed(this, time);
}
};
handlerLast.postDelayed(rLast, time);
}
private void configureHandler(final int time) {
handler = new Handler();
r = new Runnable() {
public void run() {
removeLastEntry();
addEntry(true);
addLineEntry();
handler.postDelayed(this, time);
}
};
handler.postDelayed(r, time);
}
public void stopLast() {
handlerLast.removeCallbacks(rLast);
}
public void stop() {
handler.removeCallbacks(r);
}
private void configureChart() {
mChart.getDescription().setEnabled(false);
mChart.getLegend().setTextColor(Color.WHITE);
mChart.setMaxVisibleValueCount(50);
XAxis xAxis = mChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setTextColor(Color.WHITE);
xAxis.setDrawGridLines(false);
YAxis leftAxis = mChart.getAxisLeft();
leftAxis.setLabelCount(12, false);
leftAxis.setDrawGridLines(false);
leftAxis.setDrawAxisLine(true);
leftAxis.setTextColor(Color.WHITE);
YAxis rightAxis = mChart.getAxisRight();
rightAxis.setEnabled(false);
float highmax = 1.0700f;
float highlow = 1.1700f;
float lowmax = 0.5700f;
float lowlow = 0.63000f;
int prog = 50;
float last = Float.NEGATIVE_INFINITY;
String date = String.valueOf(android.text.format.DateFormat.format("yyyy-MM-dd", new java.util.Date()));
for (int i = 0; i < prog; i++) {
float open = highlow + new Random().nextFloat() * (highmax - highlow);
float close = lowlow + new Random().nextFloat() * (lowmax - lowlow);
float max = Math.max(open, close);
if (last < max) {
float tmp = open;
open = close;
close = tmp;
}
last = max;
float high = open + 0.3f;
float low = close - 0.3f;
yVals1.add(new CandleEntry(i, high, low, open, close));
}
set1 = new CandleDataSet(yVals1, date);
data = new CandleData(set1);
mChart.setData(data);
set1.setAxisDependency(YAxis.AxisDependency.LEFT);
set1.setColor(Color.rgb(80, 80, 80));
set1.setIncreasingColor(Color.GREEN);
set1.setIncreasingPaintStyle(Paint.Style.FILL);
set1.setDecreasingColor(Color.RED);
set1.setDecreasingPaintStyle(Paint.Style.FILL);
set1.setNeutralColor(Color.BLUE);
set1.setBarSpace(0.2f);
set1.setValueTextColor(Color.TRANSPARENT);
mChart.notifyDataSetChanged();
mChart.animateX(4000);
}
private void setText() {
buttonCurrency.setText("Assets: \n" + buttonPosition);
}
private void configureColorProgresBar() {
progress.getIndeterminateDrawable().setColorFilter(
getResources().getColor(R.color.white),
android.graphics.PorterDuff.Mode.SRC_IN);
}
#OnClick(R.id.invest_text)
public void invest() {
float highmax = 1.0700f;
float highlow = 1.1700f;
float lowmax = 0.5700f;
float lowlow = 0.63000f;
float open = highlow + new Random().nextFloat() * (highmax - highlow);
float close = lowlow + new Random().nextFloat() * (lowmax - lowlow);
float high = open + 0.3f;
float low = close - 0.3f;
if (pos == 0) {
yVals1.add(new CandleEntry(50, high, low, open, close));
pos++;
} else if (pos == 1) {
yVals1.add(new CandleEntry(51, high, low, open, close));
pos++;
} else if (pos == 2) {
yVals1.add(new CandleEntry(52, high, low, open, close));
pos++;
} else if (pos == 3) {
yVals1.add(new CandleEntry(53, high, low, open, close));
pos++;
} else if (pos == 4) {
yVals1.add(new CandleEntry(54, high, low, open, close));
pos++;
}
mChart.invalidate();
}
#OnClick({R.id.btn_buy, R.id.btn_sell})
public void onGameButtonsClicked() {
final FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.addToBackStack(null);
String cashText = btnCashCurrency.getText().toString();
final int[] cash = {Integer.valueOf(cashText)};
if (cash[0] <= 0) {
restartGame.setVisibility(View.VISIBLE);
Toast.makeText(getContext(), "Your cash is on -, u cant play. Please restart game.", Toast.LENGTH_SHORT).show();
} else if (Integer.valueOf(spinnerData.getSelectedItem().toString()) >= Integer.valueOf(btnCashCurrency.getText().toString())) {
Toast.makeText(getContext(), "You not have available cash, change the money in Invest Section.", Toast.LENGTH_SHORT).show();
} else {
int min = 0;
int max = 2;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
String text = spinnerData.getSelectedItem().toString();
final int temp = Integer.parseInt(text);
final int temp2 = temp * 2;
disableAndEnableButtons(false);
if (i1 == 0 || i1 == 1) {
progress.setVisibility(View.VISIBLE);
stop();
configureHandler(900);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
lostFragment.show(ft, DIALOG_LOST);
cash[0] -= temp2;
btnCashCurrency.setText(cash[0] + "");
progress.setVisibility(View.GONE);
disableAndEnableButtons(true);
String score = "LOSE " + MainActivity.getUsername(getContext()).trim() + ": "
+ btnCashCurrency.getText().toString().trim() + " -" + temp2;
HISTORYTRANSACTION.add(score);
getUserInfoAndSave();
stop();
configureHandler(5000);
}
}, 5000);
} else {
progress.setVisibility(View.VISIBLE);
stop();
configureHandler(900);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
winFragment.show(ft, DIALOG_WIN);
cash[0] += temp2;
btnCashCurrency.setText(cash[0] + "");
progress.setVisibility(View.GONE);
disableAndEnableButtons(true);
String score = "WIN " + MainActivity.getUsername(getContext()).trim()
+ ": " + btnCashCurrency.getText().toString().trim() + " +" + temp2;
HISTORYTRANSACTION.add(score);
getUserInfoAndSave();
stop();
configureHandler(5000);
}
}, 5000);
}
}
}
private void disableAndEnableButtons(boolean on) {
btnBuy.setEnabled(on);
btnSell.setEnabled(on);
}
#OnClick(R.id.restart_game)
public void restartGame() {
Intent intent = new Intent(getContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
MainGameFragment.LEADERBOARDUSER.add(MainGameFragment.userNameAndScore);
((CurrencySelectActivity) getContext()).hideGameFragment();
((CurrencySelectActivity) getContext()).closeCurrencyActivity();
SharedPreferences prefs = getContext().getSharedPreferences("app.forex", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
Set<String> set = new HashSet<>();
set.add(String.valueOf(MainGameFragment.LEADERBOARDUSER));
edit.putStringSet("user_and_score", set);
HISTORYTRANSACTION.clear();
edit.apply();
}
private void configureSpinnerDataAndLogic() {
String[] arraySpinner = new String[]{
"50", "100", "150", "200", "250", "300", "400", "500"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(),
android.R.layout.simple_list_item_1, arraySpinner);
spinnerData.setAdapter(adapter);
spinnerData.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
String text = spinnerData.getSelectedItem().toString();
int temp = Integer.parseInt(text);
text_profit.setText((temp * 2) + " $ " + "100%");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
AAnd here is xml files
<com.github.mikephil.charting.charts.CandleStickChart
android:id="#+id/chart"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/butonCurrency"
android:layout_margin="30dp" />
<com.github.mikephil.charting.charts.LineChart
android:id="#+id/chartLine"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/butonCurrency"
android:layout_margin="30dp" />
And thiswork like:
Highly help needed
Instead of adding the new entry to your entries array.. you could try using the method lineData.addEntry().
Something like this :
private void addEntry() {
LineData data = mChart.getData();
ILineDataSet set = data.getDataSetByIndex(0);
if (set == null) {
set = createSet();
data.addDataSet(set);
}
data.addEntry(new Entry(data.getDataSetByIndex(dataSetIndex).getEntryCount(), yValue), dataSetIndex);
data.notifyDataChanged();
mChart.notifyDataSetChanged();
}
your "dataSetIndex" will always be 0 if you only have a single dataset in your linechart.
For more information, you can check this class
Problem is here, after i change, everything work good
private void addLineEntry() {
lineData = lineChart.getData();
if (lineDataSet == null) {
lineDataSet = createLineSet();
lineData.addDataSet(lineDataSet);
}
int prog = 1;
int xMax = (int) lineDataSet.getXMax();
for (int i = 0; i < prog; i++) {
CandleEntry lastEntry = set1.getEntryForIndex(yVals1.size() - 1);
float lastOpenCloseMax = Math.max(lastEntry.getOpen(), lastEntry.getClose());
entries.add(new Entry(xMax + 1, lastOpenCloseMax));
}
lineDataSet.notifyDataSetChanged();
lineChart.notifyDataSetChanged();
lineChart.invalidate();
lineChart.moveViewTo(xMax, 2f, YAxis.AxisDependency.RIGHT);
}
I have JFrame with a start button, which triggers the calculation of a Julia Set.
The code that is executed when the start button is clicked is as follows:
public void actionPerformed(ActionEvent aActionEvent)
{
String strCmd = aActionEvent.getActionCommand();
if (strCmd.equals("Start"))
{
m_cCanvas.init();
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_bRunning = true;
this.handleCalculation();
}
else if (aActionEvent.getSource() == m_cTReal)
Which used to work fine, except that the application could not be closed anymore. So I tried to use m_bRunning in a separate method so that actionPerformed() isn't blocked all the time to see if that would help, and then set m_bRunning = false in the method stop() which is called when the window is closed:
public void run()
{
if(m_bRunning)
{
this.handleCalculation();
}
}
The method run() is called from the main class in a while(true) loop.
Yet unfortunately, neither did that solve the problem, nor do I now have any output to the canvas or any debug traces with System.out.println(). Could anyone point me in the right direction on this?
EDIT:
Here are the whole files:
// cMain.java
package juliaSet;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.Dimension;
public class cMain {
public static void main(String[] args)
{
int windowWidth = 1000;//(int)screenSize.getWidth() - 200;
int windowHeight = 800;//(int)screenSize.getHeight() - 50;
int plotWidth = 400;//(int)screenSize.getWidth() - 600;
int plotHeight = 400;//(int)screenSize.getHeight() - 150;
JuliaSet cJuliaSet = new JuliaSet("Julia Set", windowWidth, windowHeight, plotWidth, plotHeight);
cJuliaSet.setVisible(true);
while(true)
{
cJuliaSet.run();
}
}
}
// JuliaSet.java
package juliaSet;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.util.Random;
import java.io.*;
import java.lang.ref.*;
public class JuliaSet extends JFrame implements ActionListener
{
private JButton m_cBStart;
private JTextField m_cTReal;
private JTextField m_cTImag;
private JTextField m_cTDivergThresh;
private JLabel m_cLReal;
private JLabel m_cLImag;
private JLabel m_cLDivergThresh;
private int m_iDivergThresh = 10;
private String m_cMsgDivThresh = "Divergence threshold = " + m_iDivergThresh;
private JuliaCanvas m_cCanvas;
private int m_iPlotWidth; // number of cells
private int m_iPlotHeight; // number of cells
private Boolean m_bRunning = false;
private double m_dReal = 0.3;
private double m_dImag = -0.5;
private String m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
private String m_cMsgIter = "x = 0, y = 0";
private Complex m_cCoordPlane[][];
private double m_dAbsSqValues[][];
private int m_iIterations[][];
private Complex m_cSummand;
private BufferedImage m_cBackGroundImage = null;
private FileWriter m_cFileWriter;
private BufferedWriter m_cBufferedWriter;
private String m_sFileName = "log.txt";
private Boolean m_bWriteLog = false;
private static final double PLOTMAX = 2.0; // we'll have symmetric axes
// ((0,0) at the centre of the
// plot
private static final int MAXITER = 0xff;
JuliaSet(String aTitle, int aFrameWidth, int aFrameHeight, int aPlotWidth, int aPlotHeight)
{
super(aTitle);
this.setSize(aFrameWidth, aFrameHeight);
m_iPlotWidth = aPlotWidth;
m_iPlotHeight = aPlotHeight;
m_cSummand = new Complex(m_dReal, m_dImag);
m_cBackGroundImage = new BufferedImage(aFrameWidth, aFrameHeight, BufferedImage.TYPE_INT_RGB);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
stop();
super.windowClosing(e);
System.exit(0);
}
});
GridBagLayout cLayout = new GridBagLayout();
GridBagConstraints cConstraints = new GridBagConstraints();
this.setLayout(cLayout);
m_cCanvas = new JuliaCanvas(m_iPlotWidth, m_iPlotHeight);
m_cCanvas.setSize(m_iPlotWidth, m_iPlotHeight);
m_cBStart = new JButton("Start");
m_cBStart.addActionListener(this);
m_cTReal = new JTextField(5);
m_cTReal.addActionListener(this);
m_cTImag = new JTextField(5);
m_cTImag.addActionListener(this);
m_cTDivergThresh = new JTextField(5);
m_cTDivergThresh.addActionListener(this);
m_cLReal = new JLabel("Re(c):");
m_cLImag = new JLabel("Im(c):");
m_cLDivergThresh = new JLabel("Divergence Threshold:");
cConstraints.insets.top = 3;
cConstraints.insets.bottom = 3;
cConstraints.insets.right = 3;
cConstraints.insets.left = 3;
// cCanvas
cConstraints.gridx = 0;
cConstraints.gridy = 0;
cLayout.setConstraints(m_cCanvas, cConstraints);
this.add(m_cCanvas);
// m_cLReal
cConstraints.gridx = 0;
cConstraints.gridy = 1;
cLayout.setConstraints(m_cLReal, cConstraints);
this.add(m_cLReal);
// m_cTReal
cConstraints.gridx = 1;
cConstraints.gridy = 1;
cLayout.setConstraints(m_cTReal, cConstraints);
this.add(m_cTReal);
// m_cLImag
cConstraints.gridx = 0;
cConstraints.gridy = 2;
cLayout.setConstraints(m_cLImag, cConstraints);
this.add(m_cLImag);
// m_cTImag
cConstraints.gridx = 1;
cConstraints.gridy = 2;
cLayout.setConstraints(m_cTImag, cConstraints);
this.add(m_cTImag);
// m_cLDivergThresh
cConstraints.gridx = 0;
cConstraints.gridy = 3;
cLayout.setConstraints(m_cLDivergThresh, cConstraints);
this.add(m_cLDivergThresh);
// m_cTDivergThresh
cConstraints.gridx = 1;
cConstraints.gridy = 3;
cLayout.setConstraints(m_cTDivergThresh, cConstraints);
this.add(m_cTDivergThresh);
// m_cBStart
cConstraints.gridx = 0;
cConstraints.gridy = 4;
cLayout.setConstraints(m_cBStart, cConstraints);
this.add(m_cBStart);
if (m_bWriteLog)
{
try
{
m_cFileWriter = new FileWriter(m_sFileName, false);
m_cBufferedWriter = new BufferedWriter(m_cFileWriter);
} catch (IOException ex) {
System.out.println("Error opening file '" + m_sFileName + "'");
}
}
this.repaint();
this.transformCoordinates();
}
public synchronized void stop()
{
if (m_bRunning)
{
m_bRunning = false;
boolean bRetry = true;
}
if (m_bWriteLog)
{
try {
m_cBufferedWriter.close();
m_cFileWriter.close();
} catch (IOException ex) {
System.out.println("Error closing file '" + m_sFileName + "'");
}
}
}
public void collectGarbage()
{
Object cObj = new Object();
WeakReference ref = new WeakReference<Object>(cObj);
cObj = null;
while(ref.get() != null) {
System.gc();
}
}
public void setSummand(Complex aSummand)
{
m_cSummand.setIm(aSummand.getIm());
m_dImag = aSummand.getIm();
m_cSummand.setRe(aSummand.getRe());
m_dReal = aSummand.getRe();
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
}
public void paint(Graphics aGraphics)
{
Graphics cScreenGraphics = aGraphics;
// render on background image
aGraphics = m_cBackGroundImage.getGraphics();
this.paintComponents(aGraphics);
// drawString() calls are debug code only....
aGraphics.setColor(Color.BLACK);
aGraphics.drawString(m_cSMsg, 10, 450);
aGraphics.drawString(m_cMsgIter, 10, 465);
aGraphics.drawString(m_cMsgDivThresh, 10, 480);
// rendering is done, draw background image to on screen graphics
cScreenGraphics.drawImage(m_cBackGroundImage, 0, 0, null);
}
public void actionPerformed(ActionEvent aActionEvent)
{
String strCmd = aActionEvent.getActionCommand();
if (strCmd.equals("Start"))
{
m_cCanvas.init();
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_bRunning = true;
}
else if (aActionEvent.getSource() == m_cTReal)
{
m_dReal = Double.parseDouble(m_cTReal.getText());
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_cSummand.setRe(m_dReal);
}
else if (aActionEvent.getSource() == m_cTImag)
{
m_dImag = Double.parseDouble(m_cTImag.getText());
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_cSummand.setIm(m_dImag);
}
else if (aActionEvent.getSource() == m_cTDivergThresh)
{
m_iDivergThresh = Integer.parseInt(m_cTDivergThresh.getText());
m_cMsgDivThresh = "Divergence threshold = " + m_iDivergThresh;
}
this.update(this.getGraphics());
}
public void transformCoordinates()
{
double dCanvasHeight = (double) m_cCanvas.getHeight();
double dCanvasWidth = (double) m_cCanvas.getWidth();
// init matrix with same amount of elements as pixels in canvas
m_cCoordPlane = new Complex[(int) dCanvasHeight][(int) dCanvasWidth];
double iPlotRange = 2 * PLOTMAX;
for (int i = 0; i < dCanvasHeight; i++)
{
for (int j = 0; j < dCanvasWidth; j++)
{
m_cCoordPlane[i][j] = new Complex((i - (dCanvasWidth / 2)) * iPlotRange / dCanvasWidth,
(j - (dCanvasHeight / 2)) * iPlotRange / dCanvasHeight);
}
}
}
public void calcAbsSqValues()
{
int iCanvasHeight = m_cCanvas.getHeight();
int iCanvasWidth = m_cCanvas.getWidth();
// init matrix with same amount of elements as pixels in canvas
m_dAbsSqValues = new double[iCanvasHeight][iCanvasWidth];
m_iIterations = new int[iCanvasHeight][iCanvasWidth];
Complex cSum = new Complex();
if (m_bWriteLog) {
try
{
m_cBufferedWriter.write("m_iIterations[][] =");
m_cBufferedWriter.newLine();
}
catch (IOException ex)
{
System.out.println("Error opening file '" + m_sFileName + "'");
}
}
for (int i = 0; i < iCanvasHeight; i++)
{
for (int j = 0; j < iCanvasWidth; j++)
{
cSum.setRe(m_cCoordPlane[i][j].getRe());
cSum.setIm(m_cCoordPlane[i][j].getIm());
m_iIterations[i][j] = 0;
do
{
m_iIterations[i][j]++;
cSum.square();
cSum.add(m_cSummand);
m_dAbsSqValues[i][j] = cSum.getAbsSq();
} while ((m_iIterations[i][j] < MAXITER) && (m_dAbsSqValues[i][j] < m_iDivergThresh));
this.calcColour(i, j, m_iIterations[i][j]);
m_cMsgIter = "x = " + i + " , y = " + j;
if(m_bWriteLog)
{
System.out.println(m_cMsgIter);
System.out.flush();
}
if (m_bWriteLog) {
try
{
m_cBufferedWriter.write(Integer.toString(m_iIterations[i][j]));
m_cBufferedWriter.write(" ");
}
catch (IOException ex) {
System.out.println("Error writing to file '" + m_sFileName + "'");
}
}
}
if (m_bWriteLog) {
try
{
m_cBufferedWriter.newLine();
}
catch (IOException ex) {
System.out.println("Error writing to file '" + m_sFileName + "'");
}
}
}
m_dAbsSqValues = null;
m_iIterations = null;
cSum = null;
}
private void calcColour(int i, int j, int aIterations)
{
Color cColour = Color.getHSBColor((int) Math.pow(aIterations, 4), 0xff,
0xff * ((aIterations < MAXITER) ? 1 : 0));
m_cCanvas.setPixelColour(i, j, cColour);
cColour = null;
}
private void handleCalculation()
{
Complex cSummand = new Complex();
for(int i = -800; i <= 800; i++)
{
for(int j = -800; j <= 800; j++)
{
cSummand.setRe(((double)i)/1000.0);
cSummand.setIm(((double)j)/1000.0);
this.setSummand(cSummand);
this.calcAbsSqValues();
this.getCanvas().paint(m_cCanvas.getGraphics());
this.paint(this.getGraphics());
}
}
cSummand = null;
this.collectGarbage();
System.gc();
System.runFinalization();
}
public boolean isRunning()
{
return m_bRunning;
}
public void setRunning(boolean aRunning)
{
m_bRunning = aRunning;
}
public Canvas getCanvas()
{
return m_cCanvas;
}
public void run()
{
if(m_bRunning)
{
this.handleCalculation();
}
}
}
class JuliaCanvas extends Canvas
{
private int m_iWidth;
private int m_iHeight;
private Random m_cRnd;
private BufferedImage m_cBackGroundImage = null;
private int m_iRed[][];
private int m_iGreen[][];
private int m_iBlue[][];
JuliaCanvas(int aWidth, int aHeight)
{
m_iWidth = aWidth;
m_iHeight = aHeight;
m_cRnd = new Random();
m_cRnd.setSeed(m_cRnd.nextLong());
m_cBackGroundImage = new BufferedImage(m_iWidth, m_iHeight, BufferedImage.TYPE_INT_RGB);
m_iRed = new int[m_iHeight][m_iWidth];
m_iGreen = new int[m_iHeight][m_iWidth];
m_iBlue = new int[m_iHeight][m_iWidth];
}
public void init() {
}
public void setPixelColour(int i, int j, Color aColour)
{
m_iRed[i][j] = aColour.getRed();
m_iGreen[i][j] = aColour.getGreen();
m_iBlue[i][j] = aColour.getBlue();
}
private int getRandomInt(double aProbability)
{
return (m_cRnd.nextDouble() < aProbability) ? 1 : 0;
}
#Override
public void paint(Graphics aGraphics)
{
// store on screen graphics
Graphics cScreenGraphics = aGraphics;
// render on background image
aGraphics = m_cBackGroundImage.getGraphics();
for (int i = 0; i < m_iWidth; i++)
{
for (int j = 0; j < m_iHeight; j++)
{
Color cColor = new Color(m_iRed[i][j], m_iGreen[i][j], m_iBlue[i][j]);
aGraphics.setColor(cColor);
aGraphics.drawRect(i, j, 0, 0);
cColor = null;
}
}
// rendering is done, draw background image to on screen graphics
cScreenGraphics.drawImage(m_cBackGroundImage, 1, 1, null);
}
#Override
public void update(Graphics aGraphics)
{
paint(aGraphics);
}
}
class Complex {
private double m_dRe;
private double m_dIm;
public Complex()
{
m_dRe = 0;
m_dIm = 0;
}
public Complex(double aRe, double aIm)
{
m_dRe = aRe;
m_dIm = aIm;
}
public Complex(Complex aComplex)
{
m_dRe = aComplex.m_dRe;
m_dIm = aComplex.m_dIm;
}
public double getRe() {
return m_dRe;
}
public void setRe(double adRe)
{
m_dRe = adRe;
}
public double getIm() {
return m_dIm;
}
public void setIm(double adIm)
{
m_dIm = adIm;
}
public void add(Complex acComplex)
{
m_dRe += acComplex.getRe();
m_dIm += acComplex.getIm();
}
public void square()
{
double m_dReSave = m_dRe;
m_dRe = (m_dRe * m_dRe) - (m_dIm * m_dIm);
m_dIm = 2 * m_dReSave * m_dIm;
}
public double getAbsSq()
{
return ((m_dRe * m_dRe) + (m_dIm * m_dIm));
}
}
I'm quoting a recent comment from #MadProgrammer (including links)
"Swing is single threaded, nothing you can do to change that, all events are posted to the event queue and processed by the Event Dispatching Thread, see Concurrency in Swing for more details and have a look at Worker Threads and SwingWorker for at least one possible solution"
There is only one thread in your code. That thread is busy doing the calculation and can not respond to events located in the GUI. You have to separate the calculation in another thread that periodically updates the quantities that appears in the window. More info about that in the links, courtesy of #MadProgrammer, I insist.
UPDATED: As pointed by #Yusuf, the proper way of launching the JFrame is
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JuliaSet("Julia Set", windowWidth, windowHeight, plotWidth, plotHeight);
}
});
Set the frame visible on construction and start calculation when the start button is pressed.
First;
Endless loop is not a proper way to do this. This part is loops and taking CPU and never give canvas to refresh screen. if you add below code your code will run as expected. but this is not the proper solution.
cMain.java:
while (true) {
cJuliaSet.run();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Second: you could call run method when start button clicked. But you should create a thread in run method to not freeze screen.
public static void main(String[] args) {
int windowWidth = 1000;// (int)screenSize.getWidth() - 200;
int windowHeight = 800;// (int)screenSize.getHeight() - 50;
int plotWidth = 400;// (int)screenSize.getWidth() - 600;
int plotHeight = 400;// (int)screenSize.getHeight() - 150;
JuliaSet cJuliaSet = new JuliaSet("Julia Set", windowWidth, windowHeight, plotWidth, plotHeight);
cJuliaSet.setVisible(true);
//While loop removed
}
actionPerformed:
if (strCmd.equals("Start")) {
m_cCanvas.init();
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_bRunning = true;
this.run(); // added call run method.
} else if (aActionEvent.getSource() == m_cTReal) {
run method:
public void run()
{
if(m_bRunning)
{
new Thread(){ //Thread to release screen
#Override
public void run() {
JuliaSet.this.handleCalculation();
}
}.start(); //also thread must be started
}
}
As said by #RubioRic, SwingUtilities.invokeLater method is also a part of solution. But you need to check whole of your code and you should learn about Threads.
I'm writing a test program currently to check for points within a circle. But the method to check if the point is in the circle isn't invoked. Did I do something? Can someone kindly advise on how to solve this issue?
btSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rad = spRadius.getSelectedItem().toString();
if (rad.equals("1km")) {
circle.setRadius(500);
processJSON();
} else if (rad.equals("100m")) {
circle.setRadius(50);
processJSON();
} else if (rad.equals("500m")) {
circle.setRadius(250);
processJSON();
}
}
private void processJSON() {
try {
if (mJSONObject != null) {
Iterator<String> keys = mJSONObject.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject jsonObj = mJSONObject.getJSONObject(key);
String point = jsonObj.getString("coords");
String[] latlong = point.split(",");
latpoint = Double.parseDouble(latlong[0]);
lngpoint = Double.parseDouble(latlong[1]);
Toast.makeText(this,latpoint+"+"+lngpoint,Toast.LENGTH_SHORT).show();
if (checkPointInCircle(latcenter, lngcenter, latpoint, lngpoint)) {
mMap.addMarker(new MarkerOptions().
position(new LatLng(latpoint, lngpoint)).title("busstop"));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean checkPointInCircle(double latcenter, double lngcenter, double latpoint, double lngpoint) {
Double radi = Double.parseDouble(rad);
double latdiff = (latpoint - latcenter);
latdiff = Math.pow(latdiff, 2);
double longdiff = (lngpoint - lngcenter);
longdiff = Math.pow(longdiff, 2);
radi = Math.pow(radi, 2);
if (latdiff + longdiff < radi) {
return true;
}
return false;
}
I have to build a GPS parser. I need to parse the NMEA string in another thread, which will be parsing a single NMEA string and update chart at 1 Hz. For now I build part of my code, but I parse data in main thread in while loop; my teacher said that is wrong. I was programming some on Java but not in multi-threading aspects. How I could move parsing process and refreshing chart to background thread?
public class MainFrame extends JFrame {
private JButton btnWybPlik;
private JLabel jlDroga;
private JLabel jlPredkosc;
private JLabel jlCzas;
private JPanel mainjpanel;
private JPanel jpMenu;
private JPanel jpTablica;
//private String sciezkaPliku;
private SekwencjaGGA sekGGA = null;
private SekwencjaGGA popSekGGA = null;
private SekwencjaGSA sekGSA;
private SekwencjaGLL sekGLL;
private SekwencjaRMC sekRMC;
private double droga;
private double predkosc;
private XYSeries series1;
private XYSeriesCollection dataset;
public MainFrame() {
droga = 0;
btnWybPlik.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(mainjpanel);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
//System.out.println("Selected file: " + selectedFile.getAbsolutePath());
String sciezkaPliku = selectedFile.getAbsolutePath();
wczytaniePliku(sciezkaPliku);
}
}
});
jpTablica = new JPanel();
mainjpanel.add(jpTablica);
this.series1 = new XYSeries("Trasa", false);
final XYSeriesCollection dataset = new XYSeriesCollection(this.series1);
final JFreeChart chart = createChart(dataset);
final ChartPanel chartPanel = new ChartPanel(chart);
jpTablica.add(chartPanel);
}
private void wczytaniePliku(String sciezkaDoPliku) {
try (BufferedReader br = new BufferedReader(new FileReader(sciezkaDoPliku))) {
String line;
//series1.add(53.448, 14.4907);
while ((line = br.readLine()) != null) {
parseLine(line);
}
//series1.add(53.4485, 14.4910);
} catch (IOException e) {
e.printStackTrace();
}
}
private void parseLine(String line) {
String bezSumKont = line.substring(0, line.length() - 3);
List<String> podzSekw = Arrays.asList(bezSumKont.split(","));
if (podzSekw.get(0).equalsIgnoreCase("$GPGGA")) {
if (check(line)) {
if (sekGGA != null)
popSekGGA = sekGGA;
sekGGA = new SekwencjaGGA(podzSekw);
if (popSekGGA != null) {
droga += obliczOdleglosc(popSekGGA, sekGGA);
jlDroga.setText(String.valueOf(droga));
}
series1.add(sekGGA.getWspolzedne().getLongitude(), sekGGA.getWspolzedne().getLatitude());
System.out.println(sekGGA.getWspolzedne().getLatitude() + " " + sekGGA.getWspolzedne().getLongitude());
//System.out.println(series1.getMaxY() + " " + series1.getMinY());
} else {
//TODO: Zlicz błąd
}
}
if (podzSekw.get(0).equalsIgnoreCase("$GPGSA")) {
if (check(line)) {
sekGSA = new SekwencjaGSA(podzSekw);
} else {
//TODO: Zlicz błąd
}
}
if (podzSekw.get(0).equalsIgnoreCase("$GPGLL")) {
if (check(line)) {
sekGLL = new SekwencjaGLL(podzSekw);
} else {
//TODO: Zlicz błąd
}
}
if (podzSekw.get(0).equalsIgnoreCase("$GPRMC")) {
//TODO: Sekwencja RMC (Recommended minimum of data)
if (check(line)) {
sekRMC = new SekwencjaRMC(podzSekw);
} else {
//TODO: Zlicz błąd
}
}
}
private double obliczOdleglosc(SekwencjaGGA pkt1, SekwencjaGGA pkt2) {
double odleglosc = 0;
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(pkt2.getWspolzedne().getLatitude() - pkt1.getWspolzedne().getLatitude());
double dLng = Math.toRadians(pkt2.getWspolzedne().getLongitude() - pkt1.getWspolzedne().getLongitude());
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(pkt1.getWspolzedne().getLatitude())) * Math.cos(Math.toRadians(pkt1.getWspolzedne().getLatitude())) *
Math.sin(dLng / 2) * Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
odleglosc = earthRadius * c;
return odleglosc;
}
/**
* Funkcja sprawdzająca sume kontrolną
*
* #param tekst cała linia NMEA
* #return true jeśli się suma kontrolna zgadza
*/
private boolean check(String tekst) {
String suma = tekst.substring(tekst.length() - 2, tekst.length());
tekst = tekst.substring(1, tekst.length() - 3);
int checksum = 0;
for (int i = 0; i < tekst.length(); i++) {
checksum = checksum ^ tekst.charAt(i);
}
if (Integer.parseInt(suma, 16) == checksum) {
return true;
}
return false;
}
private JFreeChart createChart(final XYDataset dataset) { ... }
private void customizeChart(JFreeChart chart) { ... }
public static void main(String[] args) {
JFrame frame = new JFrame("MainFrame");
frame.setContentPane(new MainFrame().mainjpanel);
frame.setPreferredSize(new Dimension(640, 480));
frame.pack();
frame.setVisible(true);
}
To avoid blocking the event dispatch thread, construct an instance of SwingWorker. Collect data in your implementation of doInBackground(), publish() intermediate results, and update the XYSeries in your implementation of process(). The listening chart will update itself in response. A related example that uses jfreechart is seen below and examined here.
I'm using the streaming API of twitter4j v2.2.6 and having some filtering issues. I can get the sample stream just fine but when I attempt to add a geolocation filter the stream output does not change (I'm still getting tweets with no geolocation and with geoloc but outside my bounding box). Here's some of my code:
private static FilterQuery getBoundingBoxFilter() {
// New Delhi India
double lat = 28.6;
double lon = 77.2;
double lon1 = lon - .5;
double lon2 = lon + .5;
double lat1 = lat - .5;
double lat2 = lat + .5;
double bbox[][] = {{lon1, lat1}, {lon2, lat2}};
FilterQuery filtro = new FilterQuery();
return filtro.locations(bbox);
}
public static void streamIt() {
TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
FilterQuery fq = getBoundingBoxFilter();
StatusListener listener = new StatusListener() {
#Override
public void onStatus(Status status) {
GeoLocation gl = status.getGeoLocation();
StringBuilder msg = new StringBuilder();
if (gl != null) {
msg.append("Lat/Lon: ").append(gl.getLatitude()).append(",").append(gl.getLongitude()).append(" - ");
msg.append(status.getText());
LOG.info(msg.toString());
} else {
msg.append(status.getText());
LOG.info(msg.toString());
}
}
#Override
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
#Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
#Override
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
#Override
public void onException(Exception ex) {
if (!(ex instanceof IllegalStateException)) {
ex.printStackTrace();
}
}
#Override
public void onStallWarning(StallWarning sw) {
throw new UnsupportedOperationException("Not supported yet.");
}
};
twitterStream.addListener(listener);
if (fq != null) {
twitterStream.filter(fq);
}
twitterStream.sample();
}
So, what am I doing wrong? Any ideas?
Regards,
Tim
Remove the following line and try again.
twitterStream.sample();