Search Results

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

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

  • Including hibernate jar dependencies in ant build

    - by Patrick
    Hi, I'm trying to compile a runnable jar-file for a project that makes use of hibernate. I'm trying to construct an ant build.xml file to streamline my build process, but I'm having troubles with the inclusion of the hibernate3.jar inside the final jar-file. If I run the ant script I manage to include all my library jars, and they are put in the final jar-file's root. When I run the jar-file I get a java.lang.NoClassDefFoundError: org/hibernate/Session error. If I make use of the built-in export to jar in Eclipse, it works only if I choose "extract required libraries into jar". But that bloats the jar, and includes too much of my project (i.e. unit tests). Below is my generated manifest: Manifest-Version: 1.0 Main-Class: main.ServerImpl Class-Path: ./ antlr-2.7.6.jar commons-collections-3.1.jar dom4j-1.6.1.jar hibernate3.jar javassist-3.9.0.GA.jar jta-1.1.jar slf4j-api-1.5.11.jar slf4j-simple-1.5.11.jar mysql-connector-java-5.1.12-bin.jar rmiio-2.0.2.jar commons-logging-1.1.1.jar And the part of the build.xml looks like this: <target name="dist" depends="compile" description="Generates the Distribution Jar(s)"> <mkdir dir="${dist.dir}" /> <jar destfile="${dist.dir}/${dist.file.name}.jar" basedir="${build.prod.dir}" filesetmanifest="mergewithoutmain"> <manifest> <attribute name="Main-Class" value="${main.class}" /> <attribute name="Class-Path" value="./ ${manifest.classpath} " /> <attribute name="Implementation-Title" value="${app.name}" /> <attribute name="Implementation-Version" value="${app.version}" /> <attribute name="Implementation-Vendor" value="${app.vendor}" /> </manifest> <zipfileset refid="hibernatefiles" /> <zipfileset refid="slf4jfiles" /> <zipfileset refid="mysqlfiles" /> <zipfileset refid="commonsloggingfiles" /> <zipfileset refid="rmiiofiles" /> </jar> </target> The refids' for the zipfilesets point to the directories in a library directory lib in the root of the project. The manifest.classpath-variable takes the classpath of all those library jar-files, and flattens them with pathconvert and mapper. I've also tried to set the manifest classpath to ".", "./" and only the library jar, but to no difference at all. I'm hoping there's a simple remedy to my problems...

    Read the article

  • design for a wrapper around command-line utilities

    - by hatchetman82
    im trying to come up with a design for a wrapper for use when invoking command line utilities in java. the trouble with runtime.exec() is that you need to keep reading from the process' out and err streams or it hangs when it fills its buffers. this has led me to the following design: public class CommandLineInterface { private final Thread stdOutThread; private final Thread stdErrThread; private final OutputStreamWriter stdin; private final History history; public CommandLineInterface(String command) throws IOException { this.history = new History(); this.history.addEntry(new HistoryEntry(EntryTypeEnum.INPUT, command)); Process process = Runtime.getRuntime().exec(command); stdin = new OutputStreamWriter(process.getOutputStream()); stdOutThread = new Thread(new Leech(process.getInputStream(), history, EntryTypeEnum.OUTPUT)); stdOutThread.setDaemon(true); stdOutThread.start(); stdErrThread = new Thread(new Leech(process.getErrorStream(), history, EntryTypeEnum.ERROR)); stdErrThread.setDaemon(true); stdErrThread.start(); } public void write(String input) throws IOException { this.history.addEntry(new HistoryEntry(EntryTypeEnum.INPUT, input)); stdin.write(input); stdin.write("\n"); stdin.flush(); } } public class Leech implements Runnable{ private final InputStream stream; private final History history; private final EntryTypeEnum type; private volatile boolean alive = true; public Leech(InputStream stream, History history, EntryTypeEnum type) { this.stream = stream; this.history = history; this.type = type; } public void run() { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line; try { while(alive) { line = reader.readLine(); if (line==null) break; history.addEntry(new HistoryEntry(type, line)); } } catch (Exception e) { e.printStackTrace(); } } } my issue is with the Leech class (used to "leech" the process' out and err streams and feed them into history - which acts like a log file) - on the one hand reading whole lines is nice and easy (and what im currently doing), but it means i miss the last line (usually the prompt line). i only see the prompt line when executing the next command (because there's no line break until that point). on the other hand, if i read characters myself, how can i tell when the process is "done" ? (either complete or waiting for input) has anyone tried something like waiting 100 millis since the last output from the process and declaring it "done" ? any better ideas on how i can implement a nice wrapper around things like runtime.exec("cmd.exe") ?

    Read the article

  • Getting problem in Java OpenCV code.

    - by Chetan
    I had successfully compile my java code in Eclipse with name FaceDetection.java... I am getting an Exception in thread "main" java.lang.NoSuchMethodError: main.... Please help me to remove this Exception.. Here is the code import java.awt.; import java.awt.event.; import java.awt.image.MemoryImageSource; import hypermedia.video.OpenCV; @SuppressWarnings("serial") public class FaceDetection extends Frame implements Runnable { /** * Main method. * @param String[] a list of user's arguments passed from the console to this program */ public static void main( String[] args ) { System.out.println( "\nOpenCV face detection sample\n" ); new FaceDetection(); } // program execution frame rate (millisecond) final int FRAME_RATE = 1000/30; OpenCV cv = null; // OpenCV Object Thread t = null; // the sample thread // the input video stream image Image frame = null; // list of all face detected area Rectangle[] squares = new Rectangle[0]; /** * Setup Frame and Object(s). */ FaceDetection() { super( "Face Detection Sample" ); // OpenCV setup cv = new OpenCV(); cv.capture( 320, 240 ); cv.cascade( OpenCV.CASCADE_FRONTALFACE_ALT ); // frame setup this.setBounds( 100, 100, cv.width, cv.height ); this.setBackground( Color.BLACK ); this.setVisible( true ); this.addKeyListener( new KeyAdapter() { public void keyReleased( KeyEvent e ) { if ( e.getKeyCode()==KeyEvent.VK_ESCAPE ) { // ESC : release OpenCV resources cv.dispose(); System.exit(0); } } } ); // start running program t = new Thread( this ); t.start(); } /** * Draw video frame and each detected faces area. */ public void paint( Graphics g ) { // draw image g.drawImage( frame, 0, 0, null ); // draw squares g.setColor( Color.RED ); for( Rectangle rect : squares ) g.drawRect( rect.x, rect.y, rect.width, rect.height ); } /** * Execute this sample. */ @SuppressWarnings("static-access") public void run() { while( t!=null && cv!=null ) { try { t.sleep( FRAME_RATE ); // grab image from video stream cv.read(); // create a new image from cv pixels data MemoryImageSource mis = new MemoryImageSource( cv.width, cv.height, cv.pixels(), 0, cv.width ); frame = createImage( mis ); // detect faces squares = cv.detect( 1.2f, 2, OpenCV.HAAR_DO_CANNY_PRUNING, 20, 20 ); // of course, repaint repaint(); } catch( InterruptedException e ) {;} } } }

    Read the article

  • How do I make my multicast program work between computers on different networks?

    - by George
    I made a little chat applet using multicast. It works fine between computers on the same network, but fails if the computers are on different networks. Why is this? import java.io.*; import java.net.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ClientA extends JApplet implements ActionListener, Runnable { JTextField tf; JTextArea ta; MulticastSocket socket; InetAddress group; String name=""; public void start() { try { socket = new MulticastSocket(7777); group = InetAddress.getByName("233.0.0.1"); socket.joinGroup(group); socket.setTimeToLive(255); Thread th = new Thread(this); th.start(); name =JOptionPane.showInputDialog(null,"Please enter your name.","What is your name?",JOptionPane.PLAIN_MESSAGE); tf.grabFocus(); }catch(Exception e) {e.printStackTrace();} } public void init() { JPanel p = new JPanel(new BorderLayout()); ta = new JTextArea(); ta.setEditable(false); ta.setLineWrap(true); JScrollPane sp = new JScrollPane(ta); p.add(sp,BorderLayout.CENTER); JPanel p2 = new JPanel(); tf = new JTextField(30); tf.addActionListener(this); p2.add(tf); JButton b = new JButton("Send"); b.addActionListener(this); p2.add(b); p.add(p2,BorderLayout.SOUTH); add(p); } public void actionPerformed(ActionEvent ae) { String message = name+":"+tf.getText(); tf.setText(""); tf.grabFocus(); byte[] buf = message.getBytes(); DatagramPacket packet = new DatagramPacket(buf,buf.length, group,7777); try { socket.send(packet); } catch(Exception e) {} } public void run() { while(true) { byte[] buf = new byte[256]; String received = ""; DatagramPacket packet = new DatagramPacket(buf, buf.length); try { socket.receive(packet); received = new String(packet.getData()).trim(); } catch(Exception e) {} ta.append(received +"\n"); ta.setCaretPosition(ta.getDocument().getLength()); } } }

    Read the article

  • Custom Monitor Resolution not recognized by Java

    - by Angie
    My weird monitor's native resolution isn't recognized by Windows, so I have to set a custom resolution for it. The problem is that java doesn't recognize it since it's not on Win7's "approved" list, so full-screen mode gets "stuck". Netbeans comes out of full-screen fine, so there has to be a way around this. Anyone know it? This example reproduces the issue: package resolutionexample; import java.awt.Dimension; import java.awt.DisplayMode; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import javax.swing.JFrame; import javax.swing.SwingUtilities; public class Main { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable(){ public void run() { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gd = ge.getDefaultScreenDevice(); DisplayMode currentDM = gd.getDisplayMode(); boolean currentInAvailable = false; System.out.println("Available resolutions:"); for ( DisplayMode availDM : gd.getDisplayModes() ){ //System.out.println(availDM.getWidth() + "x" + availDM.getHeight()); if ( availDM.equals(currentDM) ){ currentInAvailable = true; } } System.out.println("Current resolution: " + currentDM.getWidth() + "x" + currentDM.getHeight() ); System.out.println("Current in available: " + currentInAvailable); JFrame frame = new JFrame("Resolution Bug Example"); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); if ( !gd.isFullScreenSupported() ){System.exit(0);} gd.setFullScreenWindow(frame); gd.setFullScreenWindow(null); } }); } } Output running 1680x1050 (the monitor's wonky native resolution): run: Available resolutions: Current resolution: 1680x1050 Current in available: false Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Invalid display mode at sun.awt.Win32GraphicsDevice.setDisplayMode(Win32GraphicsDevice.java:393) at sun.awt.Win32GraphicsDevice.setFullScreenWindow(Win32GraphicsDevice.java:329) at resolutionexample.Main$1.run(Main.java:43) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209) at java.awt.EventQueue.dispatchEvent(EventQueue.java:597) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) BUILD SUCCESSFUL (total time: 2 seconds) Output if I set my resolution to 1024x768 before running: run: Available resolutions: Current resolution: 1024x768 Current in available: true BUILD SUCCESSFUL (total time: 2 seconds)

    Read the article

  • Component must be a valid peer (when i remove frame.add(Component);)

    - by boyd
    i have this code here for creating and drawing array of pixels into an image import javax.swing.JFrame; import java.awt.Canvas; import java.awt.Graphics; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; public class test extends Canvas implements Runnable{ private static final long serialVersionUID = 1L; public static int WIDTH = 800; public static int HEIGHT = 600; public boolean running=true; public int[] pixels; public BufferedImage img; public static JFrame frame; private Thread thread; public static void main(String[] arg) { test wind = new test(); frame = new JFrame("WINDOW"); frame.add(wind); frame.setVisible(true); frame.setSize(WIDTH, HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); wind.init(); } public void init(){ thread=new Thread(this); thread.start(); img=new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB); pixels=((DataBufferInt)img.getRaster().getDataBuffer()).getData(); } public void run(){ while(running){ render(); try { thread.sleep(55); } catch (InterruptedException e) { e.printStackTrace(); } } } public void render(){ BufferStrategy bs=this.getBufferStrategy(); if(bs==null){ createBufferStrategy(4); return; } drawRect(0,0,150,150); Graphics g= bs.getDrawGraphics(); g.drawImage(img, 0, 0, WIDTH, HEIGHT, null); g.dispose(); bs.show(); } private void drawRect(int x, int y, int w, int h) { for(int i=x;i<w;i++) for(int j=x;j<h;j++) pixels[i+j*WIDTH]=346346; } } Why i get "Component must be a valid peer" error when i remove the line: frame.add(wind); Why I want to remove it? Because I want to create a frame using a class object(from another file) and use the code Window myWindow= new Window() to do exactly the same thing BTW: who knows Java and understands what i wrote please send me a message with your skype or yahoo messenger id.I want to cooperate with you for a project (graphics engine for games)

    Read the article

  • log4j performance

    - by Bob
    Hi, I'm developing a web app, and I'd like to log some information to help me improve and observe the app. (I'm using Tomcat6) First I thought I would use StringBuilders, append the logs to them and a task would persist them into the database like every 2 minutes. Because I was worried about the out-of-the-box logging system's performance. Then I made some test. Especially with log4j. Here is my code: Main.java public static void main(String[] args) { Thread[] threads = new Thread[LoggerThread.threadsNumber]; for(int i = 0; i < LoggerThread.threadsNumber; ++i){ threads[i] = new Thread(new LoggerThread("name - " + i)); } LoggerThread.startTimestamp = System.currentTimeMillis(); for(int i = 0; i < LoggerThread.threadsNumber; ++i){ threads[i].start(); } LoggerThread.java public class LoggerThread implements Runnable{ public static int threadsNumber = 10; public static long startTimestamp; private static int counter = 0; private String name; public LoggerThread(String name) { this.name = name; } private Logger log = Logger.getLogger(this.getClass()); @Override public void run() { for(int i=0; i<10000; ++i){ log.info(name + ": " + i); if(i == 9999){ int c = increaseCounter(); if(c == threadsNumber){ System.out.println("Elapsed time: " + (System.currentTimeMillis() - startTimestamp)); } } } } private synchronized int increaseCounter(){ return ++counter; } } } log4j.properties log4j.logger.main.LoggerThread=debug, f log4j.appender.f=org.apache.log4j.RollingFileAppender log4j.appender.f.layout=org.apache.log4j.PatternLayout log4j.appender.f.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n log4j.appender.f.File=c:/logs/logging.log log4j.appender.f.MaxFileSize=15000KB log4j.appender.f.MaxBackupIndex=50 I think this is a very common configuration for log4j. First I used log4j 1.2.14 then I realized there was a newer version, so I switched to 1.2.16 Here are the figures (all in millisec) LoggerThread.threadsNumber = 10 1.2.14: 4235, 4267, 4328, 4282 1.2.16: 2780, 2781, 2797, 2781 LoggerThread.threadsNumber = 100 1.2.14: 41312, 41014, 42251 1.2.16: 25606, 25729, 25922 I think this is very fast. Don't forget that: in every cycle the run method not just log into the file, it has to concatenate strings (name + ": " + i), and check an if test (i == 9999). When threadsNumber is 10, there are 100.000 loggings and if tests and concatenations. When it is 100, there are 1.000.000 loggings and if tests and concatenations. (I've read somewhere JVM uses StringBuilder's append for concatenation, not simple concatenation). Did I missed something? Am I doing something wrong? Did I forget any factor that could decrease the performance? If these figures are correct I think, I don't have to worry about log4j's performance even if I heavily log, do I?

    Read the article

  • JPanel components paint-time problem

    - by Tom Brito
    I'm having a problem that when my frame is shown (after a login dialog) the buttons are not on correct position, then in some miliseconds they go to the right position (the center of the panel with border layout). When I make a SSCCE, it works correct, but when I run my whole code I have this fast-miliseconds delay to the buttons to go to the correct place. Unfortunately, I can't post the whole code, but the method that shows the frame is: public void login(JComponent userView) { centerPanel.removeAll(); centerPanel.add(userView); centerPanel.revalidate(); centerPanel.repaint(); frame.setVisible(true); } What would cause this delay to the panel layout? (I'm running everything in the EDT) -- update In my machine, this SSCCE shows the layout problem in 2 of 10 times I run it: import java.awt.BorderLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class TEST { public static void main(String[] args) throws Exception { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { System.out.println("Debug test..."); JPanel btnPnl = new JPanel(); btnPnl.add(new JButton("TEST")); JFrame f = new JFrame("TEST"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().setLayout(new BorderLayout()); f.getContentPane().add(btnPnl); f.pack(); f.setSize(800, 600); f.setVisible(true); System.out.println("End debug test!"); } }); } } The button first appers in the up-left, and then it goes to the center. Please, note that I'm understand, not just correct. Is it a java bug? --update OK, so the SSCCE don't show the problem with you that tried till now. Maybe it's my computer performance problem. But this don't answer the question, I still think Java Swing is creating new threads for make the layout behind the scenes.

    Read the article

  • java concurrency: many writers, one reader

    - by Janning
    I need to gather some statistics in my software and i am trying to make it fast and correct, which is not easy (for me!) first my code so far with two classes, a StatsService and a StatsHarvester public class StatsService { private Map<String, Long> stats = new HashMap<String, Long>(1000); public void notify ( String key ) { Long value = 1l; synchronized (stats) { if (stats.containsKey(key)) { value = stats.get(key) + 1; } stats.put(key, value); } } public Map<String, Long> getStats ( ) { Map<String, Long> copy; synchronized (stats) { copy = new HashMap<String, Long>(stats); stats.clear(); } return copy; } } this is my second class, a harvester which collects the stats from time to time and writes them to a database. public class StatsHarvester implements Runnable { private StatsService statsService; private Thread t; public void init ( ) { t = new Thread(this); t.start(); } public synchronized void run ( ) { while (true) { try { wait(5 * 60 * 1000); // 5 minutes collectAndSave(); } catch (InterruptedException e) { e.printStackTrace(); } } } private void collectAndSave ( ) { Map<String, Long> stats = statsService.getStats(); // do something like: // saveRecords(stats); } } At runtime it will have about 30 concurrent running threads each calling notify(key) about 100 times. Only one StatsHarvester is calling statsService.getStats() So i have many writers and only one reader. it would be nice to have accurate stats but i don't care if some records are lost on high concurrency. The reader should run every 5 Minutes or whatever is reasonable. Writing should be as fast as possible. Reading should be fast but if it locks for about 300ms every 5 minutes, its fine. I've read many docs (Java concurrency in practice, effective java and so on), but i have the strong feeling that i need your advice to get it right. I hope i stated my problem clear and short enough to get valuable help.

    Read the article

  • What is the best way, if possible, to send information from a Java PrintStream to a JTextPane?

    - by Daniel Reeves
    In Java, I have a package that translates XML metadata from one standard to another. This package is ultimately accessed through a single function and sends all of its output through a PrintStream object. The output sent is just a status of each file and whether or not it was translated. This is pretty fine and dandy if I'm just printing to System.out, but I'm actually wanting to print this to a JTextPane while it translates (kind of like a progress text box). It wouldn't be a big deal to just print the status after it was done translating the XML, but since there may be thousands of XML files, that's just not feasible. One thing that I've tried is to use a thread that takes all of the information from the PrintStream (which is attached to a ByteArrayOutputStream) and let it send any new information to the text pane. Unfortunately, this still sends the information all at once at the end of the translation. This does work correctly for System.out. Here's the code that does the translation and tries to show the output: public class ConverterGUI extends javax.swing.JFrame { boolean printToResultsBox = false; PrintStream printStream = null; ByteArrayOutputStream baos = null; private class ResultsPrinter implements Runnable { public ResultsPrinter() { baos = new ByteArrayOutputStream(); printStream = new PrintStream(baos); } public void run() { String tempString = ""; while (printToResultsBox) { try { if (!baos.toString().equals(tempString)) { tempString = baos.toString(); resultsBox.setText(tempString); } } catch (Exception ex) { } } } } ... ResultsPrinter rp = new ResultsPrinter(); Thread thread = new Thread(rp); thread.start(); // Do the translation. try { printToResultsBox = true; boolean success = false; TranslationEngine te = new TranslationEngine(); // fileOrFolderToConvert is a text box in the GUI. // linkNeeded and destinationFile are just parameters for the translation process. success = te.translate(fileOrFolderToConvert.getText(), linkNeeded, destinationFile, printStream); if (success) { printStream.println("File/folder translation was a success."); } resultsBox.setText(baos.toString()); } catch (Exception ex) { printStream.println("File translation failed."); } finally { printToResultsBox = false; } ... } Ultimately, this code prints out to the JTextPane just fine after all the translation is done but not during. Any suggestions? Do I need to change the PrintStream to something else?

    Read the article

  • J2ME/Java: Referencing StringBuffer through Threads

    - by Jemuel Dalino
    This question might be long, but I want to provide much information. Overview: I'm creating a Stock Quotes Ticker app for Blackberry. But I'm having problems with my StringBuffer that contains an individual Stock information. Process: My app connects to our server via SocketConnection. The server sends out a formatted set of strings that contains the latest Stock trade. So whenever a new trade happens, the server will send out an individual Stock Quote of that trade. Through an InputStream I am able to read that information and place each character in a StringBuffer that is referenced by Threads. By parsing based on char3 I am able to determine a set of stock quote/information. char1 - to separate data char3 - means end of a stock quote/information sample stock quote format sent out by our server: stock_quote_name(char 1)some_data(char1)some_data(char1)(char3) My app then parses that stock quote to compare certain data and formats it how it will look like when displayed in the screen. When trades happen gradually(slow) the app works perfectly. However.. Problem: When trades happen too quickly and almost at the same time, My app is not able to handle the information sent efficiently. The StringBuffer has its contents combined with the next trade. Meaning Two stock information in one StringBuffer. field should be: Stock_quote_name some_data some_data sample of what's happening: Stock_quote_name some_data some_dataStock_quote_name some_data some_data here's my code for this part: while (-1 != (data = is.read())) { sb.append((char)data); while(3 != (data = is.read())) { sb.append((char)data); } UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { try { synchronized(UiApplication.getEventLock()) { SetStringBuffer(sb); DisplayStringBuffer(); RefreshStringBuffer(); } } catch (Exception e) { System.out.println("Error in setting stringbuffer: " + e.toString()); } } }); } public synchronized void DisplayStringBuffer() { try { //parse sb - string buffer ...... } catch(Exception ex) { System.out.println("error in DisplayStringBuffer(): " + ex.toString()); } } public synchronized void SetStringBuffer(StringBuffer dataBuffer) { this.sb =dataBuffer; System.out.println(sb); } public synchronized void RefreshStringBuffer() { this.sb.delete(0, this.sb.length()); } From what I can see, when trades happen very fast, The StringBuffer is not refreshed immediately and still has the contents of the previous trade, when i try to put new data. My Question is: Do you guys have any suggestion on how i can put data into the StringBuffer, without the next information being appended to the first content

    Read the article

  • How to set text above and below a JButton icon?

    - by mre
    I want to set text above and below a JButton's icon. At the moment, in order to achieve this, I override the layout manager and use three JLabel instances (i.e. 2 for text and 1 for the icon). But this seems like a dirty solution. Is there a more direct way of doing this? Note -I'm not looking for a multi-line solution, I'm looking for a multi-label solution. Although this article refers to it as a multi-line solution, it actually seems to refer to a multi-label solution. EXAMPLE import java.awt.Component; import java.awt.FlowLayout; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; import javax.swing.UIManager; public final class JButtonDemo { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI(){ final JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new FlowLayout()); frame.add(new JMultiLabelButton()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static final class JMultiLabelButton extends JButton { private static final long serialVersionUID = 7650993517602360268L; public JMultiLabelButton() { super(); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); add(new JCenterLabel("Top Label")); add(new JCenterLabel(UIManager.getIcon("OptionPane.informationIcon"))); add(new JCenterLabel("Bottom Label")); } } private static final class JCenterLabel extends JLabel { private static final long serialVersionUID = 5502066664726732298L; public JCenterLabel(final String s) { super(s); setAlignmentX(Component.CENTER_ALIGNMENT); } public JCenterLabel(final Icon i) { super(i); setAlignmentX(Component.CENTER_ALIGNMENT); } } }

    Read the article

  • java double buffering problem

    - by russell
    Whats wrong with my applet code which does not render double buffering correctly.I am trying and trying.But failed to get a solution.Plz Plz someone tell me whats wrong with my code. import java.applet.* ; import java.awt.* ; import java.awt.event.* ; public class Ball extends Applet implements Runnable { // Initialisierung der Variablen int x_pos = 10; // x - Position des Balles int y_pos = 100; // y - Position des Balles int radius = 20; // Radius des Balles Image buffer=null; //Graphics graphic=null; int w,h; public void init() { Dimension d=getSize(); w=d.width; h=d.height; buffer=createImage(w,h); //graphic=buffer.getGraphics(); setBackground (Color.black); } public void start () { // Schaffen eines neuen Threads, in dem das Spiel l?uft Thread th = new Thread (this); // Starten des Threads th.start (); } public void stop() { } public void destroy() { } public void run () { // Erniedrigen der ThreadPriority um zeichnen zu erleichtern Thread.currentThread().setPriority(Thread.MIN_PRIORITY); // Solange true ist l?uft der Thread weiter while (true) { // Ver?ndern der x- Koordinate repaint(); x_pos++; y_pos++; //x2--; //y2--; // Neuzeichnen des Applets if(x_pos>410) x_pos=20; if(y_pos>410) y_pos=20; try { Thread.sleep (30); } catch (InterruptedException ex) { // do nothing } Thread.currentThread().setPriority(Thread.MAX_PRIORITY); } } public void paint (Graphics g) { Graphics screen=null; screen=g; g=buffer.getGraphics(); g.setColor(Color.red); g.fillOval(x_pos - radius, y_pos - radius, 2 * radius, 2 * radius); g.setColor(Color.green); screen.drawImage(buffer,0,0,this); } public void update(Graphics g) { paint(g); } } what change should i make.When offscreen image is drawn the previous image also remain in screen.How to erase the previous image from the screen??

    Read the article

  • Execute a jar file using Ant

    - by geetha
    I am trying to create a runnable jar file from java classes using ant. The java classes use external jars. When I execute the build.xml its showing class not found exception while running the java program. Its compiling fine. Part of My source code: <path id="project-libpath"> <fileset dir="${lib.dir}"> <include name="*.jar"/> </fileset> </path> <path id="project-classpath"> <fileset dir="C:/xmldecode/lib"> <include name="*.jar"/> </fileset> </path> <target name="compile" depends="prepare"> <javac srcdir="${src.dir}" destdir="${classes.dir}"> <classpath refid="project-classpath"/> </javac> </target> <target name="jar" depends="compile"> <copy todir="${classes.dir}"> <fileset dir="C:/xmldecode/lib"/> </copy> <pathconvert property="mf.classpath" pathsep=";"> <path refid="project-classpath" /> <flattenmapper /> </pathconvert> <jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}"> <manifest> <attribute name="Main-Class" value="${main-class}"/> <attribute name="Class-Path" value="${mf.classpath}"/> </manifest> </jar> </target> <target name="run" depends="jar"> <java jar="${jar.dir}/${ant.project.name}.jar" fork="true"> </java>

    Read the article

  • Efficient algorithm to distribute work?

    - by Zwei Steinen
    It's a bit complicated to explain but here we go. We have problems like this (code is pseudo-code, and is only for illustrating the problem. Sorry it's in java. If you don't understand, I'd be glad to explain.). class Problem { final Set<Integer> allSectionIds = { 1,2,4,6,7,8,10 }; final Data data = //Some data } And a subproblem is: class SubProblem { final Set<Integer> targetedSectionIds; final Data data; SubProblem(Set<Integer> targetedSectionsIds, Data data){ this.targetedSectionIds = targetedSectionIds; this.data = data; } } Work will look like this, then. class Work implements Runnable { final Set<Section> subSections; final Data data; final Result result; Work(Set<Section> subSections, Data data) { this.sections = SubSections; this.data = data; } @Override public void run(){ for(Section section : subSections){ result.addUp(compute(data, section)); } } } Now we have instances of 'Worker', that have their own state sections I have. class Worker implements ExecutorService { final Map<Integer,Section> sectionsIHave; { sectionsIHave = {1:section1, 5:section5, 8:section8 }; } final ExecutorService executor = //some executor. @Override public void execute(SubProblem problem){ Set<Section> sectionsNeeded = fetchSections(problem.targetedSectionIds); super.execute(new Work(sectionsNeeded, problem.data); } } phew. So, we have a lot of Problems and Workers are constantly asking for more SubProblems. My task is to break up Problems into SubProblem and give it to them. The difficulty is however, that I have to later collect all the results for the SubProblems and merge (reduce) them into a Result for the whole Problem. This is however, costly, so I want to give the workers "chunks" that are as big as possible (has as many targetedSections as possible). It doesn't have to be perfect (mathematically as efficient as possible or something). I mean, I guess that it is impossible to have a perfect solution, because you can't predict how long each computation will take, etc.. But is there a good heuristic solution for this? Or maybe some resources I can read up before I go into designing? Any advice is highly appreciated!

    Read the article

  • Java accessing variables using extends

    - by delo
    So here I have two classes: Customer Order Class and Confirmation Class. I want to access the data stored in LastNameTextField (Customer Order Class) and set it as the text for UserLastNameLabel (Confirmation Class) after clicking a "Submit" button. For some reason however, the output displays nothing. Snippet of my code: package customer_order; public class customer_order extends Frame{ private static final long serialVersionUID = 1L; private JPanel jPanel = null; private JLabel LastNameLabel = null; protected JTextField LastNameTextField = null; private JButton SubmitButton = null; public String s; public customer_order() { super(); initialize(); } private void initialize() { this.setSize(729, 400); this.setTitle("Customer Order"); this.add(getJPanel(), BorderLayout.CENTER); } /** * This method initializes LastNameTextField * * @return javax.swing.JTextField */ public JTextField getLastNameTextField() { if (LastNameTextField == null) { LastNameTextField = new JTextField(); LastNameTextField.setBounds(new Rectangle(120, 100, 164, 28)); LastNameTextField.setName("LastNameTextField"); } return LastNameTextField; } /** * This method initializes SubmitButton * * @return javax.swing.JButton */ private JButton getSubmitButton() { if (SubmitButton == null) { SubmitButton = new JButton(); SubmitButton.setBounds(new Rectangle(501, 225, 96, 29)); SubmitButton.setName("SubmitButton"); SubmitButton.setText("Submit"); SubmitButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed() //THE STRING I WANT s = LastNameTextField.getText(); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new confirmation().setVisible(true); } }); } }); } return SubmitButton; } package customer_order; public class confirmation extends customer_order{ private static final long serialVersionUID = 1L; private JPanel jPanel = null; // @jve:decl-index=0:visual-constraint="58,9" private JLabel LastNameLabel = null; private JLabel UserLastNameLabel = null; // @jve:decl-index=0: /** * This method initializes frame * * @return java.awt.Frame */ public confirmation() { super(); initialize(); } private void initialize() { this.setSize(729, 400); this.setTitle("Confirmation"); this.add(getJPanel(), BorderLayout.CENTER); } /** * This method initializes jPanel * * @return javax.swing.JPanel */ private JPanel getJPanel() { if (jPanel == null) { UserLastNameLabel = new JLabel(); UserLastNameLabel.setBounds(new Rectangle(121, 60, 167, 26)); //THE PROBLEM? UserLastNameLabel.setText(s); } return jPanel; }

    Read the article

  • Thread sleep and thread join.

    - by Dhruv Gairola
    hi guys, if i put a thread to sleep in a loop, netbeans gives me a caution saying Invoking Thread.sleep in loop can cause performance problems. However, if i were to replace the sleep with join, no such caution is given. Both versions compile and work fine tho. My code is below (check the last few lines for "Thread.sleep() vs t.join()"). public class Test{ //Display a message, preceded by the name of the current thread static void threadMessage(String message) { String threadName = Thread.currentThread().getName(); System.out.format("%s: %s%n", threadName, message); } private static class MessageLoop implements Runnable { public void run() { String importantInfo[] = { "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too" }; try { for (int i = 0; i < importantInfo.length; i++) { //Pause for 4 seconds Thread.sleep(4000); //Print a message threadMessage(importantInfo[i]); } } catch (InterruptedException e) { threadMessage("I wasn't done!"); } } } public static void main(String args[]) throws InterruptedException { //Delay, in milliseconds before we interrupt MessageLoop //thread (default one hour). long patience = 1000 * 60 * 60; //If command line argument present, gives patience in seconds. if (args.length > 0) { try { patience = Long.parseLong(args[0]) * 1000; } catch (NumberFormatException e) { System.err.println("Argument must be an integer."); System.exit(1); } } threadMessage("Starting MessageLoop thread"); long startTime = System.currentTimeMillis(); Thread t = new Thread(new MessageLoop()); t.start(); threadMessage("Waiting for MessageLoop thread to finish"); //loop until MessageLoop thread exits while (t.isAlive()) { threadMessage("Still waiting..."); //Wait maximum of 1 second for MessageLoop thread to //finish. /*******LOOK HERE**********************/ Thread.sleep(1000);//issues caution unlike t.join(1000) /**************************************/ if (((System.currentTimeMillis() - startTime) > patience) && t.isAlive()) { threadMessage("Tired of waiting!"); t.interrupt(); //Shouldn't be long now -- wait indefinitely t.join(); } } threadMessage("Finally!"); } } As i understand it, join waits for the other thread to complete, but in this case, arent both sleep and join doing the same thing? Then why does netbeans throw the caution?

    Read the article

  • AnimationDrawable, when does it end?

    - by Syb
    I know there have been several people with the same question. Which is: How do i know when a frame by frame animation has ended? I have not had any useful answer on fora i visited. So i thought, let's see if they know at stackoverflow. But I could not sit still in the mean time, so i made a work around of this, but it does not really work the way i would like it to. here is the code: public class Main extends Activity { AnimationDrawable sybAnimation; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ImageView imageView = (ImageView)findViewById(R.id.ImageView01); imageView.setBackgroundResource(R.anim.testanimation); sybAnimation = (AnimationDrawable) imageView.getBackground(); imageView.post(new Starter()); } class Starter implements Runnable { public void run() { sybAnimation.start(); long totalDuration = 0; for(int i = 0; i< sybAnimation.getNumberOfFrames();i++){ totalDuration += sybAnimation.getDuration(i); } Timer timer = new Timer(); timer.schedule(new AnimationFollowUpTimerTask(R.id.ImageView01, R.anim.testanimation_reverse),totalDuration); } } class AnimationFollowUpTimerTask extends TimerTask { private int id; private int animationToRunId; public AnimationFollowUpTimerTask(int idOfImageView, int animationXML){ id = idOfImageView; animationToRunId = animationXML; } @Override public void run() { ImageView imageView = (ImageView)findViewById(id); imageView.setBackgroundResource(animationToRunId); AnimationDrawable anim = (AnimationDrawable) imageView.getBackground(); anim.start(); } } basically I make a timertask which is scheduled with the same time as the animation to take. In that run() I want to load a new animation into the imageView and start that animation, this however does not work. Does anyone know how to get this to work, or even better, have a better way to find out when an AnimationDrawable has ended its animation?

    Read the article

  • jframe adding own design jinternal frame error

    - by Van Minh
    I designed a title bar color on my JInternal frame. Then I took attempt to add it to my JFrame, but I cannot. Here is the code of my title bar: public class MyIFtitleBar extends BasicInternalFrameTitlePane { public MyIFtitleBar(JInternalFrame jif) { super(jif); } protected void paintTitleBackground(Graphics g){ g.setColor(Color.pink); g.fillRect(0, 0, getWidth(), getHeight()); } } Here is my JInternal frame. I tried running it in its psvm method, that worked! public class FitnessProg_Frame extends javax.swing.JInternalFrame { public FitnessProg_Frame() { initComponents(); this.setUI(new BasicInternalFrameUI(this){ @Override protected JComponent createNorthPane(JInternalFrame jif) { return new MyIFtitleBar(jif); } }); } @SuppressWarnings("unchecked") private void initComponents() { setBackground(new java.awt.Color(255, 255, 255)); setBorder(new javax.swing.border.MatteBorder(null)); setTitle("Fitness Progarm"); setPreferredSize(new java.awt.Dimension(507, 304)); pack(); } } But when I add it to my JFrame I get an error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Here is my JFrame code: public class NewJFrame extends javax.swing.JFrame { public NewJFrame() { initComponents(); FitnessProg_Frame ff = new FitnessProg_Frame(); ff.setVisible(true); mydes.add(ff); // this line made errors } @SuppressWarnings("unchecked") private void initComponents() { mydes = new javax.swing.JDesktopPane(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); javax.swing.GroupLayout mydesLayout = new javax.swing.GroupLayout(mydes); mydes.setLayout(mydesLayout); mydesLayout.setHorizontalGroup( mydesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 400, Short.MAX_VALUE) ); mydesLayout.setVerticalGroup( mydesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); getContentPane().add(mydes, java.awt.BorderLayout.CENTER); pack(); } public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); } private javax.swing.JDesktopPane mydes; }

    Read the article

  • Getting huge lags when downloading files via Service

    - by Copa
    I have a Service which receives URLs to download. The Service than downloads these URLs and save them to a file on the SD Card. When I put more than 2 items in the download queue my device is unusable. It nearly freezes. Huge lags and so on. Any idea? Sourcecode: private static boolean downloading = false; private static ArrayList<DownloadItem> downloads = new ArrayList<DownloadItem>(); /** * called once when the service started */ public static void start() { Thread thread = new Thread(new Runnable() { @Override public void run() { while (true) { if (downloads.size() > 0 && !downloading) { downloading = true; DownloadItem item = downloads.get(0); downloadSingleFile(item.getUrl(), item.getFile()); } } } }); thread.start(); } public static void addDownload(DownloadItem item) { downloads.add(item); } private static void downloadSuccessfullFinished() { if (downloads.size() > 0) downloads.get(0).setDownloaded(true); downloadFinished(); } private static void downloadFinished() { // remove the first entry; it has been downloaded if (downloads.size() > 0) downloads.remove(0); downloading = false; } private static void downloadSingleFile(String url, File output) { final int maxBufferSize = 4096; HttpResponse response = null; try { response = new DefaultHttpClient().execute(new HttpGet(url)); if (response != null && response.getStatusLine().getStatusCode() == 200) { // request is ok InputStream is = response.getEntity().getContent(); BufferedInputStream bis = new BufferedInputStream(is); RandomAccessFile raf = new RandomAccessFile(output, "rw"); ByteArrayBuffer baf = new ByteArrayBuffer(maxBufferSize); long current = 0; long i = 0; // read and write 4096 bytes each time while ((current = bis.read()) != -1) { baf.append((byte) current); if (++i == maxBufferSize) { raf.write(baf.toByteArray()); baf = new ByteArrayBuffer(maxBufferSize); i = 0; } } if (i > 0) // write the last bytes to the file raf.write(baf.toByteArray()); baf.clear(); raf.close(); bis.close(); is.close(); // download finished get start next download downloadSuccessfullFinished(); return; } } catch (Exception e) { // not successfully downloaded downloadFinished(); return; } // not successfully downloaded downloadFinished(); return; }

    Read the article

  • Java: Multithreading & UDP Socket Programming

    - by Ravi
    I am new to multithreading & socket programming in Java. I would like to know what is the best way to implement 2 threads - one for receiving a socket and one for sending a socket. If what I am trying to do sounds absurd, pls let me know why! The code is largely inspired from Sun's tutorials online.I want to use Multicast sockets so that I can work with a multicast group. class server extends Thread { static protected MulticastSocket socket = null; protected BufferedReader in = null; public InetAddress group; private static class receive implements Runnable { public void run() { try { byte[] buf = new byte[256]; DatagramPacket pkt = new DatagramPacket(buf,buf.length); socket.receive(pkt); String received = new String(pkt.getData(),0,pkt.getLength()); System.out.println("From server@" + received); Thread.sleep(1000); } catch (IOException e) { System.out.println("Error:"+e); } catch (InterruptedException e) { System.out.println("Error:"+e); } } } public server() throws IOException { super("server"); socket = new MulticastSocket(4446); group = InetAddress.getByName("239.231.12.3"); socket.joinGroup(group); } public void run() { while(1>0) { try { byte[] buf = new byte[256]; DatagramPacket pkt = new DatagramPacket(buf,buf.length); //String msg = reader.readLine(); String pid = ManagementFactory.getRuntimeMXBean().getName(); buf = pid.getBytes(); pkt = new DatagramPacket(buf,buf.length,group,4446); socket.send(pkt); Thread t = new Thread(new receive()); t.start(); while(t.isAlive()) { t.join(1000); } sleep(1); } catch (IOException e) { System.out.println("Error:"+e); } catch (InterruptedException e) { System.out.println("Error:"+e); } } //socket.close(); } public static void main(String[] args) throws IOException { new server().start(); //System.out.println("Hello"); } }

    Read the article

  • A Surface view and a canvas to move Bitmap

    - by John Apple Sim
    I have a SurfaceView and I want the Bitmap Logo inside it in the canvas to be movable What I'm doing wrong ? static float x, y; Bitmap logo; SurfaceView ss = (SurfaceView) findViewById(R.id.svSS); logo = BitmapFactory.decodeResource(getResources(), R.drawable.logo); x = 40; y = 415; ss.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent me) { try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } switch(me.getAction()) { case MotionEvent.ACTION_DOWN: x = me.getX(); y = me.getY(); break; case MotionEvent.ACTION_UP: x = me.getX(); y = me.getY(); break; case MotionEvent.ACTION_MOVE: x = me.getX(); y = me.getY(); break; } return true; } }); public class OurView extends SurfaceView implements Runnable{ Thread t = null; SurfaceHolder holder; boolean isItOK = false; public OurView(Context context) { super(context); holder = getHolder(); } public void run (){ while (isItOK == true){ //canvas DRAWING if (!holder.getSurface().isValid()){ continue; } Canvas c = holder.lockCanvas(); c.drawARGB(255, 200, 100, 100); c.drawBitmap(logo, x,y,null); holder.unlockCanvasAndPost(c); } } public void pause(){ isItOK = false; while(true){ try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } break; } t = null; } public void resume(){ isItOK = true; t = new Thread(this); t.start(); } } Now the surface view is just black .. nothing happens also its not colored 200, 100, 100

    Read the article

  • JPanel's child components paint/layout problem

    - by Tom Brito
    I'm having a problem that when my frame is shown (after a login dialog) the buttons are not on correct position, then in some miliseconds they go to the right position (the center of the panel with border layout). When I make a SSCCE, it works correct, but when I run my whole code I have this fast-miliseconds delay to the buttons to go to the correct place. Unfortunately, I can't post the whole code, but the method that shows the frame is: public void login(JComponent userView) { centerPanel.removeAll(); centerPanel.add(userView); centerPanel.revalidate(); centerPanel.repaint(); frame.setVisible(true); } What would cause this delay to the panel layout? (I'm running everything in the EDT) -- update In my machine, this SSCCE shows the layout problem in 2 of 10 times I run it: import java.awt.BorderLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class TEST { public static void main(String[] args) throws Exception { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { System.out.println("Debug test..."); JPanel btnPnl = new JPanel(); btnPnl.add(new JButton("TEST")); JFrame f = new JFrame("TEST"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().setLayout(new BorderLayout()); f.getContentPane().add(btnPnl); f.pack(); f.setSize(800, 600); f.setVisible(true); System.out.println("End debug test!"); } }); } } The button first appers in the up-left, and then it goes to the center. Please, note that I'm understand, not just correct. Is it a java bug? --update OK, so the SSCCE don't show the problem with you that tried till now. Maybe it's my computer performance problem. But this don't answer the question, I still think Java Swing is creating new threads for make the layout behind the scenes.

    Read the article

  • Command Not working in separate thread in J2me.

    - by RishiPatel
    I am creating a bluetooth application. I created a simple midlet with a exit command and i create a thread for finding the service and discovering the device. While doing so it displays a animated screen on which i added the parent commandListener for exit command. After successful connection both user is represented with greetings(Current screen calls the parent Display method setCurrent for displaying itself). This screen also have CommandListener set to the parent. Now i want to add few more commands. I Implemented the CommandLIstener Interface in this class, added few commands but the commands are not working. I dont whats wen wrong. I am giving u Code snippets to fully describle my issue : - package name Imports here public class MyMidlet extends MIDlet implements CommandListener { public CommandListener theListener; public Display theDisplay; public Command exitCommand; public MyMidlet() { // Retrieve the display for this MIDlet //Create the initial screen } public void startApp() throws MIDletStateChangeException { } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command c, Displayable d) { // Determine if the exit command was selected if (c == exitCommand) { //End application here notifyDestroyed(); } else { //Start the new thread here } } } Now here is the code for the class which is invoked by the above midlet in a separate thread; package here; imports here public class MyService implements Runnable, CommandListener { private MyMidlet parent; private StreamConnection conn; private OutputStream output; private InputStream input; public Command sendCommand; private TextField messageToSend Form form; public BChatService(boolean isServer, BChatMidlet parent) { //some stuff here this.parent = parent; } public void run() { //functino for showing animation here try { input = conn.openInputStream(); output = conn.openOutputStream(); } catch (IOException e) { displayError("IO Error", "An error occurred while opening " + "the input and output streams" + "(IOException: " + e.getMessage() + ")"); try { conn.close(); } catch (Exception ex) { } return; } // Create the Form here when service is discoverd and greets the users Command sendCommand = new Command("Send", Command.ITEM, 2); exitCommand = new Command("Exit", Command.EXIT, 1); form.addCommand(exitCommand); form.addCommand(sendCommand); parent.theDisplay.setCurrent(form); form.setCommandListener(this); public void commandAction(Command c, Displayable d) { if (c == exitCommand) { // End the game parent.destroyApp(true); parent.notifyDestroyed(); } if(c == sendCommand) { form.append("SOme text here"); } } } When i select the Send command, the string doesnt append in form neither exit command works. What can be the possible cause for it?? I need to implement this functionality...Is there any other way to achieve this??

    Read the article

  • Threadpool with pasistant worker instances

    - by Matt Smokey-waters Holmes
    So basically what im trying to do is queue up tasks in a thread pool to be executed as soon as a worker becomes free, i have found various examples of this but in all cases the examples have been setup to use a new Worker instance for each job, i want persistent workers. Im trying to make a ftp backup tool, i have it working but because of the limitations of a single connection it is slow. What i ideally want to do is have a single connection for scanning directories and building up a file list then four workers to download said files. Here is an example of my worker /** * FTP Worker */ public class Worker implements Runnable { protected FTPClient _ftp; // Connection details protected String _host = ""; protected String _user = ""; protected String _pass = ""; // worker status protected boolean _working = false; public Worker(String host, String user, String pass) { this._host = host; this._user = user; this._pass = pass; } // Check if the worker is in use public boolean inUse() { return this._working; } @Override public void run() { this._ftp = new FTPClient(); this._connect(); } // Download a file from the ftp server public boolean download(String base, String path, String file) { this._working = true; boolean outcome = true; //create directory if not exists File pathDir = new File(base + path); if (!pathDir.exists()) { pathDir.mkdirs(); } //download file try { OutputStream output = new FileOutputStream(base + path + file); this._ftp.retrieveFile(file, output); output.close(); } catch (Exception e) { outcome = false; } finally { this._working = false; return outcome; } } // Connect to the server protected boolean _connect() { try { this._ftp.connect(this._host); this._ftp.login(this._user, this._pass); } catch (Exception e) { return false; } return this._ftp.isConnected(); } // Disconnect from the server protected void _disconnect() { try { this._ftp.disconnect(); } catch (Exception e) { /* do nothing */ } } } and basically i want to be able to call Worker.download(...) for each task in a queue whenever a worker becomes available without having to create a new connection to the ftp server for each download Any help would be appreciated as iv'e never used threads before and I'm going round in circles at the moment

    Read the article

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