Image Viewer auto slide codenamone - codenameone

How can i auto slide the imageViewer for instance in the interval of 3 seconds.
Or is there any other component that can do the auto swipe task.
ImageViewer imv = new ImageViewer();
DefaultListModel<Image> images = new DefaultListModel<Image>(new Image[]{a, thumbnail1, thumbnail2});
imv.setImage(images.getItemAt(0));
imv.setImageList(images);
imv.setSwipePlaceholder(Image.createImage(100, 100));

Declare this global static variable:
private static int slideIndex = 0;
//And this UITimer
UITimer t;
And then try out below code
final ImageViewer imv = new ImageViewer();
final DefaultListModel<Image> images = new DefaultListModel<Image>(new Image[]{a, thumbnail1, thumbnail2});
imv.setImage(images.getItemAt(0));
imv.setImageList(images);
imv.setSwipePlaceholder(Image.createImage(100, 100));
Runnable r = new Runnable() {
public void run() {
if (slideIndex < images.getSize()) {
slideIndex++;
} else {
slideIndex = 0;
}
Image nextImage = (Image) images.getItemAt(slideIndex);
if (nextImage != null) {
imv.setImage(nextImage);
}
}
};
if (t == null) {
t = new UITimer(r);
}
if (t != null) {
t.schedule(3000, true, f); //3 seconds
}

Related

Combining two instantiate scripts (Unity 3D)

I need to combine the following scripts into one script containing two functions, one that instantiates the next prefab in the array and the other that instantiates the previous prefab in the array (it is a virtual tour app). Both should also destroy the current prefab. I could then call the functions via event triggers.
I have this code for the "next Prefab" script.
public GameObject[] Spheres;
int currentIndex = 0;
GameObject currentObject;
public Camera MainCamera;
void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
if (gameObject.tag == "ArrowNEXT")
{
Vector3 rayOrigin = MainCamera.ViewportToWorldPoint(new Vector3(0.1f, 0.1f, 0));
RaycastHit hit;
if (Physics.Raycast(rayOrigin, MainCamera.transform.forward, out hit))
{
if (hit.collider != null)
{
{
Destroy(currentObject);
currentIndex++;
if (currentIndex > Spheres.Length - 1) currentIndex = 0;
currentObject = Instantiate(Spheres[currentIndex]);
}
}
}
}
}
I need to combine it with the following:
using UnityEngine;
public class RayCastPrevFIX: MonoBehaviour
{
public GameObject[] Spheres;
int currentIndex = 0;
GameObject currentObject;
public Camera MainCamera;
void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
if (gameObject.tag == "ArrowPREV")
{
Vector3 rayOrigin = MainCamera.ViewportToWorldPoint(new Vector3(0.1f, 0.1f, 0));
RaycastHit hit;
if (Physics.Raycast(rayOrigin, MainCamera.transform.forward, out hit))
{
if (hit.collider != null)
{
{
Destroy(currentObject);
currentIndex--;
if (currentIndex < 0) currentIndex = Spheres.Length - 1;
currentObject = Instantiate(Spheres[currentIndex]);
}
}
}
}
}
}
How would I go about this? Any help is greatly appreciated.I have this so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SphereSwap : MonoBehaviour
{
public GameObject[] Spheres;
int currentIndex = 0;
GameObject currentObject;
public Camera MainCamera;
void Next()
{
Destroy(currentObject);
currentIndex++;
if (currentIndex > Spheres.Length - 1) currentIndex = 0;
currentObject = Instantiate(Spheres[currentIndex]);
}
void Previous()
{
Destroy(currentObject);
currentIndex--;
if (currentIndex < 0) currentIndex = Spheres.Length - 1;
currentObject = Instantiate(Spheres[currentIndex]);
}
}
You're on the right path, but you could shorten the code as well as use one function for both cases to avoid boilerplate:
using UnityEngine;
public class SphereSwap : MonoBehaviour
{
public GameObject[] Spheres;
int currentIndex = 0;
GameObject currentObject;
public Camera MainCamera;
const string ArrowPrevTag = "ArrowPREV";
const string ArrowNextTag = "ArrowNEXT";
private void HandleClick(bool next)
{
if(Spheres == null || Spheres.Length == 0)
{
Debug.Log($"Spheres list is empty, nothing to swap.");
return;
}
Vector3 rayOrigin = MainCamera.ViewportToWorldPoint(new Vector3(0.1f, 0.1f, 0));
RaycastHit hit;
if (Physics.Raycast(rayOrigin, MainCamera.transform.forward, out hit))
{
if (hit.collider != null)
{
// destroy current sphere.
Destroy(currentObject);
// go next or previous.
currentIndex += next ? 1 : -1;
// circular clamp if overflow
if (currentIndex < 0)
currentIndex = Spheres.Length - 1;
else if (currentIndex >= Spheres.Length)
currentIndex = 0;
// finally do instantiate.
currentObject = Instantiate(Spheres[currentIndex]);
}
}
}
private void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
{
// 'CompareTag' is more efficient than gameobject.tag == "sometag"
if (gameObject.CompareTag(ArrowNextTag))
HandleClick(true);
else if (gameObject.CompareTag(ArrowPrevTag))
HandleClick(false);
}
}
}

