Swing & Threads....help me!

Hi all,
I am writting an application that requires a file to be read. I need to be able to read a file and display the first 10 lines of the file into a Jeditorpane, and display it , while still processing the rest of the file to also display it in an other jeditorpane.
Or is it possible to read the first 10 lines, display them... and continue to read the rest of the file and finaly overwrite the existing jeditorpane.??
I was thinking of using threads to do this task.
Any comments are welcome.

WRITING LIKE THIS!!!!!! DOES NOT!!!!!! MAKE PEOPLE!!!! WANT TO ANSWER YOUR!!!!! QUESTIONS!!!!!! IN FACT,!!!!!! IT'S RATHER ANNOYING!!!!! TO READ!!!!!! AND VERY!!!! FEW PEOPLE WILL!!!!!! BOTHER TO READ A POST!!!!!! THAT LOOKS LIKE!!!!! THIS!!!!!!!
To repeat the excellent guidelines from JavaRanch:
* We all answer questions here voluntarily, in our leisure time. We do that because doing so is fun for us, because we enjoy helping people and having interesting discussions. Guess what? It is much less fun if it gets stressful. So the last thing you want to do to get us to answer your question is to pass your stress over to us.
* People who are stressed and want a fast answer often don't even find the time to do the necessary research or to formulate their question in an easy to comprehend way. That's even less fun to work with. So you really don't want us to feel your stress. Instead you want to take your time to write a well formulated post that is fun to answer. The less likely it is for us to know that your question is urgent, the more likely you are to get a fast answer!
* The simple notion that you want your post to be answered faster than those of the other members might feel rather unfair to some of us. Doubly so because often "urgent" questions actually are homework questions. Yours might be different, but someone who had bad experiences with this type of question might not read far enough to notice.
* If it is really that urgent, my answer may already come too late, so I will think twice before taking the time to formulate it.
* Last but not least, having the word "urgent" in the subject line actually obfuscates it, makes it harder to decipher what the actual question is, and therefore to decide to actually read the thread. This grossly conflicts with the important practice to UseAMeaningfulSubjectLine.
~

