how to ViewFlipper addView or removeView after autoStart set to true - viewflipper

For my app, I have lots of images(from url not from phone memory) required to be shown as slideshow. I am using ViewFlipper for this. I am getting this images from url and adding them in viewFlipper. Problem is when i add 5-6 images it works fine but for more than 5-6 it goes into OutOfMemory error.
I think, this can be done if we can somehow do something like this..
1. add some set of images to ViewFlipper
2. startFlipping, remove view after showing that image/view,
3. add more images.
Not sure if it can be done using viewFlipper or are there any other way ?
Sample Code of my AutoSlideShow:
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ViewFlipper;
public class AutoSlideShow extends Activity {
ViewFlipper viewFlipper = null;
Button pauseButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_slide_show);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Intent intent = getIntent();
String[] allUrls = intent.getExtras().getStringArray("allImageUrls");
viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
viewFlipper.setFlipInterval(2000);
viewFlipper.setAutoStart(true);
for (int i = 0; i < allUrls.length; i++) {
setFlipperImage(allUrls[i]);
}
pauseButton = (Button) findViewById(R.id.pauseButton);
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pauseButton.getText().equals("Resume")) {
viewFlipper.startFlipping();
pauseButton.setText("Pause");
} else {
viewFlipper.stopFlipping();
pauseButton.setText("Resume");
}
}
});
}
private void setFlipperImage(String url) {
ImageView image = new ImageView(getApplicationContext());
Bitmap bitmap = null;
try {
InputStream content = (InputStream) new URL(url).getContent();
bitmap = BitmapFactory.decodeStream(content);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
image.setImageBitmap(bitmap);
viewFlipper.addView(image);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.auto_slide_show, menu);
return true;
}
}

private ViewFlipper mViewFlipper;
private GestureDetector mGestureDetector;
int i = 0;
int k = 0;
int l = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_slide_show);
mViewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Intent intent = getIntent();
String[] allUrls = intent.getExtras().getStringArray("allImageUrls");
if (i == 0) {
for (int i = 0; i < 2; i++) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(allUrls[i]);
mViewFlipper.addView(imageView);
k++;
}
i = 1;
}
mViewFlipper.getDisplayedChild();
// Add all the images to the ViewFlipper
CustomGestureDetector customGestureDetector = new CustomGestureDetector();
mGestureDetector = new GestureDetector(this, customGestureDetector);
mViewFlipper.setInAnimation(this, android.R.anim.fade_in);
mViewFlipper.setOutAnimation(this, android.R.anim.fade_out);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
class CustomGestureDetector extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
// Swipe left (next)
if (e1.getX() > e2.getX()) {
mViewFlipper.setInAnimation(MainActivity.this, R.anim.left_in);
mViewFlipper.setOutAnimation(MainActivity.this, R.anim.left_out);
mViewFlipper.showNext();
if (mViewFlipper.getDisplayedChild() > 1) {
mViewFlipper.removeViewAt(l);
}
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(allUrls[k]);
mViewFlipper.addView(imageView);
k++;
Log.d("Count", "" + mViewFlipper.getChildCount());
}
// Swipe right (previous)
if (e1.getX() < e2.getX()) {
mViewFlipper.setInAnimation(MainActivity.this, R.anim.right_in);
mViewFlipper.setOutAnimation(MainActivity.this, R.anim.right_out);
mViewFlipper.showPrevious();
if (mViewFlipper.getDisplayedChild() > 1) {
mViewFlipper.removeViewAt(l);
}
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(allUrls[k]);
mViewFlipper.addView(imageView);
k++;
}
return super.onFling(e1, e2, velocityX, velocityY);
}
}

Related

Moving JavaFX Nodes Between Stages