dropdown error on device in codenameone

I am implementing drop-drown feature in my app. Its implemented using container with list of elements in it.
Suppose the drop down list has following items aa1, aa2, aa3, aa4 aa5 and so on. And if i search as 'aa' it displays items starting from 'aa', if I select aa5 from list, it takes aa1 and displays that. But whereas if I scroll the items and select its working fine. This problem occurring only on iOS device working perfectly fine on simulator.
the first picture depicts how drop down looks like, in second picture if I search 'ee', it gives list of items starting with 'ee'. If I select 'ee5', it sets to ee1 as shown in picture 3. Problem only on device. Any workaround for this?
So, please let me know whats the issue with this.
Thanks
[![enter image description here][1]][1]
private CustomList itemList;
class CustomList extends List {
int startYPos = -1;
long lastDiff = 0;
Timer t = null;
int draggingState = 0;
public CustomList() {
this.setTensileDragEnabled(false);
}
}
private class ButtonListener implements ActionListener {
public void actionPerformed(final ActionEvent evt) {
final Runnable rn = new Runnable() {
public void run() {
// Create and show a dialog to allow users to make a selection.
final UiBuilder uib = dm.UiBuilder();
dialog = (Dialog) uib.createContainer(DESIGNER_NAME_DIALOG_COMBOBOX_CONTAINER);
GenericSpinner itemSpinner = (GenericSpinner) uib.findByName(DESIGNER_NAME_DIALOG_COMBOBOX_GENERIC_SPINNER, dialog);
itemSpinner.setPreferredW(Display.getInstance().getDisplayWidth() * 4 / 5);
//remove from parent and replace with a linear list
Container parent = itemSpinner.getParent();
parent.removeComponent(itemSpinner);
// Add the searchable text field box
final TextField tf = (TextField)uib.findByName("Search", dialog);
tf.addDataChangedListener(new DataChangedListener() {
#Override
public void dataChanged(int type, int index) {
Object[] items = model.getFilteredItems(tf.getText());
itemList.setModel(new DefaultListModel(items));
}
});
itemList = new CustomList();
itemList.getAllStyles().setBgTransparency(0);
itemList.setItemGap(0);
parent.addComponent(BorderLayout.CENTER, itemList);
final String[] items = model.getItems();
itemList.setModel(new DefaultListModel(items));
itemList.getStyle().setMargin(10, 10, 10, 10);
itemList.setFireOnClick(true);
itemList.setLongPointerPressActionEnabled(false);
ActionListener list = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (model.isUserEditable() && model.getItemCount() > 0) {
int i = itemList.getSelectedIndex();
if (i > items.length - 1) {
return;
}
itemList.getModel().setSelectedIndex(i);
model.onUserDataEntered((String) itemList.getModel().getItemAt(i));
String textToDisplay = (String) itemList.getModel().getItemAt(i);
button.setText(textToDisplay);
}
dialog.dispose();
}
};
itemList.addActionListener(list);
CommonTransitions tran = CommonTransitions.createEmpty();
dialog.setTransitionInAnimator(tran);
dialog.setTransitionOutAnimator(tran);
itemList.setRenderer(new ListRenderer());
//related to dialog to show list of items
//how much space do we really need???
if (cellHeight == 0) {
int dip = Display.getInstance().convertToPixels(1);
int siz = 2;
if (Display.getInstance().isTablet()) {
siz = 4;
}
siz *= 2;
cellHeight = siz * dip;
}
int heightRequired = cellHeight * (items.length + 8);
//is this too much for the screen - we will use 3/4 of the screen height max
int availableHeight = Display.getInstance().getDisplayHeight() * 3;
availableHeight /= 4;
if (heightRequired > availableHeight) {
int topPos = Display.getInstance().getDisplayHeight() / 8;
int bottomPos = topPos + availableHeight;
dialog.show(topPos, topPos, 40, 40);
}
else {
int topPos = (Display.getInstance().getDisplayHeight() - heightRequired) / 2;
int bottomPos = topPos + heightRequired;
dialog.show(topPos, topPos, 40, 40);
}
}
};
}
}
//new code using Multibutton implementation
final String[] listItems = model.getItems();
Display.getInstance().callSerially(() ->{
multiButton= new MultiButton();
multiButton.setTextLine1(s);
dialog.add(multiButton);
multiButton.addActionListener(e -> Log.p("you picked " + multiButton.getSelectCommandText(), Log.ERROR));
}
dialog.revalidate();
});
I would recommend using a Container and simple layout search as demonstrated by code such as this. The code below was taken from the Toolbar javadoc:
Image duke = null;
try {
duke = Image.createImage("/duke.png");
} catch(IOException err) {
Log.e(err);
}
int fiveMM = Display.getInstance().convertToPixels(5);
final Image finalDuke = duke.scaledWidth(fiveMM);
Toolbar.setGlobalToolbar(true);
Form hi = new Form("Search", BoxLayout.y());
hi.add(new InfiniteProgress());
Display.getInstance().scheduleBackgroundTask(()-> {
// this will take a while...
Contact[] cnts = Display.getInstance().getAllContacts(true, true, true, true, false, false);
Display.getInstance().callSerially(() -> {
hi.removeAll();
for(Contact c : cnts) {
MultiButton m = new MultiButton();
m.setTextLine1(c.getDisplayName());
m.setTextLine2(c.getPrimaryPhoneNumber());
Image pic = c.getPhoto();
if(pic != null) {
m.setIcon(fill(pic, finalDuke.getWidth(), finalDuke.getHeight()));
} else {
m.setIcon(finalDuke);
}
hi.add(m);
}
hi.revalidate();
});
});
hi.getToolbar().addSearchCommand(e -> {
String text = (String)e.getSource();
if(text == null || text.length() == 0) {
// clear search
for(Component cmp : hi.getContentPane()) {
cmp.setHidden(false);
cmp.setVisible(true);
}
hi.getContentPane().animateLayout(150);
} else {
text = text.toLowerCase();
for(Component cmp : hi.getContentPane()) {
MultiButton mb = (MultiButton)cmp;
String line1 = mb.getTextLine1();
String line2 = mb.getTextLine2();
boolean show = line1 != null && line1.toLowerCase().indexOf(text) > -1 ||
line2 != null && line2.toLowerCase().indexOf(text) > -1;
mb.setHidden(!show);
mb.setVisible(show);
}
hi.getContentPane().animateLayout(150);
}
}, 4);
hi.show();

