PaintComponent method problems...

Hi, I am developing an game application ( just for fun ) and I have a huge problem with paintComponent method. I Have a class ImagePanel that extends JPanel class. The ImagePanel class overrides the paintComponent method and paintChildren method ( since i have added components inside the JPanel also these must be painted ). The ImagePanel is instantied in my main class IntroView which extends JFrame where it's added. Now when the IntroPanel is created i have noticed that the paintComponent and paintChildren method is called all over again . I Have a soundclip playing in background in it's own thread and this continously paintComponent method call causes the sound clip to break off in few seconds. I Have tried to use JLabel instead of JPanel, but then the image is not shown( alltougth the methods are called only once ). I Have also tried next code to get rid of continous paintComponent call
...from ImagePanel class
ImagePanel extends JPanel.....
public final void paintComponent( Graphics g )
if( firstTime )
super.paintComponent( g );
g.drawImage( myImage, 0, 0, this );
firstTime = false;
public final void paintChildrens( Graphics g )
if( paintChildren )
super.paintChildren( g );
add( startLabel );
add( optionsLabel );
paintChildren = false;
public boolean isOpaque()
return true;
Now the paintComponent and paintChildren is called only once. There is still a "little problem" since the paintComponent doesen't paint the image, it paints only the background( I think g.drawImage(...) didint have time to paint the image? ). Also the labels added in paintChildren method are not shown. Sounds paly now just fine.This situation makes me grazy. Please consult me with this problem.....i can surely send also the whole source if needed. There is no effect if I change isOpaque to true or false.

Hi,
Thanks for advices, I solved the problem...it was simplier than i thought. When the g.drawImage(.... is called ) i just added Thread.sleep( time ) after that line. This gives the sound therad time to play the sound without interrput and time to main thread to handle the image. All works now pretty much as i thought, except when JFrame is overlapped the image is not drawn again...this can be corrected ( maybe?)by adding windoslistener and implement the methods in that inteface and make some repainting in different situations. But cause you gave me the magic work Thread priority I hox! the problem, so here goes 10 duke dollars.