I'm rewriting a Swing application in JavaFX, where I allow users to present multiple workspaces as either windows or tabs. However, my FX code will not display the contents moved from more than one tab into a new stage; only the contents of the currently-selected tab appear in my new stages. I've distilled my code into a small example below. Can anyone clue me in as to what's gone wrong?
package scenes;
import java.util.ArrayList;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class StageSwapper extends Application {
static public void main(String[] args) {
launch(args);
}
private TabPane tabs = new TabPane();
public void start(Stage stage) {
stage.setTitle("Stage Swapper");
BorderPane p = new BorderPane();
p.setCenter(tabs);
tabs.getTabs().addAll(new Swapee("First").createTab(), new Swapee("Second").createTab());
Scene s = new Scene(p);
stage.setScene(s);
stage.show();
launchSwap();
}
private void launchSwap() {
new Thread() {
public void run() {
try {
sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
Platform.runLater(new Runnable() {
public void run() {
for (Swapee s : Swapee.list) {
createWindow(s);
}
}
});
}
}.start();
}
public void createWindow(Swapee s) {
Stage window = new Stage();
window.setTitle("New Window");
window.setY(200);
window.setX(200);
BorderPane p = new BorderPane();
p.setCenter(s);
window.setScene(new Scene(p));
window.show();
}
}
class Swapee extends Label {
static private int count;
static ArrayList<Swapee> list = new ArrayList<>();
String name;
Swapee(String name) {
super("Swappable Item " + ++count);
this.name = name;
list.add(this);
}
Tab createTab() {
Tab t = new Tab(name);
t.setContent(this);
return t;
}
}
You haven't specified the size of the windows that you're creating. Right now they have width and length equal to 0. You may use the following approach:
BorderPane p = new BorderPane();
p.setPrefSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE);
p.setCenter(s);
BorderPane will be resized according to its content and the window will be resized as well.

sleep function not working correctly

I am using the code below to make my splash screen
package Splashscreentest;
/*
* SplashDemo.java
*
*/
import java.awt.*;
import java.awt.event.*;
public class Splashscreentest extends Frame implements ActionListener {
static void renderSplashFrame(Graphics2D g, int frame) {
final String[] comps = {"foo", "bar", "baz"};
g.setComposite(AlphaComposite.Clear);
g.fillRect(300,140,400,400);
g.setPaintMode();
g.setColor(Color.BLACK);
g.drawString("Loading "+comps[(frame/5)%3]+"...", 120, 150);
}
public Splashscreentest() {
super("SplashScreen demo");
setSize(3000, 2000);
setLayout(new BorderLayout());
Menu m1 = new Menu("File");
MenuItem mi1 = new MenuItem("Exit");
m1.add(mi1);
mi1.addActionListener(this);
this.addWindowListener(closeWindow);
MenuBar mb = new MenuBar();
setMenuBar(mb);
mb.add(m1);
final SplashScreen splash = SplashScreen.getSplashScreen();
if (splash == null) {
System.out.println("SplashScreen.getSplashScreen() returned null");
return;
}
Graphics2D g = splash.createGraphics();
if (g == null) {
System.out.println("g is null");
return;
}
for(int i=0; i<100; i++) {
renderSplashFrame(g, i);
splash.update();
try {
Thread.sleep(5000);
}
catch(InterruptedException ex) {
}
}
splash.close();
setVisible(true);
toFront();
}
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
private static final WindowListener closeWindow = new WindowAdapter(){
#Override
public void windowClosing(WindowEvent e){
e.getWindow().dispose();
}
};
public static void main (String args[]) {
}
}
The splash screen is not remaining on screen for the 5 seconds I would expect it to from the Thread.sleep command I used. The image for my splash screen is in this project within source packages
You're calling Thread.Sleep within the for loop. Change it to
for(int i=0; i<100; i++) {
renderSplashFrame(g, i);
splash.update();
try {
Thread.sleep(50);
}
catch(InterruptedException ex) {
}
}

Is this a bug in Swing in JDK1.6/JDK1.7 but not in JDK1.5?