How to build a swipable intro screen?

A lot of apps have swipable intro screens - You know - those with the dots below which indicate the page one is currently viewing.
What would be the best way to create one in Codename One - a Container with snapToGrid?
I have my own implementation for this use case. There are two classes : TutoDialog which could be in your case the "intro screens" dialog and Caroussel with the dots indicator.
A tuto dialog has a title and some images in parameter. It automatically adjust the number of dots of the caroussel according to the number of images. For my use case, each image is a screenshot of my app with some advise. The tuto dialog contains 3 buttons to navigate between images (next/previous/finish).
public class Caroussel extends Container {
private final static Image CIRCLE = MainClass.getResources().getImage("circle-blue20.png");
private final static Image CIRCLE_EMPTY = MainClass.getResources().getImage("circle-empty-blue20.png");
private Label[] circles;
private int currentIndex = -1;
public Caroussel(int nbItems, boolean selectFirst) {
if (nbItems < 2 || nbItems > 50) {
throw new IllegalArgumentException("Can't create Caroussel component with nbItems<2 || nbItems>50 ! ");
}
this.circles = new Label[nbItems];
setLayout(new BoxLayout(BoxLayout.X_AXIS));
for (int i = 0; i < nbItems; i++) {
circles[i] = new Label("", CIRCLE_EMPTY);
add(circles[i]);
}
if (selectFirst) {
select(0);
}
}
public void select(int index) {
if (index >= 0 && index <= circles.length) {
if (currentIndex > -1) {
circles[currentIndex].setIcon(CIRCLE_EMPTY);
}
circles[index].setIcon(CIRCLE);
currentIndex = index;
repaint();
}
}
public void selectNext() {
if (currentIndex <= circles.length) {
select(currentIndex + 1);
}
}
public void selectPrevious() {
if (currentIndex >= 1) {
select(currentIndex - 1);
}
}}
And
public class TutoDialog extends Dialog {
private Caroussel caroussel = null;
public TutoDialog(String title, Image... images) {
if (images == null) {
return;
}
this.caroussel = new Caroussel(images.length, true);
setTitle(title);
setAutoAdjustDialogSize(true);
getTitleComponent().setUIID("DialogTitle2");
setBlurBackgroundRadius(8.5f);
Tabs tabs = new Tabs();
tabs.setSwipeActivated(false);
tabs.setAnimateTabSelection(false);
int px1 = DisplayUtil.getScaledPixel(800), px2 = DisplayUtil.getScaledPixel(600);
for (Image img : images) {
tabs.addTab("", new Label("", img.scaled(px1, px2)));
}
Container cButtons = new Container(new BorderLayout());
Button bSuivant = new Button("button.suivant");
Button bPrecedent = new Button("button.precedent");
Button bTerminer = new Button("button.terminer");
bPrecedent.setVisible(false);
bTerminer.setVisible(false);
bSuivant.addActionListener(new ActionListener<ActionEvent>() {
public void actionPerformed(ActionEvent evt) {
int currentInd = tabs.getSelectedIndex();
if (currentInd == 0) {
bPrecedent.setVisible(true);
}
if (currentInd + 1 <= tabs.getTabCount() - 1) {
if (caroussel != null)
caroussel.selectNext();
tabs.setSelectedIndex(currentInd + 1);
if (currentInd + 1 == tabs.getTabCount() - 1) {
bTerminer.setVisible(true);
bSuivant.setVisible(false);
cButtons.revalidate();
}
}
};
});
bPrecedent.addActionListener(new ActionListener<ActionEvent>() {
public void actionPerformed(ActionEvent evt) {
int currentInd = tabs.getSelectedIndex();
tabs.setSelectedIndex(currentInd - 1);
bSuivant.setVisible(true);
if (caroussel != null)
caroussel.selectPrevious();
if (currentInd - 1 == 0) {
bPrecedent.setVisible(false);
cButtons.revalidate();
}
};
});
bTerminer.addActionListener(new ActionListener<ActionEvent>() {
#Override
public void actionPerformed(ActionEvent evt) {
tabs.setSelectedIndex(0);
bPrecedent.setVisible(false);
bTerminer.setVisible(false);
bSuivant.setVisible(true);
if (caroussel != null)
caroussel.select(0);
TutoDialog.this.dispose();
}
});
cButtons.add(BorderLayout.WEST, bPrecedent).add(BorderLayout.CENTER, bSuivant).add(BorderLayout.EAST, bTerminer);
add(BoxLayout.encloseY(tabs, BoxLayout.encloseY(FlowLayout.encloseCenter(caroussel), cButtons)));
}
public static void showIfFirstTime(AbstractComponentController ctrl) {
if (ctrl == null) {
Log.p("Can't execute method showIfFirstTime(...) with null AbstractComponentController");
return;
}
String key = getKey(ctrl);
if (ctrl.getTutoDlg() != null && !Preferences.get(key, false)) {
Display.getInstance().callSerially(new Runnable() {
#Override
public void run() {
Preferences.set(key, true);
ctrl.getTutoDlg().show();
}
});
}
}
public static String getKey(AbstractComponentController ctrl) {
String key = "tuto" + ctrl.getClass().getSimpleName();
if (UserController.getCurrentUser() != null) {
key += "-" + UserController.getCurrentUser().getId();
}
return key;
}
public static boolean isAlreadyShown(AbstractComponentController ctrl) {
return Preferences.get(getKey(ctrl), false);
}
}
It's look like this :
OK - so that is my first attempt and I am pretty content with that:
private void showIntro() {
Display display = Display.getInstance();
int percentage = 60;
int snapWidth = display.getDisplayWidth() * percentage / 100;
int snapHeight = display.getDisplayHeight() * percentage / 100;
Dialog dialog = new Dialog(new LayeredLayout()) {
#Override
protected Dimension calcPreferredSize() {
return new Dimension(snapWidth, snapHeight);
}
};
Tabs tabs = new Tabs();
tabs.setTensileLength(0);
tabs.hideTabs();
int[] colors = {
0xc00000,
0x00c000,
0x0000c0,
0x909000,
0x009090,
};
for (int colorIndex = 0; colorIndex < colors.length; colorIndex++) {
Container containerElement = new Container() {
#Override
protected Dimension calcPreferredSize() {
return new Dimension(snapWidth, snapHeight);
}
};
Style style = containerElement.getAllStyles();
style.setBgTransparency(0xff);
style.setBgColor(colors[colorIndex]);
tabs.addTab("tab" + tabs.getTabCount(), containerElement);
}
int tabCount = tabs.getTabCount();
Button[] buttons = new Button[tabCount];
Style styleButton = UIManager.getInstance().getComponentStyle("Button");
styleButton.setFgColor(0xffffff);
Image imageDot = FontImage.createMaterial(FontImage.MATERIAL_LENS, styleButton);
for (int tabIndex = 0; tabIndex < tabCount; tabIndex++) {
buttons[tabIndex] = new Button(imageDot);
buttons[tabIndex].setUIID("Container");
final int tabIndexFinal = tabIndex;
buttons[tabIndex].addActionListener(aActionEvent -> tabs.setSelectedIndex(tabIndexFinal, true));
}
Container containerButtons = FlowLayout.encloseCenter(buttons);
dialog.add(tabs);
Button buttonWest = new Button("Skip");
buttonWest.setUIID("Container");
buttonWest.getAllStyles().setFgColor(0xffffff);
buttonWest.addActionListener(aActionEvent -> dialog.dispose());
Button buttonEast = new Button(">");
buttonEast.setUIID("Container");
buttonEast.getAllStyles().setFgColor(0xffffff);
buttonEast.addActionListener(aActionEvent -> {
int selectedIndex = tabs.getSelectedIndex();
if (selectedIndex < (tabs.getTabCount() - 1)) {
tabs.setSelectedIndex(selectedIndex + 1, true);
} else {
dialog.dispose();
}
});
Container containerSouth = BorderLayout.south(BorderLayout.centerAbsoluteEastWest(containerButtons, buttonEast, buttonWest));
Style styleContainerSouth = containerSouth.getAllStyles();
styleContainerSouth.setMarginUnit(
Style.UNIT_TYPE_DIPS,
Style.UNIT_TYPE_DIPS,
Style.UNIT_TYPE_DIPS,
Style.UNIT_TYPE_DIPS);
styleContainerSouth.setMargin(2, 2, 2, 2);
dialog.add(containerSouth);
SelectionListener selectionListener = (aOldSelectionIndex, aNewSelectionIndex) -> {
for (int buttonIndex = 0; buttonIndex < buttons.length; buttonIndex++) {
if (buttonIndex == aNewSelectionIndex) {
buttons[buttonIndex].getAllStyles().setOpacity(0xff);
} else {
buttons[buttonIndex].getAllStyles().setOpacity(0xc0);
}
}
buttonEast.setText((aNewSelectionIndex < (tabs.getTabCount() - 1)) ? ">" : "Finish");
buttonEast.getParent().animateLayout(400);
};
tabs.addSelectionListener(selectionListener);
dialog.addShowListener(evt -> {
buttonEast.getParent().layoutContainer();
selectionListener.selectionChanged(-1, 0);
});
Command command = dialog.showPacked(BorderLayout.CENTER, true);
}

