Could some one help me with my Runnable. I have tried 3 different ways to handle this but I still can not seem to figure it out - multithreading

my problem is in the onClick method. I just can't seem to figure out the how to properly construct a running Runnable/Thread/Handler.
package sed.jeff.conversion;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity
{
private static final String TAG = "MainActivity";
Button btConvert;
EditText etInitialValue;
TextView tvAnswer;
Spinner spInitialType, spFinalType;
int mInitialValue, mInitialType, mFinalValue, mFinalType, mRegion = 0;
Distance D1;
Handler handler;
Runnable r;
//initialization
#Override
protected void onCreate(Bundle savedInstanceState)
{
Log.i(TAG, "entered onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btConvert = (Button)findViewById(R.id.btnConvert);
etInitialValue = (EditText)findViewById(R.id.etInitialValue);
spInitialType = (Spinner)findViewById(R.id.spInitialType);
spFinalType = (Spinner)findViewById(R.id.spFinalType);
D1 = new Distance();
}
//implementation
protected void onStart()
{
Log.i(TAG, "entered onStart()");
super.onStart();
spInitialType.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// TODO Auto-generated method stub
Log.i(TAG, "Initial Type position 1: " + position);
mInitialType = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
// TODO Auto-generated method stub
}
});
spFinalType.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// TODO Auto-generated method stub
Log.i(TAG, "Initial Type position 2: " + position);
mFinalType = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
// TODO Auto-generated method stub
}
});
btConvert.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Log.i(TAG, "entered onClick()");
handler = new Handler();
r = new Runnable()
{
#Override
public void run()
{
tvAnswer.setText(D1.getAnswer(mRegion, mInitialType, mFinalType, Double.parseDouble(etInitialValue.getText().toString())));
handler.post(this);
}
};
handler.post(r);
}
});
}
}
This is the class I am using to do the conversion. The only important methods here as of right now are the constructor with no inputs and the String getAnswer() method.
package sed.jeff.conversion;
public class Distance
{
double league, mile, yard, feet, inch, line, thou;
double decameter, hectometer, kilometer, megameter, meter, decimeter, centermeter, micrometer;
double fathom, nauticalMile;
double chain, rod;
double furlong, horseLength;
double hubbleLength, parsec, lightYear, astronomicalUnit;
/*(
private static double[] THOU = {1, 83.333333, 1000, 12000, 36000, 63360000, 190080000};
private static double[] LINE = {.012, 1, 12, 144, 432, 760320, 2280960};
private static double[] INCH = {.001, .083333, 1, 12, 36, 63360, 190080};
private static double[] FOOT = {.000083, .006944, .083333, 1, 3, 5280, 15840};
private static double[] YARD = {.000028, .002315, .027778, .333333, 1, 1760, 5280};
private static double[] MILE = {.00000001578, .000001315, .0000157828, .00018939, .0005681818, 1, 3};
private static double[] LEAGUE = {.00000000526, .00000043841, .00000526094, .00006313131, .0001893939, .33333333, 1};
*/
private static double[][] CONVERSION_USA = {{1, 83.333333, 1000, 12000, 36000, 63360000, 190080000},
{.012, 1, 12, 144, 432, 760320, 2280960},
{.001, .083333, 1, 12, 36, 63360, 190080},
{.000083, .006944, .083333, 1, 3, 5280, 15840},
{.000028, .002315, .027778, .333333, 1, 1760, 5280},
{.00000001578, .000001315, .0000157828, .00018939, .0005681818, 1, 3},
{.00000000526, .00000043841, .00000526094, .00006313131, .0001893939, .33333333, 1}
};
public double[] answer;
public Distance()
{
answer = new double[7];
}
public Distance(int type, int initialMeasurement, double value)
{
answer = new double[7];
switch(type)
{
case 0:
uSMeasurments(initialMeasurement, value);
break;
}
}
private void uSMeasurments(int initialType, double value)
{
for(int i = 0; i < 7; i++ )
{
answer[i] = CONVERSION_USA[initialType][i] * value;
}
}
public String getAnswer(int region, int initialType, int finalType, double value)
{
String answer = null;
switch(region)
{
case 0:
answer = Double.toString(CONVERSION_USA[initialType][finalType] * value);
break;
}
return answer;
}
public String toString()
{
String finalAnswer = "";
for(int i = 0; i < 7; i++ )
{
finalAnswer += answer[i] + " ";
}
return finalAnswer;
}
}

