Search Results

Search found 514 results on 21 pages for 'runnable'.

Page 15/21 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • Java's Swing Threading

    - by nevets1219
    My understanding is that if I start up another thread to perform some actions, I would need to SwingUtilities.invokeAndWait or SwingUtilities.invokeLater to update the GUI while I'm in said thread. Please correct me if I'm wrong. What I'm trying to accomplish is relatively straightforward: when the user clicks submit, I want to (before performing any actions) disable the submit button, perform the action, and at the end of the action re-enable the button. My method to perform the action updates the GUI directly (displays results) when it gets the results back. This action basically queries a server and gets some results back. What I have so far is: boolean isRunning = false; synchronized handleButtonClick() { if ( isRunning == false ) { button.setEnabled( false ); isRunning = true; doAction(); } } doAction() { new Thread() { try { doAction(); // Concern A } catch ( ... ) { displayStackTrace( ... ); // Concern B } finally { SwingUtilities.invokeLater ( /* simple Runnable to enable button */ ); isRunning = false; } } } For both of my concerns above, do I would have to use SwingUtilities.invokeAndWait since they both will update the GUI? All GUI updates revolve around updating JTextPane. Do I need to in my thread check if I'm on EDT and if so I can call my code (regardless of whether it updates the GUI or not) and NOT use SwingUtilities.invokeAndWait?

    Read the article

  • Simple Physics Simulation in java not working.

    - by Static Void Main
    Dear experts, I wanted to implement ball physics and as i m newbie, i adapt the code in tutorial http://adam21.web.officelive.com/Documents/JavaPhysicsTutorial.pdf . i try to follow that as i much as i can, but i m not able to apply all physical phenomenon in code, can somebody please tell me, where i m mistaken or i m still doing some silly programming mistake. The balls are moving when i m not calling bounce method and i m unable to avail the bounce method and ball are moving towards left side instead of falling/ending on floor**, Can some body recommend me some better way or similar easy compact way to accomplish this task of applying physics on two ball or more balls with interactivity. here is code ; import java.awt.*; public class AdobeBall { protected int radius = 20; protected Color color; // ... Constants final static int DIAMETER = 40; // ... Instance variables private int m_x; // x and y coordinates upper left private int m_y; private double dx = 3.0; // delta x and y private double dy = 6.0; private double m_velocityX; // Pixels to move each time move() is called. private double m_velocityY; private int m_rightBound; // Maximum permissible x, y values. private int m_bottomBound; public AdobeBall(int x, int y, double velocityX, double velocityY, Color color1) { super(); m_x = x; m_y = y; m_velocityX = velocityX; m_velocityY = velocityY; color = color1; } public double getSpeed() { return Math.sqrt((m_x + m_velocityX - m_x) * (m_x + m_velocityX - m_x) + (m_y + m_velocityY - m_y) * (m_y + m_velocityY - m_y)); } public void setSpeed(double speed) { double currentSpeed = Math.sqrt(dx * dx + dy * dy); dx = dx * speed / currentSpeed; dy = dy * speed / currentSpeed; } public void setDirection(double direction) { m_velocityX = (int) (Math.cos(direction) * getSpeed()); m_velocityY = (int) (Math.sin(direction) * getSpeed()); } public double getDirection() { double h = ((m_x + dx - m_x) * (m_x + dx - m_x)) + ((m_y + dy - m_y) * (m_y + dy - m_y)); double a = (m_x + dx - m_x) / h; return a; } // ======================================================== setBounds public void setBounds(int width, int height) { m_rightBound = width - DIAMETER; m_bottomBound = height - DIAMETER; } // ============================================================== move public void move() { double gravAmount = 0.02; double gravDir = 90; // The direction for the gravity to be in. // ... Move the ball at the give velocity. m_x += m_velocityX; m_y += m_velocityY; // ... Bounce the ball off the walls if necessary. if (m_x < 0) { // If at or beyond left side m_x = 0; // Place against edge and m_velocityX = -m_velocityX; } else if (m_x > m_rightBound) { // If at or beyond right side m_x = m_rightBound; // Place against right edge. m_velocityX = -m_velocityX; } if (m_y < 0) { // if we're at top m_y = 0; m_velocityY = -m_velocityY; } else if (m_y > m_bottomBound) { // if we're at bottom m_y = m_bottomBound; m_velocityY = -m_velocityY; } // double speed = Math.sqrt((m_velocityX * m_velocityX) // + (m_velocityY * m_velocityY)); // ...Friction stuff double fricMax = 0.02; // You can use any number, preferably less than 1 double friction = getSpeed(); if (friction > fricMax) friction = fricMax; if (m_velocityX >= 0) { m_velocityX -= friction; } if (m_velocityX <= 0) { m_velocityX += friction; } if (m_velocityY >= 0) { m_velocityY -= friction; } if (m_velocityY <= 0) { m_velocityY += friction; } // ...Gravity stuff m_velocityX += Math.cos(gravDir) * gravAmount; m_velocityY += Math.sin(gravDir) * gravAmount; } public Color getColor() { return color; } public void setColor(Color newColor) { color = newColor; } // ============================================= getDiameter, getX, getY public int getDiameter() { return DIAMETER; } public double getRadius() { return radius; // radius should be a local variable in Ball. } public int getX() { return m_x; } public int getY() { return m_y; } } using adobeBall: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AdobeBallImplementation implements Runnable { private static final long serialVersionUID = 1L; private volatile boolean Play; private long mFrameDelay; private JFrame frame; private MyKeyListener pit; /** true means mouse was pressed in ball and still in panel. */ private boolean _canDrag = false; private static final int MAX_BALLS = 50; // max number allowed private int currentNumBalls = 2; // number currently active private AdobeBall[] ball = new AdobeBall[MAX_BALLS]; public AdobeBallImplementation(Color ballColor) { frame = new JFrame("simple gaming loop in java"); frame.setSize(400, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pit = new MyKeyListener(); pit.setPreferredSize(new Dimension(400, 400)); frame.setContentPane(pit); ball[0] = new AdobeBall(34, 150, 7, 2, Color.YELLOW); ball[1] = new AdobeBall(50, 50, 5, 3, Color.BLUE); frame.pack(); frame.setVisible(true); frame.setBackground(Color.white); start(); frame.addMouseListener(pit); frame.addMouseMotionListener(pit); } public void start() { Play = true; Thread t = new Thread(this); t.start(); } public void stop() { Play = false; } public void run() { while (Play == true) { // bounce(ball[0],ball[1]); runball(); pit.repaint(); try { Thread.sleep(mFrameDelay); } catch (InterruptedException ie) { stop(); } } } public void drawworld(Graphics g) { for (int i = 0; i < currentNumBalls; i++) { g.setColor(ball[i].getColor()); g.fillOval(ball[i].getX(), ball[i].getY(), 40, 40); } } public double pointDistance (double x1, double y1, double x2, double y2) { return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); } public void runball() { while (Play == true) { try { for (int i = 0; i < currentNumBalls; i++) { for (int j = 0; j < currentNumBalls; j++) { if (pointDistance(ball[i].getX(), ball[i].getY(), ball[j].getX(), ball[j].getY()) < ball[i] .getRadius() + ball[j].getRadius() + 2) { // bounce(ball[i],ball[j]); ball[i].setBounds(pit.getWidth(), pit.getHeight()); ball[i].move(); pit.repaint(); } } } try { Thread.sleep(50); } catch (Exception e) { System.exit(0); } } catch (Exception e) { e.printStackTrace(); } } } public static double pointDirection(int x1, int y1, int x2, int y2) { double H = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); // The // hypotenuse double x = x2 - x1; // The opposite double y = y2 - y1; // The adjacent double angle = Math.acos(x / H); angle = angle * 57.2960285258; if (y < 0) { angle = 360 - angle; } return angle; } public static void bounce(AdobeBall b1, AdobeBall b2) { if (b2.getSpeed() == 0 && b1.getSpeed() == 0) { // Both balls are stopped. b1.setDirection(pointDirection(b1.getX(), b1.getY(), b2.getX(), b2 .getY())); b2.setDirection(pointDirection(b2.getX(), b2.getY(), b1.getX(), b1 .getY())); b1.setSpeed(1); b2.setSpeed(1); } else if (b2.getSpeed() == 0 && b1.getSpeed() != 0) { // B1 is moving. B2 is stationary. double angle = pointDirection(b1.getX(), b1.getY(), b2.getX(), b2 .getY()); b2.setSpeed(b1.getSpeed()); b2.setDirection(angle); b1.setDirection(angle - 90); } else if (b1.getSpeed() == 0 && b2.getSpeed() != 0) { // B1 is moving. B2 is stationary. double angle = pointDirection(b2.getX(), b2.getY(), b1.getX(), b1 .getY()); b1.setSpeed(b2.getSpeed()); b1.setDirection(angle); b2.setDirection(angle - 90); } else { // Both balls are moving. AdobeBall tmp = b1; double angle = pointDirection(b2.getX(), b2.getY(), b1.getX(), b1 .getY()); double origangle = b1.getDirection(); b1.setDirection(angle + origangle); angle = pointDirection(tmp.getX(), tmp.getY(), b2.getX(), b2.getY()); origangle = b2.getDirection(); b2.setDirection(angle + origangle); } } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { new AdobeBallImplementation(Color.red); } }); } } *EDIT:*ok splitting the code using new approach for gravity from this forum: this code also not working the ball is not coming on floor: public void mymove() { m_x += m_velocityX; m_y += m_velocityY; if (m_y + m_bottomBound > 400) { m_velocityY *= -0.981; // setY(400 - m_bottomBound); m_y = 400 - m_bottomBound; } // ... Bounce the ball off the walls if necessary. if (m_x < 0) { // If at or beyond left side m_x = 0; // Place against edge and m_velocityX = -m_velocityX; } else if (m_x > m_rightBound) { // If at or beyond right side m_x = m_rightBound - 20; // Place against right edge. m_velocityX = -m_velocityX; } if (m_y < 0) { // if we're at top m_y = 1; m_velocityY = -m_velocityY; } else if (m_y > m_bottomBound) { // if we're at bottom m_y = m_bottomBound - 20; m_velocityY = -m_velocityY; } } thanks a lot for any correction and help. jibby

    Read the article

  • Facebook Android SDK. Error validating access token

    - by Mj1992
    I am trying to access user information from facebook sdk.But I keep getting this error. {"error":{"message":"Error validating access token: The session has been invalidated because the user has changed the password.","type":"OAuthException","code":190,"error_subcode":460}} Here is the call which returns me the error in the response parameter of the oncomplete function. mAsyncRunner.request("me", new RequestListener() { @Override public void onComplete(String response, Object state) { Log.d("Profile", response); String json = response; //<-- error in response try { JSONObject profile = new JSONObject(json); MainActivity.this.userid = profile.getString("id"); new GetUserProfilePic().execute(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Name: " + MainActivity.this.userid, Toast.LENGTH_LONG).show(); } }); } catch (JSONException e) { e.printStackTrace(); Log.e("jsonexception",e.getMessage()); facebook.extendAccessTokenIfNeeded(MainActivity.this, null); GetUserInfo(); } } @Override public void onIOException(IOException e, Object state) { } @Override public void onFileNotFoundException(FileNotFoundException e, Object state) { } @Override public void onMalformedURLException(MalformedURLException e, Object state) { } @Override public void onFacebookError(FacebookError e, Object state) { } }); Sometimes I get the correct response also.I think this is due to the access token expiration if I am right. So can you guys tell me how to extend the access token although I've used this facebook.extendAccessTokenIfNeeded(this, null); in the onResume method of the activity. How to solve this?

    Read the article

  • AudioRecord - empty buffer

    - by Arxas
    I' m trying to record some audio using AudioRecord class. Here is my code: int audioSource = AudioSource.MIC; int sampleRateInHz = 44100; int channelConfig = AudioFormat.CHANNEL_IN_MONO; int audioFormat = AudioFormat.ENCODING_PCM_16BIT; int bufferSizeInShorts = 44100; int bufferSizeInBytes = 2*bufferSizeInShorts; short Data[] = new short[bufferSizeInShorts]; Thread recordingThread; AudioRecord audioRecorder = new AudioRecord(audioSource, sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } public void startRecording(View arg0) { audioRecorder.startRecording(); recordingThread = new Thread(new Runnable() { public void run() { while (Data[bufferSizeInShorts-1] == 0) audioRecorder.read(Data, 0, bufferSizeInShorts); } }); audioRecorder.stop(); } Unfortunately my short array is empty after the recording is over. May I kindly ask you to help me figure out what's wrong?

    Read the article

  • JLabel transparency problem

    - by Rendicahya
    I have a dark-gray JPanel with a JLabel on it. I set new Color(0, 0, 0, .5f) (tranparent) as the background of the JLabel and I change the text several times using a button. The problem is, everytime the text is changed, the previous text still remains behind the new text. I change the text from "123456789" to "1234567", "12345" and "123". Here is the screenshot: How do I get rid of this "shadow"? Here's the code: public class TransparentJLabel extends JFrame { private int i = 0; private String[] value = {"123456789", "1234567", "12345", "123", "1"}; public TransparentJLabel() { setSize(300, 160); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(null); JPanel panel = new JPanel(); panel.setBackground(new Color(102, 102, 102)); panel.setLayout(null); panel.setBounds(0, 0, 300, 160); final JLabel label = new JLabel(); label.setText(value[0]); label.setFont(new Font("Times New Roman", 1, 36)); label.setForeground(new Color(255, 255, 255)); label.setBackground(new Color(0, 0, 0, .5f)); label.setHorizontalAlignment(SwingConstants.CENTER); label.setOpaque(true); label.setBounds(10, 10, 270, 70); JButton button = new JButton(); button.setText("Change"); button.setBounds(100, 90, 90, 25); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { label.setText(value[++i]); } }); panel.add(label); panel.add(button); add(panel); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { new TransparentJLabel().setVisible(true); } }); } }

    Read the article

  • Using an empty column as a divider in a JTable.

    - by Catalina Island
    I'm trying to use an empty column as a divider between pairs of columns in a JTable. Here's a picture and code for what I have so far. I know I can change the look using a custom TableCellRenderer. Before I go down that road, is there a better way to do this? Any ideas appreciated. import javax.swing.*; import javax.swing.table.*; public class TablePanel extends JPanel { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame f = new JFrame("TablePanel"); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.add(new TablePanel()); f.pack(); f.setVisible(true); } }); } public TablePanel() { TableModel dataModel = new MyModel(); JTable table = new JTable(dataModel); table.getColumnModel().getColumn(MyModel.DIVIDER).setMaxWidth(0); JScrollPane jsp = new JScrollPane(table); jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); this.add(jsp); } private static class MyModel extends AbstractTableModel { private static final int DIVIDER = 2; private final String[] names = { "A1", "A2", "", "B1", "B2" }; @Override public int getRowCount() { return 32; } @Override public int getColumnCount() { return names.length; } @Override public String getColumnName(int col) { if (col == DIVIDER) return ""; return names[col]; } @Override public Object getValueAt(int row, int col) { if (col == DIVIDER) return ""; return (row + 1) / 10.0; } @Override public Class<?> getColumnClass(int col) { if (col == DIVIDER) return String.class; return Number.class; } } }

    Read the article

  • Trouble accessing fields of a serialized object in Java

    - by typoknig
    I have instantized a class that implements Serializable and I am trying to stream that object like this: try{ Socket socket = new Socket("localhost", 8000); ObjectOutputStream toServer = new ObjectOutputStream(socket.getOutputStream()); toServer.writeObject(myObject); } catch (IOException ex) { System.err.println(ex); } All good so far right? Then I am trying to read the fields of that object like this: //This is an inner class class HandleClient implements Runnable{ private ObjectInputStream fromClient; private Socket socket; // This socket was established earlier try { fromClient = new ObjectInputStream(socket.getInputStream()); GetField inputObjectFields = fromClient.readFields(); double myFristVariable = inputObjectFields.get("myFirstVariable", 0); int mySecondVariable = inputObjectFields.get("mySecondVariable", 0); //do stuff } catch (IOException ex) { System.err.println(ex); } catch (ClassNotFoundException ex) { System.err.println(ex); } finally { try { fromClient.close(); } catch (Exception ex) { ex.printStackTrace(); } } } But I always get the error: java.io.NotActiveException: not in call to readObject This is my first time streaming objects instead of primitive data types, what am I doing wrong? BONUS When I do get this working correctly, is the ENTIRE CLASS passed with the serialized object (i.e. will I have access to the methods of the object's class)? My reading suggests that the entire class is passed with the object, but I have been unable to use the objects methods thus far. How exactly do I call on the object's methods? In addition to my code above I also experimented with the readObject method, but I was probably using it wrong too because I couldn't get it to work. Please enlighten me.

    Read the article

  • Android: How to periodically check current location without draining the battery

    - by uyahalom
    I have a background service which works periodically by timer.scheduleAtFixedRate. It wakes up every amount of time (let's say 60 seconds for example) and checks for the location. The location is checked by locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, listener); and the actual location is collected from the listener's onLocationChanged. Now, when the phone is outside and GPS reception is good, this works fine. But, if the phone is inside, the GPS is almost always active - looking for a signal, and the battery is drained rapidly. I created another thread using a Handler and a Runnable in order to conrol the GPS active time accurately: I used locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener); and locManager.removeUpdates(listener); so I can open and close the GPS as I want. In this case, I can open the GPS for the exact amount of time, but found out that it doesn't lock in an area with good reception even after 10 seconds. So here I'm draining the battery again... I'm using API level 7, hence I cannot use locationManager.requestSingleUpdate. I have two questions: Is there any way to optimize this process? Will upgrading to API level 9 (and use locationManager.requestSingleUpdate) improve the process significantly? I mean, does it worth upgrading?

    Read the article

  • Java Swing rendering bug on Windows 7 look-and-feel?

    - by John B.
    The knob on vertical JSlider's on my Windows 7 machine (with native look-and-feel) is really, really tiny in both directions. Not just skinny but short as well. Can anyone confirm this? Should I report it? If so, where? Thanks! Here is the code for the sample program (in the screen shot): import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.SwingConstants; import javax.swing.UIManager; public class SliderTest { public static void main( String[] args ) { // Set the look and feel to that of the system try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); } catch ( Exception e ) { System.err.println( e ); } // Launch the GUI from the event dispatch thread javax.swing.SwingUtilities.invokeLater( new Runnable() { public void run () { JFrame window = new JFrame(); window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); JPanel contentPane = new JPanel(); contentPane.add( new JSlider(SwingConstants.HORIZONTAL) ); contentPane.add( new JSlider(SwingConstants.VERTICAL) ); window.setContentPane( contentPane ); window.pack(); window.setLocationRelativeTo( null ); // Center window window.setVisible( true ); } }); } }

    Read the article

  • How to run an async task afor every x mins in android?

    - by Shan
    how to run the async task at specific time? (I want to run it every 2 mins) I tried using post delayed but it's not working? tvData.postDelayed(new Runnable(){ @Override public void run() { readWebpage(); }}, 100); In the above code readwebpage is function which calls the async task for me.. Right now below is the method which I am using public void onCreate(Bundle savedInstanceState) { readwebapage(); } public void readWebpage() { DownloadWebPageTask task = new DownloadWebPageTask(); task.execute("http://www.google.com"); } private class DownloadWebPageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { String response1 = ""; response1=read(); //read is my another function which does the real work response1=read(); super.onPostExecute(response1); return response1; } protected void onPostExecute(String result) { try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } TextView tvData = (TextView) findViewById(R.id.TextView01); tvData.setText(result); DownloadWebPageTask task = new DownloadWebPageTask(); task.execute(new String[] { "http://www.google.com" }); } } This is what I my code is and it works perfectly fine but the big problem I drains my battery?

    Read the article

  • passing reference of class to another class android error

    - by prolink007
    I recently asked the precursor to this question and had a great reply. However, when i was working this into my android application i am getting an unexpected error and was wondering if everyone could take a look at my code and help me see what i am doing wrong. Link to the initial question: passing reference of class to another class My ERROR: "The constructor ConnectDevice(new View.OnClickListener(){}) is undefined" The above is an error detected by eclipse. Thanks in advance! Below are My code snippets: public class SmartApp extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.intro); final Button connectDeviceButton = (Button) findViewById(R.id.connectDeviceButton); connectDeviceButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Thread cThread = new Thread(new ConnectDevice(this)); cThread.start(); } }); } } public class ConnectDevice implements Runnable { private boolean connected; private SmartApp smartAppRef; private ObjectInputStream ois; public ConnectDevice(SmartApp smartAppRef) { this.smartAppRef = smartAppRef; } }

    Read the article

  • C Static Function Confusion

    - by Lime
    I am trying to make the s_cord_print function visible in the cord_s.c file only. Currently the function is visible/runnable in main.c even when it is declared static. How do I make the s_cord_print function private to cord_s.c? Thanks! s_cord.c typedef struct s_cord{ int x; int y; struct s_cord (*print)(); } s_cord; void* VOID_THIS; #define $(EL) VOID_THIS=&EL;EL static s_cord s_cord_print(){ struct s_cord *THIS; THIS = VOID_THIS; printf("(%d,%d)\n",THIS->x,THIS->y); return *THIS; } const s_cord s_cord_default = {1,2,s_cord_print}; main.c #include <stdio.h> #include <stdlib.h> #include "s_cord.c" int main(){ s_cord mycord = s_cord_default; mycord.x = 2; mycord.y = 3; $(mycord).print().print(); //static didn't seem to hide the function s_cord_print(); return 0; } ~

    Read the article

  • Is this use of PreparedStatements in a Thread in JAVA correct?

    - by Gormcito
    I'm still an undergrad just working part time and so I'm always trying to be aware of better ways to do things. Recently I had to write a program for work where the main thread of the program would spawn "task" threads (for each db "task" record) which would perform some operations and then update the record to say that it has finished. Therefore I needed a database connection object and PreparedStatement objects in or available to the ThreadedTask objects. This is roughly what I ended up writing, is creating a PreparedStatement object per thread a waste? I thought static PreparedStatments could create race conditions... Thread A stmt.setInt(); Thread B stmt.setInt(); Thread A stmt.execute(); Thread B stmt.execute(); A´s version never gets execed.. Is this thread safe? Is creating and destroying PreparedStatement objects that are always the same not a huge waste? public class ThreadedTask implements runnable { private final PreparedStatement taskCompleteStmt; public ThreadedTask() { //... taskCompleteStmt = Main.db.prepareStatement(...); } public run() { //... taskCompleteStmt.executeUpdate(); } } public class Main { public static final db = DriverManager.getConnection(...); }

    Read the article

  • Cannot make a static reference to the non-static type MyRunnable

    - by kaiwii ho
    Here is the whole code : import java.util.ArrayList; public class Test{ ThreadLocal<ArrayList<E>>arraylist=new ThreadLocal<ArrayList<E>>(){ @Override protected ArrayList<E> initialValue() { // TODO Auto-generated method stub //return super.initialValue(); ArrayList<E>arraylist=new ArrayList<E>(); for(int i=0;i<=20;i++) arraylist.add((E) new Integer(i)); return arraylist; } }; class MyRunnable implements Runnable{ private Test mytest; public MyRunnable(Test test){ mytest=test; // TODO Auto-generated constructor stub } @Override public void run() { System.out.println("before"+mytest.arraylist.toString()); ArrayList<E>myarraylist=(ArrayList<E>) mytest.arraylist.get(); myarraylist.add((E) new Double(Math.random())); mytest.arraylist.set(myarraylist); System.out.println("after"+mytest.arraylist.toString()); } // TODO Auto-generated method stub } public static void main(String[] args){ Test test=new Test<Double>(); System.out.println(test.arraylist.toString()); new Thread(new MyRunnable(test)).start(); new Thread(new MyRunnable(test)).start(); System.out.println(arraylist.toString()); } } my questions are: 1\ why the new Thread(new MyRunnable(test)).start(); cause the error: Cannot make a static reference to the non-static type MyRunnable ? 2\ what is the static reference refer to right here? thx in advanced

    Read the article

  • (Android) Why won't invalidate() update my buttons immediately?

    - by frustrated user
    I have read several forums and examples on using invalidate() in order to update views immediately but I still do not understand why what I am doing will not work. The code below uses image buttons defined by "red", "blue", "green", and "yellow". I set a 1 second delay between each time I try and change a button's appearance. Please someone tell me what i'm doing wrong. private void showPattern() { if (correct == true) { for (int k = 0; k < temp_basket.length; k++) { if (temp_basket[k] == 0) { red.setPressed(true); red.invalidate(); final Handler handler = new Handler(); Timer t = new Timer(); t.schedule(new TimerTask() { public void run() { handler.post(new Runnable() { public void run() { red.setPressed(false); red.invalidate(); } }); } }, 1000); There are 3 more or these blocks after this one that are blue, green, and yellow.

    Read the article

  • NullPointerException on Activity Testint Tutorial

    - by Bendik
    Hello, I am currently trying the activity testing tutorial (Found here), and have a problem. It seems that whenever I try to call something inside the UIThread, I get a java.lang.NullPointerException. public void testSpinnerUI() { mActivity.runOnUiThread( new Runnable() { public void run() { mSpinner.requestFocus(); } }); } This gives me: Incomplete: java.lang.NullPointerException and nothing else. I have tried this on two different samples now, with the same result. I tried with a try/catch clause around the mSpinner.requestFocus() call, and it seems that mSpinner is null inside the thread. I have set it properly up with the setUp() function found in the same sample, and a quick assertNotNull( mSpinner ) shows me that mSpinner is in fact not null after the setUp() function. What can be the cause of this? EDIT; ok, some more testing has been done. It seems that the application that is being tested resets between each test. This essentially makes me have to reinstantiate all variables between each test. Is this normal?

    Read the article

  • Threading in client-server socket program - proxy sever

    - by crazyTechie
    I am trying to write a program that acts as a proxy server. Proxy server basically listens to a given port (7575) and sends the request to the server. As of now, I did not implement caching the response. The code looks like ServerSocket socket = new ServerSocket(7575); Socket clientSocket = socket.accept(); clientRequestHandler(clientSocket); I changed the above code as below: //calling the same clientRequestHandler method from inside another method. Socket clientSocket = socket.accept(); Thread serverThread = new Thread(new ConnectionHandler(client)); serverThread.start(); class ConnectionHandler implements Runnable { Socket clientSocket = null; ConnectionHandler(Socket client){ this.clientSocket = client; } @Override public void run () { try { PrxyServer.clientRequestHandler(clientSocket); } catch (Exception ex) { ex.printStackTrace(); } } } Using the code, I am able to open a webpage like google. However, if I open another web page even I completely receive the first response, I get connection reset by peer expection. 1. How can I handle this issue Can i use threading to handle different requests. Can someone give a reference where I look for example code that implements threading. Thanks. Thanks.

    Read the article

  • How do I remove an old JPanel and add a new one?

    - by Roman
    I would like to remove an old JPanel from the Window (JFrame) and add a new one. How should I do it? I tried the following: public static void showGUI() { JFrame frame = new JFrame("Colored Trails"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(partnerSelectionPanel); frame.setSize(600,400); frame.setVisible(true); } private static void updateGUI(final int i, final JLabel label, final JPanel partnerSelectionPanel) { SwingUtilities.invokeLater( new Runnable() { public void run() { label.setText(i + " seconds left."); } partnerSelectionPanel.setVisible(false); \\ <------------ } ); } So, my code update the "old" JPanel and them it makes the whole JPanel invisible. It was the idea. But it does not work. The compiler complains about the line indicated with "<------------". It writes: <identifier> expected, illegal start of type.

    Read the article

  • Implementing deadlock condition

    - by Bhaskar
    I am trying to implementing deadlock condition but somehow I am not able to get it working. Both the threads Thread1 and Thread2 are entering in the run function but only one of them enters in Sub/Sum depending on who entered run first. Example : if Thread2 entered run first the it will call sub() and Thread1 never calls sum(). I have also added sleep time so that Thread2 sleeps before calling sum() and Thread1 gets enough time to enter Sum() but Thread1 never enters. public class ExploringThreads { public static void main(String[] args) { // TODO Auto-generated method stub threadexample a1 = new threadexample(); Thread t1 = new Thread(a1, "Thread1"); Thread t2 = new Thread(a1,"Thread2"); t1.start(); t2.start(); } } class threadexample implements Runnable{ public int a = 10; public void run(){ if(Thread.currentThread().getName().equals("Thread1")) sum(); else if(Thread.currentThread().getName().equals("Thread2")) sub(); } public synchronized void sum() { try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"In Sum"); sub(); } public synchronized void sub() { try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"In Sub"); sum(); } }

    Read the article

  • How do I make this Java code operate properly? [Multi-threaded, race condition]

    - by Fixee
    I got this code from a student, and it does not work properly because of a race condition involving x++ and x--. He added synchronized to the run() method trying to get rid of this bug, but obviously this only excludes threads from entering run() on the same object (which was never a problem in the first place) but doesn't prevent independent objects from updating the same static variable x at the same time. public class DataRace implements Runnable { static volatile int x; public synchronized void run() { for (int i = 0; i < 10000; i++) { x++; x--; } } public static void main(String[] args) throws Exception { Thread [] threads = new Thread[100]; for (int i = 0; i < threads.length; i++) threads[i] = new Thread(new DataRace()); for (int i = 0; i < threads.length; i++) threads[i].start(); for (int i = 0; i < threads.length; i++) threads[i].join(); System.out.println(x); // x not always 0! } } Since we cannot synchronize on x (because it is primitive), the best solution I can think of is to create a new static object like static String lock = ""; and enclose the x++ and x-- within a synchronized block, locking on lock. But this seems really awkward. Is there a better way?

    Read the article

  • Why is android:transcriptMode="normal" not working properly?

    - by BCS
    I've been doing a lot of fiddling with an issue I've been having. What happens is each time an item gets added to my listview (adapter) I expect it to auto-scroll if I'm at the last item (which it will do to an extent); HOWEVER, if 3 or more items get added at once, it will not auto-scroll. Here is the XML of that listview: <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1" android:transcriptMode="normal"/> I tried a workaround using a snippet I found here. My code is as follows: public void addChat(final String text, final String username) { this.runOnUiThread(new Runnable() { public void run() { globals.chatAdapter.add(DateFormat.format("hh:mmaa", Calendar.getInstance()).toString(), username, text); globals.chatAdapter.notifyDataSetChanged(); int lastP = getListView().getLastVisiblePosition(); int count = globals.chatAdapter.getCount() - 1; if (lastP == globals.chatAdapter.oldP || lastP == -1) { getListView().setSelection(count); } globals.chatAdapter.oldP = count; } }); } The problem with this is when a bunch of items come in at once, getListView().getLastVisiblePosition() will not update right away causing a setSelection() to never get called, and thus no auto-scroll. Any suggestions?

    Read the article

  • android service using SystemClock.elapsedRealTime() instead of SystemClock.uptimeMillis() works in emulator but not in samsung captivate ?

    - by Aleadam
    First question here in stackoverflow :) I'm running a little android 2.2 app to log cpu frequency usage. It is set up as a service that will write the data every 10 seconds using a new thread. The code for that part is very basic (see below). It works fine, except that it would not keep track of time while the phone is asleep (which, I know, is the expected behavior). Thus, I changed the code to use SystemClock.elapsedRealTime() instead. Problem is, in emulator both commands are equivalent, but in the phone the app will start the thread but it will never execute the mHandler.postAtTime command. Any advice regarding why this is happening or how to overcome the issue is greatly appreciated. PS: stopLog() is not being called. That's not the problem. mUpdateTimeTask = new Runnable() { public void run() { long millis = SystemClock.uptimeMillis() - mStartTime; int seconds = (int) (millis / 1000); int minutes = seconds / 60; seconds = seconds % 60; String freq = readCPU (); if (freq == null) Toast.makeText(CPU_log_Service.this, "CPU frequency is unreadable.\nPlease make sure the file has read rights.", Toast.LENGTH_LONG).show(); String str = new String ((minutes*60 + seconds) + ", " + freq + "\n"); if (!writeLog (str)) stopLog(); mHandler.postAtTime(this, mStartTime + (((minutes * 60) + seconds + 10) * 1000)); }}; mStartTime = SystemClock.uptimeMillis(); mHandler.removeCallbacks(mUpdateTimeTask); mHandler.postDelayed(mUpdateTimeTask, 100);

    Read the article

  • Java redirected system output to jtext area, doesnt update until calculation is finished

    - by user1806716
    I have code that redirects system output to a jtext area, but that jtextarea doesnt update until the code is finished running. How do I modify the code to make the jtextarea update in real time during runtime? private void updateTextArea(final String text) { SwingUtilities.invokeLater(new Runnable() { public void run() { consoleTextAreaInner.append(text); } }); } private void redirectSystemStreams() { OutputStream out = new OutputStream() { @Override public void write(int b) throws IOException { updateTextArea(String.valueOf((char) b)); } @Override public void write(byte[] b, int off, int len) throws IOException { updateTextArea(new String(b, off, len)); } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } }; System.setOut(new PrintStream(out, true)); System.setErr(new PrintStream(out, true)); } The rest of the code is mainly just an actionlistener for a button: private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: String shopRoot = this.shopRootDirTxtField.getText(); String updZipPath = this.updateZipTextField.getText(); this.mainUpdater = new ShopUpdater(new File(shopRoot), updZipPath); this.mainUpdater.update(); } That update() method begins the process of copying+pasting files on the file system and during that process uses system.out.println to provide an up-to-date status on where the program is currently at in reference to how many more files it has to copy.

    Read the article

  • java threads don't see shared boolean changes

    - by andymur
    Here the code class Aux implements Runnable { private Boolean isOn = false; private String statusMessage; private final Object lock; public Aux(String message, Object lock) { this.lock = lock; this.statusMessage = message; } @Override public void run() { for (;;) { synchronized (lock) { if (isOn && "left".equals(this.statusMessage)) { isOn = false; System.out.println(statusMessage); } else if (!isOn && "right".equals(this.statusMessage)) { isOn = true; System.out.println(statusMessage); } if ("left".equals(this.statusMessage)) { System.out.println("left " + isOn); } } } } } public class Question { public static void main(String [] args) { Object lock = new Object(); new Thread(new Aux("left", lock)).start(); new Thread(new Aux("right", lock)).start(); } } In this code I expect to see: left, right, left right and so on, but when Thread with "left" message changes isOn to false, Thread with "right" message don't see it and I get ("right true" and "left false" console messages), left thread don't get isOn in true, but right Thread can't change it cause it always see old isOn value (true). When i add volatile modifier to isOn nothing changes, but if I change isOn to some class with boolean field and change this field then threads are see changes and it works fine Thanks in advance.

    Read the article

  • how to get http responses continuously to a java application?

    - by senrulz
    I have the coding shown below where I have sheduled to get a http response from a php web server page. public static void stopPHPDataChecker() { canStop=true; } public static void main (String args[]) { // http request to the php page and get the response PHPDataChecker pdc = new PHPDataChecker(); ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); final ScheduledFuture<?> pdcHandle = scheduler.scheduleAtFixedRate(pdc, 0L, 10L, TimeUnit.MILLISECONDS);// Start schedule scheduler.schedule(new Runnable() { public void run() { System.out.println(">> TRY TO STOP!!!"); pdcHandle.cancel(true); Sheduler.stopPHPDataChecker(); System.out.println("DONE"); } }, 1L, TimeUnit.MILLISECONDS); do { if (canStop) { scheduler.shutdown(); } } while (!canStop); System.out.println("END"); } this coding only returns one response but I want it to get responses continuously so i can do different tasks according to the returned value. how can i do it? Thank you in advance :)

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21  | Next Page >