Custom paint() and rare repainting

I have made custom paint() method like this:
@Override
          public void paint(Graphics  g){
               int time;               
               if(renderer != null)
                    renderer.updateImage();
               time = Simulation.getCurrentStepTime();          
               if(time>=0)          labelCurrentTimeVal.setText(""+time);
               else              labelCurrentTimeVal.setText("-");
               time = Simulation.getAverageStepTime();          
               if(time>=0)          labelAvgTimeVal.setText(""+time);
               else              labelAvgTimeVal.setText("-");
               super.paint(g);
          }     I have some calculations going on in the background (separate thread). 'renderer' is responsible for repainting the JLabel holding an ImageIcon (which gets changed by the calculations). The case is that my background calculations take a few seconds. After they're done I call the repaint() method, which updates the image and paints the whole thing.
My problem is that I want to have up-to-date info on how much the iteration is taking so I`ve made the labelCurrentTimeVal JLabel to display it. The label only repaints when I call the repaint() method. However when I keep moving some slider in this panel repaint gets called all the time (I can see the labelCurrentTimeVal value changing constantly as I move the knob).
So what should I do to make the repaint() method get called often enough (20-30 times /sec to get about 20-30 fps)? I tried creating a different thread that calls repaint all the time (just to test it) and it doesn't solve the case.new Runnable() {
            public void run() {
                 while(true)
                      if(MainWindow.instance != null)
                           MainWindow.instance.repaint();
          };

I`ve made same code to represent the problem. The calculationThread does the calculations - in this case sets the iteration counter and the repaintThread is supposed to update the GUI and repaint it once in a while. GUI doesn't update at all and I don't get why?
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main extends JFrame{     
     private JPanel panel;
     private JLabel label;
     public static Main window;
     private Runnable calcThread,repaintThread;
     private static int it;
     public static void main(String[] args) {
          new Main();
     private void createComponents(){
          window = this;
          panel = new JPanel();
          label = new JLabel("iteration:");
          panel.setPreferredSize(new Dimension(200,200));
          panel.add(label);
          this.add(panel);
          this.pack();
          this.setVisible(true);
     public Main(){
          createComponents();
          calcThread = new Runnable(){
               public void run(){
                    int i=0;                    
                    while(true){                         
                         Main.it = i;
                         System.out.println("check - iteration: "+i);
                         i++;
          repaintThread = new Runnable(){
               public void run(){
                    while(true){
                         try{
                              wait(30);
                              label.setText("iteration: "+it);     
                              window.repaint();
                         }catch(InterruptedException e){}
          calcThread.run();
          repaintThread.run();
}

Similar Messages

  • Simultaneous custom painting

    I have created a JPanel which is a long rectangle "setPreferredSize(new Dimension(321, 21));" that performs custom painting . The custom painting is to represent a loop; a colored rectangle moves along the length of the panel when the process loops it repeats the painting. I have to create many instances of this panel and add these instances to the program's main panel. I have managed to get the colored rectangle to move through every instance of the panel but as each one progress they are not in sync, they each need to be at the same point of the panel at the same time. I have used a thread to control the custom painting and I think because each instance of the panel uses its own thread they are being interleaved which is resulting in time lags. Can anyone give me some ideas of how I can imlement this so each colored rectangle is at the same point at the same time. Here are some relevent code snippets:
    * This method is called from within paintComponent
    private void moveRect(Graphics g){
              if(looped==true){
                   Dimension d = getSize();
                   offscreen = createImage(d.width, d.height);
                   offscreensize = d;
                   offgraphics = offscreen.getGraphics();
                   offgraphics.setColor(new Color(115,212,236));
                   offgraphics.fillRect(xpos+1, 1, 19 ,19);
                   g.drawImage(offscreen, 0, 0, this);
    public void run(){
              while(true){
                   for(xpos = 0;xpos<=320;xpos = xpos+20){
                        repaint();
                       try{
                        Thread.sleep(116);
                       }catch(InterruptedException e){}
         

    Thanks for your reply. The Timer seems to work better. I have created a separate class for the Timer and when a new instance of the Bar JPanel is created a Timer is also created. I have made the Time class a JPanel, the problem I am having now is I need to place the Time JPanel on top of the Bar JPanel but below the Graphics on the Bar JPanel. When I try to do it the Time JPanel just sits on top of the Bar JPanel and all the graphics are not seen. The Time JPanel needs to be in the back ground; Is there a method call like setBackground that accepts components, or any ideas on how this can be achieved?

  • (Another) problem with custom painting using JApplet and JPanel

    Hi all,
    I posted regarding this sort of issue yesterday (http://forums.sun.com/message.jspa?messageID=10883107). I fixed the issue I was having, but have run into another issue. I've tried solving this myself to no avail.
    Basically I'm working on creating the GUI for my JApplet and it has a few different JPanels which I will be painting to, hence I'm using custom painting. My problem is that the custom painting works fine on the mainGUI() class, but not on the rightGUI() class. My code is below:
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    public class TetrisClone extends JApplet {
         public void init() {
              setSize( 450, 500 );
              Container content = getContentPane();
              content.add( new mainGUI(), BorderLayout.CENTER );
              content.add( new rightGUI() , BorderLayout.LINE_END );
    class mainGUI extends JPanel {
         // Main bit where blocks fall
         public mainGUI() {
              setBackground( new Color(68,75,142) );
              setPreferredSize( new Dimension( 325, 500 ) );
              validate();
         public Dimension getPreferredSize() {
              return new Dimension( 450, 500 );
         public void paintComponent( Graphics g ) {
              super.paintComponent(g);
              // As a test. This shows up fine.
              g.setColor( Color.black );
              g.fillRect(10,10,100,100);
              g.setColor( Color.white );
              g.drawString("Main",45,55);
    class rightGUI extends JPanel {
         BufferedImage img = null;
         int currentLevel = 0;
         int currentScore = 0;
         int currentLines = 0;
         public rightGUI() {
              // The right panel. Has quite a few bits. Starts here..
              FlowLayout flow = new FlowLayout();
              flow.setVgap( 20 );
              setLayout( flow );
              setPreferredSize( new Dimension( 125, 500 ) );
              setBackground( new Color(27,34,97) );
              setBorder( BorderFactory.createMatteBorder(0,2,0,0,Color.black) );
              // Next block bit
              JPanel rightNext = new JPanel();
              rightNext.setPreferredSize( new Dimension( 100, 100 ) );
              //rightNext.setBackground( new Color(130,136,189) );
              rightNext.setOpaque( false );
              rightNext.setBorder( BorderFactory.createEtchedBorder(EtchedBorder.LOWERED) );
              Font rightFont = new Font( "Courier", Font.BOLD, 18 );
              // The player's playing details
              JLabel rightLevel = new JLabel("Level: " + currentLevel, JLabel.LEFT );
              rightLevel.setFont( rightFont );
              rightLevel.setForeground( Color.white );
              JLabel rightScore = new JLabel("Score: " + currentScore, JLabel.LEFT );
              rightScore.setFont( rightFont );
              rightScore.setForeground( Color.white );
              JLabel rightLines = new JLabel("Lines: " + currentLines, JLabel.LEFT );
              rightLines.setFont( rightFont );
              rightLines.setForeground( Color.white );
              JPanel margin = new JPanel();
              margin.setPreferredSize( new Dimension( 100, 50 ) );
              margin.setBackground( new Color(27,34,97) );
              JButton rightPause = new JButton("Pause");
              try {
                  img = ImageIO.read(new File("MadeBy.gif"));
              catch (IOException e) { }
              add( rightNext );
              add( rightLevel );
              add( rightScore );
              add( rightLines );
              add( margin );
              add( rightPause );
              validate();
         public Dimension getPreferredSize() {
                   return new Dimension( 125, 500 );
         public void paintComponent( Graphics g ) {
              super.paintComponent(g);
              g.setColor( Color.black );
              g.drawString( "blah", 425, 475 ); // Doesn't show up
              g.drawImage( img, 400, 400, null ); // Nor this!
              System.out.println( "This bit gets called fine" );
    }Any help would be greatly appreciated. I've read loads of swing and custom painting tutorials and code samples but am still running into problems.
    Thanks,
    Tristan Perry

    Many thanks for reminding me about the error catching - I've added a System.out.println() call now. Anywhoo, the catch block never gets run; the image get call works fine.
    My problem was/is:
    "My problem is that the custom painting works fine on the mainGUI() class, but not on the rightGUI() class. My code is below:"
    I guess I should have expanded on that. Basically whatever I try to output in the public void paintComponent( Graphics g ) method of the rightGUI class doesn't get output.
    So this doesn't output anything:
    g.drawString( "blah", 425, 475 ); // Doesn't show up
    g.drawImage( img, 400, 400, null ); // Nor this!
    I've checked and experimented with setOpaque(false), however this doesn't seem to be caused by any over-lapping JPanels or anything.
    Let me know if I can expand on this :)
    Many thanks,
    Tristan Perry
    Edited by: TristanPerry on Dec 10, 2009 8:40 AM

  • Custom painting on jpanel with scrollable

    i have a jpanel with custom painting. because the painting can be wider than the view of the panel i need to implement scrollbars. i have experimented with implementing scrollable and using scrollpanes but i have no result. i need a hint or a tutorial how this can be done

    ok, that was the key. but perhaps you can help me with two other problems:
    because i dont know how large my panel ( or my scroll-area) has to be, i need to expand it on demand. i tried setpreferredsize for that reason, but nothing happens. i think this method is only for initializing but doesnt seem to function properly at a later point.
    next prop:
    when i scroll my custom panting area the jpanel isnt repainted. i have some difficulties finding the right eventlistener so that i can get scrollbar events (repaint after each move)

  • What's the difference between paint and paintComponent?

    can any body tell me the difference between paint and paintComponent?and when i should use paint and when use paintComponent?
    I know that when I use repaint,it will clear all the objects and then paint again?
    is there a method similar to repaint?
    thanks in advance!

    and when i should use paint and when use paintComponent?Simple answer:
    a) override paint() when doing custom painting on an AWT component
    b) override paintComponent() when doing custom painting on a Swing component
    Detailed answer:
    Read the article on [url http://java.sun.com/products/jfc/tsc/articles/painting/index.html]Painting in AWT and Swing.
    Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/14painting/index.html]Custom Painting.

  • Diff b/w "Customer exits" and "User-exit"

    Hi,
    What is the difference b/w customer exits and user-exit and also please explain me what are the various types of customer and user-exits.
    Thanks in advance.
    Ramana

    Hi,
    Types of Exits
    There are several different types of customer exits. Each of these exits acts as hooks where you can attach or "hang" your own add-ons.
    Menu Exits
    Menu exits add items to the pulldown menus in standard SAP applications. You can use these menu items to call up your own screens or to trigger entire add-on applications.
    SAP creates menu exits by defining special menu items in the Menu Painter. These special entries have function codes that begin with "+" (a plus sign). You specify the menu item’s text when activating the item in an add-on project.
    Screen Exits
    Screen exits add fields to screens in R/3 applications. SAP creates screen exits by placing special subscreen areas on a standard R/3 screen and calling a customer subscreen from the standard screen’s flow logic.
    Function Module Exits
    Function module exits add functions to R/3 applications. Function module exits play a role in both menu and screen exits. When you add a new menu item to a standard pulldown menu, you use a function module exit to define the actions that should take place once your menu is activated. Function module exits also control the data flow between standard programs and screen exit fields.
    SAP application developers create function module exits by writing calls to customer functions into the source code of standard R/3 programs. These calls have the following syntax: CALL CUSTOMER-FUNCTION ‘001’.
    <b>User exits:</b>
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/abap/abap-code-samples/userexits%20in%20a%20transaction.doc
    In order to find out the user exits for any tcode,
    1. get the developement class of the tcode from SE93.
    2. Now goto transaction SMOD and press F4,
    3. give in the Deve class in the dev class and Press ENTER
    this will show u the exits for any tcode.
    or execute this report
    http://www.erpgenie.com/sap/abap/code/abap26.htm
    which gives the list of exits for a tcode
    http://help.sap.com/saphelp_nw04/helpdata/en/bf/ec079f5db911d295ae0000e82de14a/frameset.htm
    For information on Exits, check these links
    http://www.sap-img.com/abap/a-short-tutorial-on-user-exits.htm
    http://www.sapgenie.com/abap/code/abap26.htm
    http://www.sap-img.com/abap/what-is-user-exits.htm
    http://wiki.ittoolbox.com/index.php/HOWTO:Implement_a_screen_exit_to_a_standard_SAP_transaction
    http://www.easymarketplace.de/userexit.php
    http://www.sap-img.com/abap/a-short-tutorial-on-user-exits.htm
    http://www.sappoint.com/abap/userexit.pdfUser-Exit
    http://www.sap-img.com/abap/a-short-tutorial-on-user-exits.htm
    http://www.ficoexpertonline.com/downloads/User%20ExitsWPedit.doc
    http://www.easymarketplace.de/userexit.php
    http://help.sap.com/saphelp_nw04/helpdata/en/c8/1975cc43b111d1896f0000e8322d00/content.htm
    Check out these links too...
    http://www.sap-img.com/abap/a-short-tutorial-on-user-exits.htm
    http://www.sapgenie.com/abap/code/abap26.htm
    http://www.sap-img.com/abap/what-is-user-exits.htm
    http://wiki.ittoolbox.com/index.php/HOWTO:Implement_a_screen_exit_to_a_standard_SAP_transaction
    http://www.easymarketplace.de/userexit.php
    http://www.sap-img.com/abap/a-short-tutorial-on-user-exits.htm
    http://www.sappoint.com/abap/userexit.pdfUser-Exit
    http://www.planetsap.com/userexit_main_page.htm
    http://wiki.ittoolbox.com/index.php/HOWTO:Implement_a_screen_exit_to_a_standard_SAP_transaction
    USER EXITS
    https://forums.sdn.sap.com/click.jspa?searchID=672084&messageID=312792
    https://forums.sdn.sap.com/click.jspa?searchID=672084&messageID=1320078
    https://forums.sdn.sap.com/click.jspa?searchID=672084&messageID=2669896
    ****Reward points if helpful.
    All the best

  • Problem with custom control and focus

    I've a problem with the focus in a custom control that contains a TextField and some custom nodes.
    If i create a form with some of these custom controls i'm not able to navigate through these fields by using the TAB key.
    I've implemented a KeyEvent listener on the custom control and was able to grab the focus and forward it to the embedded TextField by calling requestFocus() on the TextField but the problem is that the TextField won't get rid of the focus anymore. Means if i press TAB the first embedded TextField will get the focus, after pressing TAB again the embedded TextField in the next custom control will get the focus AND the former focused TextField still got the focus!?
    So i'm not able to remove the focus from an embeded TextField.
    Any idea how to do this ?

    Here you go, it contains the control, skin and behavior of the custom control, the css file and a test file that shows the problem...
    control:
    import javafx.scene.control.Control;
    import javafx.scene.control.TextField;
    public class TestInput extends Control {
        private static final String DEFAULT_STYLE_CLASS = "test-input";
        private TextField           textField;
        private int                 id;
        public TestInput(final int ID) {
            super();
            id = ID;
            textField = new TextField();
            init();
        private void init() {
            getStyleClass().add(DEFAULT_STYLE_CLASS);
        public TextField getTextField() {
            return textField;
        @Override protected String getUserAgentStylesheet() {
                return getClass().getResource("testinput.css").toExternalForm();
        @Override public String toString() {
            return "TestInput" + id + ": " + super.toString();
    }skin:
    import com.sun.javafx.scene.control.skin.SkinBase;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.event.EventHandler;
    import javafx.scene.control.TextField;
    import javafx.scene.input.KeyCode;
    import javafx.scene.input.KeyEvent;
    public class TestInputSkin extends SkinBase<TestInput, TestInputBehavior> {
        private TestInput control;
        private TextField textField;
        private boolean   initialized;
        public TestInputSkin(final TestInput CONTROL) {
            super(CONTROL, new TestInputBehavior(CONTROL));
            control     = CONTROL;
            textField   = control.getTextField();
            initialized = false;
            init();
        private void init() {
            initialized = true;
            paint();
        public final void paint() {
            if (!initialized) {
                init();
            getChildren().clear();
            getChildren().addAll(textField);
        @Override public final TestInput getSkinnable() {
            return control;
        @Override public final void dispose() {
            control = null;
    }behavior:
    import com.sun.javafx.scene.control.behavior.BehaviorBase;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.event.EventHandler;
    import javafx.scene.input.KeyCode;
    import javafx.scene.input.KeyEvent;
    public class TestInputBehavior extends BehaviorBase<TestInput> {
        private TestInput control;
        public TestInputBehavior(final TestInput CONTROL) {
            super(CONTROL);
            control = CONTROL;
            control.getTextField().addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
                @Override public void handle(final KeyEvent EVENT) {
                    if (KeyEvent.KEY_PRESSED.equals(EVENT.getEventType())) {
                        keyPressed(EVENT);
            control.focusedProperty().addListener(new ChangeListener<Boolean>() {
                @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean wasFocused, Boolean isFocused) {
                    if (isFocused) { isFocused(); } else { lostFocus(); }
        public void isFocused() {
            System.out.println(control.toString() + " got focus");
            control.getTextField().requestFocus();
        public void lostFocus() {
            System.out.println(control.toString() + " lost focus");
        public void keyPressed(KeyEvent EVENT) {
            if (KeyCode.TAB.equals(EVENT.getCode())) {
                control.getScene().getFocusOwner().requestFocus();
    }the css file:
    .test-input {
        -fx-skin: "TestInputSkin";
    }and finally the test app:
    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.GridPane;
    import javafx.stage.Stage;
    public class Test extends Application {
        TestInput input1;
        TestInput input2;
        TestInput input3;
        TextField input4;
        TextField input5;
        TextField input6;
        Scene     scene;
        @Override public void start(final Stage STAGE) {
            setupStage(STAGE, setupScene());
        private Scene setupScene() {
            input1 = new TestInput(1);
            input2 = new TestInput(2);
            input3 = new TestInput(3);
            input4 = new TextField();
            input5 = new TextField();
            input6 = new TextField();
            GridPane pane = new GridPane();
            pane.add(input1, 1, 1);
            pane.add(input2, 1, 2);
            pane.add(input3, 1, 3);
            pane.add(input4, 2, 1);
            pane.add(input5, 2, 2);
            pane.add(input6, 2, 3);
            scene = new Scene(pane);
            return scene;
        private void setupStage(final Stage STAGE, final Scene SCENE) {
            STAGE.setTitle("Test");
            STAGE.setScene(SCENE);
            STAGE.show();
        public static void main(String[] args) {
            launch(args);
    The test app shows three custom controls on the left column and three standard textfields on the right column. If you press TAB you will see what i mean...

  • Custom painting/ graphics in a panel

    Ten Duke Dollars for whoever gives the best high level solution for my problem.
    I'm writing a small application that displays music notation on screen and lets the user move the notes vertically to the desired locations on the staves. The user can then do various kinds of analysis on each example. The analysis stuff is done, but I'm having trouble finding an approach that will work for the graphics.
    My basic approach so far is to subclass JPanel and use it to handle all the custom painting. I'm planning to add all needed JPEG's to JLabels. Some of the images (e.g. treble and bass clef images) will always be in a fixed location, while others (note images) will move vertically when the user drags them. For the lines on the staves and the measure lines, I'm planning to use g.drawLine.
    The following questions occur to me:
    1. How will I prevent the note images from hiding the lines? Will I need to make the images transparent GIFs or something? Or can I set some layering property in the JPanel to build up a layered drawing?
    2. to detect mouse events, should I attach mouse listeners to my panel, or to each label that contains a note image? (I considered using Ellipse objects for the note heads and lines for the stems, but this will not give me a high enough quality of image.)
    3. I will probably need to use absolute positioning in the panel class rather than FlowLayout or whatever, but I'm having trouble getting rid of the layout manager. Can you give me a few lines of code to do this?
    4. Is my overall approach correct? Is there a better, easier way to accomplish what I'm trying to do?
    thanks,
    Eric

    >
    The following questions occur to me:
    1. How will I prevent the note images from hiding the
    lines? Will I need to make the images transparent GIFs
    or something? Or can I set some layering property in
    the JPanel to build up a layered drawing?If you are going to use images (probably BufferedImages), their Transparency will probably be BITMASK or TRANSLUSCENT.
    2. to detect mouse events, should I attach mouse
    listeners to my panel, or to each label that contains
    a note image? (I considered using Ellipse objects for
    the note heads and lines for the stems, but this will
    not give me a high enough quality of image.)I don't think using JLabel objects is a good idea. Instead of add labels to a panel, I would define a custom JComponent that did its own painting in paintComponent.
    >
    3. I will probably need to use absolute positioning in
    the panel class rather than FlowLayout or whatever,
    but I'm having trouble getting rid of the layout
    manager. Can you give me a few lines of code to do
    this?If you follow my last comment, your component isn't being used as a container, so this is not relevant.
    >
    4. Is my overall approach correct? Is there a better,
    easier way to accomplish what I'm trying to do?
    thanks,
    EricCheck out forum Java 2D. That's where this topic belongs. You also need to learn the 2D API. Search for some text book references in that forum.
    From the Imipolex G keyboard of...
    Lazlo Jamf

  • A problem with custom painting.

    I was trying to make a bar chart from a given data. I used an extension JLabel (mentioned as inner class Leonardo) inside a scrollpane for the custom painting of the bars (rectangles).
    The problem I am facing is the component is not visible when I open the screen. If I drag the scrool bar then the next area is painted and the component looks fine. If the frame is minimized and then maximized the custom painting is not visible. Any idea why it is doing so? I am pasting the full code in case some body wants to run it.
    Thanks in advance,
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    import java.util.Vector;
    import java.util.Hashtable;
    import java.util.Enumeration;
    import java.awt.geom.*;
    public class Reporter extends JFrame
    private JPanel basePanel = new JPanel();
    private Leonardo1 leo = null;
    private JScrollPane scrollPane = new JScrollPane();
    public Reporter()
    try
    jbInit();
    catch(Exception e)
    e.printStackTrace();
    public static void main(String[] args)
    Reporter reporter = new Reporter();
         reporter.pack();
         reporter.setSize(700,500);
    reporter.setVisible(true);
    private void jbInit() throws Exception
    this.setSize(new Dimension(679, 497));
    this.getContentPane().setLayout(null);
    this.setTitle("Process Reporter");
    // this.addWindowListener(new Reporter_this_windowAdapter(this));
    basePanel.setLayout(null);
    basePanel.setBounds(new Rectangle(15, 60, 640, 405));
    basePanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
    /* Hard code data */
    Vector d= new Vector();
    for (int j=0; j<131;j++)
    Data d1 = new Data(j*j*1.0,new java.sql.Date(System.currentTimeMillis()+j*1000000000),"yy","xx",Color.red);
    d.add(d1);
    leo = new Leonardo1(d);
    /*End of Hard Code data*/
    leo.setBounds(new Rectangle(10, 65, 656, 346));
    scrollPane.setBounds(new Rectangle(10, 10, 620, 330));
    scrollPane.getViewport().add(leo);
    basePanel.add(scrollPane, null);
    this.getContentPane().add(basePanel, null);
    class Data implements java.io.Serializable
    public double time;
    public java.sql.Date day;
    public String timeText;
    public String dayText;
    public Color color;
    public Data(double t,java.sql.Date dt, String strT,String strD,java.awt.Color col)
    time = t;
    day=dt;
    timeText=strT;
    dayText=strD;
    color=col;
    public void setTime(double t) {time =t;}
    public void setDay(java.sql.Date t) {day =t;}
    public void setTimeText(String t) {timeText =t;}
    public void setDayText(String t) {dayText =t;}
    public void setColor(Color t) {color =t;}
    public double getTime() {return time;}
    public java.sql.Date getDay() {return day;}
    public String getTimeText() {return timeText;}
    public String getDayText() {return dayText;}
    public Color getColor() {return color;}
    class Leonardo1 extends JLabel implements java.io.Serializable
    private Vector dataVec = new Vector();
    private double xGap = 5.0;//Gap between 2 bars
    private double xWidth = 12.0;//Width of a bar
    private double yGap = 40.0;//Gap from start of Y axis to first data.
    private int xLength = 645;//Length of the component
    private int yLength = 330;//Height of the component
    private int xMargin = 50;//The gap from the corner of the axis to the y axis
    private int yMargin = 20;//The gap from the corner of the axis to the x axis
    private double avgTime = 0.0;
    protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);
    public int getWidth(){ return xLength;}
    public int getHeight(){ return yLength;}
    public Dimension getMaximumSize(){return new Dimension(xLength,yLength);}
    public Dimension getMinimumSize(){return new Dimension(xLength,yLength);}
    public Dimension getSize(Dimension rv){ return new Dimension(xLength,yLength);}
    public Rectangle getBounds(Rectangle rv){ return new Rectangle(xLength,yLength); }
    public Leonardo1(Vector vec) {
         super();
    setOpaque(true);
    super.setBackground(Color.white);
    setData(vec);
    setBorder(noFocusBorder);
    protected void setData(Vector vec){
    if (vec == null) return;
    dataVec = (Vector)vec.clone();
    public void paintComponent(Graphics gin)
    super.paintComponent(gin);
    Graphics2D g2 = (Graphics2D)gin;
         // setBackground(Color.white);
    Color bl = Color.blue;
    g2.setPaint(bl);
    g2.setStroke(new BasicStroke(5.0f));
    drawData(g2,dataVec);
    g2.setPaint(Color.gray);
    g2.setStroke(new BasicStroke(0.5f));
    g2.draw(new Rectangle2D.Double(0, 0,xLength,yLength));
    g2.setStroke(new BasicStroke(1.5f));
    g2.draw(new Line2D.Double(xMargin, yMargin,xMargin,yLength -yMargin));
    g2.draw(new Line2D.Double(xMargin, yLength -yMargin,xLength -xMargin,yLength -yMargin));
    System.out.println("End1 ");
    public Dimension getPreferredSize(){
    if (dataVec.size()*(xGap+xWidth) > xLength)
    xLength = (int)(dataVec.size()*(xGap+xWidth));
    return new Dimension(xLength,yLength);
    else
    return new Dimension(xLength,yLength);
    protected void drawData(Graphics2D g2, Vector vec)
    if (vec == null || vec.size() == 0)
    return;
    //Check if expansion is required or not
    if (vec.size()*(xGap+xWidth) > (xLength - 2*xMargin))
    xLength = (int)(vec.size()*(xGap+xWidth)+xGap);//Expanded
    setPreferredSize(new Dimension(xLength,yLength));
    double maxTime = 0.0;
    double minTime = 0.0;
    double t=0.0;
    double total=0.0;
    for (int i=0;i<vec.size();i++)
    if ((t = ((Data)vec.elementAt(i)).getTime()) > maxTime)
    maxTime = t;
    if (t < minTime)
    minTime =t;
    total += t;
    avgTime = total/vec.size();
    System.out.println("Avg:"+avgTime+" tot:"+total);
    double scale = (yLength - 2*yMargin - 2*yGap )/(maxTime - minTime);
    //Now the y-axis scale is calculated, we can draw the bar.
    //Currently only bar is supported
    //I asume data are in the order of dates otherwise have to sort it here
    for (int i=1;i<=vec.size();i++)
    //Set color to fill
    if (((Data)vec.elementAt(i-1)).getColor() != null)
    g2.setPaint(((Data)vec.elementAt(i-1)).getColor() );
              //Fill
    g2.fill(new Rectangle2D.Double(xMargin+xGap+(i-1)*(xGap+xWidth), yMargin+yGap+/*length of active y axis*/
    (yLength-2*yMargin-2*yGap)-/*y value converted to scale*/(((Data)vec.elementAt(i-1)).getTime()- minTime)*scale,
    xWidth,(((Data)vec.elementAt(i-1)).getTime()- minTime)*scale+yGap));
    g2.setPaint(Color.black);
    g2.setStroke(new BasicStroke(0.5f));
    g2.draw(new Rectangle2D.Double(xMargin+xGap+(i-1)*(xGap+xWidth), yMargin+yGap+/*length of active y axis*/
    (yLength-2*yMargin-2*yGap)-/*y value converted to scale*/(((Data)vec.elementAt(i-1)).getTime()- minTime)*scale,
    xWidth,(((Data)vec.elementAt(i-1)).getTime()- minTime)*scale+yGap));
    g2.setPaint(Color.blue);
    float[] dash1 = {10.0f};
    g2.setStroke(new BasicStroke(1.5f,BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f));
    g2.draw(new Line2D.Double(xMargin,
    yMargin+yGap+/*length of active y axis*/(yLength-2*yMargin-2*yGap)-
    /*y value converted to scale*/(avgTime- minTime)*scale,
    xMargin+(xGap+xWidth)*vec.size()+xGap,
    yMargin+yGap+/*length of active y axis*/(yLength-2*yMargin-2*yGap)-
    /*y value converted to scale*/(avgTime- minTime)*scale));

    Replace getBounds(Rectangle) by the following.
    public Rectangle getBounds(Rectangle rv){
    if (rv != null) {
    rv.x = 0; rv.y = 0; rv.width = xLength; rv.height = yLength;
    return rv;
    } else
    return new Rectangle(xLength,yLength);

  • Non-modal JDialog is not painted and blocks the GUI

    I have developed a GUI that's basically a JFrame with a JDesktopPane.
    The user can, via a menu item, pop up a JDialog that contains some JLists and then select some value from it. Once he/she has done the selection and clicks on OK, the dialog disappears (data processing is then done in the main GUI) and comes back once a specific event has happened. The user then selects other data and so on, until he/she clicks on Cancel, which definitely disposes of the JDialog.
    The graphics of the JDialog are build in the class constructor, which does a pack() but does not make the dialog visible yet. The dialog appears only when doSelection() is called.
         /** Called the first time when user selects the menu item, and then
         when a specific event has happened. */
         public Data[] doSelection() {
              dialog.setVisible(true);
              // ... Code that reacts to user's input. Basically, the ActionListener
              // added to the buttons retrieves the user's selection and calls
              // dialog.setVisible(false) if OK is clicked, or calls dialog.dispose()
              // if Cancel is clicked.
         }Now, everything works fine if the JDialog is modal, but if I make it non-modal only the window decorations of the JDialog are painted, and the control doesn't return to the main GUI. Calling doLayout() or repaint() on the doSelection() has no effect. How can this be fixed?
    I hope I have been able to explain the problem satisfactorily, I could not create a suitable SSCCEE to show you. Thanks in advance for any hint.

    Ok, I've taken some time to think about this problem and I've modified the code a bit.
    Now the dialog shows itself and is responsive (i.e. its JLists can be operated), but the Ok button does not close the dialog as I'd want. I believe that I'm messing up things about threading, and the operations in actionPerformed() should be carried out in another thread, if possible.
    Thanks in advance for any hint / suggestion / comment / insult.
         private Data[] selection;
         /** Constructor */
         public MyDialog() {
              // ... Here is the code that builds the dialog...
              dialog.setModal(false);
              dialog.pack();
              // Note that the dialog is not visible yet
         public Data[] doSelection() {
              operatorAnswer = NONE_YET;
              dialog.setVisible(true);          
              while (operatorAnswer == NONE_YET) {
                   try {
                        wait();
                   } catch (InterruptedException e) { }
              return (operatorAnswer == OK ? selection : null);
         public void actionPerformed(ActionEvent evt) {
              if (okButton.equals(evt.getSource())) {
                   operatorAnswer = OK;
                   retrieveSelection();
                   dialog.setVisible(false);
              else if (cancelButton.equals(evt.getSource())) {               
                   operatorAnswer = CANCEL;
                   dialog.dispose();
         private void retrieveSelection() {
              // ... Here is the code that retrieves selected data from the dialog's JLists
              // and stores it in the "selection" private array...
              notifyAll();
         }

  • Design advice for custom painting

    Hi,
    Can someone give me some high-level design advice on designing a JPanel subclass for custom painting? My panel class is becoming very complex, with lots of drawing and scaling methods, so I'm wondering if I could abstract away some of these graphical elements by creating new classes to make the design more object-oriented. However, I'm finding that there are also disadvantages in representing some of my graphic components as classes. Specifically,
    1. It will lead to a much higher level of class coupling. My panel will depend on all these new classes to work correctly. In fact the situation is even worse because my panel is an inner class and, to do some of the scaling, needs to use methods from an object stored in the parent class. I would therefore have to also pass this object reference as an argument to many of these new classes.
    2. It will lead to a lot of awkward passing of data between classes. For example, I need to use g2.drawImage(img, x, y, w, h, this), so I will have to pass not only the graphics context but also the panel reference itself.
    Is it common for panel subclasses that do custom painting to be complex?
    thanks,
    Eric

    I wrote the map view for a commercial GIS system. Drawing and scaling on a JPanel is challenging, but it need not be complex.
    1. To eliminate class coupling, you need to create a couple of interfaces: Renderable (what you want drawn) and Renderer (the thing doing the low-level drawing). Renderer will have before and after setup and reset methods (to do things like scaling and rotation), and methods that the renderables can use to draw graphics. The Renderable interface can be as simple as a single method: draw(Renderer).
    Every type of graphic that you draw on the screen would be a different class that implements Renderable, and which knows how to draw itself using whatever lower-level drawing commands you put in the Renderer. If you construct each Renderable in terms of java.awt.Shape, then Renderable.draw() could call a method Renderer.draw(java.awt.Shape, java.awt.Color).
    2. The Panel becomes fairly simple. It has a Renderer and a collection of Renderable objects. Its paint() method calls the Renderer setup method, calls Renderable.draw(Renderer) on each object, and calls the Renderer reset method. Each Renderable in turn calls Renderable.draw(java.awt.Shape, java.awt.Color) one or more times.
    Renderer should get a Graphics2D from the Panel when the setup method is called. That's when the Renderer does all of the scaling, positioning, and rotation on the Graphics2D. The Renderable implementations shouldn't even need to know about it.
    I don't think custom painting code is necessarily complex, merely challenging to write. If you're only drawing a few lines and circles, you probably don't have to be too concerned about design elegance and code maintainability. The map view I designed for our GIS system, on the other hand, has to handle all kinds of map geometry, icons, text, and aerial photos.

  • Making custom non-standard components aware of custom look and feels.

    Hello all.
    Maybe the subject of this post could also be the opposite: "Making custom look and feels aware of non-standard custom components". I'm not sure.
    If I code a new custom component (extending JComponent, or extending the UI delegate of a standard component) and pretend it to be laf aware then I must create the corresponding UI delegate for each laf, like it happens to be with standard swing components. But I'm not sure it is feasible to create the UI delegates for all unknown existing custom lafs.
    On the other side, if I create a custom laf then I will also create a custom UI delegate for each standard component, but I can not create UI delegate for all unknown existing custom components.
    The point here is that standard components and standard lafs are universally known, while custom components (or custom ui delegates) and custom lafs are not.
    So the question is: How does a swing developer deal with the case of a new custom component that will be used in an unknown custom laf?
    For instance:
    1. Custom text UI delegate for dealing with styled documents in JTextField. See {thread:id=2284487}.
    2. JTabbedPane with custom UI delegate that paints no tab if the component only contains one tab.
    In both cases I need a UI delegate for each known laf, but what happens if the application is using a laf that certainly will not be aware of this custom functionally?
    Thank you!

    If I code a new custom component (extending JComponent, or extending the UI delegate of a standard component) and pretend it to be laf aware then I must create the corresponding UI delegate for each laf, like it happens to be with standard swing components. But I'm not sure it is feasible to create the UI delegates for all unknown existing custom lafs.You are right, this is never going to work. I suggest if you want to make your custom component look & feel aware, you design the way it displays around the l & f of other components that are part of j2se and have l&f implementations.
    http://download.oracle.com/javase/7/docs/api/javax/swing/plaf/ComponentUI.html
    There are instructions here:
    http://download.oracle.com/javase/7/docs/api/javax/swing/LookAndFeel.html
    >
    On the other side, if I create a custom laf then I will also create a custom UI delegate for each standard component, but I can not create UI delegate for all unknown existing custom components.
    The point here is that standard components and standard lafs are universally known, while custom components (or custom ui delegates) and custom lafs are not.
    So the question is: How does a swing developer deal with the case of a new custom component that will be used in an unknown custom laf?
    For instance:
    1. Custom text UI delegate for dealing with styled documents in JTextField. See {thread:id=2284487}.
    2. JTabbedPane with custom UI delegate that paints no tab if the component only contains one tab.
    In both cases I need a UI delegate for each known laf, but what happens if the application is using a laf that certainly will not be aware of this custom functionally?
    Thank you!

  • Custom Painting in Swing Panels.

    I am trying to implement a custom painted panel on a JFrame. The panel performs custom painting in a separate thread. In additon, the frame also adds other swing panels (containing standard components) dynamically as per menu selection. I use box layout on frame to add / remove panels.
    The paint panel doesnt render properly whenever other panels are added or replaced. The paint panel is rendered only when no other are panels added to the frame.
    There is no problem however with adding / replacing components-only panels containing no custom painting.
    Please help me understand what I am missing. Any clues / suggestions most welcome
    sridhar

    Hi,
    You have problem only when adding custom painting JPanel to the same custom painting JPanel??? Are you layering your painting methods??? Like the most upper JPanel paints and then the childs??? What do you get for drawings??? Do you use invoque later method??? What is your priority on the Threads you are using???
    JRG

  • Custom painting in JFC

    I have an app that does custom painting in a extended JWindow, however, when I add controls (an extended JButton that does custom painting) the entire window, not including any components turns gray. This happens if I use paint or paintComponent. I am starting to think that the delegate UI is causing a problem, this is because if I remove the paintComponents, I get the image as usual. Any ideas???
    A code snippet shows the gist
    class sWindow extends JWindow {
    public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.drawImage(mainform, null, 0, 0);
    paintComponents(g);
    class sButton extends JButton {
    public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    switch(state) {
    case DEFAULT:
    g2.drawImage(defaultImage, 0, 0, getSize().width, getSize().height, this);
    break;
    case PRESSED:
    g2.drawImage(pressedImage, 0, 0, getSize().width, getSize().height, this);
    break;
    case HIGHLIGHTED:
    g2.drawImage(hilightedImage, 0, 0, getSize().width, getSize().height, this);
    break;
    case DISABLED:
    g2.drawImage(disabledImage, 0, 0, getSize().width, getSize().height, this);
    break;
    }

    Hi,
    You have problem only when adding custom painting JPanel to the same custom painting JPanel??? Are you layering your painting methods??? Like the most upper JPanel paints and then the childs??? What do you get for drawings??? Do you use invoque later method??? What is your priority on the Threads you are using???
    JRG

  • Standart painting and Tools

    Hello!
    I'm interesting in way to get access to the standart panel "Tools". Is it possible to insert my custom mode(s) like paint in this toolbar?
    I'm coding the plugin which looks like the standart painting, but some differs. I guess, I should create an AEGP plugin to create my custom panel, and I want to know something about engine of the standart painting.
    Thanks a lot!

    You probably can't do this with threads. Rule #1 of threading is that you cannot determine the order of execution, and you basically have no control over this. If you need the images and sound to be displayed sequentially, then by all means download them or load them with separate threads. But you must display them in the same thread to get them displayed sequentially.
    Alan

Maybe you are looking for

  • Open BI Publisher Report After Submit

    I have a page with 2 date fields, which are parameters for a report. I also have a button called RUN_REPORT. What I need to do is that the user puts the parameters in, then clicks RUN_REPORT. The page should submit (putting parameters into session st

  • Segfaulting on full container operations - debugging help

    Hi all - I have some data that has been through lots of dbxml upgrades and the last two upgrades have full container operations segfaulting. I was able to ignore this data for a year but now its coming back to haunt me. All full container operations,

  • URL link to forum

    Sorry, I should have added that I am using a Macbook 10.6.4.

  • How to Define Oracle Server Availability?

    Our environment is Oracle E-Business Suite 11.5.4 with Oracle 9.0.1.4 RAC. We would like to define a service level agreement for users. Can you share your opinion how much down time per year is reasonable? Thanks Eric

  • Documents take over 30 seconds to render and also require Function F5 to refresh

    We have a four page document, 2 pages in Spanish and 2 pages in English that takes over 30 seconds to render. We have put a 30 second counter in so the user doesn't keep pressing F5 over and over. The document will display after the 30 seconds when F