In this case i do not think that you need to use a handler.
Otherwise a proper way would be to do something on these lines:
Runnable r=new Runnable() {
#Override
public void run() {
tvAnswer.setText(D1.getAnswer(mRegion, mInitialType, mFinalType, Double.parseDouble(etInitialValue.getText().toString())));
}
};
handler.post(r);

Related

caling fragment method inside adapter but my value going null what should add?

This is my CartAdapter I called GetCart function in this adapter my function is calling successfully but my orgmst id and userid going null to database.
quantity.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
new GetUpdateQuantity().execute();
TwoFragment fragment = new TwoFragment();
fragment.Getcart();
if (quantity.length() == 0) {
} else {
quan = Double.parseDouble(quantity.getText().toString());
rate = Double.parseDouble(rate1.getText().toString());
total1 = Double.parseDouble(String.valueOf(rate * quan));
// convert double to string to get value
String show = Double.toString(total1);
//show in Textview
total.setText(show);
Log.d("<<<hcvyd", "" + show);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
----------
In myfragment i create method to send data to webservice this method i call in GetCart function then this function call inside adapter
MyFragment
'''GetCart Function'''
public void Getcart(){
String gh = orgmstid;
String hj = userid;
new GetCartItems().execute();
}
private class GetCartItems extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall("VIEW_CART", "F", "" + 'N' + "~" + orgmstid + "~" + userid);
Code for background CAll
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.os.AsyncTask;
import android.util.Log;
public class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... f_url) {
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
byte data[] = new byte[1024];
String file_string = "";
while ((count = input.read(data)) != -1) {
for (int i = 0; i < count; i++) {
file_string += (char) data[i];
}
}
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
// dismissDialog(progress_bar_type);
}
}
Code for calling
new DownloadFileFromURL().execute("URL");

JavaFX 2 TableView how to update cell when object is changed