Similar Messages

  • In this case, can I modify swing GUI out of swing thread?

    I know the Swing single thread rule and design (Swing is not thread safe).
    For time-consuming task, we are using other thread to do the task and
    we use SwingUtilities.invokeAndWait() or SwingUtilities.invokeLater (or SwingWorker) to update Swing GUI.
    My problem is, my time-consuming task is related to Swing GUI stuff
    (like set expanded state of a huge tree, walk through entire tree... etc), not the classic DB task.
    So my time-consuming Swing task must executed on Swing thread, but it will block the GUI responsivity.
    I solve this problem by show up a modal waiting dialog to ask user to wait and
    also allow user to cancel the task.
    Then I create an other thread (no event-dispatch thread) to do my Swing time-consuming tasks.
    Since the modal dialog (do nothing just allow user to cancel) is a thread spawn by
    Swing event-dispatch thread and block the Swing dispatch-thread until dialog close.
    So my thread can modify Swing GUI stuff safely since there are no any concurrent access problem.
    In this case, I broke the Swing's suggestion, modify Swing stuff out of Swing event-dispatch thread.
    But as I said, there are no concurrent access, so I am safe.
    Am I right? Are you agree? Do you have other better idea?
    Thanks for your help.

    If you drag your modal dialog around in front of the background UI, then there is concurrent access: paint requests in your main window as the foreground window moves around.

  • Killing a Swing thread

    Hello,
    How can I kill a Swing thread? For example the program below would never exit. Sure you can type System.exit(0) which would exit anything, but what are the other solutions?
    I tried putting chooser = null;
    System.gc();in the end of main() but this won’t work.
    To formulate my question better - how would I kill a thread I do not have complete command of (i.e. I can’t do usual do/while thread stopping)?
    Big thanks in advance.
    public class SwingLiveTest{
        public static void main(String[] args) {
            JFileChooser chooser = new JFileChooser();
            if (chooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION) return;
            File file = chooser.getSelectedFile();
            System.out.println(file);
            /*chooser = null;
            System.gc(); */

    You can't kill any Thread like this, at least not those where there is no method to call.
    It is possible to cause a Thread to stop, call the stop method, however this is not the recommended approach for very good reasons (Read the JavaDocs for java.lang.Thread.stop() method to see why.
    It should be possible, once you have obtained a reference to the Thread you wish to stop, to call interrupt() on that Thread.
    This is not guaranteed to work because you are dependent on the implementation of the Thread class you are manipulating or the Runnable that the Thread instance is currently running.
    There may be classes in the com.sun packages which can aid you with this problem, this is where Sun usually sticks undocumented implementation however these packages are not officially supported and there is no guarantee that classes you use in one VM are available in another, in particular when the VM you are using is not a Sun VM.

  • Thread in Swing -Please help

    Hi
    I want to use thread in loading data in the JFrame / JInternalFrame and thus separating the initialization of the GUI.
    The sample is as follows-
    public class TestThreadFrame extends javax.swing.JFrame {
    public TestThreadFrame() {
    initComponents();
    loadData();
    private void initComponents() {
    jComboBox1 = new javax.swing.JComboBox();
    getContentPane().setLayout(new java.awt.GridBagLayout());
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    jComboBox1.setPreferredSize(new java.awt.Dimension(150, 25));
    getContentPane().add(jComboBox1, new java.awt.GridBagConstraints());
    pack();
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
    * @param args the command line arguments
    public static void main(String args[]) {
    new TestThreadFrame().show();
    // variable declare
    private javax.swing.JComboBox jComboBox1;
    void loadData(){
    //code for loading data e.g. loading data in the JCombobox
    ---> Any help is appreciated.
    mortoza

    Do you mean something like this ?
    public class TestThreadFrame extends javax.swing.JFrame {
    public TestThreadFrame() {
    initComponents();
    // loadData();
    loadData l = new loadData();
    l.start();
    private void initComponents() {
    jComboBox1 = new javax.swing.JComboBox();
    getContentPane().setLayout(new java.awt.GridBagLayout());
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    jComboBox1.setPreferredSize(new java.awt.Dimension(150, 25));
    getContentPane().add(jComboBox1, new java.awt.GridBagConstraints());
    pack();
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
    * @param args the command line arguments
    public static void main(String args[]) {
    new TestThreadFrame().show();
    // variable declare
    private javax.swing.JComboBox jComboBox1;
    class loadData extends Thread
    public void run()
    {   try  {
    //code for loading data e.g. loading data in the JCombobox
    jComboBox1.addItem("Hello");
    Thread.sleep(2000);
    jComboBox1.addItem("Hello2");
    Thread.sleep(2000);
    jComboBox1.addItem("Hello3");
    Thread.sleep(2000);
    jComboBox1.addItem("Hello3");
    catch( Exception x ) { System.out.println(" Ooops : "+x.toString() ); }

  • In need of thread help...please!

    Have a map like applet running on netscape6.2 and IE5.0 both using the java plug-in 1.4. Here is the deal, want to make applet as a thread so I can stop and start at will. Unfortunately my applet wont show as a thread. It runs all the way through to the run and just stays at run, but doesnt show the "Map". Whereas it shows the map without the thread. Reason I'm trying to do the thread is b/c of post: "cache or stop/start problem" Please help!
    Code before thread:
    public class myApplet extends JApplet
    public MapObj map;
    public myApplet() {}
    public void init()
    System.out.println("DApplet: init");
    try
    jbInit();
    catch(Exception e)
    e.printStackTrace();
    private void jbInit() throws Exception
    addComponentListener(new java.awt.event.ComponentAdapter()
    public void componentResized(java.awt.event.ComponentEvent e)
    java.awt.Component c = e.getComponent();
    Map = new MapObj(int, int);
    getContentPane().add(Map);
    public void start()
    System.out.println("DApplet: started");
    public void stop() {
    System.gc();
    System.out.println("DApplet: stoped");
    public void destroy()
    System.out.println("DApplet: destroyed");
    Code after thread:
    public class DApplet extends JApplet implements Runnable{
    public MapObj Map;
    public Thread AppletThread = null;
    public myApplet() {}
    public void init()
    try
    jbInit();
    catch(Exception e)
    e.printStackTrace();
    /**Component initialization*/
    private void jbInit() throws Exception
    java.awt.Dimension sd = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    addComponentListener(new java.awt.event.ComponentAdapter()
    public void componentResized(java.awt.event.ComponentEvent e) {
    java.awt.Component c = e.getComponent();}
    Map = new MapObj(int, int);
    public void start()
    if(AppletThread == null)
    AppletThread = new Thread(this, "myApplet");
    AppletThread.start();
    public void stop()
    AppletThread = null;
    System.gc();
    public void run()
    getContentPane().add(Map);
    }

    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import javax.swing.*;
    import java.lang.*;
    import java.*;
    public class Applet extends JApplet implements Runnable{
    boolean isStandalone = false;
    public MapObj Map;
    private int winW =1960;
    private int winH = 1700;
    public Thread AppletThread;
    public DApplet() {
    public void run(){
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void jbInit() throws Exception {
    java.awt.Dimension sd = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    winW = sd.width - 30;
    winH = sd.height - 30;
    setSize(winW, winH);
    addComponentListener(new java.awt.event.ComponentAdapter() {
    public void componentResized(java.awt.event.ComponentEvent e) {
    java.awt.Component c = e.getComponent();
    Map = new MapObj(winW, winH);
    getContentPane().add(Map);
    public void start() {
    if(AppletThread == null)
         AppletThread = new Thread(this, "Applet");
         AppletThread.start();
    public void stop() {
    AppletThread.stop();
    AppletThread = null;
    System.exit();
    System.gc();
    public void destroy()
    System.gc();
    }

  • Swing/Threads, changing the GUI

    Hey all, I have a question related to the java swing class, and manipulating a GUI which is something that I have never done before. Basically I have a threaded Listener class which returns a status boolean. Related to that status, I have a Jlabel which is supposed to display green if the status is true, and red if the status is false, however it is not working correctly. Below is my code, and I would appreciate some help if anyone has a fix, or better way to do this... Thanks in advance
    //Listener Class
    public class Listener extends Thread{
         private boolean isGood = false;
         public Listener(//...) {
         public void run()
              // does stuff here that sets the isGood var
         public bool getIsGood()
              return this.isGood;
    //GUI
    public class Visualizer {
         private static Listener listener;
         public Visualizer(Listener listener){
              this.listener = listener;
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
         private static JFrame frame;
         private static JLabel status;
         public static void createAndShowGUI() {
    //Create and set up the window.
    frame = new JFrame("Window");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    status = new JLabel("Listener... ");
    status.setOpaque(true);
    status.setBackground(Color.RED);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    frame.setSize(new Dimension(204, 115));
    frame.setContentPane(status);
    listener.start();
    while(true){
         boolean isGood = listener.getIsGood();
    if(isGood){
    status.setBackground(Color.GREEN);
    else{
    status.setBackground(Color.RED);
         try{
              Thread.sleep(1000);
         }catch(Exception E){
              E.printStackTrace();
    I purposely left out some of the code because I wanted to make it simpler to follow. Essentially this is what is going on, and hopefully someone can point out why its not working and how to fix it. Thank you for reading this.

    thanks for the advice Petes, I was looking for the code tag before but didnt see it. I have created an SSCCE, and I apologize for not making it earlier. Here is the code. The threads seem to be getting stuck, and the label doesnt alternate between red and green as it should. Let me know if you need anything else:
    package simplified;
    public class Main{
         public static void main(String[] args) {
              Listener theListener = new Listener();
              theListener.start();
              Visualizer theView = new Visualizer(theListener);
    //Listener Class
    public class Listener extends Thread{
         private boolean isGood = false;
         public Listener() {
         public void run(){
              if(this.isGood == true){
                   this.isGood = false;
              else{
                   this.isGood = true;
              try{
                   this.sleep(1000);
              }catch(Exception e){
                   e.printStackTrace();
         public boolean getIsGood(){
              return this.isGood;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.Dimension;
    public class Visualizer {
         private static Listener listener;
         public Visualizer(Listener listener){
         this.listener = listener;
         javax.swing.SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                   createAndShowGUI();
         private static JFrame frame;
         private static JLabel status;
         public static void createAndShowGUI() {
              //Create and set up the window.
              frame = new JFrame("Window");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              status = new JLabel("Listener... ");
              status.setOpaque(true);
              status.setBackground(Color.RED);
              //Display the window.
              frame.pack();
              frame.setVisible(true);
              frame.setSize(new Dimension(204, 115));
              frame.setContentPane(status);
              while(true){
                   boolean isGood = listener.getIsGood();
                   if(isGood){
                        status.setBackground(Color.GREEN);
                   else{
                        status.setBackground(Color.RED);
                   try{
                        Thread.sleep(1000);
                   }catch(Exception E){
                        E.printStackTrace();
    }

  • Swing ActionListener help?

    Hi there,
    I'm trying to get to grips with Swing and I'm reasonably comfortable with laying out the GUI now. However, I'm still trying to get to grips with ActionListeners. As I understand it, you can have any old class as an ActionListener as long as it implements the ActionListener interface.....then you can just add this ActionListener to a component using .addActionListener().
    Couple of questions though....
    1. Is it generally bad design to just have a component call <whatever>.addActionListener(this) and then just implement the actionPerformed() method within the same class?
    2. Do you have to define a seperate ActionListener class for each type of component, or can you use one ActionListener for, say, one whole GUI screen? How do you usually organise these things?
    3. Anyone point me towards some decent tutorials on Java Swing event-handling?....preferably not the Sun ones, although if they are regarded as the best, I'll take 'em. :)
    Thanks for your time.

    URgent help need.
    i need to link the page together : by clicking the button on the index page.
    it will show the revelant class file. I have try my ationPerformed method to the actionlistener, it cannot work.
    Thanks in advance.
    // class mtab
    // the tab menu where it display the gui
    import javax.swing.*;
    import java.awt.*;
    public class mtab {
    private static final int frame_height = 480;
    private static final int frame_width = 680;
    public static void main (String [] args){
    JFrame frame = new JFrame ("Mrt Timing System");
    frame.setDefaultCloseOperationJFrame.EXIT_ON_CLOSE);
    frame.setSize(frame_width,frame_height);
    JTabbedPane tp = new JTabbedPane ();
    tp.addTab("Mrt Timing System", new sample());
    frame.setResizable(false);
    frame.getContentPane().add(tp);
    frame.setSize(680,480);
    frame.show();
    // index page
    // class sample
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Image;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.text.*;
    import javax.swing.border.*;
    class sample extends JPanel implements ActionListener
    //button
    private JButton TimingButton;
    private JButton ViewButton;
    private JButton FrequencyButton;
    private JButton calculateButton;
    private CardLayout mycard;
    private JPanel SelectXPanel;
    private JPanel SelectYPanel;
    private JPanel SelectZPanel;
    private JPanel bigFrame, mainPane;
    // constructor
    public sample() {
    super(new BorderLayout());
    //create the object
    //create button and set it
    TimingButton = new JButton("MRT Timing Calculator");
    TimingButton.addActionListener(this);
    ViewButton = new JButton("View First and Last Train");
    ViewButton.addActionListener(this);
    FrequencyButton = new JButton("Show the Train Frequency");
    FrequencyButton.addActionListener(this);
    // Layout
    //Lay out the button in a panel.
    JPanel buttonPane = new JPanel(new GridLayout(3,0));
    buttonPane.add(TimingButton);
    buttonPane.add(ViewButton);
    buttonPane.add(FrequencyButton);
    // Layout the button panel into another panel.
    JPanel buttonPane2 = new JPanel(new GridLayout(0,1));
    buttonPane2.add(buttonPane);
    tfrequency x = new tfrequency();
    fviewl2 y = new fviewl2 ();
    timing z = new timing ();
    JPanel SelectXPanel = new JPanel(new GridLayout(0,1));
    SelectXPanel.add(x);
    JPanel SelectYPanel = new JPanel(new GridLayout(0,1));
    SelectYPanel.add(y);
    JPanel SelectZPanel = new JPanel(new GridLayout(0,1));
    SelectZPanel.add(z);
    // Layout the button by putting in between the rigid area
    JPanel mainPane = new JPanel(new GridLayout(3,0));
    mainPane.add(Box.createRigidArea(new Dimension(0,1)));
    mainPane.add(buttonPane2);
    mainPane.add(Box.createRigidArea(new Dimension(0,1)));
    mainPane.setBorder(new TitledBorder("MRT Timing System"));
    // x = new tfrequency();
    // The overall panel -- divide the frame into two parts: west and east.
    JPanel bigFrame = new JPanel(new GridLayout(0,2));
    bigFrame.add(mainPane, BorderLayout.WEST);
    //bigFrame.add(x,BorderLayout.EAST); // this is where i want to link the page
    // this page being the index page. there being nothing to display.
    add(bigFrame);
    //Create the GUI and show it. For thread safety,
    public void actionPerformed (ActionEvent e){
    if (e.getSource() == TimingButton ){
    JPanel bigFrame = new JPanel(new GridLayout(0,2));
    bigFrame.add(mainPane, BorderLayout.WEST);
    bigFrame.add(SelectZPanel,BorderLayout.EAST);
    add(bigFrame);
    else if (e.getSource() == ViewButton ){
    JPanel bigFrame = new JPanel(new GridLayout(0,2));
    bigFrame.add(mainPane, BorderLayout.WEST);
    bigFrame.add(SelectYPanel,BorderLayout.EAST);
    add(bigFrame);
    else if (e.getSource() == FrequencyButton ){
    JPanel bigFrame2 = new JPanel(new GridLayout(0,2));
    bigFrame.add(mainPane, BorderLayout.WEST);
    bigFrame.add(SelectXPanel,BorderLayout.EAST);
    add(bigFrame);
    // Train Frequency Page
    // class fviewl2
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Image;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.text.*;
    import javax.swing.border.*;
    class fviewl2 extends JPanel implements ActionListener
    //Labels to identify the fields
    private JLabel stationLabel;
    private JLabel firstLabel;
    private JLabel lastLabel;
    //Strings for the labels
    private static String station = "MRT Station:";
    private static String first = "First Train Time:";
    private static String last = "Last Train Time:";
    //Fields for data entry
    private JFormattedTextField stationField;
    private JFormattedTextField firstField;
    private JFormattedTextField lastField;
    //button
    private JButton homeButton;
    private JButton cancelButton;
    private JButton calculateButton;
    public fviewl2()
    super(new BorderLayout());
    //create the object
    //Create the Labels
    stationLabel = new JLabel(station);
    firstLabel = new JLabel (first);
    lastLabel = new JLabel (last) ;
    //Create the text fields .// MRT Station:
    stationField = new JFormattedTextField();
    stationField.setColumns(10);
    stationField.setBounds(300,300,5,5);
    //Create the text fields // First Train Time:
    firstField = new JFormattedTextField();
    firstField.setColumns(10);
    firstField.setBounds(300,300,5,5);
    //Create the text fields //Last Train Time:
    lastField = new JFormattedTextField();
    lastField.setColumns(10);
    lastField.setBounds(300,300,5,5);
    //Tell accessibility tools about label/textfield pairs, matching label for the field
    stationLabel.setLabelFor(stationField);
    firstLabel.setLabelFor(firstField);
    lastLabel.setLabelFor(lastField);
    //create button and set it
    homeButton = new JButton("Home");
    //homeButton.addActionListener(this);
    cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(this);
    calculateButton = new JButton("Get Time");
    // Layout
    //MRT Station Label // insert into the panel
    JPanel StationPane = new JPanel(new GridLayout(0,1));
    StationPane.add(stationLabel);
    //MRT Station input field // insert into the panel
    JPanel StationInput = new JPanel(new GridLayout(0,1));
    StationInput.add(stationField);
    //Get Time Button // insert into the panel
    JPanel GetTime = new JPanel(new GridLayout(0,1));
    GetTime.add(calculateButton);
    //Lay out the labels in a panel.
    JPanel FlabelL = new JPanel(new GridLayout(0,1));
    FlabelL.add(firstLabel);
    FlabelL.add(lastLabel);
    // Layout the fields in a panel
    JPanel FFieldL = new JPanel(new GridLayout(0,1));
    FFieldL.add(firstField);
    FFieldL.add(lastField);
    //Lay out the button in a panel.
    JPanel buttonPane = new JPanel(new GridLayout(1,0));
    buttonPane.add(homeButton);
    buttonPane.add(cancelButton);
    // Layout all components in the main panel
    JPanel mainPane = new JPanel(new GridLayout(4,2));
    mainPane.add(StationPane);
    mainPane.add(StationInput);
    mainPane.add(Box.createRigidArea(new Dimension(0,1)));
    mainPane.add(GetTime);
    mainPane.add(FlabelL);
    mainPane.add(FFieldL);
    mainPane.add(Box.createRigidArea(new Dimension(0,1)));
    mainPane.add(buttonPane);
    mainPane.setBorder(new TitledBorder("View First and Last Train"));
    JPanel leftPane = new JPanel(new GridLayout(1,0));
    leftPane.add(Box.createRigidArea(new Dimension(0,1)));
    leftPane.add(mainPane);
    leftPane.add(Box.createRigidArea(new Dimension(0,1)));
    JPanel hahaFrame = new JPanel(new GridLayout(0,1));
    hahaFrame.add(Box.createRigidArea(new Dimension(0,1)));
    hahaFrame.setBorder(BorderFactory.createEmptyBorder(30, 10, 80, 150));
    hahaFrame.add(Box.createRigidArea(new Dimension(0,1)));
    JPanel bigFrame = new JPanel();
    bigFrame.add(hahaFrame, BorderLayout.NORTH);
    bigFrame.add(leftPane, BorderLayout.CENTER);
    add(bigFrame, BorderLayout.CENTER);
    //Create the GUI and show it. For thread safety,
    private void cancelButtonClicked()
    stationField.setText("");
    firstField.setText("");
    lastField.setText("");
    public void actionPerformed (ActionEvent e){
    if (e.getSource() == cancelButton){
    cancelButtonClicked();
    }

  • Swing Thread handling

    Dear all,
    The question is as the follow:
    Condition
    Class A purpose: Get Data from SQL server 2000 e.g.
    SQLDB transaction = new SQLDB();
    transaction.getData();
    Now, I would like to handle the transaction time in order to show that it is processing with Swing component: JLabel, JButton and JFrame. How to write a swing program? Please help me or give me some reference. Thank you so much for your help!
    Regards,
    kzyo

    If java 6, this is an article which I think will probably help you immensely:
    http://java.sun.com/developer/technicalArticles/javase/swingworker/
    It's all about how to implement SwingWorker, a background threader that can among other things give progress reports to the GUI.
    Message was edited by:
    petes1234

  • Problems with swing, please help!!!

    im trying to display an image made up of a set of squares.
    i have a JFrame class which has the main method placing a JComponent into its Container using the getContentPane().add method.
    the JComponent class sets up the image using the paintComponent() method
    When i try to run the program all i get is a grey frame.
    Ive looked at other threads in this forum to fix my problem but it doesnt seem to fix it.
    any help is much appreciated.

    import java.awt.*;
    import java.awt.event.*;
    import java.util.EventListener;
    import javax.swing.*;
    import java.applet.*;
    public class Display extends JFrame
         protected DisCanvas canvas;
         protected EventListener listener;
         protected boolean isApplet = false;
         public Display(boolean isApplet)
              this.isApplet = isApplet;
              //setLayout(new BorderLayout());
         //     add(makeCanvas(), BorderLayout.CENTER);
         public Display()
              //this(true);
    canvas = new DisCanvas();
    this.getContentPane().setLayout(new BorderLayout());
    this.getContentPane().add(canvas, BorderLayout.CENTER);
    this.addWindowListener(new AppCloser());
    this.setSize(300, 300);
    this.setVisible(true);
    this.repaint();
    public static void main(String[] args)
    new Display();
    static class AppCloser extends WindowAdapter
              public void windowClosing(WindowEvent e)
                   System.exit(0);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.image.*;
    public class DisCanvas extends java.awt.Canvas
    Patch[] patchArray = new Patch[100];
    int width = 200;
    int height = 300;
    BufferedImage image;
    Graphics2D g2D;
    public DisCanvas()
    patchArray[0] = new Patch(0, 0, 20, 30); patchArray[10] = new Patch(0, 30, 20, 30);
    patchArray[1] = new Patch(20, 0, 20, 30); patchArray[11] = new Patch(20, 30, 20, 30);
    patchArray[2] = new Patch(40, 0, 20, 30); patchArray[12] = new Patch(40, 30, 20, 30);
    patchArray[3] = new Patch(60, 0, 20, 30); patchArray[13] = new Patch(60, 30, 20, 30);
    patchArray[4] = new Patch(80, 0, 20, 30); patchArray[14] = new Patch(80, 30, 20, 30);
    patchArray[5] = new Patch(100, 0, 20, 30); patchArray[15] = new Patch(100, 30, 20, 30);
    patchArray[6] = new Patch(120, 0, 20, 30); patchArray[16] = new Patch(120, 30, 20, 30);
    patchArray[7] = new Patch(140, 0, 20, 30); patchArray[17] = new Patch(140, 30, 20, 30);
    patchArray[8] = new Patch(160, 0, 20, 30); patchArray[18] = new Patch(160, 30, 20, 30);
    patchArray[9] = new Patch(180, 0, 20, 30); patchArray[19] = new Patch(180, 30, 20, 30);
    patchArray[20] = new Patch(0, 60, 20, 30); patchArray[30] = new Patch(0, 90, 20, 30);
    patchArray[21] = new Patch(20, 60, 20, 30); patchArray[31] = new Patch(20, 90, 20, 30);
    patchArray[22] = new Patch(40, 60, 20, 30); patchArray[32] = new Patch(40, 90, 20, 30);
    patchArray[23] = new Patch(60, 60, 20, 30); patchArray[33] = new Patch(60, 90, 20, 30);
    patchArray[24] = new Patch(80, 60, 20, 30); patchArray[34] = new Patch(80, 90, 20, 30);
    patchArray[25] = new Patch(100, 60, 20, 30); patchArray[35] = new Patch(100, 90, 20, 30);
    patchArray[26] = new Patch(120, 60, 20, 30); patchArray[36] = new Patch(120, 90, 20, 30);
    patchArray[27] = new Patch(140, 60, 20, 30); patchArray[37] = new Patch(140, 90, 20, 30);
    patchArray[28] = new Patch(160, 60, 20, 30); patchArray[38] = new Patch(160, 90, 20, 30);
    patchArray[29] = new Patch(180, 60, 20, 30); patchArray[39] = new Patch(180, 90, 20, 30);
    patchArray[40] = new Patch(0, 120, 20, 30); patchArray[50] = new Patch(0, 150, 20, 30);
    patchArray[41] = new Patch(20, 120, 20, 30); patchArray[51] = new Patch(20, 150, 20, 30);
    patchArray[42] = new Patch(40, 120, 20, 30); patchArray[52] = new Patch(40, 150, 20, 30);
    patchArray[43] = new Patch(60, 120, 20, 30); patchArray[53] = new Patch(60, 150, 20, 30);
    patchArray[44] = new Patch(80, 120, 20, 30); patchArray[54] = new Patch(80, 150, 20, 30);
    patchArray[45] = new Patch(100, 120, 20, 30); patchArray[55] = new Patch(100, 150, 20, 30);
    patchArray[46] = new Patch(120, 120, 20, 30); patchArray[56] = new Patch(120, 150, 20, 30);
    patchArray[47] = new Patch(140, 120, 20, 30); patchArray[57] = new Patch(140, 150, 20, 30);
    patchArray[48] = new Patch(160, 120, 20, 30); patchArray[58] = new Patch(160, 150, 20, 30);
    patchArray[49] = new Patch(180, 120, 20, 30); patchArray[59] = new Patch(180, 150, 20, 30);
    patchArray[60] = new Patch(0, 180, 20, 30); patchArray[70] = new Patch(0, 210, 20, 30);
    patchArray[61] = new Patch(20, 180, 20, 30); patchArray[71] = new Patch(20, 210, 20, 30);
    patchArray[62] = new Patch(40, 180, 20, 30); patchArray[72] = new Patch(40, 210, 20, 30);
    patchArray[63] = new Patch(60, 180, 20, 30); patchArray[73] = new Patch(60, 210, 20, 30);
    patchArray[64] = new Patch(80, 180, 20, 30); patchArray[74] = new Patch(80, 210, 20, 30);
    patchArray[65] = new Patch(100, 180, 20, 30); patchArray[75] = new Patch(100, 210, 20, 30);
    patchArray[66] = new Patch(120, 180, 20, 30); patchArray[76] = new Patch(120, 210, 20, 30);
    patchArray[67] = new Patch(140, 180, 20, 30); patchArray[77] = new Patch(140, 210, 20, 30);
    patchArray[68] = new Patch(160, 180, 20, 30); patchArray[78] = new Patch(160, 210, 20, 30);
    patchArray[69] = new Patch(180, 180, 20, 30); patchArray[79] = new Patch(180, 210, 20, 30);
    patchArray[80] = new Patch(0, 240, 20, 30); patchArray[90] = new Patch(0, 270, 20, 30);
    patchArray[81] = new Patch(20, 240, 20, 30); patchArray[91] = new Patch(20, 270, 20, 30);
    patchArray[82] = new Patch(40, 240, 20, 30); patchArray[92] = new Patch(40, 270, 20, 30);
    patchArray[83] = new Patch(60, 240, 20, 30); patchArray[93] = new Patch(60, 270, 20, 30);
    patchArray[84] = new Patch(80, 240, 20, 30); patchArray[94] = new Patch(80, 270, 20, 30);
    patchArray[85] = new Patch(100, 240, 20, 30); patchArray[95] = new Patch(100, 270, 20, 30);
    patchArray[86] = new Patch(120, 240, 20, 30); patchArray[96] = new Patch(120, 270, 20, 30);
    patchArray[87] = new Patch(140, 240, 20, 30); patchArray[97] = new Patch(140, 270, 20, 30);
    patchArray[88] = new Patch(160, 240, 20, 30); patchArray[98] = new Patch(160, 270, 20, 30);
    patchArray[89] = new Patch(180, 240, 20, 30); patchArray[99] = new Patch(180, 270, 20, 30);
    image = new BufferedImage(width, height,BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2D = image.createGraphics();
    public void paint/*Component*/(Graphics g)
    g = (Graphics2D) g2D;
    super.paint/*Component*/(g);
    for (int i = 0; i == 99; i++)
    //for (int s = 0; s > 5; s++)
    // Color[] colours = new Color[6];
    // colours[0] = Color.blue;
    // colours[1] = Color.red;
    // colours[2] = Color.green;
    // colours[3] = Color.orange;
    // colours[4] = Color.black;
    // colours[5] = Color.white;
    // g2D.setColor(colours[s]);
    g2D.setColor(Color.red);
    g2D.fillRect(patchArray.getX(), patchArray[i].getY(),
    patchArray[i].getWidth(), patchArray[i].getHeight());
    g2D.drawImage(image,0, 0, this);

  • Swing thread safe ?

    Hi
    Are swing comonents are thread safe ?
    If i am not wrong the thread safe objects are those whose data changes are predictable ( i mean no race condition)
    Is this correct ?
    I had worked on multithreaded application in MFC where we used Message queues for hadling the multithreading
    Can i use the same logic in java also ? If yes can anybody help me how can i do it
    Thanks in advance

    The Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html]Using Threads explains the concept of "Thread Safe".

  • Swing thread issu

    I have a javax.swing.JFrame extended object that after running the code
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new chatUi().setVisible(true);
            });Continues to communicate with a network server over TCP and updates a table with information. By calls to System.out.println I can see that the communication with the server is succesfull but I cant update the gui. The only way i seme able to update the gui after that point is by events that are triggerd by the user and not by functions in my code.
    What am I missing ?
    Is the only way to work with the frame object by creating threads and running them by: SwingUtilities.invokeLater. ??
    Any help would be greatly appriciated // Tomas

    Hi,
    A little bit of more code would be nice to see where your app don't do what it should do.
    In general you should post every code that interacts with the gui into the EventDispatchThread(EDT)
    a common way is to use the EventQueue as you did.
    If one of your methods invokes changes on the gui you should them post on the EDT too.
    If you want to look timebased for a special value or some networkoperations you can use
    a Timer - in your case a javax.swing.Timer and not the java.util.Timer.
    for further informations look at this tutorials :
    http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html
    http://java.sun.com/products/jfc/tsc/articles/timer/
    An other nice way to let run longer threads posting intermediate results on the gui
    is to use a SwingWorker -> javax.swing.SwingWorker
    try those things
    Olek

  • I need to control the position and size of each java swing component, help!

    I setup a GUI which include 2 panels, each includes some components, I want to setup the size and position of these components, I use setBonus or setSize, but doesn't work at all. please help me to fix it. thanks
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.FlowLayout;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.event.*;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;
    import javax.swing.JPanel;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.DefaultListModel;
    public class weather extends JFrame {
    private String[] entries={"1","22","333","4444"} ;
    private JTextField country;
    private JList jl;
    private JTextField latitude;
    private JTextField currentTime;
    private JTextField wind;
    private JTextField visibilityField;
    private JTextField skycondition;
    private JTextField dewpoint;
    private JTextField relativehumidity;
    private JTextField presure;
    private JButton search;
    private DefaultListModel listModel;
    private JPanel p1,p2;
    public weather() {
         setUpUIComponent();
    setTitle("Weather Report ");
    setSize(600, 400);
    setResizable(false);
    setVisible(true);
    private void setUpUIComponent(){
         p1 = new JPanel();
    p2 = new JPanel();
         country=new JTextField(10);
         latitude=new JTextField(12);
    currentTime=new JTextField(12);
    wind=new JTextField(12);
    visibilityField=new JTextField(12);
    skycondition=new JTextField(12);
    dewpoint=new JTextField(12);
    relativehumidity=new JTextField(12);
    presure=new JTextField(12);
    search=new JButton("SEARCH");
    listModel = new DefaultListModel();
    jl = new JList(listModel);
    // jl=new JList(entries);
    JScrollPane jsp=new JScrollPane(jl);
    jl.setVisibleRowCount(8);
    jsp.setBounds(120,120,80,80);
    p1.add(country);
    p1.add(search);
    p1.add(jsp);
    p2.add(new JLabel("latitude"));
    p2.add(latitude);
    p2.add(new JLabel("time"));
    p2.add(currentTime);
    p2.add(new JLabel("wind"));
    p2.add(wind);
    p2.add(new JLabel("visibility"));
    p2.add(visibilityField);
    p2.add(new JLabel("skycondition"));
    p2.add(skycondition);
    p2.add(new JLabel("dewpoint"));
    p2.add(dewpoint);
    p2.add(new JLabel("relativehumidity"));
    p2.add(relativehumidity);
    p2.add(new JLabel("presure"));
    p2.add(presure);
    this.getContentPane().setLayout(new FlowLayout());
    this.setLayout(new GridLayout(1,2));
    p2.setLayout(new GridLayout(8, 2));
    this.add(p1);
    this.add(p2);
    public static void main(String[] args) {
    JFrame frame = new weather();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    [http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html]
    db

  • Swing Threads

    Does anybody know how the threads in a swing application are organized. I noticed, that when i start a swing application more then 10 threads are created. Furthermore, when the "main" thread is terminated after showing the main window (a JFrame window), two windows are displayed. When the main-thread is ran in a loop (while (true) {try{Thread.sleep(100);}catch(Exception x){}), only one window is displayed. So, even if the main thread does nothing, it's necessary.
    Furthermore, i realized that, when starting other threads out from the main thread, on some win 2000 systems the threads are properly terminated but the associated handles are not freed - this leads to a "handle leak" after a certain time (48 hours). If the threads are started with invokeLater out from the main thread, then the handles are freed properly when the thread terminates.
    Does anybody know how these facts can be put together to get a bigger whole ?
    Thanks a lot.
    Stephan Gloor
    Switzerland

    hi,
    the rule is:
    swing components are not thread-safe except some, and therefore they should only be changed from within the event dispatch thread. this can be accomplished using the methods invokeLater(Runnable) and invokeAndWait(Runnable) in class javax.swing.SwingUtilities.
    best regards, Michael

  • Is it a bug of Swing? (help!!!)

    meet problem of abnormal table blinking.
    The scenario is like this,
    For Table 1, there is a backgroup thread which receive message and
    update table's model and then call
    table1.updateUI();
    table1.validate();
    directly to let JTalbe fresh. (update in non-AWT-Event dispather)
    If user try do many operation in this table, soon we can observe the blinking in this table.
    For table 2, A timer is setup up to do periodically update (update is guarantee in AWT-event dispacher)
    We found that when table 1 is blinking, table 2 is start blinking too. I really don't know why.
    It is a bug of Swing? If that is true, one table has prolem, all tables in the same VM would have problems. That is realy too bad!!

    It is a bug of Swing? No. Its a bug in your code.
    For Table 1, there is a backgroup thread which receive message and update table's model and then call
    Then thats all you need to do. The model will tell the table to repaint itself.
    table1.updateUI();
    table1.validate();Completely wrong.

  • HTML in Swing Tutorial/Help

    I'm looking for a tutorial or just help here on how to display an HTML file in a swing component.

    http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html
    These components won't be able to display anything but the most basic HTML page. I've seen better components out there (you will have to search).
    When I needed to do this, I used the browser itself. I had an applet in one frame which sent html to the other frame via javascript.

Maybe you are looking for