recently I started learning Java, I watched a YT video where a programmer used static methods and variables to create a simple guess game using JFrame.
Afterwards I tried to implement a close/restart button, after reading some Threads I relized static methods arenĀ“t made that for. So my question is now how do I solve my problem now. :)
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ThreadLocalRandom;
public class main extends JFrame {
JLabel text = new JLabel("Please choose a number between 1 & 10 ");
JLabel textVersuch = new JLabel();
JButton button = new JButton("Try");
int myNumber = ThreadLocalRandom.current().nextInt(1,10+1);
JTextField textField = new JTextField();
int count = 0;
//is there a better way to hide all this information, but still keep them useable for my methods?
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.openUI(); //error occurs
}
//How do I manage to start my method openUI() to start my game?
public void openUI(){
JFrame frame = new JFrame("Program");
frame.setSize(400,400);
frame.setLocation(800,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultLookAndFeelDecorated(true);
text.setBounds(0,50,400,25);
textVersuch.setBounds(300,0,100,25);
textField.setBounds(0,150,50,25);
button.setBounds(50,150,100,25);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
String textFromTextfield = textField.getText();
int number = Integer.parseInt(textFromTextfield);
if(number<1 || number>10){
text.setText("Your number has to be between 1 & 10 ");
textField.setText("");
}else{
guess(number);
}
}catch (Exception error){
text.setText("Please enter a digit! ");
textField.setText("");
}
}});
frame.add(button);
frame.add(textField);
frame.add(text);
frame.add(textVersuch);
frame.setLayout(null);
frame.setVisible(true);
}
public void close(JFrame frame){
frame.dispose(); //here I want to close the game
}
public void guess(int number ) throws InterruptedException {
count++;
textVersuch.setText(count + " tries!");
if(number == myNumber){
text.setText("You was right! " + " You tried " + count + " time(s) :)" );
button.setText("Restart");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//How can I restart my JFrame?
}
});
} else if (count < 3) {
text.setText("Wrong guess! Retry");
if (number < myNumber){
text.setText("Your searched number is bigger than" + number );
}else {
text.setText("Your searched number is lower than" + number );
}
} else {
text.setText("Sorry, you lost the number was " + myNumber);
}
textField.setText("");
}
}
Related
Full respect for your talents, please ignore how awful my code is. I am no natural and appreciate many of you will find my coding offensive!
I am wanting to create a GUI that 1 -chooses a text file, 2- displays the text to text panel and 3- validates the code ( i have a valid and invalid text file to demonstrate the validations work).
I can get points 1 and 2 to work but none of my validations are erroring when i select an invalid text file.
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.Image;
public class MainClass extends JFrame implements ActionListener {
#SuppressWarnings("deprecation")
public static void main(String[] args) {
// Creates new Window Frame with title and sets app to close on clicking cross
JFrame frame = new JFrame("SE2 - Graphics Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Creates JFrame as top level container in hierarchy
Container toplevelContainer = frame.getContentPane();
// Sets Grid Layout
GridLayout layout = new GridLayout(1, 0);
frame.setLayout(layout);
// Splits Panel into 2 halves and sets parameters for text panel and area
String str = "This is the area your imported text will be displayed";
JTextArea TextPanel = new JTextArea(str);
TextPanel.setBackground(Color.YELLOW);
TextPanel.setEditable(false);
TextPanel.setLineWrap(true);
TextPanel.setWrapStyleWord(true);
frame.add(TextPanel);
// calls graphicspanel class
GraphicsPanel grp = new GraphicsPanel();
toplevelContainer.add(grp);
grp.drawLine(Color.BLACK, 100, 100, 200, 100);
grp.drawLine(Color.BLACK, 200, 100, 200, 200);
grp.drawLine(Color.BLACK, 200, 200, 100, 200);
grp.drawLine(Color.BLACK, 100, 200, 100, 100);
// adds graphic panel to frame
frame.pack();
frame.setVisible(true);
// Creates new menubar within frame
JMenuBar menubar = new JMenuBar();
frame.setJMenuBar(menubar);
// Creates new menu with new jmenuitems for File (load,save,exit) with shortcuts
JMenu file = new JMenu("File");
menubar.add(file);
JMenuItem load = new JMenuItem("Load");
load.setIcon(new ImageIcon("Images/Looad.png"));
load.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, KeyEvent.SHIFT_MASK));
file.add(load);
// enables user to browse and choose files to load from filepath
load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
try
{
// reads file and displays in text panel
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
TextPanel.read(br, null);
br.close();
TextPanel.requestFocus();
File Fileobject = new File(filename);
#SuppressWarnings("resource")
Scanner fileReader = new Scanner(Fileobject);
fileReader = new Scanner(Fileobject);
while (fileReader.hasNext())
{
String line = fileReader.nextLine();
String[] splitArray = line.split(" ");
String command = splitArray[0];
if (command.contains ("MOVE"))
{
String MOVE = splitArray[0];
String x1 = splitArray[1];
String y1 = splitArray[2];
if (isNumeric(MOVE))
{
JOptionPane.showMessageDialog(null, "Command cannot be a number");
}
if(isLetter(x1))
{
JOptionPane.showMessageDialog(null, "Must be integer value");
}
if(isLetter(y1))
{
JOptionPane.showMessageDialog(null, "Must be integer value");
}
else if (command.contains("LINE"))
{
String LINE = splitArray[0];
String x2 = splitArray[1];
String y2 = splitArray[2];
if (isNumeric(LINE))
{
JOptionPane.showMessageDialog(null, "Command cannot be a number");
}
if(isLetter(x2))
{
JOptionPane.showMessageDialog(null, "Must be integer value");
}
if(isLetter(y2))
{
JOptionPane.showMessageDialog(null, "Must be integer value");
}
else if(command.contains("CIRCLE"))
{
String CIRCLE =splitArray[0];
int r = Integer.parseInt(splitArray[1]);
if(r < 0)
{
JOptionPane.showMessageDialog(null, "Must be positive number");
}
JOptionPane.showMessageDialog(null, "Must be integer value");
}
else if (command.contains("SOLID_CIRCLE"))
{
String SOLID_CIRCLE = splitArray[0];
try {
int r = Integer.parseInt(splitArray[1]);
if(r<0)
{
JOptionPane.showMessageDialog(null, "Must be positive number");
}
}
catch(NumberFormatException e) {
}
JOptionPane.showMessageDialog(null, "Must be integer value");
}
else if (command.contains("CLEAR"))
{
JOptionPane.showMessageDialog(null, "Commands have been cleared");
}
else if (command.contains("COLOUR"))
{
String Colour = splitArray[0];
int red = Integer.parseInt(splitArray[1]);
int green = Integer.parseInt(splitArray[2]);
int blue = Integer.parseInt(splitArray[3]);
if(red>255)
if(red<0)
if (green>255)
if(green<0)
if(blue>255)
if(blue<0)
{
JOptionPane.showMessageDialog(null, "Colour values must range between 0 and 255");
}
else if (command.contains("TEXT"))
{
String text = null;
if(isNumeric(text))
{
JOptionPane.showMessageDialog(null, "Text must not contain numbers");
}
if (!contains(""))
{
JOptionPane.showMessageDialog(null, "Text must contain double quotation marks");
}
}
}
}
}
}}
//confirm checks are complete for user
catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error Check Complete");
}
}
private boolean contains(String string) {
// TODO Auto-generated method stub
return false;
}
private boolean isLetter(String string) {
// TODO Auto-generated method stub
return false;
}
private boolean isNumeric(String command) {
// TODO Auto-generated method stub
return false;
}
});
// adds image icon and shortcut keys to JMenuItems
JMenuItem save = new JMenuItem("Save");
save.setIcon(new ImageIcon("Images/Saveas.png"));
save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.SHIFT_MASK));
// Attempt at requirement 4 to add functionality to save JMENUITEM
// save.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent ae) {
// JFileChooser fc = new JFileChooser();
// fc.showSaveDialog(this);
// encoder.encode(image);
// byte[] jpgData = bos.toByteArray();
// FileOutputStream fos = new FileOutputStream(fc.getSelectedFile()+".jpeg");
// fos.write(jpgData);
// fos.close();
file.add(save);
JMenuItem exit = new JMenuItem("Exit");
exit.setIcon(new ImageIcon("Images/Exiit.png"));
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, KeyEvent.SHIFT_MASK));
file.add(exit);
JMenu help = new JMenu("Help");
menubar.add(help);
JMenuItem about = new JMenuItem("About");
about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.SHIFT_MASK));
help.add(about);
// Adds Action listener to display dialog box with app description
about.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(about,
"This Application allows you to import, save and display graphical content from a file containing a set of instructions.",
"About", JOptionPane.INFORMATION_MESSAGE);
}
});
frame.setVisible(true);
class exitaction implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
exit.addActionListener(new exitaction());
}
protected static int isEmpty() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
I have a very similar problem like
Seekbar 'unhooking' from media player on orientation change, I get the correct output onSaveInstanceState and onCreateView of my progress bar.
I have implemented a media player in a fragment, on device rotation the song is is working fine but the seekbar progress is getting set to 0. I have done the following.
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
//NOTE: When navigating from one fragment to the next
// Bundle/savedInstanceState is always null
// Implemented it using Shared Preferences.
// Always call the superclass so it can save the view hierarchy state
savedInstanceState.putInt(SEEKBAR_PROGRESS, utils.getProgressPercentage(getCurrentPosition(), getDuration()));
Log.i(LOG_TAG, ">>>>> onSaveInstanceState : " + savedInstanceState.getInt(SEEKBAR_PROGRESS));
}
and onCreateView I am checking the savedInstanceState if it is not null and > 0 I am setting the seekbar progress, but it is not working, can someone please tell me why?
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
Bundle arguments = getArguments();
if (arguments != null) {
mUri = arguments.getParcelable(TrackPlayerActivityFragment.DETAIL_URI);
}
final View rootView = inflater.inflate(R.layout.fragment_track_player, container, false);
currentTimeTextView = (TextView) rootView.findViewById(R.id.current_time);
totalTimeView = (TextView) rootView.findViewById(R.id.total_time);
playButtonView = (ToggleButton) rootView.findViewById(R.id.media_play);
Cursor cur = getActivity().getContentResolver().query(mUri,null, null, null, null);
mTrackPlayerAdapter = new TrackPlayerAdapter(getActivity(), cur, 0, this);
mListView = (ListView) rootView.findViewById(R.id.listview_player);
mListView.setAdapter(mTrackPlayerAdapter);
//initialize the play button
playButtonView = (ToggleButton) rootView.findViewById(R.id.media_play);
if(savedInstanceState != null && savedInstanceState.getInt(SEEKBAR_PROGRESS) > 0) {
Log.i(LOG_TAG, ">>>>> onCreateView savedInstance : " + savedInstanceState.getInt(SEEKBAR_PROGRESS));
mSpotifyMusicSeekBar.setProgress(savedInstanceState.getInt(SEEKBAR_PROGRESS));
}
return rootView;
}
the play song is a runnable thread which is working till the completion even on device rotation.
public void playSong(String songUrl, String songTitle) {
Log.i(LOG_TAG, ">>>>> Song URL fragment - " + songUrl);
mSpotifyMusicService.setSongURL(songUrl);
mSpotifyMusicService.setSongTitle(songTitle);
mSpotifyMusicService.playSong();
View v = getActivity().findViewById(R.id.listview_player);
mSpotifyMusicSeekBar = (SeekBar) v.findViewById(R.id.musicSeekBar);
new Thread(new Runnable() {
#Override
public void run() {
try {
int progress = 0;
if(startingPoint > 0) {
progress = startingPoint;
}
while (progress <= 100) {
Thread.sleep(100);
final long totalDuration = getDuration();
progress = utils.getProgressPercentage(getCurrentPosition(), totalDuration);
//set the seekbar position, will be used in saved instance later on
mSpotifyMusicSeekBar.setProgress(progress);
}
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
}
}).start();
//implement the OnSeekBarChangeListener interface methods
mSpotifyMusicSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
Log.i(LOG_TAG, ">>>>> User Progress change" + progress);
mSpotifyMusicService.seek(progress);
} else {
updateMediaPlayerControls(
utils.milliSecondsToTimer(getCurrentPosition()),
utils.milliSecondsToTimer(getDuration())
);
//Log.i(LOG_TAG, ">>>>> System progress %age - " + progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
Log.i("onStartTrackingTouch - ",
"" + seekBar.getProgress());
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
Log.i("onStopTrackingTouch - ",
"" + seekBar.getProgress());
startingPoint = seekBar.getProgress();
mSpotifyMusicService.seek(startingPoint);
}
});
}
The way I solved it was to have the seekbar outside of the custom adapter and made it part of the fragment, and then used onSaveInstanceState to get the percentage and used it onCreateView after checking if the saved instance bundle is not null.
I made a simple code to calculate BMI but it shows error in the line with the parseInt method can anyone help (a bit new to java :P)
public BmiF(){
super("BMI Calculator");
setLayout(new FlowLayout());
t1 = new JTextField("enter wieght in kg",10);
final int num1 =Integer.parseInt(t1.getText());
add(t1);
t2 = new JTextField("enter hieght in m",10);
final int num2 =Integer.parseInt(t2.getText());
add(t2);
t3 = new JTextField("",10);
t3.setEditable(false);
add(t3, BorderLayout.SOUTH);
b = new JButton("Claculate BMI");
add(b);
b.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event) {
int k = num1/(num2*num2);
t3.setText(String.format("Your BMI is %d",k));
}
}
);
}
}
You're trying to parse the String "enter weight in kg" as int. See java doc here for what your initialization means.
You need to parse the string in the ActionListener and add a catch exception rule.
I've gotten the bellow code to work. Another problem you have is that you need to declare the int or double in the try block of code without the final qualifier, so that you can change the variable after initialization
frame.setLayout(new FlowLayout());
textArea.setEditable(true);
textArea.setPreferredSize(new Dimension(50, 15));
button = new JButton("ok");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
String string = textArea.getText().trim();
int weight = Integer.parseInt(string);
//do stuff with weight variable
System.out.println(weight);
} catch(Exception e1) {
System.out.println("number exception");
}
}
});
frame.add(textField);
frame.add(textArea);
frame.add(button);
frame.setSize(300, 100);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
I continuously have this problem with all my most recent animation projects. Every time I run my animations, they never seem to be completely visible and full, but rather they blink and flash similar to a light bulb that is not fully screwed in ( i know, strange comparison but I can't think of what else it resembles). I feel like it must have something to do with my placement of repaint(); but I'm just not sure at this point. On a previous animation I made, the problem was that my "private BufferedImage offScr" variable wasn't set correctly, but viewing other programs similar to the one I am working on now, I don't see why that variable would be necessary. Thanks for all your help folks, and I apologize for my lack of knowledge in programming vocabulary.
Here is my program so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class DoveAnimator extends JFrame implements ActionListener {
private int DELAY = 40; // the delay for the animation
private final int WIDTH = 400; // the window width
private final int HEIGHT = 180; // the window height
private final int IMAGEAMT = 8;
private Image [] doveLeft = new Image[IMAGEAMT];
private Image [] doveRight = new Image[IMAGEAMT];
private int doveIndex = 0;
private boolean isRight = true;
private JPanel dovePanel;
private Image dove;
private JButton slowerButton = new JButton ("Slower");
private JButton fasterButton = new JButton ("Faster");
private JButton reverseButton = new JButton ("Reverse");
private JButton pauseResumeButton = new JButton (" pause ");
private Timer timer;
private int clicks = 2;
private boolean pause = false;
/** The constructor */
public DoveAnimator() {
MediaTracker track = new MediaTracker(this);
for (int i = 0; i < IMAGEAMT; ++i) {
doveLeft[i] = new ImageIcon("doves/ldove" + (i+1) + ".gif").getImage();
doveRight[i] = new ImageIcon("doves/rdove" + (i+1) + ".gif").getImage();
track.addImage(doveLeft[i],0);
track.addImage(doveRight[i],0);
}
// dove = doveRight[0];
//track.addImage(bkgImage,0);
// track.addImage(dove,0);
try {
track.waitForAll();
} catch ( InterruptedException e ) { }
dove = doveRight[0];
JPanel mainPanel = new JPanel();
mainPanel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
setTitle ("Dove Animator");
dovePanel = new JPanel();
dovePanel.setPreferredSize(new Dimension(100, 125));
dovePanel.setBackground(Color.WHITE);
mainPanel.add(dovePanel);
JPanel buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(WIDTH, 40));
// button 1
slowerButton.addActionListener (this);
buttonPanel.add (slowerButton);
// button 2
fasterButton.addActionListener (this);
buttonPanel.add (fasterButton);
// button 3
reverseButton.addActionListener (this);
buttonPanel.add (reverseButton);
// button 4
pauseResumeButton.addActionListener (this);
buttonPanel.add (pauseResumeButton);
mainPanel.add(buttonPanel);
add(mainPanel);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setVisible (true);
pack();
timer = new Timer(DELAY,this); // setting timer delay
timer.start(); // start the timer
}
public void switchDove() {
++doveIndex;
if (doveIndex >= IMAGEAMT)
doveIndex = 0;
if (isRight)
dove = doveRight[doveIndex];
else
dove = doveLeft[doveIndex];
dove = (isRight) ? doveRight[doveIndex] : doveLeft[doveIndex];
}
/** Handler for button clicks and timer events */
public void actionPerformed (ActionEvent evt) {
if (evt.getSource() == slowerButton)
{
DELAY += 10;
}
else if (evt.getSource() == reverseButton)
{
if(evt.getSource() == reverseButton && isRight == true){
isRight = false;
}
else if(evt.getSource() == reverseButton && !isRight){
isRight = true;
}
}
else if (evt.getSource() == fasterButton)
{
DELAY -= 10;
if (DELAY <= 10 ){
DELAY = 10;
}
}
else if (evt.getSource() == pauseResumeButton)
{
if(evt.getSource() == pauseResumeButton && !pause){
pauseResumeButton.setText(" Resume ");
timer.stop();
pause = true;
}
else if(evt.getSource() == pauseResumeButton && pause == true){
pauseResumeButton.setText(" Pause ");
timer.start();
pause = false;
}
}
else if (evt.getSource() == timer)
{
drawAnimation();
switchDove();
repaint();
}
}
/** Draws the dove in the dovePanel */
public void drawAnimation() {
Graphics page = dovePanel.getGraphics();
page.drawImage(dove,0,0,Color.WHITE,null);
}
/** The main method */
public static void main (String [] args) {
new DoveAnimator();
}
}
Yep it seems to be one of your repaint() calls. Take out your repaint() method call here:
else if (evt.getSource() == timer)
{
drawAnimation();
switchDove();
repaint();
It's confusing the program because you are already switching the doves. That's my best guess. I ran it and it seems to work though. Cheers!
Also I just noticed that the way you are adjusting your timer will yeild you no results. You need to use the command: timer.setDelay(newDelay); you can also put arguments in the parenthesis like timer.setDelay(DELAY -= 10);
I am having Images stored in SD Card and using that images i wish to run an animation. I am using the following code for this but my animation is not working at all.
Code Snippet
playAnimation("xxx", medid, 25);//calling method
break;
public void playAnimation(String string, int medid2, int length) {
// TODO Auto-generated method stub
animation = new AnimationDrawable();
Bitmap bitMap;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2; //reduce quality
player = MediaPlayer.create(this.getApplicationContext(), medid2);
try {
for (int i = 0; i <= length; i++) {
System.out.println("File Name : - " + Environment.getExternalStorageDirectory().toString() + "/" + string + i);
bitMap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().toString() + "/" + string + i);
Drawable bmp = new BitmapDrawable(bitMap);
animation.addFrame(bmp, DURATION);
}
animation.setOneShot(true);
animation.setVisible(true, true);
int frames = animation.getNumberOfFrames();
System.out.println("Number of Frames are - " + frames);
img.setBackgroundDrawable(animation);
img.post(new Starter());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
class Starter implements Runnable {
public void run() {
try {
if(animation.isRunning()) {
animation.stop();
animation.start();
if (player.isPlaying()) {
player.stop();
player.start();
}
else {
player.start();
}
} else {
animation.start();
if (player.isPlaying()) {
player.stop();
player.start();
}
else {
player.start();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
Using concept of Frame Animation i need to run my animation. I am able fetch images as i have done some debugging but when i click on button and this methods are called my screen is not displaying any animation. It just display black screen only. I am not getting any error in this. If anyone having idea please kindly let me know.
Thanks
An AnimationDrawable just shows black screen, may be caused by different reasons. For example, in the Android Dev Guide, Drawable Animation, the following code lets you load a series of Drawable resources.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
rocketImage.setBackgroundResource(R.drawable.rocket_thrust);
rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
}
However, if you set resource after getBackground() like the following code, the screen will keep black.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
rocketImage.setBackgroundResource(R.drawable.rocket_thrust);
}
If you want to load images from SD card, and show them as animation, you can refer to the following code. I write and test on API 8 (2.3).
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showedImage = (ImageView) findViewById(R.id.imageView_showedPic);
showedImage.setBackgroundResource(R.drawable.slides);
frameAnimation = (AnimationDrawable) showedImage.getBackground();
addPicturesOnExternalStorageIfExist();
}
#Override
public void onWindowFocusChanged (boolean hasFocus){
super.onWindowFocusChanged (hasFocus);
frameAnimation.start();
}
private void addPicturesOnExternalStorageIfExist() {
// check if external storage
String state = Environment.getExternalStorageState();
if ( !(Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) ) {
return;
}
// check if a directory named as this application
File rootPath = Environment.getExternalStorageDirectory();
// 'happyShow' is the name of directory
File pictureDirectory = new File(rootPath, "happyShow");
if ( !pictureDirectory.exists() ) {
Log.d("Activity", "NoFoundExternalDirectory");
return;
}
// check if there is any picture
//create a FilenameFilter and override its accept-method
FilenameFilter filefilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.endsWith(".jpeg") ||
name.endsWith(".jpg") ||
name.endsWith(".png") );
}
};
String[] sNamelist = pictureDirectory.list(filefilter);
if (sNamelist.length == 0) {
Log.d("Activity", "No pictures in directory.");
return;
}
for (String filename : sNamelist) {
Log.d("Activity", pictureDirectory.getPath() + '/' + filename);
frameAnimation.addFrame(
Drawable.createFromPath(pictureDirectory.getPath() + '/' + filename),
DURATION);
}
return;
}