I have an application for which GUI was developed in Java Swing JDK1.5.I am planning to upgrade the JDK to JDK1.6 but doing so produces problem for me.
Problem Statement : If I open few dialogs(say 10) and dispose them and than call method 'getOwnedWindows()' , it returns 0 in JDK1.5 but returns 10 in JDK1.6. As in JDK1.6 it returns 10, my algorithm to set focus is not working correctly as it is able to find invlaid/disposed dialogs and try to set the focus on it but not on the correct and valid dialog or component because algorithm uses getOwnedWindows() to get the valid and currently open dialog.
Can anyone suggest me the workaround to avoid this problem in JDK1.6?
Following piece of code can demonstrate the problem.
Custom Dialog Class :
Java Code:
import javax.swing.JDialog;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
public class CustomDialog extends JDialog implements ActionListener {
private JPanel myPanel = null;
private JButton yesButton = null;
private JButton noButton = null;
private boolean answer = false;
public boolean getAnswer() { return answer; }
public CustomDialog(JFrame frame, boolean modal, String myMessage) {
super(frame, modal);
myPanel = new JPanel();
getContentPane().add(myPanel);
myPanel.add(new JLabel(myMessage));
yesButton = new JButton("Yes");
yesButton.addActionListener(this);
myPanel.add(yesButton);
noButton = new JButton("No");
noButton.addActionListener(this);
myPanel.add(noButton);
pack();
setLocationRelativeTo(frame);
setVisible(true);
//System.out.println("Constrtuctor ends");
}
public void actionPerformed(ActionEvent e) {
if(yesButton == e.getSource()) {
System.err.println("User chose yes.");
answer = true;
//setVisible(false);
}
else if(noButton == e.getSource()) {
System.err.println("User chose no.");
answer = false;
//setVisible(false);
}
}
public void customFinalize() {
try {
finalize();
} catch (Throwable e) {
e.printStackTrace();
}
}
}
Main Class:
Java Code:
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionEvent;
import java.awt.FlowLayout;
import java.awt.Window;
public class TestTheDialog implements ActionListener {
JFrame mainFrame = null;
JButton myButton = null;
JButton myButton_2 = null;
public TestTheDialog() {
mainFrame = new JFrame("TestTheDialog Tester");
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
myButton = new JButton("Test the dialog!");
myButton_2 = new JButton("Print no. of owned Windows");
myButton.addActionListener(this);
myButton_2.addActionListener(this);
mainFrame.setLocationRelativeTo(null);
FlowLayout flayout = new FlowLayout();
mainFrame.setLayout(flayout);
mainFrame.getContentPane().add(myButton);
mainFrame.getContentPane().add(myButton_2);
mainFrame.pack();
mainFrame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(myButton == e.getSource()) {
System.out.println("getOwnedWindows 1 " + mainFrame.getOwnedWindows().length);
createMultipleDialogs();
int i = 0;
for (Window singleWindow : mainFrame.getOwnedWindows()) {
System.out.println("getOwnedWindows " + i++ + " "
+ singleWindow.isShowing() + " "
+ singleWindow.isVisible() + " " + singleWindow);
}
System.out.println("getOwnedWindows 2 " + mainFrame.getOwnedWindows().length);
//System.gc();
System.out.println("getOwnedWindows 3 " + mainFrame.getOwnedWindows().length);
//System.gc();
System.out.println("getOwnedWindows 4 " + mainFrame.getOwnedWindows().length);
} else if (myButton_2 == e.getSource()) {
System.out.println("getOwnedWindows now: " + mainFrame.getOwnedWindows().length);
}
}
public void createMultipleDialogs() {
for (int a = 0; a < 10; a++) {
CustomDialog myDialog = new CustomDialog(mainFrame, false,
"Do you like Java?");
myDialog.dispose();
myDialog.customFinalize();
}
}
public static void main(String argv[]) {
TestTheDialog tester = new TestTheDialog();
}
}
Running the above code gives different output for JDK1.5 and JDK1.6
I would appreciate your help in this regards.
Thanks

