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)

Similar Messages

  • Painting in JPanel with PaintComponent.

    Hi I've got a problem, if i define my JPanel like this then I can't paint in it.
    public class kvadrat
    JPanel aPanel;
    public void Panel()
      aPanel = new JPanel();
      aPanel.setBackground(Color.white);
      aPanel.add(sendButton);
    public void Frame()
      Panel();
      JFrame frame = new JFrame("Considerate Music");
      Container iRutan = frame.getContentPane();
      iRutan.setLayout(new BorderLayout());
      iRutan.add(aPanel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setBounds(300,300,700,400);
      frame.setVisible(true);
    public kvadrat()
      Frame();
    public static void main(String[] args)
      new kvadrat();
    public void paintComponent(Graphics g)
    }I can't use the line super.paintComponent(g); in paintComponent because I don't have any extend. I don't want to have any extends on my class so this is why I'm asking, is there a way to paint on my panel(aPanel) in any other way that using extends. You see if I'd like to add more panels I'll have to create a class for each panel and I don't like that.

    2 Ways.
    #1: An Inner Class
    public class kvadrat{
    public kvadrat(){
    new MyPanel();
    //inner class
    public class MyPanel extends JPanel{
    // methods
    }or
    #2: Anonymous Inner Classes (very sloppy)
    public class kvadrat
    JPanel aPanel;
    public void Panel()
    // right here:
      aPanel = new JPanel(){
           public void paintComponent(Graphics g){
      // code goes here
      aPanel.setBackground(Color.white);
      aPanel.add(sendButton);
    public void Frame()
      Panel();
      JFrame frame = new JFrame("Considerate Music");
      Container iRutan = frame.getContentPane();
      iRutan.setLayout(new BorderLayout());
      iRutan.add(aPanel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setBounds(300,300,700,400);
      frame.setVisible(true);
    public kvadrat()
      Frame();
    public static void main(String[] args)
      new kvadrat();
    // removed: public void paintComponent(Graphics g)
    }

  • Scrolling a custom Component (e.g. JPanel) with overridden paint(Graphic g)

    Hi.
    I’m creating an application for modelling advanced electrical systems in a house. Until now I have focused on the custom canvas using Java2D to draw my model. I can move the model components around, draw lines between them, and so on.
    But now I want to implement a JScrollPane to be able to scroll a large model. I’m currently using a custom JPanel with a complete override of the paint(Graphic g) method.
    Screen-shot of what I want to scroll:
    http://pchome.grm.hia.no/~aalbre99/ScreenShot.png
    Just adding my custom JPanel to a JScrollPane will obviously not work, since the paint(Graphic g) method for the JPanel would not be used any more, since the JScrollPane now has to analyze which components inside the container (JPanel) to paint.
    So my question is therefore: How do you scroll a custom Component (e.g. JPanel) where the paint(Graphic g) method is totally overridden.
    I believe the I have to paint on a JViewport instructing the JScrollPane my self, but how? Or is there another solution to the problem?
    Thanks in advance for any suggestions.
    Aleksander.

    I�m currently using a custom JPanel with a complete override of the paint(Graphic g) method. Althought this isn't your problem, you should be overriding the paintComponent(..) method, not the paint(..) method.
    But now I want to implement a JScrollPane to be able to scroll a large model.When you create a custom component to do custom painting then you are responsible for determining the preferredSize of the component. So, you need to override the getPreferredSize(...) method to return the preferredSize of your component. Then scrolling will happen automatically when the component is added to a scrollPane.

  • (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

  • JScrollPane function with Custom Paint ???

    Hi, I'm having a problem with scrolling with components for which I've overidden the paint method for.
    I have a scrollpane which contains a ContentPanel (my own subclass of JPanel in which I implemented paint and paintComponent). The ContentPanel contains Subclasses JButton's which also have their own paintComponent methods.
    Problem: Everything (including scrollbars) paint correctly initially. The problem arises when one tries to scroll. When I pull the scrollbar in any direction, the JButtons paint oscillate between painting themselves at the correct scrolled position and at the original position in the Viewport. Then when one lets go of the scroll, the component rests in exactly the same position in the Viewport as it started.
    I tried implementing the Scrollable inteface, still no luck. The documentation seems to imply that custom painting should have no effect on scrolling because the content is contained in the view and the ScrollBar commissions a Viewport class to help it move around. I'm not sure, but it seems like it should not be the result of my overidding the paint methods.
    I'm so confused, is there something else I need to implement to use JScrollPanes, like Adjustment Listener?
    Thanks for your help, Aurora

    Dear Tom,
    It looks like the code you have was originally made for awt, not swing. In swing, one should override the paintComponent(Graphics g) method, not the paint() method.
    For reasons why check out this tutotial on how painting works.
    http://java.sun.com/docs/books/tutorial/uiswing/overview/draw.html
    The reason why you need to call super.paintComponent() in the JPanel is because the JPanel you have is not completely opaque, (I think). Anyway, it has to do with how painting works.
    public class myPanel extends JPanel
    public myPanel()
    setVisible(true);
    setSize(600,200);
    setLayout(null);
    setBackground(Color.white);
    myBox m1 = new myBox();
    //is the bounds of myBox set appropriately??? Perhaps you need to setBounds() in the constructor of mybox.
    add(m1);
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    g.setColor(Color.black);
    g.drawString("Test", 10, 13);
    m1.paint(g);
    //this is important. The subcomponents will not paint themselves unless they are told to by their containers.
    In Swing, basically painting works as a hierarchy where the top level Component paints itself and then paints all it's children component, they paint their children and so on. Swing also determines many important things using the bounds of each component. To ensure correct painting and listening behavior, make sure the bounds for your myBoxes are the correct size. Also, implement public void paintComponent(Graphics g) in the myBox so that it will draw it's own rectangle when called by myPanel.
    If that doesn't work, check out how myPanel is being added to the overall JFrame. It may not be displaying correctly because you have forgotten to add it or don't have a layout manager etc.
    Good luck,
    Aurora

  • 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);

  • Painting in JPanels

    Hey guys, thanks for the help with the last question. Heres another for the same program!
    So this program generates a JFrame which is populated with JPanel's in a gridLayout() format. The grid is supposed to represent a maze which is navigated by clicking on the appropriate panels.
    The first problem I'm having is trying to get the starting square, the current square and the squares that have previously stepped on to change color. Also the current square should show a circle to indicate where you are.
    Instead of doing that the squares are just showing random graphics on them due to an arbitrary line of code i put in:
    Graphics g = getGraphics();If i take that out then nothing changes color/graphics.
    The second problem I'm having is when i load a new maze (or the same one) instead of replacing the displayed one it tries to squish them both in. Yet when i print out all the values like the number of columns in the gridLayout it they are all correct. I'm hoping this is just a display error and will be fixed with the first problem.
    The Maze.java class brings everything together and calls the Walls.java class which creates and adds the JPanel's which are GridPanel.java objects. The Move.java and Maze.java alters the GridPanel's to be current or not... Good Luck =) and thanks heaps as always! YOU GUYS ARE LIFESAVERS!!!
    //Ass2.java
    public class Assign2
         public static void main(String[] args)
              Maze theMaze = new Maze();
    //Maze.java
    import java.io.*;
    import java.util.Vector;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class Maze extends JFrame
         Vector<String> data = new Vector<String>();
         GridPanel[][] panel;
         private int[] endPoints = new int[4];
         private int[] size = new int[2];
         private int moveNum;
         private int theSize;
         private int cX;
         private int cY;
         private int pX;
         private int pY;
         public Maze()
              MazeApp s = new MazeApp(this);
              moveNum = 0;
              File f = new File("maze.txt");
              readMaze(f);
         public void readMaze(File fName)
              File fileName = fName;
              Read r = new Read();
              data.clear();
              size = r.readFile(endPoints, data, fileName);
              theSize = (size[1] * size[0]);
              cX = endPoints[0];
              cY = endPoints[1];
              GridLayout layout = new GridLayout();
              layout.setRows(size[1]);
              layout.setColumns(size[0]);
              this.setLayout(layout);
              System.out.println(data.size());
              makeMaze();
         public void makeMaze()
              panel = new GridPanel [size[1]][size[0]];
              Walls w = new Walls(data, size, this);
              w.drawWalls(panel);
              panel[endPoints[1]][endPoints[0]].setStart();
              panel[endPoints[3]][endPoints[2]].setEnd();
              this.setSize(size[0]*100, size[1]*100);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setVisible(true);
         public void checkMove(Point clicked, int w, int h, int wall)
              pY = (int)(clicked.getX())/w;
              pX = (int)(clicked.getY())/h;
              Move m = new Move(cX, cY, pX, pY, w, h, wall);
              if(m.check() == 1) //MOVE NORTH
                   if((panel[cX-1][cY].checkWall() != 2) && (panel[cX-1][cY].checkWall() != 3))
                   {setCurrent();}else{JOptionPane.showMessageDialog(this, "Invalid Move! Cannot move through walls!");}
              if(m.check() == 2) //MOVE SOUTH
                   if((panel[cX][cY].checkWall() != 2) && (panel[cX][cY].checkWall() != 3))
                   {setCurrent();}else{JOptionPane.showMessageDialog(this, "Invalid Move! Cannot move through walls!");}
              if(m.check() == 3) //MOVE WEST
                   if((panel[pX][pY].checkWall() != 1) && (panel[pX][pY].checkWall() != 3))
                   {setCurrent();}else{JOptionPane.showMessageDialog(this, "Invalid Move! Cannot move through walls!");}
              if(m.check() == 4) //MOVE EAST
                   if((panel[cX][cY].checkWall() != 1) && (panel[cX][cY].checkWall() != 3))
                   {setCurrent();}else{JOptionPane.showMessageDialog(this, "Invalid Move! Cannot move through walls!");}
              if(m.check() == 0 )
              {JOptionPane.showMessageDialog(this, "Invalid Move! Invalid square selected!\nPlease choose an adjacent square.");}
         public void setCurrent()
              panel[cX][cY].setUsed();
              panel[pX][pY].setCurrent();
              cX = pX;
              cY = pY;
              moveNum++;
              if(cY == endPoints[2] && cX == endPoints[3])
              {JOptionPane.showMessageDialog(this, "Congratulations!\nYou finished in" + moveNum + "moves!");}
    // MazeApp.java
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    public class MazeApp extends JFrame
           private Maze theMaze;
           public MazeApp(Maze m)
                   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   theMaze = m;
                   // create the menu bar to hold the menus...
                   JMenuBar menuBar = new JMenuBar();
                   // create the menus to hold the menu items...
                   JMenu menuFile = new JMenu("File");
                   JMenu menuOptions = new JMenu("Options");
                   JMenu menuHelp = new JMenu("Help");
                   // create file menu options:
                   JMenuItem itemLoad = new JMenuItem("Load");
                   JMenuItem itemSaveAs = new JMenuItem("Save As...");
                   JRadioButtonMenuItem itemModePlay = new JRadioButtonMenuItem("Play");
                   JRadioButtonMenuItem itemModeEdit = new JRadioButtonMenuItem("Edit");
                   JMenuItem itemExit = new JMenuItem("Exit");
                   //create options menu:
                   JRadioButtonMenuItem itemNoRats = new JRadioButtonMenuItem("No Rats");
                   JRadioButtonMenuItem itemOneRat = new JRadioButtonMenuItem("One Rat");
                   JRadioButtonMenuItem itemTwoRats = new JRadioButtonMenuItem("Two Rats");
                   //create help option:
                   JMenuItem itemHelp = new JMenuItem("Help");
                   JMenuItem itemAbout = new JMenuItem("About");
                   //set default options:
                   itemModePlay.setSelected(true);                    
                   itemNoRats.setSelected(true);
                   // add File options:
                   menuFile.add(itemLoad);
                   menuFile.add(itemSaveAs);
                   menuFile.addSeparator();
                   menuFile.add(itemModePlay);
                   menuFile.add(itemModeEdit);
                   menuFile.addSeparator();
                   menuFile.add(itemExit);
                   //add Options:
                   menuOptions.add(itemNoRats);
                   menuOptions.add(itemOneRat);
                   menuOptions.add(itemTwoRats);
                   //add Help options:
                   menuHelp.add(itemHelp);
                   menuHelp.add(itemAbout);
                   // add the menu to the menu bar...
                   menuBar.add(menuFile);
                   menuBar.add(menuOptions);
                   menuBar.add(menuHelp);
                   // finally add the menu bar to the app...
                   m.setJMenuBar(menuBar);
                   //listeners
                   itemExit.addActionListener(
                           new ActionListener()
                                   public void actionPerformed( ActionEvent event )
                                           System.exit( 0 );
                itemLoad.addActionListener(
                   new ActionListener()
                        public void actionPerformed( ActionEvent event )
                             final JFileChooser fc = new JFileChooser();
                             int returnVal = fc.showOpenDialog(MazeApp.this);
                          File fileName = fc.getSelectedFile();
                             if(fileName.exists())
                                  theMaze.readMaze(fileName);
                             else
                                  System.out.println("404. File not found");
                   itemAbout.addActionListener(
                           new ActionListener()
                                   public void actionPerformed( ActionEvent event )
                                           //do stuff
                                           JOptionPane.showMessageDialog(MazeApp.this, "Author: Pat Purcell\[email protected]", "About", JOptionPane.ERROR_MESSAGE);
    //Read.java
    import java.io.*;
    import java.util.Vector;
    public class Read
         private BufferedReader input;
         private String line;
         private String fileName;
         private String[] temp;
         private int[] size = new int[2];
         public int[] readFile(int[] endPoints, Vector<String> data, File fileName)
              try
                   data.clear();
                   FileReader fr = new FileReader(fileName);
                   input = new BufferedReader(fr);
                   line = input.readLine();
                   temp = line.split("\\s");
                   for(int i =0;i<2;i++)
                   {size[i] = Integer.parseInt(temp);}
                   line = input.readLine();
                   temp = line.split("\\s");
                   for(int i =0;i<4;i++)
                   {endPoints[i] = Integer.parseInt(temp[i]);}
                   line = input.readLine();
                   while (line != null)
                        String[] temp = line.split("\\s");
                        for(int i=0;i<size[0];i++)
                             data.addElement(temp[i]);
                        line = input.readLine();
                   input.close();
              catch (IOException e)
                   System.err.println(e);
              return size;
    }//Walls.java
    import java.util.Vector;
    import java.awt.GridLayout;
    import javax.swing.*;
    public class Walls extends JFrame
         private Vector<String> data = new Vector<String>();
         private int size;
         private Maze bm;
         private int row;
         private int column;
         public Walls(Vector<String> theData, int[] theSize, Maze m)
              data = theData;
              row = theSize[1];
              column = theSize[0];
              size = row*column;
              bm = m;
         public boolean testEast(int position)
              boolean exists;
              String temp = data.get(position);
              int eastData = ((int)temp.charAt(0) - (int)'0');
              if(1 == (eastData))
                   return true;
              return false;
         public boolean testSouth(int position)
              boolean exists;
              String temp = data.get(position);
              int southData = ((int)temp.charAt(1) - (int)'0');
              if(1 == (southData))
                   return true;
              return false;
         public boolean testBoth(int position)
              boolean exists;
              if((testEast(position) && testSouth(position)) == true)
                   return true;
              return false;
         public void drawWalls(GridPanel panel[][])
              int i = 0;
              for(int y=0;y<row;y++)
                   for(int x=0;x<column;x++, i++)
                   if (testBoth(i) == true)
                   {     GridPanel temp = new GridPanel(3, bm);
                        panel[y][x] = temp;
                                  bm.add(temp);}
                   else{
                        if (testEast(i) == true)
                        {     GridPanel temp = new GridPanel(1, bm);
                             panel[y][x] = temp;
                                  bm.add(temp);}
                        else{
                             if (testSouth(i) == true)
                             {     GridPanel temp = new GridPanel(2, bm);
                                  panel[y][x] = temp;
                                  bm.add(temp);}
                             else{
                                  GridPanel temp = new GridPanel(0, bm);
                                  panel[y][x] = temp;
                                  bm.add(temp);}
    }//GridPanel.java
    import javax.swing.JPanel;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    public class GridPanel extends JPanel implements MouseListener
    private int wall;
    private Maze bm;
    private Ellipse2D.Double circle = new Ellipse2D.Double();
    private Graphics gr;
    boolean current = false;
    boolean start = false;
    boolean finish = false;
    public GridPanel(int theWall, Maze m)
         wall = theWall;
         this.addMouseListener(this);
         bm = m;
         public void paintComponent(Graphics g)
              Graphics2D g2 = (Graphics2D)g;
              g2.setStroke(new BasicStroke(1));
              g2.draw(new Line2D.Double(this.getWidth()-1, 0, this.getWidth()-1, this.getHeight()-1));
              g2.draw(new Line2D.Double(0, this.getHeight()-1, this.getWidth()-1, this.getHeight()-1));
              g2.setStroke(new BasicStroke(4));
              if(wall == 0) //NO WALL
              if(wall == 1) //EAST WALL
                   g2.draw(new Line2D.Double(this.getWidth()-1, 0, this.getWidth()-1, this.getHeight()-1));
              if(wall == 2) //SOUTH WALL
                   g2.draw(new Line2D.Double(0, this.getHeight()-1, this.getWidth()-1, this.getHeight()-1));
              if(wall == 3) //BOTH WALLS
                   g2.draw(new Line2D.Double(0, this.getHeight()-1, this.getWidth()-1, this.getHeight()-1));
                   g2.draw(new Line2D.Double(this.getWidth()-1, 0, this.getWidth()-1, this.getHeight()-1));
              if(current == true)
                   setBackground(SystemColor.green);
                   circle = new Ellipse2D.Double();
                   circle.x = 0;
                   circle.y = 0;
                   circle.height = this.getHeight()-1; // -1 so it fits inside the panel.
                   circle.width = this.getWidth()-1;
                   g2.draw(circle);
                   repaint();
              if(start == true)
              {     setBackground(SystemColor.green);
                   g2.drawString("S", this.getWidth()/2, this.getHeight()/2);}
              if(finish == true)
              {     setBackground(SystemColor.green);
                   g2.drawString("F", this.getWidth()/2, this.getHeight()/2);}
         public int checkWall()
              return wall;
         public void setCurrent()
              Graphics g = getGraphics();
              repaint();
         public void setUsed()
              current = false;
              repaint();
         public void setStart()
              start = true;
              repaint();
         public void setEnd()
              finish = true;
              repaint();
         public void mouseClicked(MouseEvent e){bm.checkMove(this.getLocation(), this.getWidth(), this.getHeight(), wall);}
         public void mouseReleased (MouseEvent e) {}
         public void mouseEntered (MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}
         public void mousePressed(MouseEvent e) {}
    }//Move.java
    import java.awt.*;
    public class Move
         private int pX;
         private int pY;
         private int cX;
         private int cY;
         private int w;
         private int h;
         private int wall;
         public Move(int x1, int y1, int x2, int y2, int theWidth, int theHeight, int wallCheck)
              pX = x2;
              pY = y2;
              cX = x1;
              cY = y1;
              w = theWidth;
              h = theHeight;
         public int check()
              //System.out.println(cX + " " + (pX + 1));
              if((cX == (pX + 1)) && (cY == pY)) //MOVE NORTH
              {return 1;}
              //System.out.println(cX + " " + (pX - 1));
              if((cX == (pX - 1)) && (cY == pY)) //MOVE SOUTH
              {return 2;}
              //System.out.println(cY + " " + (pY + 1));
              if((cY == (pY + 1)) && (cX == pX))//MOVE WEST
              {return 3;}
              //System.out.println(cY + " " + (pY - 1));
              if((cY == (pY - 1)) && (cX == pX))//MOVE EAST
              {return 4;}
              return 0;
    }This is the file the maze is read out of: Maze.txt6 5
    0 0 3 2
    10 00 01 01 01 10
    10 10 00 01 10 10
    10 10 01 11 10 10
    10 01 01 01 11 10
    01 01 01 01 01 11                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    -> Second proplem that still remains is the circle stays after you leave the square...
    Thats why I suggested you use a Border and not do custom painting. There is no such method as remove(...). You need to repaint the entire panel. If you use a Border you just use setBorder(...) to whatever. So you have two different Borders. One for when the component has focus and one for when the component doesn't.
    -> but the same two problems remain.
    Well, I don't know whats wrong and I am not about to debug your program since I have no idea what it is doing. So create a SSCCE to post.
    see http://homepage1.nifty.com/algafield/sscce.html,
    Basically all you need to do is create a JFrame. Create a "main" panel with a flow layout and add it to the content pane. Then create 3 or 4 panels with a default Border on a black line and add the panels to the "main" panel. Then add you MouseListeners and FocusListeners to the panels. The whole program should be 30 lines of code or so. Understand how that program works and then apply the same concepts to you real program.
    The point is when you attempt to do something new that you don't understand write a simple program so you can prove to yourself that it works. If you can't get it working then you have a simple SSCCE to post and then maybe someone will look at it.

  • 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.

  • 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/ 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

  • 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();
    }

  • 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

  • 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?

  • Setting the bounds of a JPanel with double values

    Hi,
    I want to use a JPanel in my application, but the setBounds() method is limited to only int. Now I'm wondering if there is a way to set the bounds on the JPanel with doubles, so I can paint it for example x = 15.5;
    I was thinking about override the setBounds method, but is this even possible without causing problems to other methods? Or is there an easier way?
    Grtz

    Encephalopathic wrote:
    What is the purpose of this? Why are you using setBounds to begin with rather than layout managers?The reason I'm using absolute positioning is because the JPanels can be dragged to wherever they want. I can live with the fact that it isn't possible and solve it in another way, but I was just wondering if it is possible.

  • OverlayLayout for JPanel with two JLabels

    I can't seem to get this to work or find information (not one of my books mentions OverlayLayout, nor is there a tutorial using one). Here's the layout (pardon the pun) of my app:
    JFrame
         JMenuBar
         JToolBar
         JPanel
              JScrollPane
                   JViewport
                        JPanel (view)
                             JLabel (background image)
                             JLabel (foreground drawing)
         JLabel (status bar)The JPanel (view) has an OverlayLayout so that the two JLabels can sit ontop of one another (as specified in the API docs for OverlayLayout - which is the only info to be found on the darned thing - and little at that). The JLabel (foreground drawing) is setOpaque(false) to see the image in JLabel (image). I see the image but not the drawing. The retrieved size for the JLabel (drawing) is (0,0), but if the preferredSize is set for it, it restricts everything inside the JScrollPane (JViewport, JPanel (view), and JLabel (image)) to that value and viewport changes are not broadcast.
    This is turning out to be a lose, lose, lose, lose situation. No matter what I need to do, I cannot get two of anything on top of each other inside a JScrollPane. Any suggestions or working code are greatly appreciated.
    Robert Templeton

    Okay, here's how I did it. Couple points of interest: You MUST use setPreferredSize(image.width,image.height) and NOT setSize(image.width,image.height). The latter has no effect on the JPanel's size. Set the layout for the JPanel to GridLayout and add just that one JLabel. It will be stretched to fit the entire JPanel. Set JLabel to setOpaque(false) and the image is visible with the drawing on top. Yay!
    In the JFrame's JPanel
              // Set up the scroll pane.
              sglass = new ScrollableGlassLabel();
              scroller = new ScrollablePicture(8);
              scroller.add(sglass);
              pictureScrollPane = new JScrollPane();
              // Create our own viewport, instead of the default one
              viewport = new IViewport(this,pictureScrollPane,scroller);
              pictureScrollPane.setViewport(viewport);
              // Setup our view in the scroll pane's viewport
              pictureScrollPane.setPreferredSize(new Dimension(256, 256));
              pictureScrollPane.setViewportBorder(BorderFactory.createLineBorder(Color.black));
              // Put it in this panel.
              setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
              add(pictureScrollPane, 0);
              setBorder(BorderFactory.createEmptyBorder(20,20,20,20));ScrollablePicture:
    public class ScrollablePicture extends JPanel implements Scrollable {
         private int maxUnitIncrement = 1;
         Image image = null;
         public ScrollablePicture(int m) {
              super();
              maxUnitIncrement = m;
              setOpaque(false);
              setLayout(new GridLayout());
         public Dimension getPreferredScrollableViewportSize() {
              return getPreferredSize();
         public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
              //Get the current position.
              int currentPosition = 0;
              if (orientation == SwingConstants.HORIZONTAL)
                   currentPosition = visibleRect.x;
              else
                   currentPosition = visibleRect.y;
              //Return the number of pixels between currentPosition
              //and the nearest tick mark in the indicated direction.
              if (direction < 0) {
                   int newPosition = currentPosition - (currentPosition / maxUnitIncrement) * maxUnitIncrement;
                   return (newPosition == 0) ? maxUnitIncrement : newPosition;
              else {
                   return ((currentPosition / maxUnitIncrement) + 1) *     maxUnitIncrement - currentPosition;
         public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
              if (orientation == SwingConstants.HORIZONTAL)
                   return visibleRect.width - maxUnitIncrement;
              else
                   return visibleRect.height - maxUnitIncrement;
         public boolean getScrollableTracksViewportWidth()
              return false;
         public boolean getScrollableTracksViewportHeight()
              return false;
         public void setMaxUnitIncrement(int pixels)
              maxUnitIncrement = pixels;
         public void setImage(ImageIcon icon) {
              image = icon.getImage();
              setPreferredSize(new Dimension(icon.getIconWidth(),icon.getIconHeight()));
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              if(image != null)
                   g.drawImage(image, 0, 0, this);
    }ScrollableGlassLabel:
    public class ScrollableGlassLabel extends JLabel {
         private static Color[] colors = {
              Color.white, Color.black, Color.blue, Color.red, Color.yellow, Color.orange,
              Color.cyan, Color.pink, Color.magenta, Color.green };
         public ScrollableGlassLabel() {
              super();
              setOpaque(false);
         public void paintComponent(Graphics g) {
              int x, y, dx, dy;
              for(int i = 0; i < 32; i++) {
                   x = (int)(Math.random()*100);
                   y = (int)(Math.random()*100);
                   dx = (int)(Math.random()*100);
                   dy = (int)(Math.random()*100);
                   g.setColor(colors[(int)(Math.random()*10)]);
                   g.drawLine(x,y,x+dx,y+dy);
    }Right now, it just draws random lines, but it will be drawing 3D meshes soon.
    Thanks for you assistance, camickr. It at least got me thinking about alternatives.
    Robert Templeton

Maybe you are looking for

  • How can I delete a failed partition space?

    I tried to partition my disk for the first time, but unfortunately, it failed. Now there's a white space left for the supposed partition space. How can I retrieve it back? Help please.

  • ALV List Footer

    Hi, I have this requirement in my report to display the errors captured in logs at the end of the program after the changes made to purchase orders. There should also have a provision to download the log to an excel file. May I know on what event to

  • Oracle COM Automation

    We are getting an Error Unable to Open IPC Connection while using COM Automation feature of Oracle 8i. As specified in the documentation Listener.ora and TNSNames.ora are configured. The listener process is also running properly. But, still we are ge

  • Looking for APXXTR files on the database

    Hi to All, I have raised an SR with oracle to resolve a expense report issue that takes place in import process. SR asked to locate the following files. Currently looking for the files. Can you anyone shed some light where these files may be on the D

  • Can i watch music videos in ipod nano...?

    it says in the menu "music videos", that means you can watch, right? O.O