Similar Messages

  • Problem after over riding paintComponent() method

    I am over riding the paintComponent() method for a button to show the text in 2 lines. But when I invoke setEnabled(false) on the button, the button is getting disabled but the text is not.
    Could any one please let me know how to do that.
    The code for the paintComponent() method is pasted for reference
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    int w = getWidth();
    int h = getHeight();
    FontMetrics fm = g.getFontMetrics();
    int textw1 = fm.stringWidth(text1);
    int textw2 = fm.stringWidth(text2);
    FontRenderContext context = g2.getFontRenderContext();
    LineMetrics lm = getFont().getLineMetrics(text1, context);
    int texth = (int)lm.getHeight();
    prefHeight = texth;
    int x1 = (w - textw1) / 2;
    int x2 = (w - textw2) / 2;
    int th = (texth * 2);
    int dh = ((h - th) / 2);
    int y1 = dh + texth - 3;
    int y2 = y1 + texth;
    // Draw texts
    g.setColor(getForeground());
    g.drawString(text1, x1, y1);
    g.drawString(text2, x2, y2);
    regards,
    shantanu

    Hi,
    Thanks for advices, I solved the problem...it was simplier than i thought. When the g.drawImage(.... is called ) i just added Thread.sleep( time ) after that line. This gives the sound therad time to play the sound without interrput and time to main thread to handle the image. All works now pretty much as i thought, except when JFrame is overlapped the image is not drawn again...this can be corrected ( maybe?)by adding windoslistener and implement the methods in that inteface and make some repainting in different situations. But cause you gave me the magic work Thread priority I hox! the problem, so here goes 10 duke dollars.

  • PaintComponent method refuses to be invoked.

    Hello All!
    I have a problem with graphics representation by swing. Namely I have an application based on Jframe object. It includes three Jpanel components. I need to map information from Jtable as diagram in the plotPanel. That�s code fragment I try to use:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JComponent.*;
    import java.lang.*;
    import java.io.*;
    * @author  Administrator
    public class ROC extends javax.swing.JFrame{
    public ROC() {
            initComponents();
    /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            menuPanel = new javax.swing.JPanel();
            openButton = new javax.swing.JButton();
            tablePanel = new javax.swing.JPanel();
            pointsTable = new javax.swing.JTable();
            generateButton = new javax.swing.JButton();
            plotPanel = new javax.swing.JPanel();
            plotPanel.add(new PlotArea(), java.awt.BorderLayout.CENTER);
    ������ //This is a piece of code to initialize other components
            plotPanel.setLayout(new java.awt.BorderLayout());
            plotPanel.setBackground(java.awt.Color.white);
            plotPanel.setPreferredSize(new java.awt.Dimension(600, 380));
            plotPanel.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
            plotPanel.addContainerListener(new java.awt.event.ContainerAdapter() {
                public void componentAdded(java.awt.event.ContainerEvent evt) {
                    plotPanelComponentAdded(evt);
            getContentPane().add(plotPanel, java.awt.BorderLayout.CENTER);
            pack();
    ������  // Different functions (such as loading data from the file to JTable i.e.)
           public static void main(String args[]) {
            System.out.println("Application starts");
            new ROC().show();
        // Variables declaration - do not modify
        private javax.swing.JPanel menuPanel;
        private javax.swing.JButton openButton;
        private javax.swing.JPanel tablePanel;
        private javax.swing.JTable pointsTable;
        private javax.swing.JButton generateButton;
        private javax.swing.JPanel plotPanel;
        // End of variables declaration
    public class PlotArea extends javax.swing.JComponent{
        /** Creates new plotPanel */
        public PlotArea() {
            System.out.println("PlotArea has been created");
            setPreferredSize(new java.awt.Dimension(600, 380));
            setMinimumSize(new java.awt.Dimension(200, 100));
            super.setBorder(BorderFactory.createLineBorder(Color.red, 5));
            repaint();
        public void paintComponent(java.awt.Graphics g) {
            System.out.println("PaintComponent method has been invoked");
            Graphics2D g2d = (Graphics2D)g;
    ������ // this is the code to implement custom painting
    }The trouble is that PaintComponent method hasn�t been invoked. Help me please. What should I do to cause PaintComponent to be performed?

    You might want to ensure your "plotPanel" uses a BorderLayout if you're specifying a constraint:
    plotPanel = new javax.swing.JPanel(new BorderLayout());
    plotPanel.add(new PlotArea(), java.awt.BorderLayout.CENTER);You shouldn't need to call "repaint" in the constructor of PlotArea, either. I doubt it'll make any difference.
    Hope this helps.

  • This paintComponent Method is Annoying - HELP

    ok, I think I touched upon this problem sometime earlier, however I face a larger problem which I've been trying to solve by a different and simpler means but I get nothin.
    I have a paintComponent method which DRAWS lines, strings and shapes that get PAINTED on to a JFrame all good and well.
    Now, because of the amount of lines, strings and shapes I have on this "paintComponent", I want to put it in a class of its own. and THEN call it from the class it was in.
    So I want to create a new class, just for the paintComponent.
    Now, I've tried Numerous ways of trying to call it from another class but it just comes up as a blank screen. Oh and no I am not calling it directly too.
    Does anyone know where I am going wrong?
    help would be very much appreciated.

    ok LETS do this.
    class beep
    I call the paintComponent here to paint my JFrame BUT HOW!
    class drawingBoard----------------------------------------------------
    // create a rectangle called 'therectangle';
    protected void paintComponent(Graphics g)
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.draw(therectangle)
    g2.drawString("", 100, 100)
    Edited by: Calibre2007 on Feb 20, 2008 4:11 PM
    Edited by: Calibre2007 on Feb 20, 2008 4:11 PM

  • Overriding paintcomponent method JButton

    Hi,
    I'm trying to make my own buttons (with a JPEG image as template and a string painted on this template, depending on which button it is) by overriding the paintComponent-method of the JButton class, but I still have a small problem. I want to add some mouse-events like rollover and click and the appropriate animation with it (when going over the button, the color of the button becomes lighter, when clicking, the button is painted 2 pixels to the left and to the bottom). But my problem is there is some delay on these actions, if you move the mousepointer fast enough, the pointer can already be on another button before the previous button is restored to its original state. And of course, this isn't what I want to see.
    I know you can use methods like setRollOverIcon(...), but if doing so, I think you need a lot of images ( for each different button at least 3) and I want to keep the number of images to a minimum.
    I searched the internet and these forums for a solution, but I didn't found any. I'm quite sure there is at least one good tutorial on this since I already tried to do this once, but I forgot how to do it, and I can't find the tutorial anymore.
    This is an example of the MyButton-class I already wrote, I hope it clarifies my problem:
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class MyButton extends JButton{
         BufferedImage button = null;
         int x, y;
         String text = "";
         MyButton(String t){
              super(t);
              text = t;
              setContentAreaFilled(false);
              setBorderPainted(false);
              setFocusPainted(false);
              addMouseListener(new MouseListener(){
                   public void mouseClicked(MouseEvent arg0) {
                        x += 2;
                        y += 2;
                   public void mouseEntered(MouseEvent arg0) {
                        //turn lighter
                   public void mouseExited(MouseEvent arg0) {
                        x -= 2;
                        y -= 2;
                   public void mousePressed(MouseEvent arg0) {}
                   public void mouseReleased(MouseEvent arg0) {}
         protected void paintComponent(Graphics g){
              Graphics2D g2d = (Graphics2D)g;
              try{
                   button = ImageIO.read(new File("Red_Button.jpg"));
              }catch(IOException ioe){}
              //Drawing JButton
              g2d.drawImage(button, null, x, y);
              g2d.drawString(text, x+5, y+5);     
    }Thanks in advance,
    Sam

    Okay, thanks, I replaced the image-read-in into the constructor of a JButton, and I think it goes a lot faster now (but that can be my imagination).
    I still use a mouseListener because I have no idea how to use the ButtonModelinterface. I searched to find a good tutorial, but I didn't really find one? Any recommendations (yes, I read the sun-tutorial, but did not find it really explanatory).
    Here's a complete SSCCE (although it isn't really necessary anymore since my main problem seams to be solved):
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class MyButton extends JButton{
         BufferedImage button = null;
         int x, y;
         String text = "";
         public MyButton(String t){
              super(t);
              text = t;
              try{
                   button = ImageIO.read(new File("Blue_Button.jpg"));
              }catch(IOException ioe){}
              setBorderPainted(false);
              addMouseListener(new MouseListener(){
                   public void mouseClicked(MouseEvent arg0) {}
                   public void mouseEntered(MouseEvent arg0) {
                        x += 2;
                        y += 2;
                   public void mouseExited(MouseEvent arg0) {
                        x -= 2;
                        y -= 2;
                   public void mousePressed(MouseEvent arg0) {}
                   public void mouseReleased(MouseEvent arg0) {}
         protected void paintComponent(Graphics g){
              Graphics2D g2d = (Graphics2D)g;
              g2d.drawImage(button, null, x, y);
              g2d.drawString(text, x+25, y+15);     
         public void fireGUI(){
              JFrame frame = new JFrame("ButtonModelTester");
              frame.setLayout(new GridLayout(2,1,10,10));
              frame.add(new MyButton("Test1"));
              frame.add(new MyButton("Test2"));
              frame.setSize(200,100);
              frame.setVisible(true);
         public static void main(String[] args){
              SwingUtilities.invokeLater(new Runnable(){
                   public void run(){
                        new MyButton(null).fireGUI();
    }Thanks,
    Sam
    PS: you mentioned my earlier posts? So they are still somewhere on this forum, because I couldn't find the anymore, they aren't in my watch list. I Checked this since I thought I asked something similar before...

  • TableBorder after overwrite paintComponent Method

    Hello,
    I created my own TableCellRenderer and overwrite the paintComponent() method to rotate the content in the header of my JTable.
    Now the TableHeader has no borders anymore. I tried to set the border again, but nothing solved my problem. I tried it in all classes to set the border.
    Anyone an idea how to get the borders back in the tableheader?
    Here's the Code:
    ----------------------------- class RowHeaderTable -----------------------------
    import java.awt.*;
    import javax.swing.*;
    public class RowHeaderTable extends JFrame {
         private static final long serialVersionUID = 1L;
         public RowHeaderTable() {
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              TableModel tm = new TableModel();
              // Create a column model for the main table. This model ignores the first
              // column added, and sets a minimum width of 150 pixels for all others.
              HeaderTableColumnModel colMod = new HeaderTableColumnModel();
              // Create a column model that will serve as our row header table. This
              // model picks a maximum width and only stores the first column.
              BodyTableColumnModel rowHeaderModel = new BodyTableColumnModel();
              JTable jt = new JTable(tm, colMod);
              Dimension d = jt.getTableHeader().getPreferredSize();
              d.height = 80;
              d.width = 1000;
              jt.getTableHeader().setPreferredSize(d);
              // Set up the header column and get it hooked up to everything
              JTable headerColumn = new JTable(tm, rowHeaderModel);
              jt.createDefaultColumnsFromModel();
              headerColumn.createDefaultColumnsFromModel();
              // Make sure that selections between the main table and the header stay
              // in sync (by sharing the same model)
              jt.setSelectionModel(headerColumn.getSelectionModel());
              // Make the header column look pretty
              //headerColumn.setBorder(BorderFactory.createEtchedBorder());
              headerColumn.setBackground(jt.getTableHeader().getBackground());
              headerColumn.setColumnSelectionAllowed(false);
              headerColumn.setCellSelectionEnabled(true);
              // Put it in a viewport that we can control a bit
              JViewport jv = new JViewport();
              jv.setView(headerColumn);
              jv.setPreferredSize(headerColumn.getMaximumSize());
              // With out shutting off autoResizeMode, our tables won't scroll
              // correctly (horizontally, anyway)
              jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              // We have to manually attach the row headers, but after that, the scroll
              // pane keeps them in sync
              JScrollPane jsp = new JScrollPane(jt);
              jsp.setRowHeader(jv);
              jsp.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, headerColumn.getTableHeader());
              getContentPane().add(jsp, BorderLayout.CENTER);
         public static void main(String args[]) {
              /*try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              } catch (ClassNotFoundException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (InstantiationException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (IllegalAccessException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (UnsupportedLookAndFeelException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              RowHeaderTable rht = new RowHeaderTable();
              rht.setTitle("Fenstertitel");
              rht.setSize(500, 480);
              rht.setLocation((rht.getToolkit().getScreenSize().width/2)-(rht.getSize().width/2), (rht.getToolkit().getScreenSize().height/2)-(rht.getSize().height/2));
              rht.setVisible(true);
    }----------------------------- class RotatedTableCellRenderer -----------------------------
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.AffineTransform;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.table.TableCellRenderer;
    public class RotatedTableCellRenderer extends JLabel implements TableCellRenderer {
         private static final long serialVersionUID = 1L;
         protected int m_degreesRotation = -90;
         public RotatedTableCellRenderer(int degrees) {
              m_degreesRotation = degrees;
         public Component getTableCellRendererComponent(JTable table, Object value,
                   boolean isSelected, boolean hasFocus, int row, int column) {
              this.setToolTipText(value.toString());
              if(value.toString().length()>=15){
                   this.setText(value.toString().substring(0, 12) + "...");
              else {
                   this.setText(value.toString());
              this.setFont(new Font(this.getFont().getFamily(), Font.PLAIN, 12));
              return this;
         public void paintComponent(Graphics g) {
              Graphics2D g2 = (Graphics2D)g;
              g2.setClip(0,0,this.getWidth(),this.getHeight());
              g2.setColor(Color.BLACK);
              AffineTransform at = new AffineTransform();
              at.setToTranslation(this.getWidth(), this.getHeight());
              g2.transform(at);
              double radianAngle = ( ((double)m_degreesRotation) / ((double)180) ) * Math.PI;
              at.setToRotation(radianAngle);
              g2.transform(at);
              g2.drawString(this.getText(), 3.0f, -((this.getWidth()/2)-3));
              super.setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    }----------------------------- class HeaderTableColumnModel -----------------------------
    import javax.swing.table.DefaultTableColumnModel;
    import javax.swing.table.TableColumn;
    public class HeaderTableColumnModel extends DefaultTableColumnModel {
         private static final long serialVersionUID = 1L;
         boolean first = true;
         public void addColumn(TableColumn tc) {
              // Drop the first column . . . that'll be the row header
              if (first) { first = false; return; }
              tc.setPreferredWidth(25);
              tc.setHeaderRenderer(new RotatedTableCellRenderer(-90));
              super.addColumn(tc);
    }----------------------------- class BodyTableColumnModel -----------------------------
    import javax.swing.table.DefaultTableColumnModel;
    import javax.swing.table.TableColumn;
    public class BodyTableColumnModel extends DefaultTableColumnModel{
         private static final long serialVersionUID = 1L;
         boolean first = true;
         public void addColumn(TableColumn tc) {
              if (first) {
                   tc.setMaxWidth(tc.getPreferredWidth());
                   super.addColumn(tc);                         
                   first = false;
    }----------------------------- class TableModel -----------------------------
    import javax.swing.table.AbstractTableModel;
    public class TableModel extends AbstractTableModel{
         private static final long serialVersionUID = 1L;
         String data[] = {"", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t"};
         public String headers[] = {"Row #", "Hier steht der lange Text 1", "Hier steht der lange Text 2", "Hier steht der lange Text 3", "Hier steht der lange Text 4", "Hier steht der lange Text 5", "Hier steht der lange Text 6", "Hier steht der lange Text 7", "Hier steht der lange Text 8", "Hier steht der lange Text 9", "Hier steht der lange Text 10"
                   , "Hier steht der lange Text 11", "Hier steht der lange Text 12", "Hier steht der lange Text 13", "Hier steht der lange Text 14", "Hier steht der lange Text 15", "Hier steht der lange Text 16", "Hier steht der lange Text 17", "Hier steht der lange Text 18", "Hier steht der lange Text 19", "Hier steht der lange Text 20"};
         public int getColumnCount() {
              return data.length;
         public int getRowCount() {
              return 1000;
         public String getColumnName(int col) {
              return headers[col];
         // Synthesize some entries using the data values & the row #
         public Object getValueAt(int row, int col) {
              return data[col] + row;
    Message was edited by:
    S.Beutel

    Thanks for your reply camickr.
    I've been looking into ways around the rendering issues of paintComponent and it is interesting to see some of the methods necessary to overcome this (e.g setOpaque, repaint etc).
    One method I saw was putting the objects you want to draw into a data structure (i.e ArrayList) and then using this to draw multiple objects onto the screen. Thus overcomming the super.paintComponent issue of erasing previous drawings. Is this the "preferred" way or is there a more practical solution.
    Chris.

  • PaintComponent Method

    Hello,
    can any one tell me when paintComponent(Graphics gc){} method will be called???
    it's needed that i have to extends JPanel.
    in my prog m extending theJApplet class.
    can paintComponent(Graphics gc){} will called if m extending the JApplet..
    plz tell me..
    waiting 4 yr reply.
    Regards,
    Shruti.

    Swing related questions should be posted in the Swing forum.
    You override paintComponent of JPanel and add the panel to your JApplet. The paintComponent() method will be called as required.

  • PaintComponent method seems not to be called - im stumped

    Please find two simple classes:
    When debugging why my background image wont display I have discovered that the paintComponent() method of my BackgroundJPanel class never gets invoked. Its part of the heirarchy so im not sure why.. You will notice a few system.out's the only thing my console shows is a "zooob!" comment..
    package xrpg.client;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import javax.swing.*;  
    import javax.swing.ImageIcon;
    import javax.swing.JLayeredPane;
    import java.awt.Frame;
    import java.awt.Color;
    import jka.swingx.*;
    public class XClient {
          * @param args
         public static void main(String[] args)
              XClient app = new XClient();
         public XClient()
              //set look and feel
              try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); }
              catch (Exception e) { }
              //     Create the top-level container
              JFrame frame = new JFrame("XClient");
              frame.setUndecorated(true);
              frame.setBackground(Color.black);  
              // create background panel and add it to frame
              BackgroundJPanel bPanel = new BackgroundJPanel("xrpg/client/content/xrpg00002.jpg");
              bPanel.setBackground(Color.white);  
              frame.getContentPane().add(bPanel, java.awt.BorderLayout.CENTER);
              //JButton button = new JButton("I'm a Swing button!");
              //bPanel.add(button);
              //button.setLocation(10,10);
              frame.addWindowListener(new WindowAdapter(){
               public void windowClosing(WindowEvent e)
                    System.exit(0);
          // show & size frame
              frame.pack();
          frame.setVisible(true);
          Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
              frame.setSize(dim);
    package jka.swingx;
    import javax.swing.*;
    import java.awt.*;
    public class BackgroundJPanel extends JPanel {
              private Image img ;
              private boolean draw = true;
              public BackgroundJPanel(String imageResource)
                   System.out.println( "zooob!" );
                   // load & validate image
                   ClassLoader cl = this.getClass().getClassLoader();
                   try { img = new ImageIcon(cl.getResource(imageResource)).getImage(); } catch(Exception e){}
                   if( img == null ) {
                        System.out.println( "Image is null" );
                        draw=false;
                   if( img.getHeight(this) <= 0 || img.getWidth( this ) <= 0 ) {
                        System.out.println( "Image width or height must be +ve" );
                        draw=false;
                   setLayout( new BorderLayout() ) ;
              public void drawBackground( Graphics g ) {
                   System.out.println( "zeeeb!" );
                   int w = getWidth() ;
                   int h = getHeight() ;
                   int iw = img.getWidth( this ) ;
                   int ih = img.getHeight( this ) ;
                   for( int i = 0 ; i < w ; i+=iw ) {
                        for( int j = 0 ; j < h ; j+= ih ) {
                             g.drawImage( img , i , j , this ) ;
              protected void paintComponent(Graphics g) {
                   System.out.println( "zeeeha!" );
                   super.paintComponent(g);
                   if (draw) drawBackground( g ) ;
    }

    why my "original post with two class" example is not calling the paintComponent() A couple of things have conspired to prevent the invocation of the paintComponent() method.
    The preferredSize of your panel is (0, 0). Therefore, the size of all the components added to the frame is (0, 0). when the frame is made visible. It also appears than when you reset the size of the frame there is no need to repaint the panel since its size is (0, 0);
    Simple solution is to change the order of your code to be:
    frame.setSize(dim);
    frame.setVisible(true);A couple of notes:
    a) to maximize the frame, rather than setting the size manually it is better to use:
    frame.setExtendedState (JFrame.MAXIMIZED_BOTH);
    b) instead of using a window listener to close the frame it is easier to use:
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  • Why does the parameter of the paintComponent method have....?

    Why does the parameter of the paintComponent method have type Graphics and not Graphics2D?

    masijade. wrote:
    Additionally, it is, however, normally, a Graphics2D object's reference value that is passed around....which means most painting code starts out by casting the Graphics object to Graphics2D. You know what they say: death, taxes, and cruft... :P

  • About paintComponent method

    Hello,
    I am using swing to develop an user interface for a medium-complex program. Here is the code in the paintComponent method:
    public void paintComponent (Graphics g) {
            Graphics2D g2 = (Graphics2D)g;
            super.paintComponents(g2);
            if (frame.m == null)
                System.out.println("Es null main");
            else {
                System.out.println("No es null main");
               Vector clusters = frame.m.obtenerClusters();
                Iterator it = clusters.iterator();
                while (it.hasNext()) {
                    Cluster c = (Cluster)it.next();
                    Punto p = c.obtenerCoordinador();
                    Color color = c.obtenerColor();
                    Vector sen = c.obtenerSensores();
                    Iterator itS = sen.iterator();
                    while (itS.hasNext()) {
                       Sensor s = (Sensor)itS.next();
                       dibujarSensor(g2, s, color);
                    if (p != null) {
                        dibujarCoordinador(g2, p, color);
                        if (frame.isSelectedDibujarCirculo()) {
                            dibujarCirculoMinimo(g2, c.obtenerCoordinador(), c.obtenerRadio(), color);
                NodoSink s = frame.m.obtenerSink();
                if (s != null) {
                  dibujarSink(g2,s);
        }Every time that this method is called (by me using repaint() or by the virtual machine), the program needs to "walk" over the hole Vector structure and paint again and again the same things, which is very inefficient.
    There are some way to avoid it? I'm worry about it because the Vector structure is commonly very long.
    Thanks!

    Create a BufferedImage and do the custom painting on the BufferedImage.
    If your painting is relatively static then you could create an ImageIcon from the BufferedImage and add the icon to a label and add the label to the GUI. If you need to change the custom painting then you would need to recreate the icon and update the image.
    If you painting is relatively dynamic, then you just change the paintComponent() method to draw the buffered image.

  • BufferedReader's readLine() method problem (REPOST)

    Hello,
    If anyone can help me out I would not have to struggle :)
    Here is the thing. I have a file like this:
    1 srjetnuaazcebsqfbzerhxfbdfcbxyvihswlygzsfvjleengcftwvxcjriwdohjisnzppipiwpnniui yjpeppaezftgjfviwxunu
    2 ekjghqflatrcdteurofahxoiyvrwhvaxjgcuvkkpondsqhedxylxyjizflfbgusoizogbffgwnswohe njixwufcdlbjlkoqevqdy
    3 stfhcbslgcrywwrgbsqdkcxfbizvniyookceonscwugixgrxvvkxiqezltsiwhhepqusjdlkhadvkzg iefgarenbxnxtxnqdqpfh
    4 dcuefkdrkoovjwdrqbpgoirruutphuiobqweknxhboyktxzcczgekrlbfsbfuygjpheydiwaasxifph tldawxsfepotkgqqsivur
    5 fpfrspbuhangkeugfuwexsgivetovkoyloddgofdcajwwlrocgjrhonsrfrfxozvgohwoytycfjoycr xdhnhxyitkeqynedrbroh
    6 hgzqqsfgnotfepywbpccrosxborslqtkanyffrwknjapnzjnesjlkbbsckbyvgrxujqyocpcpctsqyz apcinhjyysxsdwfjugndr
    7 pltzealtrklzrugxdcskndqyvsrzncitqvjcnndeqossyrifzvbqovtdzsixjlizsbxwutgqipuxfid xyoktwupsuqbqgnxdfbze
    8 avpxfjgwpxnzfsfosgsryhpyaezigrqsxsgdvwdbwovhcchrijbitvbcvltrgvadogokaennwpjjpku uttidlnqftdnzqpqafels
    9 oyvztgletdwdtibshpzeuqryvulnubrqtgxwizfsdzqlgxvsebhslnovphgehfigbjyyqsirqcwflbn bnrflotpqytqzbgnkeyrk
    10 unvryrnlqucuydrasyzyiclnjvospzdoviqchdhasxzffblwsewikzbznyegrqtjvxfxfjenvrboofb xfsynlxhyuvqprqbvoruk
    and my java programs is like this:
    public String searchForAString(String fileName, int lineNumber)
    File fileObject = new File(fileName);
    String finalString ="";
    String record = "";
    int line;
    try
    FileInputStream fileInputStreamObject = new FileInputStream(fileObject);
    BufferedInputStream bufferedInputStreamObject = new BufferedInputStream(fileInputStreamObject);
    //DataInputStream dataInputStreamObject = new DataInputStream(bufferedInputStreamObject);
    BufferedReader bufferedReaderObject = new BufferedReader(new InputStreamReader(bufferedInputStreamObject));
    //System.out.println(bufferedReaderObject.readLine());
    //System.out.println("_____________________");
    while((bufferedReaderObject.readLine()) != null)
    System.out.println(bufferedReaderObject.readLine());
    Last System.out.println statement only displays second, forth, sixth, eigth, tenth and null lines. Why not every line? Any ideas? Thanks!
    Re: BufferedReader's readLine() method problem.
    Author: EagleEye101 Feb 18, 2005 8:48 PM (reply 1 of 1)
    You do relize that when you call the in.readLine() in your loop conditional and in your loop body it reads in diffrent lines. Try this:
    public String searchForAString(String fileName, int lineNumber)
    File fileObject = new File(fileName);
    String finalString ="";
    String record = "";
    int line;
    try
    FileInputStream fileInputStreamObject = new FileInputStream(fileObject);
    BufferedInputStream bufferedInputStreamObject = new BufferedInputStream(fileInputStreamObject);
    //DataInputStream dataInputStreamObject = new DataInputStream(bufferedInputStreamObject);
    BufferedReader bufferedReaderObject = new BufferedReader(new InputStreamReader(bufferedInputStreamObject));
    //System.out.println(bufferedReaderObject.readLine());
    //System.out.println("_____________________");
    String s = bufferedReaderObject.readLine();
    while(s != null)
    System.out.println(bufferedReaderObject.readLine());
    s = bufferedReaderObject.readLine();
    Every time you call the readLine method, it does read a diffrent line. Java does not know you want to read the same line twice.
    Tried it, did not work. I need to go through each line of the file I have. Any ideas?

    solution should be in your other thread.
    Please do not repeat threads--it really bugs the people here, just some 'nettiquite' --I don't mean to be a grouch.
    --later.  : )                                                                                                                                                                                                                                                                                                                                                       

  • Is that a problem of SwingUtilities.paintComponent() method ?

    Hello Everyone,
    I have succeeded to write the HTML contents of jeditorpane to buffered image. But the output image shows everything except the Radio Buttons,Text Boxes and Buttons on that HTML page. Please suggest me where might be the problem.
    Compare two images,
    1> one which is displayed on a jframe, which displays Radio button, Text Box, Submit Button.
    2> another one which is created on C: drive, named as out.jpg. This image doesn't have Radio button, Text Box, Submit Button.
    Note: I don't want to display an image anywhere. Not on even JFrame. [ I have implemented the code for displaying just to show you the difference in images]
    Thanks and Regards.
    import java.awt.image.BufferedImage;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.awt.*;
    import java.net.MalformedURLException;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import javax.swing.JEditorPane;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import java.net.URL;
    import javax.imageio.ImageIO;
    public class HTMLPageToImage
            static class Kit extends HTMLEditorKit
                public Kit() {
                public Document createDefaultDocument()
                    HTMLDocument doc = (HTMLDocument) super.createDefaultDocument();
                    doc.setTokenThreshold(Integer.MAX_VALUE);
                    doc.setAsynchronousLoadPriority(-1);
                    return doc;
               public ViewFactory getViewFactory() {
                    return new SynchronousImageViewFactory(super.getViewFactory());
                static class SynchronousImageViewFactory implements ViewFactory {
                    ViewFactory impl;
                    SynchronousImageViewFactory(ViewFactory impl) {
                        this.impl = impl;
                    public View create(Element elem) {
                        View v = impl.create(elem);
                        if((v != null) && (v instanceof ImageView)) {
                            ((ImageView)v).setLoadsSynchronously(true);
                        return v;
        public static BufferedImage getCapturedImage(String filePath, int width, int height)
            JEditorPane jep = new JEditorPane();
            Kit kit = new Kit();
            //String str = "file:" + filePath;
            String str = "http://" + filePath;
            URL url;
            try {
                url = new URL(str);
                try {
                    jep.setEditorKit(kit);
                    jep.setEditable(false);
                    jep.setContentType("text/html");
                    jep.setPage(url);
                    System.out.println("jep size : " + jep.getPreferredSize());
                    width = jep.getPreferredSize().width;
                    height = jep.getPreferredSize().height;
                        //--- Just to show that Radio Buttons, Text Box, Submit Buttons are displayed properly ----
                        JPanel p = new JPanel();
                        p.setVisible(true);
                        p.setSize(width,height);
                        p.add(jep);
                        JFrame f = new JFrame();
                        f.setSize(1024,768);
                        f.setVisible(true);
                        f.add(p);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                } catch (IOException ex) {
                    ex.printStackTrace();
            } catch (MalformedURLException ex) {
                ex.printStackTrace();
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D bufferedImageGraphics2D = bufferedImage.createGraphics();
            Container c = new Container();
            SwingUtilities.paintComponent(bufferedImageGraphics2D, jep, c, 0, 0, width, height);
            bufferedImageGraphics2D.dispose();
            return bufferedImage;
        public static void main(String[] args) throws FileNotFoundException,IOException
            //BufferedImage image = HTMLPageToImage.getCapturedImage("E:\\Texture\\my.html", 1024, 768);
            BufferedImage image = HTMLPageToImage.getCapturedImage("www.google.com", 1024, 768);
            com.sun.image.codec.jpeg.JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(new FileOutputStream("c:\\out.jpg"));
            enc.encode(image);
            System.out.println("See the image out.jpg created on C: drive ! ");
    }Edited by: nikhil_shravane on Jun 27, 2008 6:42 AM
    Edited by: nikhil_shravane on Jun 27, 2008 7:34 AM
    Edited by: nikhil_shravane on Jun 27, 2008 8:12 AM

    Hi Again, TextBox, TextArea and buttons are visible only when I place the jeditorpane with an HTML on a JPanel and JFrame before writing the captured image on a buffered Image. But when I directly captures the image from jeditorpane without placing it on JPanel and JFrame, the captured image doesn't show the TextBox, TextArea and Buttons. I want to capture the HTML image and write it directly to buffered Image. For that I don't want to open JPanel and JFrame. I can write the captured HTML from jeditorpane directly to the buffered image, but that image doesnt have tha TextBox, TextArea, Buttons and Tables. Following is the method which writes the captured HTML from jeditorpane directly to the buffered image.
    import java.awt.*;
    import java.awt.image.*;
    import java.io.IOException;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    * @author Nikhil Shravane
    public class WebImage {
        JEditorPane jep;
        Container c;
        BufferedImage bufferedImage ;
        Graphics2D bufferedImageGraphics2D;
        Object object;
        Kit kit;
         WebImage()     {
             object = new Object();
        static class Kit extends HTMLEditorKit {
                // Override createDefaultDocument to force synchronous loading
                public Document createDefaultDocument() {
                        HTMLDocument doc = (HTMLDocument) super.createDefaultDocument();
                        doc.setTokenThreshold(Integer.MAX_VALUE);
                        doc.setAsynchronousLoadPriority(-1);
                        return doc;
        public synchronized BufferedImage getCapturedImage(String src, int width, int height)    {
            jep = new JEditorPane();
            kit = new Kit();
            jep.setEditorKit(kit);
            jep.setEditable(false);
            jep.setMargin(new Insets(0,0,0,0));
            synchronized(object)        {
                try {
                    jep.setPage(src);
                } catch (IOException ex) {
                    ex.printStackTrace();
                height = width;//  * jep.getPreferredSize().height / jep.getPreferredSize().width;
                bufferedImage = new BufferedImage((int)width, (int)height, BufferedImage.TYPE_INT_RGB);
                bufferedImageGraphics2D = bufferedImage.createGraphics();
                c = new Container();
                SwingUtilities.paintComponent(bufferedImageGraphics2D, jep, c, 0, 0, (int)width, (int)height);
                bufferedImageGraphics2D.dispose();
            JLabel label = new JLabel(new ImageIcon(bufferedImage));
            JOptionPane.showMessageDialog(null, label, "clipped image",
                                              JOptionPane.PLAIN_MESSAGE);
            return bufferedImage;
        public static void main(String[] args) {
            WebImage webImage = new WebImage();
                BufferedImage image = webImage.getCapturedImage("http://www.google.com/", 640, 480);
                //BufferedImage image = webImage.getCapturedImage("file:\\E:\\Texture\\my.html", 640, 480);
                // you can write this buffered image anywhere...
    }Above code will capture the HTML image and write it to buffered image and returns the buffered image.
    Please Suggest me the way, so that I can see the Buttons, TextBox, TextArea, Tables etc.
    Thanks and Regards,
    Nikhil

  • Methods problem!

    The program below currently draws a point on the screen when the user clicks with the mouse. I call the method testPass from another program, and pass the boolean variable vertexCheck. My problem is that I want the paint program only to draw the points when this variable is true. I have been trying to do this for ages, with no luck.
    class DrawingArea extends JPanel{
      Point[] p = new Point[100];
      int i = 0;
      public void testPass(boolean vertexCheck){}
      public DrawingArea(){
        MouseEventListener mlistener = new MouseEventListener();
        addMouseListener(mlistener);
       class MouseEventListener implements MouseListener{
           public void mouseEntered(MouseEvent e){}
           public void mouseReleased(MouseEvent e){}
           public void mousePressed(MouseEvent e){}
           public void mouseExited(MouseEvent e){}
           public void mouseClicked(MouseEvent e){     
                int x = e.getX();
                int y = e.getY();
                p[i] = new Point(x,y);
                i++;
                repaint();
        public void paintComponent(Graphics g){
         super.paintComponent(g);  
         for(int i=0; i< p.length;i++)
         {   if (p!=null)
         {g.fillOval(p[i].x, p[i].y, 10, 10);}

    I have tried changing the method as follows with no
    success. I also pass the x and y values from the other
    program, and use these to create a new point. I now
    want this point to be drawn. In the paintComponent I
    have tried g.fillOval(point.x, point.y, 10, 10); but
    this still does not work. Any ideas?
    public void testPass(boolean vertexCheck, int x, int
    y)
    {  if(vertexCheck==true)
    {  point = new Point(x,y);
    repaint();
    In this code you create a new Point named "point". I don't see that var declared anywhere. You did create a Point [] but that's named "p".

  • Using Calendar.set() method problem

    Hi all,
    First of all sorry to bother with such a trivial(?) matter but I cannot solve it by myself.
    I have a piece of code which I simply want to handle the current date with the GregorianCalendar object so that the date would be set to the Calendar.SUNDAY (of the current week). Simple enough?
    Code as follows:
    import java.util.*;
    import java.text.*;
    public class Foo
    public static void main(String[] args)
         Foo foo = new Foo();
         Date newdate = foo.bar();
    public Date bar()
         GregorianCalendar m_calendar = new GregorianCalendar(new Locale("fi","FI"));
         m_calendar.setFirstDayOfWeek(Calendar.MONDAY);
         Date newDate = null;
         try
              m_calendar.setTime(new Date());
              System.out.println("Calendar='" + m_calendar.toString() + "'");
              m_calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
              SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
              StringBuffer sb = new StringBuffer();
              sdf.format(m_calendar.getTime(), sb, new FieldPosition(0));
              System.out.println("Date in format (" + sdf.toPattern()          + ") = '" + sb.toString() + "'");
         catch(Exception e)
              e.printStackTrace();
         return m_calendar.getTime();
    This should work at least accoring to my understanding of the SDK documentation as follows with
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.1_01-b01)
    Java HotSpot(TM) Client VM (build 1.4.1_01-b01, mixed mode)
    Calendar='java.util.GregorianCalendar[time=1054636838494,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Helsinki",offset=7200000,dstSavings=3600000,useDaylight=true,transitions=118,lastRule=java.util.SimpleTimeZone[id=Europe/Helsinki,offset=7200000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2003,MONTH=5,WEEK_OF_YEAR=23,WEEK_OF_MONTH=1,DAY_OF_MONTH=3,DAY_OF_YEAR=154,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=1,HOUR_OF_DAY=13,MINUTE=40,SECOND=38,MILLISECOND=494,ZONE_OFFSET=7200000,DST_OFFSET=3600000]'
    Date in format (yyyy.MM.dd) = '2003.06.08'
    Which is the sunday of this week. But as I run the same code with:
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.1.06-020625-14:20)
    Java HotSpot(TM) Server VM (build 1.3.1 1.3.1.06-JPSE_1.3.1.06_20020625 PA2.0, mixed mode)
    Calendar='java.util.GregorianCalendar[time=1054636630703,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=java.util.SimpleTimeZone[id=Europe/Helsinki,offset=7200000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2003,MONTH=5,WEEK_OF_YEAR=23,WEEK_OF_MONTH=1,DAY_OF_MONTH=3,DAY_OF_YEAR=154,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=1,HOUR_OF_DAY=13,MINUTE=37,SECOND=10,MILLISECOND=703,ZONE_OFFSET=7200000,DST_OFFSET=3600000]'
    Date in format (yyyy.MM.dd) = '2003.06.01'
    Which is sunday of the previous week and incorrect in my opinion. The latter result is run on HP-UX B.11.11 U 9000/800 and first on NT.
    Any ideas why this is happening? Thanks in advance!
    Greets, Janne

    Thanks for your answer!
    The problem is that I have to work with this older SDK version. :) But I got it solved by using the roll method with the following syntax:
    int delta = [dayToSet] - m_calendar.get(Calendar.DAY_OF_WEEK);
    in which the delta is of course the difference (negative or positive to the current day of the week)
    and then using the roll call:
    m_calendar.roll(Calendar.DAY_OF_WEEK, delta);
    which doesn't alter the current week. So this works if someone else has a similar problem with the version 1.3.1
    Greets, Janne

  • Enhance Method Problem

    I try to enhance a Method like described in this Thread...
    Re: Sending Email using the Outlook Client
    What I did so far...
    1) In Transaction "bsp_WD_CMPWB"  I choosed Component "BP_ADDR" and created a copy in our "Z_CRM" EnhancementSet
    2) I used the right Mousebutton to Enhance the "BP_ADDR/StandardAddress" View
    Two things had been automatically generated/created...
    - Table Contents BSPWD_CMP_C_REPL
    - Object ZL_BP_ADDR_STANDARDADDRES_CTXT
    3) I doubleclick on the enhanced View "BP_ADDR/StandardAddress"
        (-> In the "View Layout" node the StandardAddress.html is still using the Super Classes / Implementation Class CL_BP_ADDR_STANDARDADDRES_CN01 )
    4) If I go to Implemetation Class CL_BP_ADDR_STANDARDADDRESS_CN01
    5) Select method "GET_P_E_MAILSMT" (and look into the coding)
       The enhancement Functions there are not working for meu2026
       I tried the Button with the (Sprial / helix)
       and the Menu "Edit"-> "Enhancement Operations"
    Where is my error?! (I think I have to create a ZClass for the CL_BP_ADDR_STANDARDADDRES_CN01?!?!? But how to???)
    I will give all possible points for good answers
    Thanks for helpingu2026

    hi,
    Some times I also faced problems to create Zclass for standard ones. But you can do one trick to create Zclass.
    Try to create one dummy attribute in your context node, then it will creates  automatically Zclass for that node. Later you can delete that attribute.
    If you get any problems to create P-getter method, then copy the IF_BSP_WD_MODEL_SETTER_GETTER~_GET_P_XYZ template method and rename to GET_P_E_MAILSMT.
    regards
    Ismail

Maybe you are looking for