Swing JTextfield DnD replace the existing text with the imported text

I have two text fields and I can drag and drop the text between them. What I want is that every time I drag the text it will replace the existing text data with the text which was dragged and dropped.
import java.awt.Container;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class DragDropText extends JFrame {
public static void main(String[] args) {
new DragDropText().setVisible(true);
}
public DragDropText() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField field1 = new JTextField("Life's a drag", 20);
JTextField field2 = new JTextField("and then you drop", 20);
field1.setDragEnabled(true);
field2.setDragEnabled(true);
Container content = getContentPane();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(field1);
content.add(field2);
pack();
}
}
You can achieve the effect by creating and setting a subclass of TransferHandler.
This is an example that will work for any subclass of JTextComponent. You'll have to add the appropriate checks to make it robust.
You can find more info here: http://download.oracle.com/javase/tutorial/uiswing/dnd/transferhandler.html.
import java.io.*;
import java.awt.*;
import java.awt.datatransfer.*;
import javax.swing.*;
import javax.swing.text.*;
public class DragDropText extends JFrame {
public static void main(String[] args) {
new DragDropText().setVisible(true);
}
public DragDropText() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField field1 = new JTextField("Life's a drag", 20);
JTextField field2 = new JTextField("and then you drop", 20);
field1.setDragEnabled(true);
field2.setDragEnabled(true);
field1.setTransferHandler(new CustomTransferHandler());
field2.setTransferHandler(new CustomTransferHandler());
Container content = getContentPane();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(field1);
content.add(field2);
pack();
}
}
class CustomTransferHandler extends TransferHandler {
public int getSourceActions(JComponent c) {
return COPY_OR_MOVE;
}
public Transferable createTransferable(JComponent c) {
return new StringSelection(((JTextComponent) c).getSelectedText());
}
public void exportDone(JComponent c, Transferable t, int action) {
if(action == MOVE)
((JTextComponent) c).replaceSelection("");
}
public boolean canImport(TransferSupport ts) {
return ts.getComponent() instanceof JTextComponent;
}
public boolean importData(TransferSupport ts) {
try {
((JTextComponent) ts.getComponent())
.setText((String) ts
.getTransferable()
.getTransferData(DataFlavor.stringFlavor));
return true;
} catch(UnsupportedFlavorException e) {
return false;
} catch(IOException e) {
return false;
}
}
}

Toolbar swing application

I have to implement 4 functionalities on my GUI. Functionalities are exclusive. Each functionality can have several commands that the user can execute. All this must be represented with icons and buttons only in a toolbar. I'm searching example and ideas to create this kind of toolbar.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MultiToolBar {
private static void addButtons(Container c, int i, JButton[] b) {
int startAt = (i==0 ? 0 : i*3);
int endAt = startAt+3;
for (int ii = startAt; ii<endAt; ii++) {
c.add(b[ii]);
}
c.validate();
}
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
final JToolBar tb = new JToolBar();
final JButton[] buttons = new JButton[12];
for (int ii=0; ii<buttons.length; ii++) {
buttons[ii] = new JButton("Button " + (ii+1));
}
String[] functions = new String[4];
for (int ii=0; ii<functions.length; ii++) {
functions[ii] = "Function " + (ii+1);
}
final JComboBox cb = new JComboBox(functions);
tb.add(cb);
cb.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent lse) {
Component[] components = tb.getComponents();
for (Component component : components) {
if (!(component instanceof JComboBox)) {
tb.remove(component);
}
}
int index = cb.getSelectedIndex();
addButtons(tb, index, buttons);
}
});
cb.setSelectedIndex(3);
JOptionPane.showMessageDialog(null, tb);
}
});
}
}
Take a look at the class JToolBar, here is a good tutorial from Oracle.
Oracle - How to Use Toolbars