I'm creating a TableView to show information regarding a list of custom objects (EntityEvents).
The table view must have 2 columns.
First column to show the corresponding EntityEvent's name.
The second column would display a button. The button text deppends on a property of the EntityEvent. If the property is ZERO, it would be "Create", otherwise "Edit".
I managed to do it all just fine, except that I can't find a way to update the TableView line when the corresponding EntityEvent object is changed.
Very Important: I can't change the EntityEvent class to use JavaFX properties, since they are not under my control. This class uses PropertyChangeSupport to notify listeners when the monitored property is changed.
Note:
I realize that adding new elements to the List would PROBABLY cause the TableView to repaint itself, but that is not what I need. I say PROBABLY because I've read about some bugs that affect this behavior.
I tried using this approach to force the repaint, by I couldn't make it work.
Does anyone knows how to do it?
Thanks very much.
Here is a reduced code example that illustrates the scenario:
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javafx.application.Application;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Callback;
public class Main extends Application {
//=============================================================================================
public class EntityEvent {
private String m_Name;
private PropertyChangeSupport m_NamePCS = new PropertyChangeSupport(this);
private int m_ActionCounter;
private PropertyChangeSupport m_ActionCounterPCS = new PropertyChangeSupport(this);
public EntityEvent(String name, int actionCounter) {
m_Name = name;
m_ActionCounter = actionCounter;
}
public String getName() {
return m_Name;
}
public void setName(String name) {
String lastName = m_Name;
m_Name = name;
System.out.println("Name changed: " + lastName + " -> " + m_Name);
m_NamePCS.firePropertyChange("Name", lastName, m_Name);
}
public void addNameChangeListener(PropertyChangeListener listener) {
m_NamePCS.addPropertyChangeListener(listener);
}
public int getActionCounter() {
return m_ActionCounter;
}
public void setActionCounter(int actionCounter) {
int lastActionCounter = m_ActionCounter;
m_ActionCounter = actionCounter;
System.out.println(m_Name + ": ActionCounter changed: " + lastActionCounter + " -> " + m_ActionCounter);
m_ActionCounterPCS.firePropertyChange("ActionCounter", lastActionCounter, m_ActionCounter);
}
public void addActionCounterChangeListener(PropertyChangeListener listener) {
m_ActionCounterPCS.addPropertyChangeListener(listener);
}
}
//=============================================================================================
private class AddPersonCell extends TableCell<EntityEvent, String> {
Button m_Button = new Button("Undefined");
StackPane m_Padded = new StackPane();
AddPersonCell(final TableView<EntityEvent> table) {
m_Padded.setPadding(new Insets(3));
m_Padded.getChildren().add(m_Button);
m_Button.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent actionEvent) {
// Do something
}
});
}
#Override protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setGraphic(m_Padded);
m_Button.setText(item);
}
}
}
//=============================================================================================
private ObservableList<EntityEvent> m_EventList;
//=============================================================================================
#SuppressWarnings("unchecked")
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Table View test.");
VBox container = new VBox();
m_EventList = FXCollections.observableArrayList(
new EntityEvent("Event 1", -1),
new EntityEvent("Event 2", 0),
new EntityEvent("Event 3", 1)
);
final TableView<EntityEvent> table = new TableView<EntityEvent>();
table.setItems(m_EventList);
TableColumn<EntityEvent, String> eventsColumn = new TableColumn<>("Events");
TableColumn<EntityEvent, String> actionCol = new TableColumn<>("Actions");
actionCol.setSortable(false);
eventsColumn.setCellValueFactory(new Callback<CellDataFeatures<EntityEvent, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<EntityEvent, String> p) {
EntityEvent event = p.getValue();
event.addActionCounterChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent event) {
// TODO: I'd like to update the table cell information.
}
});
return new ReadOnlyStringWrapper(event.getName());
}
});
actionCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<EntityEvent, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<EntityEvent, String> ev) {
String text = "NONE";
if(ev.getValue() != null) {
text = (ev.getValue().getActionCounter() != 0) ? "Edit" : "Create";
}
return new ReadOnlyStringWrapper(text);
}
});
// create a cell value factory with an add button for each row in the table.
actionCol.setCellFactory(new Callback<TableColumn<EntityEvent, String>, TableCell<EntityEvent, String>>() {
#Override
public TableCell<EntityEvent, String> call(TableColumn<EntityEvent, String> personBooleanTableColumn) {
return new AddPersonCell(table);
}
});
table.getColumns().setAll(eventsColumn, actionCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
// Add Resources Button
Button btnInc = new Button("+");
btnInc.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent ev) {
System.out.println("+ clicked.");
EntityEvent entityEvent = table.getSelectionModel().getSelectedItem();
if (entityEvent == null) {
System.out.println("No Event selected.");
return;
}
entityEvent.setActionCounter(entityEvent.getActionCounter() + 1);
// TODO: I expected the TableView to be updated since I modified the object.
}
});
// Add Resources Button
Button btnDec = new Button("-");
btnDec.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent ev) {
System.out.println("- clicked.");
EntityEvent entityEvent = table.getSelectionModel().getSelectedItem();
if (entityEvent == null) {
System.out.println("No Event selected.");
return;
}
entityEvent.setActionCounter(entityEvent.getActionCounter() - 1);
// TODO: I expected the TableView to be updated since I modified the object.
}
});
container.getChildren().add(table);
container.getChildren().add(btnInc);
container.getChildren().add(btnDec);
Scene scene = new Scene(container, 300, 600, Color.WHITE);
primaryStage.setScene(scene);
primaryStage.show();
}
//=============================================================================================
public Main() {
}
//=============================================================================================
public static void main(String[] args) {
launch(Main.class, args);
}
}
Try the javafx.beans.property.adapter classes, particularly JavaBeanStringProperty and JavaBeanIntegerProperty. I haven't used these, but I think you can do something like
TableColumn<EntityEvent, Integer> actionCol = new TableColumn<>("Actions");
actionCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<EntityEvent, Integer> ev) {
return new JavaBeanIntegerPropertyBuilder().bean(ev.getValue()).name("actionCounter").build();
});
// ...
public class AddPersonCell extends TableCell<EntityEvent, Integer>() {
final Button button = new Button();
public AddPersonCell() {
setPadding(new Insets(3));
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
button.setOnAction(...);
}
#Override
public void updateItem(Integer actionCounter, boolean empty) {
if (empty) {
setGraphic(null);
} else {
if (actionCounter.intValue()==0) {
button.setText("Create");
} else {
button.setText("Add");
}
setGraphic(button);
}
}
}
As I said, I haven't used the Java bean property adapter classes, but the idea is that they "translate" property change events to JavaFX change events. I just typed this in here without testing, but it should at least give you something to start with.
UPDATE: After a little experimenting, I don't think this approach will work if your EntityEvent is really set up the way you showed it in your code example. The standard Java beans bound properties pattern (which the JavaFX property adapters rely on) has a single property change listener and an addPropertyChangeListener(...) method. (The listeners can query the event to see which property changed.)
I think if you do
public class EntityEvent {
private String m_Name;
private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private int m_ActionCounter;
public EntityEvent(String name, int actionCounter) {
m_Name = name;
m_ActionCounter = actionCounter;
}
public String getName() {
return m_Name;
}
public void setName(String name) {
String lastName = m_Name;
m_Name = name;
System.out.println("Name changed: " + lastName + " -> " + m_Name);
pcs.firePropertyChange("name", lastName, m_Name);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcs.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcs.removePropertyChangeListener(listener);
}
public int getActionCounter() {
return m_ActionCounter;
}
public void setActionCounter(int actionCounter) {
int lastActionCounter = m_ActionCounter;
m_ActionCounter = actionCounter;
System.out.println(m_Name + ": ActionCounter changed: " + lastActionCounter + " -> " + m_ActionCounter);
pcs.firePropertyChange("ActionCounter", lastActionCounter, m_ActionCounter);
}
}
it will work with the adapter classes above. Obviously, if you have existing code calling the addActionChangeListener and addNameChangeListener methods you would want to keep those existing methods and the existing property change listeners, but I see no reason you can't have both.