downloadUrlToStorageInBackground in ImageList model for imageViewer downloads & overrides the image every time

class ImageList implements ListModel<Image> {
private int selection;
private Image[] images;
private EventDispatcher listeners = new EventDispatcher();
public ImageList() {
this.images = new EncodedImage[imageURLs.length];
}
public Image getItemAt(final int index) {
if (images[index] == null) {
images[index] = placeholderForTable;
Util.downloadUrlToStorageInBackground(imageURLs[index], "list" + index, (e) -> {
try {
images[index] = EncodedImage.create(Storage.getInstance().createInputStream("list" + index));
listeners.fireDataChangeEvent(index, DataChangedListener.CHANGED);
} catch (IOException err) {
err.printStackTrace();
}
});
}
return images[index];
}
public int getSize() {
return imageURLs.length;
}
public int getSelectedIndex() {
return selection;
}
public void setSelectedIndex(int index) {
selection = index;
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addListener(l);
}
public void removeDataChangedListener(DataChangedListener l) {
listeners.removeListener(l);
}
public void addSelectionListener(SelectionListener l) {
}
public void removeSelectionListener(SelectionListener l) {
}
public void addItem(Image item) {
}
public void removeItem(int index) {
}
}
protected void postMenuForm(Form f) {
BusinessForumImagesConnection bfic = new BusinessForumImagesConnection();
bfic.businessForumImagesConnectionMethod(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (bfic.response != null) {
for (int i = 0; i < imgLoop; i++) {
HashMap hm = (HashMap) bfic.response.get(i);
String imgUrl = (String) hm.get("imgUrl");
imageURLs[i] = imgUrl;
}
}
}
});
if (imageURLs != null) {
ImageList imodel = new ImageList();
ImageViewer iv = new ImageViewer(imodel.getItemAt(0));
iv.setImageList(imodel);
Container adsContainer = BoxLayout.encloseY(adsLabel, iv);
slideIndex = 0;
Runnable r = new Runnable() {
public void run() {
if (slideIndex < imodel.getSize()) {
nextImage = (Image) imodel.getItemAt(slideIndex);
if (nextImage != null) {
iv.setImage(nextImage);
}
slideIndex++;
} else {
slideIndex = 0;
}
}
};
if (uITimer == null) {
uITimer = new UITimer(r);
}
if (uITimer != null) {
uITimer.schedule(5000, true, f); //5 seconds
}
f.add(BorderLayout.SOUTH, adsContainer);
adsContainer.setLeadComponent(adsLabel);
adsLabel.addActionListener((e) -> {
showForm("BusinessForum", null);
});
}
}
I had used URLImage.createToStorage before but imageViewer didnt work properly so I have used ImageList model. But everytime the form is opened, it jst redownloads the imgs and overrides them in storage, that makes the app slower. How can I make sure if the image is already downloaded, it doesnt download it again and jst shows them in imgViewer? thankyou
The download method will always download regardless...
You need to check if the Storage file exists and if so load that.
See the WebServices/Dogs demo in the new kitchen sink: http://www.codenameone.com/blog/kitchensink-ii.html

