2d graphics in JLayeredPanes

Hi!
I am new to Swing. Hope you guys can help me out.
I'm currently working on a JApplet that contains a JLayeredPane. I want to draw some 2d graphics (lines, dots, rectangles,...) on the DEFAULT_LAYER or FRAME_LAYER of the JApplet and then add another JLayeredPane (on a top layer) where I can do some "dragging and dropping" of lines and JLabels. I would like the background to show. The problem is I don't know how I can make the 2d graphics and the JComponents co-exist.
I already can draw some 2d graphics by the paint method but it hides/erases the JLabels. I don't know how to draw 2d graphics on the layeredpane and at the same time put some JComponents. And, how do I indicate the layer where 2d graphics will be drawn.
Thanks

unsure of what you mean...there is a paint method for applications, and it similar to the one you have been using for applets. this, for example, would draw a rectangle for you:
public void paint(Graphics g){
g.draw3DRect(50, 50, 100, 100, true);
if your problem is with flickers, I would suggest searching this forum for such a topic. i`ve seen it answered many times before

Similar Messages

  • How to erase 2D graphics in the JLayeredPane?

    How can I erase 2D graphics(lines) in the JLayeredPane?Is there a example?
    Please help me,thanks in advance.

    I am anxious to know how to put 2D graphics in 3D TransformGroup, because
    I want to pick 2D graphics in 3D scene. For example, I drew some 2D graphics
    in 3D scene, line, sphere, rect, I may pick one using mouse. As we know, we can
    use PickMouseBehavior to pick 3D Graphics, How can I to 2D Graphics? Thanks a lot!

  • How to put graphics into a JViewport?

    Hi,
    I'm trying to make a simple game, where a block can move around in a 30x30 grid with collision detection. So far, it works alright, but I want the window to hold only 10x10 and for the block that is moving to stay at the center while the painted background moves around. The program reads a .dat file to get the world.
    So is there a way to use the background world Ive painted and put it into a viewport so that it will scroll when the keys are hit to move? Also I'd like to make the block stay at the center of the screen, unless it's at a corner.
    Hopefully this makes sense and someone can help. Thanks.
    Here's my code:
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.io.*;
    public class SmallWorld extends JPanel
                              implements KeyListener,
                                         ActionListener {
         //WORLD
         String[][] worldArray = new String[30][30];
         private static Color redBlock = new Color(255,0,0,255);
         private static Color whiteBlock = new Color(255,255,255,150);
         private static Color blackBlock = new Color(0,0,0,150);
         boolean keyUP = false;
         boolean keyDOWN = false;
         boolean keyLEFT = false;
         boolean keyRIGHT = false;
         //Starting coordinates
         int blockPositionX = 1;
         int blockPositionY = 1;
         JTextField typingArea;
         JViewport viewable;
        public SmallWorld() {
            super( );
              createWorld();     
            typingArea = new JTextField(20);
            typingArea.addKeyListener(this);
              typingArea.setEditable( false );
              add(typingArea);
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              String type = "";
              for (int i = 0; i < 30; i++) {
                   for (int j = 0; j < 30; j++) {
                        type = worldArray[i][j];
                             if ( type.equals("1") )
                                  g.setColor(redBlock);
                                  g.fillRect( (j * 50),(i * 50),50,50 );
                             else {
                                  g.setColor(whiteBlock);
                                  g.fillRect( (j * 50),(i * 50),50,50 );          
              g.setColor(blackBlock);
              g.fillRect( (blockPositionX * 50),(blockPositionY * 50),50,50 );     
         //Get the world from the DAT file and translate it into a 2d array to be used by paintComponent
         public void createWorld() {
            String getData = null;
              int countRow = 0;
            try {
                   FileReader fr = new FileReader("world.dat");
                   BufferedReader br = new BufferedReader(fr);
                   getData = new String();
                   while ((getData = br.readLine()) != null) {
                  if(countRow < 30) {
                        for (int i = 0; i < 30; i++) {
                             String temp = "" + getData.charAt(i);
                             worldArray[countRow] = temp;
                        countRow++;
    } catch (IOException e) {
    // catch possible io errors from readLine()
    System.out.println("Uh oh, got an IOException error!");
    e.printStackTrace();
         //Move Block around the world
         public void moveBlock() {
              Graphics g = this.getGraphics();
              Point pt = new Point();
              pt.x = blockPositionX * 50;
              pt.y = blockPositionY * 50;
              if (keyUP) {
                   g.setColor(blackBlock);
              g.fillRect( (blockPositionX * 50),(blockPositionY * 50),50,50 );
              if (keyDOWN) {
                   g.setColor(blackBlock);
              g.fillRect( (blockPositionX * 50),(blockPositionY * 50),50,50 );
              if (keyLEFT) {
                   g.setColor(blackBlock);
              g.fillRect( (blockPositionX * 50),(blockPositionY * 50),50,50 );
              if (keyRIGHT) {
                   g.setColor(blackBlock);
              g.fillRect( (blockPositionX * 50),(blockPositionY * 50),50,50 );
         //check for collisions with blocks
         public boolean checkCollision(int row, int col) {
              if ( worldArray[col][row].equals("1") ) {
                   return true;
              else {
                   return false;
    //If key typed, put action here. none for now
    public void keyTyped(KeyEvent e) {
    /** Handle the key pressed event from the text field. */
    public void keyPressed(KeyEvent e) {
    updateView( e );
    //If key released, put action here. none for now
    public void keyReleased(KeyEvent e) {
    /** Handle the button click. */
    public void actionPerformed(ActionEvent e) {
         //Update the view of the window based on which button is pressed
         protected void updateView( KeyEvent e ) {
              //if UP is pressed
              if ( e.getKeyCode() == 38 ) {
                   keyUP = true;
                   if ( checkCollision( blockPositionX, blockPositionY - 1 ) == false ) {
                        blockPositionY = blockPositionY - 1;
                        this.repaint();
                        moveBlock();
                   keyUP = false;
              //if DOWN is pressed
              if ( e.getKeyCode() == 40 ) {
                   keyDOWN = true;
                   if ( checkCollision( blockPositionX, blockPositionY + 1 ) == false ) {
                        blockPositionY = blockPositionY + 1;
                        this.repaint();
                        moveBlock();
                   keyDOWN = false;
              //if LEFT is pressed
              if ( e.getKeyCode() == 37 ) {
                   keyLEFT = true;
                   if ( checkCollision( blockPositionX - 1, blockPositionY ) == false ) {
                        blockPositionX = blockPositionX - 1;
                        this.repaint();
                        moveBlock();
                   keyLEFT = false;
              //if RIGHT is pressed
              if ( e.getKeyCode() == 39 ) {
                   keyRIGHT = true;
                   if ( checkCollision( blockPositionX + 1, blockPositionY ) == false ) {
                        blockPositionX = blockPositionX + 1;
                        this.repaint();
                        moveBlock();
                   keyRIGHT = false;
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("SmallWorld");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new SmallWorld();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
         frame.setSize(500,520);
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    The world DAT file:
    111111111111111111111111111111
    100010001010001000101000100011
    100010001010001000101000100011
    100011101010000000001000000001
    100010000010000000001000000001
    100110000010000000001000000001
    100000000010000000001000000001
    111100011110000000001000000001
    100000000110001110111000111011
    100000000000001110111000111011
    100000000000000000001000000001
    100010001110000000000000000001
    100010001110001110111000111011
    100011101100000000000000000011
    100010000110001110111000111011
    100110000100000000000000000011
    100000000110000000001000000001
    111100011100000000000000000011
    100000000100000000000000000011
    100000000010000000000000000001
    100000000010000000000000000001
    100010000000000000000000000001
    100010000000001110111000111011
    100011101110000000011000000001
    100010000110000000011000000001
    100110000110000000001000000001
    100000000110001110111000111011
    111100011110000000011000000001
    100000000110000000011000000001
    100000000011111111111111111111

    I know this is an old posting, but I just saw another question similiar to this and I still have my old code lying around that incorporates most of the suggestions made in this posting. So I thought I'd post my code here in case anybody wants to copy/paste the code. You will still need to use the DAT file provide above as well as provide icons to represent the floor and wall.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class SmallWorld extends JPanel implements KeyListener, ActionListener
         //WORLD
         String[][] worldArray = new String[30][30];
         //Block colors
         private static Color redBlock = new Color(255,0,0,255);
         private static Color whiteBlock = new Color(255,255,255,255);
         private static Color blackBlock = new Color(0,0,0,150);
         //World images
    //     JLabel wall = new JLabel( new ImageIcon("wall.gif") );
    //     JLabel floor = new JLabel( new ImageIcon("floor.gif") );
         ImageIcon wallIcon = new ImageIcon("dukewavered.gif");
         ImageIcon floorIcon = new ImageIcon("copy16.gif");
         //Starting coordinates
         int blockPositionX = 1;
         int blockPositionY = 1;
         //Typing area to capture keyEvent
         JTextField typingArea;
         //Viewable area
         JViewport viewable;
         String type = "";
         JLayeredPane layeredPane;
         JPanel worldBack;
         JPanel panel;
         JPanel player;
         Dimension worldSize = new Dimension(1500, 1500);
         public SmallWorld() {
              super( );
              createWorld();
              layeredPane = new JLayeredPane();
              add(layeredPane);
              layeredPane.setPreferredSize( worldSize );
              worldBack = new JPanel();
              layeredPane.add(worldBack, JLayeredPane.DEFAULT_LAYER);
              worldBack.setLayout( new GridLayout(30, 30) );
              worldBack.setPreferredSize( worldSize );
              worldBack.setBounds(0, 0, worldSize.width, worldSize.height);
              worldBack.setBackground( whiteBlock );
              for (int i = 0; i < 30; i++) {
                   for (int j = 0; j < 30; j++) {
                        JPanel square = new JPanel( new BorderLayout() );
                        worldBack.add( square );
                        type = worldArray[i][j];
                        if ( type.equals("1") )
                             square.add( new JLabel(wallIcon) );
                        else
                             square.add( new JLabel(floorIcon) );
              //Draw the player
              player = new JPanel();
              player.setBounds(50, 50, 50, 50);
              player.setBackground( Color.black );
              player.setLocation(50, 50);
              layeredPane.add(player, JLayeredPane.DRAG_LAYER);
              //set where the player starts
    //          panel = (JPanel)worldBack.getComponent( 31 );
    //          panel.add( player );
              //Create the typing area with keyListener, add to window
              typingArea = new JTextField(20);
              typingArea.addKeyListener(this);
              typingArea.setEditable( false );
              add(typingArea);
         //Get the world from the DAT file and translate it into
         //a 2d array to be used by paintComponent
         public void createWorld() {
              String getData = null;
              int countRow = 0;
              try {
                   //Get file
                   FileReader fr = new FileReader("world.dat");
                   BufferedReader br = new BufferedReader(fr);
                   getData = new String();
                   //read each line from file, store to 2d array
                   while ((getData = br.readLine()) != null) {
                        if(countRow < 30) {
                             for (int i = 0; i < 30; i++) {
                                  String temp = "" + getData.charAt(i);
                                  worldArray[countRow] = temp;
                        countRow++;
              } catch (IOException e) {
              System.out.println("Uh oh, got an IOException error!");
              e.printStackTrace();
         //Move Block around the world
         public void moveBlock() {
              Point pt = new Point();
              pt.x = blockPositionX * 50;
              pt.y = blockPositionY * 50;
              int x = Math.max(0, pt.x - 250);
              int y = Math.max(0, pt.y - 250);
              Rectangle r = new Rectangle(x, y, 550, 550);
              scrollRectToVisible( r );
         //check for collisions with blocks
         public boolean checkCollision(int row, int col) {
              if ( worldArray[col][row].equals("1") ) {
                   return true;
              else {
                   return false;
         public void keyTyped(KeyEvent e) {
         public void keyPressed(KeyEvent e) {
              updateView( e );
              e.consume();
         public void keyReleased(KeyEvent e) {
         public void actionPerformed(ActionEvent e) {
         //Update the view of the window based on which button is pressed
         protected void updateView( KeyEvent e ) {
              //if UP
              if ( e.getKeyCode() == 38 ) {
                   if ( checkCollision( blockPositionX, blockPositionY - 1 ) == false ) {
                        blockPositionY = blockPositionY - 1;
                        moveBlock();
                        player.setLocation(blockPositionX *50, blockPositionY*50);
              //if DOWN
              if ( e.getKeyCode() == 40 ) {
                   if ( checkCollision( blockPositionX, blockPositionY + 1 ) == false ) {
                        blockPositionY = blockPositionY + 1;
                        moveBlock();
                        player.setLocation(blockPositionX *50, blockPositionY*50);
              //if LEFT
              if ( e.getKeyCode() == 37 ) {
                   if ( checkCollision( blockPositionX - 1, blockPositionY ) == false ) {
                        blockPositionX = blockPositionX - 1;
                        moveBlock();
                        player.setLocation(blockPositionX *50, blockPositionY*50);
              //if RIGHT
              if ( e.getKeyCode() == 39 ) {
                   if ( checkCollision( blockPositionX + 1, blockPositionY ) == false ) {
                        blockPositionX = blockPositionX + 1;
                        moveBlock();
                        player.setLocation(blockPositionX *50, blockPositionY*50);
         private static void createAndShowGUI() {
              JFrame frame = new JFrame("SmallWorld");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JComponent newContentPane = new SmallWorld();
              newContentPane.setPreferredSize( new Dimension(1500, 1500) );
              JScrollPane scrollPane = new JScrollPane( newContentPane );
              scrollPane.setPreferredSize( new Dimension(568, 568) );
              frame.getContentPane().add( scrollPane );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setResizable( false );
              //frame.setSize(500,520);
              frame.setVisible( true );
         public static void main(String[] args) {
              javax.swing.SwingUtilities.invokeLater( new Runnable() {
                   public void run() {
                        createAndShowGUI();

  • Create an image of a JLayeredPane 's content

    hi there,
    we have a problem here: we'd like to create one image out of a JLayeredPane`s content. but the only thing we get is a gray box which size is the size of the JLayeredPane.
    the purpose is: we're developing a graphic tool where you can draw and arrange objects in the JLayeredPane(which is in a JScrollPane). and now we're implementing the print-function which allows to print the graphs over several pages, therefore it is neccessary to have an image(*.jpeg) for our printpreview-window. the preview-window and the printfuntion are nearly implemented and the only problem is that we cant make an image of the JLayerdPane's content.
    maybe you have an idea or codesamples...
    thanks a lot in advance!!
    george

    1. Getting any JComponent to render onto a buffered image isn't a problem -- just call paint, passing it a graphics object backed by that buffered image.
    2. Writing an image to a file isn't a problem: use javax.imageio.ImageIO.
    Some code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Ex {
        public static void main(String[] args) {
            JFrame f = new JFrame("Ex");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            final JLayeredPane pane = new JLayeredPane();
            Border b = BorderFactory.createEtchedBorder();
            pane.add(createLabel("DEFAULT_LAYER", b, 00, 10), JLayeredPane.DEFAULT_LAYER);
            pane.add(createLabel("PALETTE_LAYER", b, 40, 20), JLayeredPane.PALETTE_LAYER);
            pane.add(createLabel("MODAL_LAYER", b, 80, 30), JLayeredPane.MODAL_LAYER);
            pane.add(createLabel("POPUP_LAYER", b, 120, 40), JLayeredPane.POPUP_LAYER);
            pane.add(createLabel("DRAG_LAYER", b, 160, 50), JLayeredPane.DRAG_LAYER);
            f.getContentPane().add(pane);
            JPanel south = new JPanel();
            JButton btn = new JButton("save");
            btn.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent evt) {
                    save(pane);
            south.add(btn);
            f.getContentPane().add(south, BorderLayout.SOUTH);
            f.setSize(400,300);
            f.show();
        static JLabel createLabel(String text, Border b, int x, int y) {
            JLabel label = new JLabel(text);
            label.setOpaque(true);
            label.setBackground(Color.WHITE);
            label.setBorder(b);
            label.setBounds(x,y, 100,20);
            return label;
        static void save(JComponent comp) {
            int w = comp.getWidth(), h = comp.getHeight();
            BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            g2.setPaint(Color.MAGENTA);
            g2.fillRect(0,0,w,h);
            comp.paint(g2);
            g2.dispose();
            try {
                ImageIO.write(image, "jpeg", new File("image.jpeg"));
            } catch(IOException e) {
                e.printStackTrace();
    }Why does the saved image have a magenta background? JLayerPane, by default, is non-opaque. You can set it to be opaque and choose its background color, as you like.

  • Resizing Components in a JLayeredPane

    Hello,
    I'm brand new to Java (formerly a VB man). I'm creating an application where icons are displayed on a background image and can be dragged around the window. The background image and the icons need to resize with the window.
    I've managed to get the back ground image to resize but can't work out how to get the icon images to resize as well. I also need to keep their relative positions as well.
    I have three classes which extend JFrame, JLayeredPane and JPanel to construct the display. I have attached them below.
    If anyone can help or at least point me in the right direction I would be very grateful indeed.
    Best regards
    Simon
    package imagelayers;
    import java.awt.*;
    import java.awt.color.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SecondFrame extends JFrame
    private JLayeredPane m_layeredPane;
    private MovingImage m_movImage1, m_movImage2, m_movImage3;
    private BackgroundImage m_background;
    public SecondFrame() {
    super("Moving Images");
    setLocation(10,10);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Load the background image in a JPanel
    ImageIcon kcIcon = new ImageIcon("images/kclogo.gif");
    m_background = new BackgroundImage(kcIcon);
    setSize(kcIcon.getIconWidth(), kcIcon.getIconHeight());
    m_movImage1 = new MovingImage("images/dukewavered.gif", 0);
    m_movImage2 = new MovingImage("images/dukewavegreen.gif", 1);
    m_movImage3 = new MovingImage("images/dukewaveblue.gif", 2);
    m_background.add(m_movImage1 , JLayeredPane.DRAG_LAYER);
    m_background.add(m_movImage2 , JLayeredPane.DRAG_LAYER);
    m_background.add(m_movImage3 , JLayeredPane.DRAG_LAYER);
    m_movImage2.topLayer = 2;
    Container contentPane = getContentPane();
    contentPane.add(m_background);
    setVisible(true);
    public static void main(String[] arguments)
    JFrame frameTwo = new SecondFrame();
    package imagelayers;
    import java.awt.*;
    import javax.swing.*;
    public class BackgroundImage extends JLayeredPane
    private Image m_backgroundImage;
    public BackgroundImage(ImageIcon bg)
    m_backgroundImage = bg.getImage();
    setBorder(BorderFactory.createTitledBorder(""));
    public void paintComponent(Graphics g)
    g.drawImage(m_backgroundImage,0,0,getWidth(),getHeight(),this);
    package imagelayers;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    import javax.swing.JLayeredPane;
    import java.awt.*;
    import java.awt.event.*;
    public class MovingImage extends JLabel implements MouseListener, MouseMotionListener
    private Image m_theImage;
    private ImageIcon m_theImageIcon;
    private int nStartX, nStartY;
    static int topLayer;
    public MovingImage(String imgLocation, int layerNum)
    addMouseListener(this);
    addMouseMotionListener(this);
    m_theImageIcon = new ImageIcon(imgLocation);
    m_theImage = m_theImageIcon.getImage();
    setBounds(0, 0, m_theImageIcon.getIconWidth(), m_theImageIcon.getIconHeight());
    public void paintComponent(Graphics g)
    g.drawImage(m_theImage,0,0,getWidth(),getHeight(),this);
    public void mousePressed(MouseEvent e)
    JLayeredPane imagesPane = (JLayeredPane)getParent();
    imagesPane.setLayer(this,topLayer,0);
    nStartX = e.getX();
    nStartY = e.getY();
    public void mouseMoved(MouseEvent e){}
    public void mouseClicked(MouseEvent e){}
    public void mouseExited(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseReleased(MouseEvent e){}
    public void mouseDragged(MouseEvent e)
    setLocation(getX() + e.getX() - nStartX, getY() + e.getY() - nStartY);
    }

    Try useing the JFrames show() method or setVisible(true) method after you have added all the other components.
    If that doesnt work use the JFrames validate() method, inherited from Container, after one of the previous methods.
    Hope this helps

  • Graphics help please...

    I am trying to use a rubberband rectangle in my app. everything works great except I can't get the rectangle to dissapear when the mouse button is released. Code is posted below - any help appreciated, thanks.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Rubber extends JLayeredPane implements MouseListener, MouseMotionListener {
          private int mouseX, mouseY; 
          private int prevX, prevY;    
          private int startX, startY;  
    public Rubber() {            
           addMouseListener(this);
           addMouseMotionListener(this);
    private void drawRect(Graphics g, int x1, int y1, int x2, int y2) {          
            int x, y;
            int w, h; 
            if (x1 >= x2) { 
                x = x2;
                w = x1 - x2;
            else {        
                  x = x1;
                  w = x2 - x1;
            if (y1 >= y2) { 
                y = y2;
                h = y1 - y2;
            else {       
                  y = y1;
                  h = y2 - y1;
            g.drawRect(x, y, w, h);   
    private void repaintRect(int x1, int y1, int x2, int y2) {          
            int x, y; 
            int w, h; 
            if (x2 >= x1) {
                x = x1;
                w = x2 - x1;
            else {       
                  x = x2;
                  w = x1 - x2;
            if (y2 >= y1) {
                y = y1;
                h = y2 - y1;
            else {        
                  y = y2;
                  h = y1 - y2;
            repaint(x,y,w+1,h+1);       
    public void paintComponent(Graphics g) {  
           g.setColor(Color.black);
           drawRect(g,startX,startY,mouseX,mouseY);
    public void mousePressed(MouseEvent evt) {    
           prevX = startX = evt.getX();
           prevY = startY = evt.getY();      
    public void mouseReleased(MouseEvent evt) {
           mouseX = evt.getX();
           mouseY = evt.getY();
           repaint();
    public void mouseDragged(MouseEvent evt) {
           mouseX = evt.getX();  
           mouseY = evt.getY();  
           repaintRect(startX,startY,prevX,prevY);
           repaintRect(startX,startY,mouseX,mouseY);
           prevX = mouseX;
           prevY = mouseY;
    public void mouseEntered(MouseEvent evt) { }
    public void mouseExited(MouseEvent evt) { }  
    public void mouseClicked(MouseEvent evt) { }
    public void mouseMoved(MouseEvent evt) { }  

    Try this;-
    public void mouseReleased(MouseEvent evt) {
    mouseX = evt.getX();
    mouseY = evt.getY();
    dontDraw=true;
    repaint();
    if(!dontDraw)g.drawRect(x, y, w, h);

  • Avoid repaint in JLayeredPane components

    I have a program including a JLayeredPane that contains a JComponent and a JPanel. Both components are set on different layers of the JLayeredPane.
    I use the JPanel for painting, so I want to avoid unnecessary repaints if I can. The problem is that when I resize the JComponent using setBounds(), the JLayeredPane performs a repaint, and consequently, the JPanel too.
    How can I avoid the repaint propagation through all the JLayeredPane? I tried to use setIgnoreRepaint(true), but it didn't seem to work.
    If you need to see some code, just ask. Thanks in advanced. :)

    Sorry for not sending my SSCCE before; there was mealtime here. Thanks for your code anyway, I'll have a look now to see if I get any idea.
    This is my code. What I'd like to avoid it's to display the setence "inner painted" (it means that the paintComponent() method of the innerPanel has been triggered):
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import javax.swing.BoxLayout;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLayeredPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.event.MouseInputListener;
    public class SelectionFrame implements MouseInputListener {
        private final static int CURSOR_WIDTH = 2;
        private final static int ALPHA_SELECTION_INT = 20;
        private JFrame frame;
        private JScrollPane scrollPane;
        private JPanel innerPanel;
        private JPanel outerPanel;
        private JComponent transComponent;
        private JLayeredPane layeredPane;
        private boolean cursorEnabled;
        private boolean selectionEnabled;
        private Color bgColor;
        public SelectionFrame() {
            cursorEnabled = true;
            selectionEnabled = true;
            frame = new JFrame();
            frame.setTitle("Adilo Selection");
            frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),
                    BoxLayout.X_AXIS));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setMinimumSize(new Dimension(400, 300));
            bgColor = Color.CYAN;
            innerPanel = new JPanel()  {
                @Override
                protected void paintComponent(Graphics g)   {
                    System.out.println("inner painted");
            innerPanel.setBackground(bgColor);
            outerPanel = new JPanel();
            outerPanel.setBackground(Color.BLUE);
            outerPanel.setBounds(0, frame.getHeight() / 3, frame.getWidth(), frame.getHeight() / 3);
            transComponent = new JComponent()
                @Override
                public void paintComponent(Graphics g)
                    Color selectionColor = new Color(255 - bgColor.getRed(),
                            255 - bgColor.getGreen(),
                            255 - bgColor.getBlue(),
                            ALPHA_SELECTION_INT);
                    g.setColor(selectionColor);
                    g.fillRect(0, 0, getSize().width, getSize().height);
            layeredPane = new JLayeredPane();
            layeredPane.add(innerPanel, new Integer(1));
            layeredPane.add(outerPanel, new Integer(2));
            layeredPane.add(transComponent, new Integer(3));
            scrollPane = new JScrollPane();
            scrollPane.setViewportView(layeredPane);
            innerPanel.setBounds(0, 0, frame.getWidth(), frame.getHeight());
            innerPanel.addMouseListener(this);
            innerPanel.addMouseMotionListener(this);
            frame.add(scrollPane, BorderLayout.CENTER);
            frame.pack();
            frame.setVisible(true);
        private int initXPos;
        public void mousePressed(MouseEvent e) {
            initXPos = e.getX();
            if(cursorEnabled)    {
                transComponent.setBounds(e.getX(), 0, CURSOR_WIDTH, frame.getHeight());
        public void mouseReleased(MouseEvent e) {
        public void mouseEntered(MouseEvent e) {
        public void mouseExited(MouseEvent e) {
        public void mouseDragged(MouseEvent e) {
            int xPos = e.getX();
            if(selectionEnabled)    {
                if(xPos > initXPos) {
                    transComponent.setBounds(initXPos, 0, xPos - initXPos, frame.getHeight());
                else    {
                    transComponent.setBounds(xPos, 0, initXPos - xPos, frame.getHeight());
        public void mouseMoved(MouseEvent e) {
        public void mouseClicked(MouseEvent e) {
        public static void main(String[] args) {
            new SelectionFrame();
    }

  • Layout management in a JLayeredPane

    hi All,
    I'm working with a JLayeredPane, and having trouble with controlling the layout. It seems that JLayeredPane is designed for its sub-components to have explicitly set sizes and locations. What I want is to have two layers - one panel on the bottom that takes up all the displayable area (re-sizing to fit the window when necessary), and another transparent one on top that does the same. Does anyone know a way to do this?
    Thanks!

    and one of the components is a JLabel that I want to be semi-translucent to the bottom layer. I did this by calling setBackground with a Color that has an alpha valueThe problem is how Swing handles opaque components.
    If you make the child component non-opaque then Swing searches for the parent component and paints it first (so the background is painted) before the child component is painted. Therefore there is no need for the childs background to be painted and you get transparency.
    If the child component is opaque then Swing doesn't need to find the parent component to paint it, since the childs background will just paint over top of it anyway. So when you use an alpha value the parent isn't repainted and garbage may be left behind.
    So you need to keep you label non-opaque and then override the paintComponent() method of the label with code something like the following to force the child to paint its background:
    protected void paintComponent(Graphics g)
         g.setColor( getBackground() );
         g.fillRect(0, 0, getSize().width, getSize().height);
         super.paintComponent(g);
    }Edited by: camickr on May 7, 2008 11:48 PM
    By the way you really should have started a new posting since the second question is unrelated to the first. Also, since you marked the question as answered most people won't bother to read the question again.

  • Problems with JLayeredPane

    I have the attached program that is supposed to show a red background that has a transparent green rectangle on top. The rectangle is created via a mouse drag. Running the program just gives a gray window with nothing happening when I drag the mouse. What is wrong?
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import static java.lang.Math.*;
    public class TestLayers extends JFrame{
         public JLayeredPane layeredPane;
         public Background background;
         public JPanel board;
         public Overlay overlay;
         public Point mPress, mRelease;
         public int left = 0, top = 0, width = 0, height= 0;
              MouseListener ml = new MouseAdapter() {
                   public void mousePressed(MouseEvent e) {
                             mPress = e.getPoint();
                   public void mouseReleased(MouseEvent e) {
                             mRelease = e.getPoint();
                             width = abs(mPress.x - mRelease.x);
                             height = abs(mPress.y - mRelease.y);
                             if (mPress.y < mRelease.y) top = mPress.y;
                             else top = mRelease.y;
                             if (mPress.x < mRelease.x) left = mPress.x;
                             else left = mRelease.x;
                             overlay.repaint();
         public TestLayers() {
              Dimension sz = new Dimension(500,500);
              layeredPane = new JLayeredPane();
              layeredPane.setPreferredSize( sz );
              getContentPane().add(layeredPane, BorderLayout.CENTER);
              layeredPane.setOpaque(true);
              background = new Background();
              layeredPane.add(background, JLayeredPane.DEFAULT_LAYER);
              overlay = new Overlay();
              layeredPane.add(overlay, JLayeredPane.PALETTE_LAYER);
              layeredPane.addMouseListener(ml);
              layeredPane.setVisible(true);
    public static void main (String args[]) {
    JFrame frame = new TestLayers();
              frame.setDefaultCloseOperation( DISPOSE_ON_CLOSE );
    frame.pack();
    frame.setResizable( false );
    frame.setLocationRelativeTo( null );
    frame.setVisible(true);
         public class Background extends JPanel {
              public Background() {
              public void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   g.setColor(Color.red);
                   g.fillRect(0,0,500,500);
         public class Overlay extends JPanel {
              public Overlay() {
              public void paintComponent(Graphics g) {
                   Color myColor = new Color(0, 255, 0, 120);
                   g.fillRect(left, top, width, height);
    }

    I made the changes you suggested, still a gay frame.
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import static java.lang.Math.*;
    public class TestLayers extends JFrame{
         public  JLayeredPane layeredPane;
         public Background background;
         public JPanel board;
         public Overlay overlay;
         public Point mPress, mRelease;
         public int left = 0, top = 0, width = 0, height= 0;
              MouseListener ml = new MouseAdapter() {
                   public void mousePressed(MouseEvent e) {
                             mPress = e.getPoint();
                   public void mouseReleased(MouseEvent e) {
                             mRelease = e.getPoint();
                             width = abs(mPress.x - mRelease.x);
                             height = abs(mPress.y - mRelease.y);
                             if (mPress.y < mRelease.y) top = mPress.y;
                             else top = mRelease.y;
                             if (mPress.x < mRelease.x) left = mPress.x;
                             else left = mRelease.x;
                             overlay.repaint();
         public TestLayers() {
              Dimension sz = new Dimension(500,500);
              layeredPane = new JLayeredPane();
              layeredPane.setPreferredSize( sz );
              getContentPane().add(layeredPane, BorderLayout.CENTER);
              layeredPane.setOpaque(true);
              background = new Background();
              background.setPreferredSize( sz );
              layeredPane.add(background, JLayeredPane.DEFAULT_LAYER);
              overlay = new Overlay();
              layeredPane.add(overlay, JLayeredPane.PALETTE_LAYER);
              layeredPane.addMouseListener(ml);
              layeredPane.setVisible(true);
        public static void main (String args[]) {
            JFrame frame = new TestLayers();
              frame.setDefaultCloseOperation( DISPOSE_ON_CLOSE );
            frame.pack();
            frame.setResizable( false );
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
         public class Background extends JPanel {
              public Background() {
              public void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   g.setColor(Color.red);
                   g.fillRect(0,0,500,500);
         public class Overlay extends JPanel {
              public Overlay() {
              public void paintComponent(Graphics g) {
                   Color myColor = new Color(0, 255, 0, 120);
                   g.setColor(myColor);
                   g.fillRect(left, top, width, height);
    }

  • Moving JPanel in JLayeredPane

    Hello!
    I'm tryiing to make information board which retrieve data from DB and shows the data graphically at the applet.
    Thus, I made some indicators,which extends JPanel, and put them on JLayeredPane. the data also have position information and if the position is changed and a position of indicator should be changed.
    However, I couldn't make it move at the layeredPane.
    I used setBounds, setLocation, repaint, revalidate with all possible cases, but failed too. :-(
    Here is my code...
    any comments or help would be appreciated.
    <code>
    import javax.swing.*;
    import org.jdom.Element;
    import java.awt.*;
    import java.util.List;
    import java.util.Vector;
    public class CenterPanel2 extends JPanel{
         private JLayeredPane layeredPane;
         private JPanel backImage;
         //width and height of background image panel(backImage)
         private int width, height;
         private Vector indicators;
         public CenterPanel2(List parts){
              //Create and set the layeredPane property
              this.layeredPane = new JLayeredPane();
              this.layeredPane.setOpaque(false);
              this.setBackground( Color.lightGray );
    //draw the background image
              backImage = new PanelBackImage();
              width = (int)backImage.getPreferredSize().getWidth();
              height = (int)backImage.getPreferredSize().getHeight();
    //set layeredPane and add image
    this.layeredPane.setPreferredSize ( new Dimension( width+20, height+20) );
    //bottommost layer
    this.layeredPane.add(backImage, JLayeredPane.DEFAULT_LAYER);
    backImage.setBounds(0, 0, width, height);
    //make vector to store indicators
    indicators = new Vector();
         for (int i = 0; i < parts.size(); i++) {
              Element epart = (Element)parts.get(i);
              PART part = new PART(epart);
              String type = part.getType();
              int x = part.getPositionX();
              int y = part.getPositionY();
              int id = part.getId();
              if( type.equals("A")){
                   Indicator a = new AType(x,y);
                   a.setID(id);
                   indicators.addElement(a);
              else if( type.equals("B")){
                   Indicator b = new BType(x,y);
                   b.setID(id);
                   indicators.addElement(b);
              else {}//do dothing
         }//for
         //add to layeredPane
              for(int i = 0; i<indicators.size();i++){
                   JPanel tmp = (JPanel) indicators.get(i);
                   //add to the second mostbottom layer
                   tmp.setBounds(tmp.getX(), tmp.getY(), 100, 100);
                   this.layeredPane.add(tmp, JLayeredPane.PALETTE_LAYER);
    //finally add layeredpane to this
    this.add(layeredPane);
         }//CenterPanel()
    ///this is called my JApplet update()
         public void updatePanel(List parts){
              System.out.println("centerpanel2: updatePanel has been called!");
              for(int i=0; i<parts.size();i++){
                   Element epart = (Element)parts.get(i);
                   PART part = new PART(epart);
                   int id = part.getId();
                   int x = part.getPositionX();
                   int y = part.getPositionY();
                   Rectangle tmpRec = new Rectangle(x, y, 100, 100);
                   for(int j=0;j<indicators.size();j++){
                        Indicator tmp = (Indicator)indicators.get(j);
                        JPanel jtmp = (JPanel) tmp;
                        //if ID is same and position was changed move panel
                        if(id == tmp.getID() && !tmpRec.equals(jtmp.getBounds())){
                             jtmp.setBounds(x,y,100,100);
                   }//inner for
              }//out for
         }//update
    }//end of centerPanle class
    </code>

    what you could do is create a sligtly smaller Panel that held a JLabel that was really small and the pull down meny and then add that as one alowing you to move stuff by grabing the JLabel which dosn't even have to have text.

  • Graphics g question.

    Is it possible to get Graphics g to draw an Image on a JLayeredPane?
    g.drawImage( background, 0, 20, screenW, screenH, layeredPane );
    or should I jump out the window?
    Jim

    A little humor on a thursday.
    Actualy there are no components at that layer(0), I got it to paint the image somewhat. Needs some fine tuning. One thing that is strange, I have an innerclass buttonPanel that extends JPanel, it's set to opaque(false) so only the buttons show, but when the layeredPane is displayed the buttonPanel is no longer transparent. The buttonPanel is added before the layeredPane is painted.
    windows are boarded up now, I feel safer.
    Jim

  • Graphics.copyArea() and transparent pixels

    Hi,
    I have a problem with a JLayeredPane.
    I have to paint a scrolling sampled signal on top of a grid. To do this I used a JLayeredPane where on the bottom layer there's a panel (let's call it GridPane) with the grid, and then some layers up I put another JPanel with setOpaque(false) that paints the signal (PaintPane). This way I have to paint the grid only one time, or so I thought.
    Now when I try to scroll the signal I use the copyArea() function to scroll one pixel to the left then paint the next line of the trace.
    The problem is that the copyArea() function ignores the transparent pixels and copies the grid that is behind them even when I'm using the PaintPane Graphics. This way is like i'm shifting the grid but I want it to be fixed.
    So do all the components in the JLayeredPane share the same graphics? that would explain the behaviour of the copyArea() func.
    Is there a way to tell the copyArea() func to copy also the transparent pixels, ignoring what stands behind them?
    Thank you.

    Nothing.
    Apparently there's no way to just repaint that portion of graphics without repainting everything.
    I now understand more on how transparent pixels are treated.
    So, when I overwrite one of the pixels in the background in a way or another I have lost it forever. and it's my function that has to take care of repainting it.(usually repainting everything).
    I hoped to improve performance with this method but, well, have to turn back on the old one.
    Thanks again.

  • Layering Graphics

    Post Author: gyetton
    CA Forum: .NET
    Using VS2005 & CR XI R2
    I have a graphic with square edges, that I want to round off, So I thought it would be easy to overlay it with a rounded box, But I can't seem to get this box on top of the graphic, I can get some text on top but I can't give that a rounded boarder. (This sort of layering is easy in MS Word, I will be surprised if I can't do it in a tool designed to produce nice reports).
    Have I missed something or am I going to have to get my graphic changed?
    TIA

    Hey b12s,
    This might be a long time since you posted, but can you past a snippet of what you did to overcome the problem? I am facing a similar problem where I have a JLayeredPane to which I want to add a JTree component.I also want to draw background rectangles behind the tree's nodes, so I over-ride the paint(Graphics) method of JLayeredPane and use g.fillRect(...) to draw them. The JLayeredPane instance is then added to a JScrollPane, which in turn is added to JSplitPane. The result is that I only see the background rectangles and not the tree. any ideas how to show both the background rectangles and the tree?
    Thanks.

  • Printing in JLayeredPane

    Okay I have a JLayeredPane which I want to print. There are two layers to it which each has a panel on it. The panels have some 2D graphics and components on it which I want to print out.
    When I print, all I get is a blank piece of paper, obviously cause the stuff I want printed isn't being rendered. Should the print method in the JLayeredPane automatically include the graphics from all its layers, or do I have to do something manually to include the two layers that I want rendered and printed?

    Maybe the getGraphics just works for the DefaultPane, so if that's the case, how do I add the graphics from each layer to the Graphics object in the print method?

  • Help adding to JLayeredPane

    basically I need to create a panel with a background, then use JLayeredPane to put 2 other panel on top of each other over the background. The problem is that each panel will display properly by with the background but not all 3 together.
    /* main gui class for the four score game.*/
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class GuiMain extends JFrame
         //declare variables
         private JButton quit = new JButton("Quit");
         private JButton restart = new JButton("Restart");
         //panels
         private BoardPanel myBoard = new BoardPanel();
         private JPanel South = new JPanel();
         //embedded main class used for testing
         public static void main(String[] args)
              new GuiMain();
         /*no arg constructor which zeroes the bead array, creates a new window using the boxlayout manager,
          * creates the board, and adds the quit/restart buttons
         public GuiMain()
              super("Four Score");
              this.addComponentListener(new ResizeListener());
              setSize(640,480);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setLayout(new BorderLayout());
              myBoard.setBorder(BorderFactory.createLineBorder(Color.black));
              restart.addActionListener(new ResetListener());
              quit.addActionListener(new QuitListener());
              South.add(quit);
              South.add(restart);
              South.setBorder(BorderFactory.createLineBorder(Color.green));
              add(myBoard, BorderLayout.CENTER);
              add(South, BorderLayout.SOUTH);
              repaint();
              setVisible(true);
         //sends a new complete set of beads to the board
         public void updateBoard(int[][][] newBeads)
              myBoard.updateBoard(newBeads);
         //updates a specific bead then calls the updateboard method
         public void updateBead(int x, int y,int z, int color)
              myBoard.updateBead(x, y, z, color);
         //checks if a peg at a set of coordinates is full
         public boolean isFull(int x, int y)
              return myBoard.isFull(x,y);
         /* customer action listener for the reset button
          * resets the beads array to all zeroes (empty) and
          * sends the command "reset;" to the player
         private class ResetListener implements ActionListener
              public void actionPerformed(ActionEvent e)
                   int[][][] beads = new int[4][4][4];
                   for(int i = 0; i < 4; i++)
                        for(int j = 0; j<4; j++)
                             for(int k=0; k<4;k++)
                                  beads[i][j][k] = 0;
                   updateBoard(beads);
                   sendCommand("reset;");
         /* customer action listener for the quit button
          * sends a "quit;" command to the player.
         public class QuitListener implements ActionListener
              public void actionPerformed(ActionEvent e)
                   sendCommand("Quit;");
                   System.exit(0);      //REMOVE AFTER TESTING
         public void sendCommand(String command)
              //so far unused as I still need to work out sending the commands to the appropriate place
         public class ResizeListener implements ComponentListener
              public void componentResized(ComponentEvent e)
                   if(getWidth() != 640 || getHeight() != 480)
                        setSize(640,480);
              public void componentMoved(ComponentEvent e){}
              public void componentShown(ComponentEvent e) {}
              public void componentHidden(ComponentEvent e) {}
    /* class which creates the actual game board
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class BoardPanel extends JPanel
         enum BeadStatus {EMPTY, WHITE, BLACK};
         //variables, basic x and y starting points for drawing the board.
         final int x = 100;
         final int y = 100;
         final int[] boardxPoints = {x,x+320,x+420,x+100};
         final int[] boardyPoints = {y,y,y+200,y+200};
         //array for the beads
         private int[][][] beads = new int[4][4][4];
         private PegButton[] pegs = new PegButton[16];
         public JPanel pegsPanel = new JPanel();
         public BeadLayer beadsPanel = new BeadLayer();
         JLayeredPane layers = new JLayeredPane();
          * no arg constructor which simply zeroes the bead array
         public BoardPanel()
              pegsPanel.setLocation(0,0);
              pegsPanel.setPreferredSize(new Dimension(630,480));
              pegsPanel.setOpaque(false);
              setOpaque(false);
              drawPegs();
              layers.setBorder(BorderFactory.createTitledBorder(
            "Test"));
              layers.add(pegsPanel, 1);
              beadsPanel.setLocation(0,0);
              beadsPanel.setPreferredSize(new Dimension(630,480));
              //layers.add(beadsPanel, new Integer(1));
              add(layers);
          * overriden paint component method which draws out the board, pegs, and beads
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              g.setColor(Color.blue); //board background color
              g.fillPolygon(boardxPoints,boardyPoints, 4); //create the basic board shape
              drawGrid(g);
          * method to draw out the grid shape
         public void drawGrid(Graphics g)
              int p;
              int q;
              g.setColor(Color.cyan);
              //draw the vertical lines
              for(int i=0; i<5;i++)
                   p=x+(i*80);
                   g.drawLine(p,y,p+100,y+200);
              //draw the horizontal lines
              for (int j=0; j<4; j++)
                   p=x+(j*25);
                   q=y+(50*j);
                   g.drawLine(p,q,p+320,q);
              g.drawLine(x+100,y+200,x+420,y+200);
          * draw out the 16 pegs in proper position
         public void drawPegs()
              int p = x;
              int q = y;
              int n;
              for(int i=0; i<4;i++)
                   for(int j=0; j < 4; j++)
                        p = x+(j*80+40)+(i*25+12)-5;
                        q = y+(i*50+25)-80;
                        //g.fillRect(p,q,10,75);
                        //g.fillArc(p, q-5, 10, 10, 0, 180);
                        n =j+(i*4);
                        pegs[n] = new PegButton(i,j);
                        pegs[n].setLocation(p,q);
                        pegsPanel.add(pegs[n]);
         //updates the board by reading in a new bead array then repainting
         public void updateBoard(int[][][] beads)
              for(int i = 0; i < 4; i++)
                   for(int j = 0; j<4; j++)
                        for(int k=0; k<4; k++)
                             this.beads[i][j][k] = beads[i][j][k];
              repaint(); //inheirited method which causes paintcomponent to be called again
         public void updateBead(int x, int y, int z, int color)
              beads[x][y][z] = color;
              repaint();
         //returns true if a peg is full
         public boolean isFull(int x, int y)
              if (beads[x][y][3] != 0)
                   return false;
              return true;
    import java.awt.*;
    import javax.swing.*;
         public class BeadLayer extends JPanel
              enum BeadStatus {EMPTY, WHITE, BLACK};
              final int x = 100;
              final int y = 100;
              private int[][][] beads = new int[4][4][4];
              public BeadLayer()
                   for(int i = 0; i < 4; i++)
                        for(int j = 0; j<4; j++)
                             for(int k=0; k<4; k++)
                                  beads[i][j][k] = 1;
                   repaint();
              //method which takes in a set of coordinates and a color then draws the bead at the correct position
              public void paintComponent(Graphics g)
                   //reads through the bead array and calls the drawbead method where required
                   for(int i = 0; i<4; i++)
                        for(int j = 0; j<4; j++)
                             for(int k=0; k<4;k++)
                                  if(beads[i][j][k] == 1)
                                       drawBead(i,j,k,BeadStatus.BLACK,g);
                                  else if(beads[i][j][k] == 2)
                                       drawBead(i,j,k,BeadStatus.WHITE,g);
              public void drawBead(int x, int y, int z, BeadStatus color, Graphics g)
                   x = this.x+(x*80+40)+(y*25+12)-10;
                   y = this.y+(y*50+25)-18-(18*z);
                   if(color == BeadStatus.WHITE)
                        g.setColor(Color.WHITE);
                   else
                        g.setColor(Color.BLACK);
                   g.fillOval(x, y, 20, 18);
                   g.setColor(Color.GREEN);
                   g.drawOval(x, y, 20, 18);
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class PegButton extends JButton implements ActionListener
         private String coord;
         public PegButton(int x, int y)
              getCoord(x,y);
              this.setPreferredSize(new Dimension(10,75));
              this.setBorderPainted(false);
              addActionListener(this);
         public void getCoord(int x, int y)
              y+=1;
              switch(x)
                   case 0: coord = "A"+Integer.toString(y)+".";
                             break;
                   case 1: coord = "B"+Integer.toString(y)+".";
                             break;
                   case 2: coord = "C"+Integer.toString(y)+".";
                             break;
                   case 3: coord = "D"+Integer.toString(y)+".";
                             break;
         public void setLocation(int x,int y)
              if (y != 5)
                   super.setLocation(x,y);
         public void paintComponent(Graphics g)
              g.setColor(Color.RED);
              g.fillRect(0, 7, 10, 75);
              g.fillArc(0, 0, 10, 15, 0, 180);
         public void actionPerformed(ActionEvent e)
              System.out.println(coord);
    }

    Multi-post: http://forum.java.sun.com/thread.jspa?threadID=5274611

Maybe you are looking for

  • Payment terms on partial payments

    Hi Everyone, Is there a configuration setting somewhere that copies the payment terms of the original invoice on to the newly created open item. I know for certain that the payment terms can be copied from original invoice on to residual items when p

  • Premiere CC 2014.2 won't play source/program monitor

    I recently installed Adobe Premiere CC 2014.2, and since then no video plays within it, or the source and monitor or the program monitor. I'm on a Dell Inspiron notebook 2.1gh i7, 8GB memory, Intel HD Graphics 4000, ATI Radeon HD 7700m. Was usually w

  • Error while starting workflow from warning msg or error msg?

    Hello experts, I m tryin to start and workflow from error msg of ME21...whn we juss click enter without entering any value, it gives error as -" enter Purch org  ". whose msg class - ME and msg num - 083. thn from t-code SWUY,i creating and linked wo

  • Wdtv not connecting to wifi unless broadcasting SSID

    Greetings from Sunny Spain  8) I've been using for several years a wd tv live (currently version of firmware: 1.16.13) wirelessly attached to my network (Netgear router). My wifi security is wpa2. I also set my wifi, among other things, to NOT broadc

  • Writting to file(need yr help)--- URGENT

    HI , i need the data "text field " from data base to be in one line with "@!" if more than 36000 char it will be apend "@@" but still i am not able to get the output. i need the only col "text" tobe in one line . and attached the code. CAN ANY ONE HE