SwingWorker Cancel Action

i've looking for How to cancel my thread, found some answers but it didn't help me.
My app needs to go from 0-X and by pressing Cancel button the thread is canceled and update Atual Label value with the last counting number.
Again: I've found some examples and explications and didn't help me, so please, do not post another post example.
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class SwingWorker extends JFrame {
Thread worker=new Thread();
boolean parar=false;
int em;
public int quantos;
public int sleep;
private JLabel contador = new JLabel("0");
private JLabel statusLabel = new JLabel("N\u00E3o completado");
private JButton startButton = new JButton("Iniciar");
private JLabel atual = new JLabel("0");
JButton btnNewButton = new JButton("Cancelar");
JLabel lblltimoNmero = new JLabel("\u00DAltimo n\u00FAmero");
public SwingWorker(String title) {
super(title);
setTitle("Contador do n\u00FAmero!");
getContentPane().setLayout(null);
contador.setBounds(106, 97, 48, 37);
contador.setFont(new Font("serif", Font.BOLD, 28));
getContentPane().add(contador);
statusLabel.setBounds(76, 155, 139, 14);
getContentPane().add(statusLabel);
startButton.setBounds(35, 210, 79, 23);
getContentPane().add(startButton);
//Button cancelar
btnNewButton.setBounds(118, 210, 100, 23);
getContentPane().add(btnNewButton);
btnNewButton.setEnabled(false);
btnNewButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
parar=true;
atual.setText(""+(em-1));
//----------------------------------------
// Worker cancel action
//worker.cancel();
//-------------------------
}
});
lblltimoNmero.setBounds(10, 288, 110, 14);
getContentPane().add(lblltimoNmero);
atual.setFont(new Font("Serif", Font.BOLD, 28));
atual.setBounds(106, 269, 59, 37);
getContentPane().add(atual);
JButton btnQuantosNmeros = new JButton("Ir at\u00E9");
btnQuantosNmeros.setBounds(35, 244, 79, 23);
getContentPane().add(btnQuantosNmeros);
JButton btnSleepPor = new JButton("Sleep por");
btnSleepPor.setBounds(118, 244, 89, 23);
getContentPane().add(btnSleepPor);
btnSleepPor.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
sleep =Integer.parseInt(JOptionPane.showInputDialog("Thread dormir por(ms): "));
startButton.setEnabled(true);
}
});
btnQuantosNmeros.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
quantos =Integer.parseInt(JOptionPane.showInputDialog("Ir até o número :"));
}
});
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnNewButton.setEnabled(true);
start();
startButton.setEnabled(false);
}
});
setSize(244, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
JOptionPane.showMessageDialog(null, "Clique em -Ir até- e em -Sleep por-");
}
private void start() {
worker = new Thread() {
public void run() {
if(quantos!=0){
for(int i=0; i<=quantos; i++) {
final int count = i;
em++;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
contador.setText(Integer.toString(count));
}
});
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
}
}}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
statusLabel.setText("Completo");
startButton.setEnabled(true);
atual.setText(Integer.toString( em-1 ));
em=0;
parar=false;
}
});
}
};
worker.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new SwingWorker("SwingWorker");
}
});
}
}
The correct way to use SwingWorker is to make a subclass of it and override its doInBackground method. See the tutorial for an example: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/simple.html, as well as the tutorial on canceling a SwingWorker: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/cancel.html.
You've created a subclass of JFrame and just named it SwingWorker, so I don't quite understand what you're trying to do. You should possibly find some tutorials on how inheritance works in Java, such as http://docs.oracle.com/javase/tutorial/java/IandI/index.html.