Update Jfreechart when update data from Webcam

My jfreeChart comes from frames of a webcam. I pass this frames and it generates a graphic of R, G and B colors of this frame. I want this chart do automatic update as I pass the frames. I've tried everything but nothing seens to work.
Any help is welcome.
class DaemonThread implements Runnable
{
protected volatile boolean runnable = false;
#Override
public void run()
{
synchronized(this)
{
while(runnable)
{
if(webSource.grab())
{
try
{
webSource.retrieve(frame);
Imgcodecs.imencode(".bmp", frame, mem);
Image im = ImageIO.read(new ByteArrayInputStream(mem.toArray()));
buff = (BufferedImage) im;
if(contHistograma==0) {
h = new Histo(buff);
contHistograma++;
}else{
h.update(buff);
}
webcamLabel.setIcon(new ImageIcon(buff));
Graphics g=webcamPanel.getGraphics();
if (g.drawImage(buff, 0, 0, getWidth(), getHeight() -150 , 0, 0, buff.getWidth(), buff.getHeight(), null))
if(runnable == false)
{
System.out.println("Going to wait()");
this.wait();
}
}
catch(Exception ex)
{
System.out.println("Error");
}
}
}
}
}
}
public class Histo{
private ChartFrame lineFrame;
private ArrayList<Integer> redArray;
private ArrayList<Integer> greenArray;
private ArrayList<Integer> blueArray;
public Histo(BufferedImage originalImage){
Color c;
redArray = new ArrayList<>();
greenArray = new ArrayList<>();
blueArray = new ArrayList<>();
for (int i = 0; i < originalImage.getWidth(null); i++) {
for (int j = 0; j < originalImage.getHeight(null); j++) {
c = new Color(originalImage.getRGB(i,j));
redArray.add(c.getRed());
greenArray.add(c.getGreen());
blueArray.add(c.getBlue());
}
}
Collections.sort(redArray);
Collections.sort(greenArray);
Collections.sort(blueArray);
XYSeriesCollection dataset = creatingDataset(redArray, greenArray, blueArray);
JFreeChart chart = createChart(dataset);
ChartPanel chartPanel = new ChartPanel(chart);
lineFrame = new ChartFrame("teste", chart);
lineFrame.add(chartPanel);
lineFrame.setVisible(true);
lineFrame.setSize(600, 450);
}
public void update(BufferedImage originalImage){
redArray.clear();
greenArray.clear();
blueArray.clear();
Color c;
for (int i = 0; i < originalImage.getWidth(null); i++) {
for (int j = 0; j < originalImage.getHeight(null); j++) {
c = new Color(originalImage.getRGB(i,j));
redArray.add(c.getRed());
greenArray.add(c.getGreen());
blueArray.add(c.getBlue());
}
}
Collections.sort(redArray);
Collections.sort(greenArray);
Collections.sort(blueArray);
XYSeriesCollection dataset = creatingDataset(redArray, greenArray, blueArray);
JFreeChart chart = createChart(dataset);
ChartPanel chartPanel = new ChartPanel(chart);
lineFrame.removeAll();
lineFrame.add(chartPanel);
lineFrame.revalidate();
lineFrame.setLayout(new BorderLayout());
lineFrame.repaint();
}
public static XYSeriesCollection creatingDataset(ArrayList<Integer> redArray,ArrayList<Integer> greenArray,ArrayList<Integer> blueArray){
int cont=1, cont2=1, cont3=1;
XYSeries series = new XYSeries("Red");
XYSeries series2 = new XYSeries("Green");
XYSeries series3 = new XYSeries("Blue");
for (int i = 0; i < redArray.size()-1; i++) {
if(redArray.get(i).intValue() == redArray.get(i+1).intValue()) {
cont++;
}else{
series.add(redArray.get(i).intValue(), cont);
cont=1;
}
}
for (int i = 0; i < greenArray.size()-1; i++) {
if(greenArray.get(i).intValue() == greenArray.get(i + 1).intValue()) {
cont2++;
}else{
series2.add(greenArray.get(i).intValue(), cont2);
cont2 = 1;
}
}
for (int i = 0; i < blueArray.size()-1; i++) {
if(blueArray.get(i).intValue() == blueArray.get(i+1).intValue()) {
cont3++;
}else{
series3.add(blueArray.get(i).intValue(), cont3);
cont3=1;
}
}
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(series);
dataset.addSeries(series2);
dataset.addSeries(series3);
return dataset;
}
private JFreeChart createChart(final XYDataset dataset) {
JFreeChart result = ChartFactory.createXYLineChart("Gráfico XY", "Eixo X", "Eixo Y", dataset, PlotOrientation.VERTICAL, true, true, false);
final XYPlot plot = result.getXYPlot();
plot.setBackgroundPaint(new Color(0xffffe0));
plot.setDomainGridlinesVisible(true);
plot.setDomainGridlinePaint(Color.lightGray);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.lightGray);
final NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis(); //RANGE EIXO X
domainAxis.setRange(0, 260);
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); //RANGE EIXO Y
rangeAxis.setRange(0, 5000);
return result;
}
}
If someone else have this problem here is the answer:
Chartframe can't get rid of chartpanel, so I made Chartpanel a atribute.
After that I update my dataset and did this:
JFreeChart chart = createChart(dataset);
chartPanel.setChart(chart);
lineFrame.setLayout(new BorderLayout());
lineFrame.repaint();
Problem solved.

Resources