Swing GUI components

Hi, I'm starting to learn swing, and I'm trying to figure what components to use for my particular application. I'm preparing to build a gui that represents the status of hardware in realtime (ie this application regularly polls hardware and receives status data over a socket) I would like this to look like a grid in which a row and column junction represent a particular hardware status.
I've been looking for a 'indicator' type of component, but can't find anything that fits the bill from the standard components.
I've been thinking that one way to implement the gui is to create a grid of JPanel components, and change the background color of individual panels to reflect status. Is there away to group JPanels together?
Any suggestions would be appreciated-
Alan

As CaptainMorgan has already pointed out, the JTable is probably a better component for what you are looking for. However, you can also group your JPanels by using the [url http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/BoxLayout.html]javax.swing.BoxLayout.

Similar Messages

  • Event handling in custom Non-GUI components

    I have a class which needs to fire events to outside. These events maybe captured by several objects in outside world. How can I achieve this? In so many places I read, they always refer to AWT and Swing whereas my objects don't have any dependency to GUI.
    I simply need to fire an event from an object, and capture that event from other objects by registering event handlers.
    I have experience in .Net programming with Events and Delegates (function pointers), but cannot find something like that in Java. All it offers is various kinds of GUI related Listeners where I can't find a proper help resource using them in Non-GUI components.

    ravinsp wrote:
    I have a class which needs to fire events to outside. These events maybe captured by several objects in outside world. How can I achieve this? In so many places I read, they always refer to AWT and Swing whereas my objects don't have any dependency to GUI.
    I simply need to fire an event from an object, and capture that event from other objects by registering event handlers.
    I have experience in .Net programming with Events and Delegates (function pointers), but cannot find something like that in Java. All it offers is various kinds of GUI related Listeners where I can't find a proper help resource using them in Non-GUI components.If you want to make your own Listener make your Listener. Create an event class that encapsulates the event as you want, create a listener interface that has a method like handleMyEvent(MyEvent me) and then add addMyEventListener, removeMyEventListener methods to your original class. Add a List<MyEvent> to your original class and add the listeners to it and then when events happen
    MyEvent someEvent = new MyEvent();
    for(MyEventListener mel : eventlisteners)
       mel.handleMyEvent(someEvent);

  • (Youtube-) Video in a Swing GUI

    Hey everyone,
    I'm currently trying to play a video in my Swing GUI with JMF but I really can't get it to work.
    With the help of google I got this far:
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.media.CannotRealizeException;
    import javax.media.Manager;
    import javax.media.NoPlayerException;
    import javax.media.Player;
    import javax.swing.JFrame;
    public class MediaPanel extends JFrame {
        public MediaPanel() {
            setLayout(new BorderLayout()); // use a BorderLayout
            // Use lightweight components for Swing compatibility
            Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, true);
            URL mediaURL = null;
            try {
                mediaURL = new URL("http://www.youtube.com/watch?v=Q7_Z_mQUBa8");
            } catch (MalformedURLException ex) {
                System.err.println(ex);
            try {
                // create a player to play the media specified in the URL
                Player mediaPlayer = Manager.createRealizedPlayer(mediaURL);
                // get the components for the video and the playback controls
                Component video = mediaPlayer.getVisualComponent();
                Component controls = mediaPlayer.getControlPanelComponent();
                if (video != null) {
                    add(video, BorderLayout.CENTER); // add video component
                if (controls != null) {
                    add(controls, BorderLayout.SOUTH); // add controls
                mediaPlayer.start(); // start playing the media clip
            } // end try
            catch (NoPlayerException noPlayerException) {
                System.err.println("No media player found");
            } // end catch
            catch (CannotRealizeException cannotRealizeException) {
                System.err.println("Could not realize media player");
            } // end catch
            catch (IOException iOException) {
                System.err.println("Error reading from the source");
            } // end catch
        } // end MediaPanel constructor
    }But all I get is errors:
    Warning: The URL may not exist. Please check URL
    No media player found
    Can you please please help me get this working? I would really appreciate a little walkthrough
    Best regards,
    Patrick
    Edited by: 954807 on Aug 24, 2012 6:52 AM

    Just use \ tags. People don't like to go to external sites.
    I really advise you to consider using JavaFX 2 here. Swing is old and not really supported anymore, JMF is also old and absolutely not supported anymore.                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Flyweight Pattern use with multiple GUI components

    Hi,
    I am creating a simple application and I would like your advice on wether I should use the flyweight pattern or not.
    My application is essentially a GUI front to a repository of small images. The GUI (in its simplest form) is a single window that will display all the images with their names in a clickable thumbnail format. The user will be able to select an thumbnail icon, drag it and move it around pretty much like the icons on your computer desktop.
    The easiest way to do that is probably to load each image and its name into a JLabel, add it in a JFrame and write just few lines of code (say by extending the JLabel class) to handle mouse pressed/dragged events in order to move the label around. The rest will be taken care of by the swing functinality (e.g. painting etc).
    However, I am considering using the flyweight pattern for efficiency but I am not sure if it is appropriate. So far I have seen simplistic examples of its use (apart from JTree) where the pattern is used to paint dozens of lines on the screen or the borders of components. But what happens if instead of lines or borders the objects in question are interactive GUI components such as my thumbnails? how does the flyweight pattern work in this case?
    For example if I create just a single JLabel and use it to paint all my icons that's great! but what happens with mouse events? what happens when I want to drag a thumbnail over another one and how the partial repainting of the thumbnail below should be handled?
    Am I missing something here, or in order to implement the flyiweight pattern in this case I will have to write endless lines of code to replicate the functionality that swing arleady provides in each JComponent? (e.g. targetting of mouse events, repainting etc)
    Cheers,
    Kyri

    I don't think Flyweight applies, because you really don't want to share any UI component that generates events unless the response is the same for all of them.
    If you read Flyweight, I think it was intended for things like caching the first 128 Integers, etc. - think finite, countable, immutable things. I don't think UI elements apply.
    %

  • Adding custom GUI components to a panel

    <sorry about the 'Hello All' subject in the previous post>
    I am creating a Backgammon game for my JAVA programming class. I would like to design a board and have certain checker pieces that can be dragged around on the board. In the course I am taking, I still have not been able to understand how a GUI interface has GUI components that is "custom built" like my checker class. My checker class below draws a picture of a checker on a JPanel. I want it to exist inside a JPanel(that has a board painted in it) with 30 checkers that can be moved around. Any feedback would be appreciated including helpful packages, classes, trails, etc.
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.util.Random;
    import javax.swing.JPanel;
    import java.awt.BasicStroke;
    // Checker.java - This will draw the checkers used in the game
    public class Checker extends JPanel
    private Color checker_color; // color of checker
    private int abs_pos;
    private int player; // player 1 or player 2
    Checker(Color check_color, int pos, int plyr)
         checker_color = check_color;
         abs_pos = pos;
         player = plyr;
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         Graphics2D g2d = (Graphics2D) g; // cast g to Graphics2D
         this.setBackground(Color.WHITE);
         // make a circle
         g2d.setColor(checker_color);
         g2d.setStroke(new BasicStroke(1.0f));
         g2d.fillOval(47,47, 35, 35);
         g2d.setColor(Color.BLACK);
         g2d.setStroke(new BasicStroke(2.0f));
         g2d.drawOval(47, 47, 35, 35);
    public int getPlayer(){
         return player;
    public Color getCheckerColor(){
         return checker_color;
    public int getPosition(){
         return abs_pos;
    public void setPosition(int pos){
         abs_pos = pos;
    }

    Um... pretty much the way you are doing it in the code you already posted. What is the problem? Not that there's not problems....
    1) setBackground called in paintComponent doesn't do much. Just set the background outside paint and super.paintComponent() will fill the BG color if the component isn't opaque.
    2) a checker, I would expect, would be opaque, actually.
    3) the oval size you draw would probably be better off being based on the size of the component (getSize()) instead, that way it scales easily.
    But other then that, you are doing it right. You probably need to set the size and location of each checker object explicitly, since most likely it's being used in a container with a null layout.

  • Initializing JDialogs or Other GUI Components within SwingWorker

    Hello Every one,
    I have been using SwingWorker class heavily in my application and recently I noticed that If I click on a button twice or thrice the third or 4th it takes more time to perform the action in which SwingWorker is being used. So I started reading more about SwingWorker and after reading number of articles and posts on this forum I believe I am not using SwingWorker correctly. But, I am not still sure ( or may be I am afriad or I am not ready to change my code in so many files and so many locations :(
    So I thought to ask some gurus following questions, in this forum before I proceeed with the code refactoring.
    Question 1:* I am performing GUI operations in doInBackground() is it ok to perform swing operations or create swing components in this method of SwingWorker?
    Example Code :
    jbtnModifyUser Action Event
    private void jbtnModifyUserActionPerformed(java.awt.event.ActionEvent evt) {
    setButtonsState(false);
    final SwingWorker worker = new SwingWorker() {
    protected Object doInBackground() {
    try {
    openUserModifierDialog(SELECTED_PROFILE);
    } catch (Exception ex) {
    ex.printStackTrace();
    } finally {
    return null;
    public void done()
    setButtonsState(true);
    worker.execute();
    }Open Dialog Method wich I call from several other Swing Components Action performed event
    private void openUserModifierDialog(UserProfile profile) throws ServerException {
    UserModifierDialog modifier = new UserModifierDialog(_frame, true, profile);
    modifier.pack();
    modifier.setVisible(true);
    if (modifier.isModified()) {
    resetFields();
    populateUserTable();
    } If I click 3 to 4 times same button the 4th or 5th time the dialog opens after soem delay like 10 seconds. But in first two three click it opens quickly like in 2 to 3 seconds. Is it due to the fact that I am perfoming Swing GUI operations in doInBackgroundMethod()?
    Question 2: Should I use EventQueue.invokeLater() but as far as I have learned from the articles, the actionPerformed events already run on EDT.
    Question 3:_ Each dialog has multiple swing components like combo boxes, tables, tress which it populates after fetching data from the Database in its constructor. It takes like 1 to 2 seconds to bring data and initialize all swing components. Once the Dialog is initialized in the constructor I call my own function to set the existing user details ( As shown below ).
    I need to set all the details before I show the Dialog to the user. To achieve this what is the best practice? Where should I use SwingWorker in current scenario? in Dialog's PostInitialize()? In Dialog's Constructor()? or in the Frame's openModifierDialog()?
    public UserModifierDialog(java.awt.Frame parent, boolean modal, UserProfile userprofile)
    throws ServerException {
    super(parent, modal);
    if (userprofile != null) {
    SELECTED_USER_PROFILE = userprofile;
    }else{
    //throw new Exception("Invalid user record. User profile cannot be null. ");
    initComponents();
    postInitialize(); // my function called to set the user details on the screen
    private void postInitialize() throws ServerException {
    _userManager = new UserManager();
    initializeAllPermissions();
    initializeUserGroups();
    setFields(SELECTED_USER_PROFILE);
    private void initializeUserGroups() throws ServerException {
    _jcbUserGroup.removeAllItems();
    _jcbUserGroup.setModel(new ArrayListModel(_userManager.getAllUserGroups ()));
    _jcbUserGroup.setSelectedIndex(0);
    private void setFields(Userprofile profile) throws ServerException{
    _jlblUserID.setText(profile.getUserid().toString());
    _jtfUserName.setText(profile.getUsername());
    _jtfFirstName.setText(profile.getFirstname());
    _jtfLastName.setText(profile.getLastname());
    _jtfPassword.setText(profile.getPassword());
    _jtfConfirmPassword.setText(profile.getPassword());
    _jtaDescription.setText(profile.getDescription());
    _jcbUserGroup.setSelectedItem(_userManager.getUserGroup(profile.getUserGroupID()));
    } Question 4: I noticed that if I use following code in my openModifierDialog function to execute the worker rather then its own execute method the dialog opens quickly each time.
    Is it good idea to use the following to execute a SwingWorker or I shouldn't as I may fall in some threading issues later on which I am not aware of?
    Thread t = new Thread(worker);
    t.start();Hope to hear some useful comments / answers to my queries.
    Thanks in advance.
    Regards

    Thanks for your prompt reply and answers to my queries.
    Well, I know there are enormous faults in this code. Thats why I am seeking guru's advice to clean the mess. Let me give you breif background of the code. The current code was written by some one else using old version of SwingWorker and I am just trying to clean the mess.
    All the JDialog or Swing Components intialization code was in construct() method of previous SwingWorker. Later on when the SwingWorker became the part of Java SE 6 all application code was refactored and the GUI components initialization was moved to the new function doInBackground().
    The sample code represents the current condition of the code. All I needed was a shortcut to clean the mess or to avoid changes at so many places. But it seems that there is no easy workout for the current situation and I have to change the entire application code. I have gone through the SwingWorker API and tutorial @ [http://java.sun.com/developer/technicalArticles/javase/swingworker] and I am doing following to clean this mess.
    Well the following code is proposed refactoring of the previous code. Hope to hear your comments on it.
    private void jbtnModifyUserActionPerformed(java.awt.event.ActionEvent evt) {
    try{
    openUserModifierDialog(SELECTED_PROFILE);
    } catch (Exception ex) {
    logger.error(ex);
    //show some message here
    } finally {
    private void openUserModifierDialog(UserProfile profile) throws ServerException {
    UserModifierDialog modifier = new UserModifierDialog(_frame, true, profile);
    modifier.pack();
    modifier.setVisible(true);
    if (modifier.isModified()) {
    resetFields();
    //UserModifierDialog Constructor
    public UserModifierDialog(java.awt.Frame parent, boolean modal, UserProfile userprofile)
    throws ServerException {
    super(parent, modal);
    if (userprofile != null) {
    SELECTED_USER_PROFILE = userprofile;
    } else {
    //throw new Exception("Invalid user record. User profile cannot be null. ");
    initComponents();
    postInitialize(); // My function called to set the user details on the screen
    private void postInitialize() {
    _userManager = new UserManager();
    setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
    final SwingWorker worker = new SwingWorker() {
    protected Object doInBackground() {
    try {
    return _userManager.getAllUserGroups(); //returns ArrayList of all user groups from database
    } catch (ServerException ex) {
    //Show Message here
    return null;
    protected void done() {
    try {
    if (get() != null) {
    _jcbUserGroup.setModel(new ArrayListModel((ArrayList) get()));
    _jcbUserGroup.setEditable(false);
    setFields(SELECTED_USER_PROFILE);
    else
    //show some error to user that data is empty
    } catch (InterruptedException ex) {
    //show message here
    } catch (ExecutionException ex) {
    //show message here
    } finally {
    setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
    worker.execute();
    private void setFields(Userprofile profile) throws ServerException {
    _jlblUserID.setText(profile.getUserid().toString());
    _jtfUserName.setText(profile.getUsername());
    _jtfFirstName.setText(profile.getFirstname());
    _jtfLastName.setText(profile.getLastname());
    _jtfPassword.setText(profile.getPassword());
    _jtfConfirmPassword.setText(profile.getPassword());
    _jtaDescription.setText(profile.getDescription());
    _jcbUserGroup.setSelectedItem(_userManager.getUserGroup(profile.getUserGroupID()));
    }In some places where data is way too huge I am going to use process and publish methods of SwingWorker.
    Now I have another question, how I can notify/throw any exceptions occured inside SwingWorker doInBackground method or done method to the function who executed SwingWorker. Currenlty I am catching the excpetions in the done method and showing a dialog box. But I want to throw it to the postInitialize method the method who created and executed the Worker. What is the best practice of handling exceptions in SwingWorker methods.
    Do you see any problems in proposed refactoring?
    Hope to hear your comments.
    Regards

  • XML as datasource in GUI components framework

    Hi all,
    I'm looking for a framework to use XML data as datasouce to GUI components like Swing ones. I've investigated SwingLabs but in it XML databinding namely is under process now. Can anyone suggest something on the subject?
    WBR, Max

    if there are few data use odbc directly to the xml...
    but the best way is to put them in a relational Db
    i hope i helped....
    http://greekoraclebi.blogspot.com/
    ///////////////////////////////////////

  • GUI components not clearing from JDialog closing

    Greetings,
    I have developed an application which works on several different computers with several different JVMs, but which does not operate as anticipated on my (new) tablet PC. It leaves GUI components on the main JFrame from various Jdialog boxes (after closing them) that I throw at the user when the program starts.
    I also have a username/password prompt at the beginning which is another JFrame that doesn't appear correctly. The input areas do not appear with a white background and the Username and Password JLabels have echoed themselves into that area.
    I'm guessing this is Windows XP, Tablet Edition issue. I'd like to know if anyone else has experienced anything similar?
    FYI, this programs works quite well on Windows 98, Windows XP Home and Professtional, Windows 2000, and Windows ME.
    Any help would be most appreciated.
    Regards

    Hi all,
    I am trying to develop a Java application on the Tablet PC. I am new to this platform and could not find much information about Java related Tablet PC development .So I am posting this question here
    Details
    I have developed a Swing Application in Java (J2SDK 1.4.2) for a Client, which currently runs on Windows XP on the Standard Laptop. The application uses the following
    1) Menus
    2) Panels
    3) Dialogs
    It consists of an entry form, which is saved as an XML file on the user's computer. Also it uses an Access Database.
    The other thing that the application uses is a Signature Capture Device to capture a user's signature
    I would like to move this application to the Tablet PC.
    I have the following questions
    1) What SDK do I use for the Tablet PC? Also what version of Java web start and Run time?
    2) What kind of changes do I need to make in my application?
    3) Can I make use of the "Ink" feature, which is provided with a Tablet PC in Java?
    4) Where can I find user samples if any for Java Tablet PC development?
    BTW I am using Toshiba Prot�g� 3500 for my project.
    Thanks,
    Raja

  • GUI Components & Graphical drawings

    Hi,
    I�m new to Swing (haven�t done much GUI since Motif!) and I�m a little confused about the relationship between GUI components and �drawn� graphics.
    In my application I have two JPanels � an upper and a lower � that display two views of the same data,
    In both of these JPanels I do my graph drawing using g.drawXXX() or g.fillXXX().
    I label the displays using g.drawString()
    However, I want to add some checkboxes to one of the JPanel displays that will trigger actions in the other JPanel. I�m not sure how to get the checkboxes to show up in the right place. It feels like the GUI components work in Layout mode whereas the graphics are in x,y coordinate space.
    I see that JComponent has setLoaction / setBounds methods � but I�ve not had any joy with these so far.
    I can see that I could create my own JComponent subclass that has the GUI and the graphics area and this could use a Layout to line things up.
    Basically � can I draw GUI components at an x,y coordinate on a JPanel?
    If this sounds like bad practice I�d welcome any sources of reference.
    Many thanks.

    Hi,
    My question probably sounds more complicated than it is owing to my inexperience with Swing. I'm sure what I'm after is done thousands of time in other apps.
    Bascially I have two set of graphs -
    One is pure graphical (plotting stock prices etc.).
    The other contains horizontal "bar" format data that lines up below the stock price graph
    (Again see latest posting here : http://www.chriswardsweblog.blogspot.com/)
    What I'm after is to have some controls at the right hand end of each bars. Presently I would imagine these to be a JCheckBox and maybe a JLabel to replace the g.drawString() rendered label in the screenshot.
    The reason I want this is that the upper graph area shows a plotted view of the bar data. I want to be able to check/uncheck the box to see the plotted quote lines turn on/off.
    I am pretty sure that I need to divide that lower JPanel into a "Graphical" panel for the bars and a "Component" panel for the controls. That feels like the correct thing to do - I just wanted someone to confirm I wasn't getting the wrong end of ths stick.
    If this is the case - I think I need to sort out what Layout I should use that will allow me to get the JCheckbox & JLabel to line up with the bars. I have been look at the Box layout which would seem to allow me to do that.
    I have another open question in this forum about how to toggle the visibilty of the upper panel quote lines - maybe that's where I need a Glass Panel?
    Does this clarify things?
    Thanks for all help.

  • Creating Undo Menu on Swing GUI

    Undo Menu is to be Created on Swing GUI on the Graphics. In the Tutorial, Undo with Text is given. But on implementing the logic of Undo with Text , some Errors come.

    You can use javax.swing.undo.* stuff only with classes implementing
    javax.swing.text.Document interface.
    To add undo/redo functionality for some Graphic components you should program this mechanism by yourself.
    So create your own object model, track all changes and implement/add appropriate listeners.

  • Need help with threading in Swing GUI !!!

    I've written an app that parses and writes
    files. I'm using a Swing GUI. The app
    could potenially be used to parse hundreds or even
    thousands of files. I've included a JProgressBar
    to monitor progress. The problem is when I parse
    a large number of files the GUI freezes and only
    updates the values of the progress bar when the
    parsing and writing process is finished.
    I assume I need to start the process in a seperate thread. But, I'm new to threads and I'm not sure
    whether to start the Progressbar code in a seperate
    thread or the parsing code. As a matter of fact I really
    don't have any idea how to go about this.
    I read that Swing requires repaints be done in the
    event dispatch thread. If I start the parsing in a seperate
    thread how do I update the progressbar from the other
    thread? I'm a thread neophyte.
    I need a cigarette.

    In other words do this:
    Inside event Thread:
    handle button action
    start thread
    return from action listener
    Inside worker Thread:
    lock interface
    loop
    perform action
    update progress bar
    unlock interface
    return from worker ThreadDoesn't updating the progress bar (and locking/unlocking the interface components) from within the worker thread violate the rule that you shouldn't mess with Swing components outside the event thread? (Do I have that rule right?)
    In any case, is there any way to just post some kind of event to the progress bar to update it from within the worker thread, thereby insuring that the GUI progress bar update is being invoked from the event thread? This would also obviate the need to use a timer to poll for an update, which I think is a waste especially when the monitored progress is at a variable rate, (or for number crunching, is executing on different speed machines).
    Also, doesn't using invokeLater() or invokeAndWait() still block the event dispatching thread? I don't understand how having a chunk of code started in the event thread doesn't block the event thread unless the code's executed in a "sub-thread", which would then make it not in the event thread.
    I'm also looking to have a progress bar updated to monitor a worker thread, but also want to include a "Stop" button, etc. and need the event queue not to be blocked.
    The last thing I can think of is to implement some kind of original event-listener class that listens to events that I define, then register it with the system event queue somehow, then have the worker thread post events to this listener which then calls setValue() in the progress bar to insure that the bar is updated from the event queue and when I want it to be updated. I don't know yet if it's possible to create and register these kinds of classes (I'm guessing it is).
    Thanks,
    Derek

  • Developing swing GUI using XML

    hi
    I must develop a GUI using swing by parsing XML documents.How to render the swing objects at run time, after parsing the XML document.I must know the process of creating the swing containers,components from XML document. Some open sources are available for the purpose but i must create a framework for our own purpose, so must know the process involved.
    kindly provide me any links or tutorial for the same.
    with Regards,
    A.Rajesh

    hey thanks for the help...i saw these tools but my problem will not be solved by these as the diagram i need to generate from XML is a class diagram. The components of class diagram cannot be made using swings...eg arrow,rectangle,aggregation symbol etc....

  • Designing a smart Swing GUI with design patterns

    Hi !
    I have to build a quite big Swing GUI from
    scratch. I would like to use smart design patterns to :
    * ensure reusability of some components
    * offer a framework-like set of solid classes
    to deal with generic problems
    * try to respect MVC pattern as close as possible
    from the real MVC spirit (not the half MVC
    pattern Swing is build upon)
    Could somebody give me any link towards ressources/docs/articles dealing with how
    to build such a smart Swing GUI ?
    Thanx a lot !

    Hi !
    I have to build a quite big Swing GUI from
    scratch. I would like to use smart design patterns to :
    * ensure reusability of some components
    * offer a framework-like set of solid classes
    to deal with generic problems
    * try to respect MVC pattern as close as possible
    from the real MVC spirit (not the half MVC
    pattern Swing is build upon)
    Could somebody give me any link towards ressources/docs/articles dealing with how
    to build such a smart Swing GUI ?
    Thanx a lot !

  • Loading large files in Java Swing GUI

    Hello Everyone!
    I am trying to load large files(more then 70 MB of xml text) in a Java Swing GUI. I tried several approaches,
    1)Byte based loading whith a loop similar to
    pane.setText("");
                 InputStream file_reader = new BufferedInputStream(new FileInputStream
                           (file));
                 int BUFFER_SIZE = 4096;
                 byte[] buffer = new byte[BUFFER_SIZE];
                 int bytesRead;
                 String line;
                 while ((bytesRead = file_reader.read(buffer, 0, BUFFER_SIZE)) != -1)
                      line = new String(buffer, 0, bytesRead);
                      pane.append(line);
                 }But this is gives me unacceptable response times for large files and runs out of Java Heap memory.
    2) I read in several places that I could load only small chunks of the file at a time and when the user scrolls upwards or downwards the next/previous chunk is loaded , to achieve this I am guessing extensive manipulation for the ScrollBar in the JScrollPane will be needed or adding an external JScrollBar perhaps? Can anyone provide sample code for that approach? (Putting in mind that I am writting code for an editor so I will be needing to interact via clicks and mouse wheel roatation and keyboard buttons and so on...)
    If anyone can help me, post sample code or point me to useful links that deal with this issue or with writting code for editors in general I would be very grateful.
    Thank you in advance.

    Hi,
    I'm replying to your question from another thread.
    To handle large files I used the new IO libary. I'm trying to remember off the top of my head but the classes involved were the RandomAccessFile, FileChannel and MappedByteBuffer. The MappedByteBuffer was the best way for me to read and write to the file.
    When opening the file I had to scan through the contents of the file using a swing worker thread and progress monitor. Whilst doing this I indexed the file into managable chunks. I also created a cache to further optimise file access.
    In all it worked really well and I was suprised by the performance of the new IO libraries. I remember loading 1GB files and whilst having to wait a few seconds to perform the indexing you wouldn't know that the data for the JList was being retrieved from a file whilst the application was running.
    Good Luck,
    Martin.

  • Running a Java application from a Swing GUI

    Hi,
    I was wondering if there is a simple way to run a Java application from a GUI built with Swing. I would presume there would be, because the Swing GUI is a Java application itself, technically.
    So, I want a user to click a button on my GUI, and then have another Java application, which is in the same package with the same classpaths and stuff, run.
    Is there a simple way to do this? Do any tutorials exist on this? If someone could give me any advice, or even a simple "yes this is possible, and it is simple" or "this is possible, but difficult" or "no this is not possible" answer, I would appreciate it. If anyone needs more information, I'll be happy to provide it.
    Thanks,
    Dan

    I don't know if it is possible to run the main method from another Java app by simply calling it...
    But you could just copy and paste the stuff from your main method into a new static method called something like runDBQuery and have all the execution run from there.
    How does that sound? Is it possible?
    What I'm suggeting is:
    Original
    public class DBQuery{
    public static void methodA(){
    public static void doQuery(){
    methodA();
    public static void main(String[] args){
    // Your method calls
    //Your initializing
    doQuery();
    }Revised:
    public class DBQuery{
    public static void methodA(){
    public static void doQuery(){
    methodA();
    public static void doMyQuery(){
    // Your method calls
    //Your initializing
    doQuery();
    // No main needed!!
    //public static void main(String[] args){
    // Your method calls
    //doQuery();
    //}

Maybe you are looking for