Java Painting issues

I need help with a "paint" program. I've got the GUI established, but I'm having issues with the actual drawing portion of the program. Everything I draw disappears immediately after I draw it, and I can't figure out why.
Here is what I have so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPaint extends JFrame implements ActionListener, MouseListener, MouseMotionListener {
int x, y, x2, y2;
private int select = 0;
private Graphics g;
private PaintPanel DrawPanel = new PaintPanel(this);
private JPanel ButtonPanel = new JPanel();
private JTextArea Draw = new JTextArea(20,20);
private JButton jbtRed = new JButton("Red");
private JButton jbtGreen = new JButton("Green");
private JButton jbtBlue = new JButton("Blue");
private JButton jbtErase = new JButton("Eraser");
private JButton jbtClear = new JButton("Clear");
PaintPanel l=new PaintPanel(this);
public JPaint(){
super("Java Paint");
setSize(480,320);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//build draw panel
DrawPanel.setBackground(Color.WHITE);
add(DrawPanel, BorderLayout.CENTER);
DrawPanel.setVisible(true);
//build button panel
ButtonPanel.add(jbtRed);
ButtonPanel.add(jbtGreen);
ButtonPanel.add(jbtBlue);
ButtonPanel.add(jbtErase);
ButtonPanel.add(jbtClear);
add(ButtonPanel, BorderLayout.SOUTH);
ButtonPanel.setVisible(true);
jbtRed.addActionListener(this);
jbtGreen.addActionListener(this);
jbtBlue.addActionListener(this);
jbtErase.addActionListener(this);
jbtClear.addActionListener(this);
DrawPanel.addMouseMotionListener(this);
DrawPanel.addMouseListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == jbtRed){
DrawPanel.setToolTipText("Color set to 'Red'");
select = 1;
}
if(e.getSource() == jbtGreen){
DrawPanel.setToolTipText("Color set to 'Green'");
}
if(e.getSource() == jbtBlue){
DrawPanel.setToolTipText("Color set to 'Blue'");
}
if(e.getSource() == jbtErase){
DrawPanel.setToolTipText("Erase Selected");
}
if(e.getSource() == jbtClear){
DrawPanel.setToolTipText("Drawing cleared");
}
}
#Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
DrawPanel.repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
#Override
public void mouseReleased(MouseEvent e) {
x2 = e.getX();
y2 = e.getY();
DrawPanel.repaint();
}
}
class PaintPanel extends JPanel
{
JPaint p;
PaintPanel(JPaint in){
p=in;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// clear the screen
g.setColor(Color.white);
g.setColor(Color.RED);
g.drawLine(p.x, p.y, p.x2, p.y2);
p.x2 = p.x;
p.y2 = p.y;
}
}
class Run_JPaint {
public static void main(String[] args){
JPaint P = new JPaint();
P.setVisible(true);
}
}
You would probably want to remove the following line of code:
super.paintComponent(g);
from inside your PaintPanel class. Otherwise with each draw command your GUI resets the screen.
Good Luck!

implementing grid view with in a horizontal scroll(view flipper)

i want to implement a horizontal slide to my grid view so that one slide displays 9 images and next slide displays the other 9 images and so on. The images here are took from sd card. can any one help out please..!!
after a trying for a long time i got the right code as
package flipper.view;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
public class NewflipperActivity extends Activity implements OnClickListener,OnTouchListener{
ViewFlipper flip;
Animation animFlipInForeward;
Animation animFlipOutForeward;
Animation animFlipInBackward;
Animation animFlipOutBackward;
int filepos=0;
int y;
private GestureDetector gestureDetector;
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
RelativeLayout rl1,rl2;
TextView tv1,tv2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Display dip=getWindowManager().getDefaultDisplay();
int width=dip.getWidth();
int actualheight=dip.getHeight();
System.out.println("width is--->"+width);
System.out.println("height is--->"+actualheight);
int layoutheight=(actualheight)/8;
int flipheight=6*layoutheight;
RelativeLayout.LayoutParams params1=new RelativeLayout.LayoutParams(width,layoutheight-30);
params1.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
tv1=(TextView)findViewById(R.id.textView1);
tv1.setLayoutParams(params1);
RelativeLayout.LayoutParams params2=new RelativeLayout.LayoutParams(width,layoutheight-30);
params2.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
tv2=(TextView)findViewById(R.id.textView2);
tv2.setLayoutParams(params2);
gestureDetector = new GestureDetector(new MyGestureDetector());
flip=(ViewFlipper)findViewById(R.id.viewFlipper1);
flip.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return false;
}
return true;
}
});
LinearLayout mylay=(LinearLayout)findViewById(R.id.linearlay);
LinearLayout.LayoutParams layparam=new LinearLayout.LayoutParams(width,flipheight);
mylay.setLayoutParams(layparam);
animFlipInForeward = AnimationUtils.loadAnimation(this, R.anim.flipin);
animFlipOutForeward = AnimationUtils.loadAnimation(this, R.anim.flipout);
animFlipInBackward = AnimationUtils.loadAnimation(this, R.anim.flipin_reverse);
animFlipOutBackward = AnimationUtils.loadAnimation(this, R.anim.flipout_reverse);
String folderpath=Environment.getExternalStorageDirectory()+"/New Folder/";
File filepath=new File(folderpath);
File[] mylist=filepath.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
// TODO Auto-generated method stub
return (filename.toLowerCase().endsWith(".jpg")||filename.toLowerCase().endsWith(".png")||filename.toLowerCase().endsWith(".jpeg"));
}
});
Arrays.sort(mylist);
int folderlength=mylist.length;
int mylength=folderlength/9;
if(folderlength%9==0)
{
y=mylength;
}
else
{
y=(mylength)+1;
}
for(int i=0;i<y;i++)
{System.out.println("abc"+i);
TableLayout mtable=new TableLayout(this);
TableLayout.LayoutParams myparams=new TableLayout.LayoutParams(width,flipheight);
mtable.setLayoutParams(myparams);
mtable.setWeightSum(3);
mtable.setOnTouchListener(NewflipperActivity.this);
for(int j=0;j<3;j++)
{
TableRow mrow=new TableRow(this);
mrow.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
mrow.setOnTouchListener(NewflipperActivity.this);
for(int k=0;k<3;k++)
{
if(filepos<folderlength)
{
Log.i("displaying","image at file pos"+mylist[filepos]);
final ImageView imageView = new ImageView(this);
Bitmap imgBitmap,b1;
try
{
if(mylist[filepos].length()>1500){
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inSampleSize = 4;
imgBitmap = BitmapFactory.decodeFile(mylist[filepos] + "",bounds);
b1=Bitmap.createScaledBitmap(imgBitmap, ((int)(width/3))-20, ((int)(flipheight/3))-20, true);
}
else
{
imgBitmap=BitmapFactory.decodeFile(mylist[filepos] + "");
b1=Bitmap.createScaledBitmap(imgBitmap, ((int)(width/3))-20,((int)(flipheight/3))-20, true);
}
imageView.setImageBitmap(b1);
imageView.setAdjustViewBounds(true);
imageView.setPadding(10,10,10,10);
imageView.setTag(mylist[filepos]+"");
imageView.setOnTouchListener(NewflipperActivity.this);
imageView.setOnClickListener(NewflipperActivity.this);
// final String imagename=mylist[filepos].getName();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
mrow.addView(imageView);
filepos++;
}
}
mtable.addView(mrow);
}
flip.addView(mtable);
}
}
private void SwipeRight(){
flip.setInAnimation(animFlipInBackward);
flip.setOutAnimation(animFlipOutBackward);
flip.showPrevious();
}
private void SwipeLeft(){
flip.setInAnimation(animFlipInForeward);
flip.setOutAnimation(animFlipOutForeward);
flip.showNext();
}
class MyGestureDetector extends SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(NewflipperActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show();
SwipeLeft();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(NewflipperActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show();
SwipeRight();
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
#Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ImageView imagename1 = (ImageView)v;
String imgName = (String) imagename1.getTag();
Toast.makeText(NewflipperActivity.this, "clicked on image-->"+imgName, Toast.LENGTH_SHORT).show();
Log.e("displaying","clicked onimage::::::"+imgName);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
}

Resources