JPanel problem

I have two JPanels in an applet window. I have attached a mouse event handler to the second JPanel, such that it repaints itself when clicked, or when the mouse moves within it. Trouble is, the contents of the first JPanel(a bunch of JCheckboxes) get painted to the second Panel, before the results of paint() are drawn on top. Why does it do this?

if(evt.getSouce() == Button2) {
remove(myCheckBox);
- and doOtherThings
Checkboxes and textFields have a higher order priority

Similar Messages

  • Jsp and JPanel problem

    Hello. I've been to this forum many times, but have always been a bit gunshy about posting anything of my own. Now I have a problem I haven't seen before, so here goes. I have a JPanel in a java program that has all sorts of other componants added to it. I am trying to display the whole thing in a jsp page. This is what I am doing in the java file to return the image ("display" is the JPanel):
    public byte[] getImage(){
        int w = display.getWidth();
        int h = display.getHeight();
        BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        display.paint(img.createGraphics());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(img, "jpeg", os);
        return os.toByteArray();
    }and then in the jsp page I say:
    <%@ page contentType="image/jpeg" %>
    <%@ page import="myPackage.MyClass" %>
    <%
         MyClass picture = new MyClass();
         byte[] b = picture.getImage();
         OutputStream os;
         os = response.getOutputStream();
         os.write(b);
         os.flush();
    %>And the problem is that the page is displaying a blank JPanel and none of the componants that were added to it. If I save the the JPanel as a jpeg in the java program, though, it does contain all the componants, so I am not sure what I am doing wrong here. If there is some way to get the all the JPanel componants returned, that would be great to know. Thanks for any help.

    nope, that didn't work.
    Maybe I am going about solving the problem all wrong. The JPanel and its componants are kind of like a template. When a user of the system submits their information it automatically puts the data into the template and displays it on screen as a jpg. It works when I save the jpg as a file from the java program but not when i send the byte array to the jsp server. It just shows the blank panel....
    Is there a better way to go about doing this?

  • Paint JPanel problem

    Hi All
    I have 2 classes
    class1. has a Jframe with a JPanel.
    class1 2. A Has a JPanel called contact
    I am calling class2 from class1.
    It is placing the the contact Panel onto the JPanel in class1 but does not show. If I resize class1 it the shows that it is there.
    I have tried repaint(); with out any luck
    any other help would be helpfull
    Thanks
    Craig

    Ok Here you go
    I have class1 witch is my main frame called Command class
    I have a menu class that has a jTree on it called Menu_Panel
    Then I have a class called DataClient which is the panel that I am have Problems with.
    Here is the Code
    This is the jbInit in the Command Class.
        mainPanel.setLayout(borderLayout3);
        mainPanel.setLayout(borderLayout4);
        topPanel = new Panel_Top();
        mainPanel.add(topPanel, BorderLayout.NORTH);
        menuPanel = new Menu_Panel();
        dataPanel = new DataPanel();
        setMenuItems();
        contentPane = (JPanel)this.getContentPane();
        contentPane.setLayout(borderLayout1);
        this.setSize(new Dimension(900, 600));
        this.setTitle("Frame Title");
        jMenuFile.add(jMenuFileExit);
        jMenuHelp.add(jMenuHelpAbout);
        jMenuBar1.add(jMenuFile);
        jMenuBar1.add(jMenuHelp);
        contentPane.add(mainPanel, BorderLayout.CENTER);
        mainPanel.add(menuPanel, BorderLayout.WEST);
        mainPanel.add(topPanel, BorderLayout.NORTH);
        mainPanel.add(dataPanel, BorderLayout.CENTER);
        mainPanel.revalidate();
        this.setJMenuBar(jMenuBar1);
        fontResize();
        menuPanel.setDataPanel(dataPanel);   // This is where the Menu_Panel calls the show of DataPanel This is from the Menu_Panel at which point fires the menuPanel.setDataPanel(dataPanel); in the Command Class.
    /** Required by TreeSelectionListener interface. */
      public void valueChanged(TreeSelectionEvent e) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)
            tree.getLastSelectedPathComponent();
        if (node != null) {
          fromMenu = tree.getLastSelectedPathComponent().toString();
          checkMenuNames ();
    public void checkMenuNames (){
      if(fromMenu.equals("Client")){
              dataPanel.showClient();
    }This is the DataPanel Class
    public class DataPanel
        extends JPanel {
      private DataClient dataClient;
      public void showClient() {
        //  dClient = new Data_Client();
    if (dataClient == null){
      System.out.println("This worked");
    dataClient = new DataClient();
    this.add(dataClient);
    }and this is the DataClient class
    public class DataClient  extends JPanel{
      XYLayout xYLayout1 = new XYLayout();
      JLabel jLabel1 = new JLabel();
      public DataClient() {
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      private void jbInit() throws Exception {
        jLabel1.setText("This is Client");
        this.setLayout(xYLayout1);
        this.add(jLabel1,    new XYConstraints(110, 95, 179, -1));
    }Hope you can help me :)
    Craig

  • Printing jpanel problem

    So I am trying to print a JPanel. When I print to a pdf after bringing up a page setup dialog and a print dialog, either one of two things is happening.
    1) all drawn lines are shifted down and to the right.
    or
    2) all text is shifted up and to the left.
    Everything on the screen of the program looks great. I think it might have something to do with the fact that I am deriving fonts by scaling them. This would not be a problem if everything was shifting. It is clear that when rendered to a pdf it is handling the text of the fonts that I am using somehow differently than all the lines I am drawing. I do not understand why this is happening. Everything looks so good on the screen.
    If anybody knows what this problem is, your help would be much appreciated.
    Thanks in advance!

    Oh... it's just a mistake because of copy and paste.
    I did also have these code (without if (pageIndex > 0) {
    return(NO_SUCH_PAGE); ) but with these
    /* calculate the no. of pages to print */
    int totalNumPages = (int)Math.ceil((panelHeight) /
    height );
    if (pageIndex >= totalNumPages) return NO_SUCH_PAGE;
    and when I use :
    System.out.println("totalNumPages: " + String.valueOf(totalNumPages));
    I can see at there are two pages. But when it prints it can only print one. So...

  • Urgent- Printing JPanel problem

    I want to print a JPanel by calling a Print utility class. JPanel is drawing with different shapes (Rectangle2D etc..)
    The problem is that I can only print the first page of the JPanel.
    My Print utility:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    public class PrintUtilities {
    private Component componentToBePrinted;
    public static void printComponent(Component c) {
    new PrintUtilities(c).print();
    public PrintUtilities(Component componentToBePrinted) {
    this.componentToBePrinted = componentToBePrinted;
    public void print() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    BookComponentPrintable printable1 = new BookComponentPrintable(componentToBePrinted);
    PageFormat pageFormat1 = printJob.pageDialog(printJob.defaultPage());
    Book book = new Book();
    book.append(printable1, pageFormat1);
    // Print the Book.
    printJob.setPageable(book);
    if (printJob.printDialog())
    try {
    printJob.print();
    } catch(PrinterException pe) {
    System.out.println("Error printing: " + pe);
    class BookComponentPrintable
    implements Printable {
    private Component mComponent;
    public BookComponentPrintable(Component c) {
    mComponent = c;
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0) {
    return(NO_SUCH_PAGE);
    else
    Graphics2D g2 = (Graphics2D)g;
    g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    mComponent.paint(g2);
    return Printable.PAGE_EXISTS;
    What did I do wrong? Thanks in advance !!!

    Oh... it's just a mistake because of copy and paste.
    I did also have these code (without if (pageIndex > 0) {
    return(NO_SUCH_PAGE); ) but with these
    /* calculate the no. of pages to print */
    int totalNumPages = (int)Math.ceil((panelHeight) /
    height );
    if (pageIndex >= totalNumPages) return NO_SUCH_PAGE;
    and when I use :
    System.out.println("totalNumPages: " + String.valueOf(totalNumPages));
    I can see at there are two pages. But when it prints it can only print one. So...

  • Help!!! Please!!! jPanel problem.....

    Hi,
    I have MainFrame that contains jPanel1. ANd jPanel1 contains jPanel2, jPanel3, jPanel4.
    My problem is with jPanel2. jPanel2 contains jScrollPane.
    Let me just give tell you what i am doing.
    I wrote something which gets the image from database & displays the Multipage Tiff IMages in
    jScrollPane which is in jPanel2. I also have something which zooms the image from 10% to 120%.
    When i zoom the image to 30% the image is shown with only Vertical Scroll Bars. The image looks fine
    the first time its loaded. But when i move the vertical scroll bar the outside the image portion is shown
    with white and gray small areas each time i move the scroll bar.
    But when i zoom the image to 50% the image is shown with both scroll bars. SO when i scroll down or sideways
    I have no problem.
    Its only when i have vertical scroll bars.
    I have done repaint and validate on jPanel2 & jScrollPane but noting was solved.
    Any help or suggestions are always appreciated.
    Thanks in advance.

    Make sure you are calling invalidate() and validate() prior to the repaint. And since you are using a JPanel, try calling revalidate() as well. When ever I run into paint problems I just use trial an error on those 3 calls along with repaint() untill I find a combination that works. I really should spend 5 minutes figuring out which order to make these calls in and when but I have yet to do that :-(
    Bryan

  • A strange JPanel problem

    i have a JPanel which have a picture as a background the problem is when i wnat to add a JLabel or JTextField into this JPanel it didnt word but it works for labels bat JLabels no???why??
    here u are the code
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    public class d extends Container
        JTextField text1,text2,text3,text4,text5,text6;
         ImageIcon icon ;
       public d()
    {  super();
       setLayout(null );                                                                         
        setBackground(Color.RED);                                                                                                 
        text1=new JTextField();
       text2=new JTextField();
       text3=new JTextField();
       text4=new JTextField();
       text5=new JTextField();
        text6=new JTextField();
        panel p=new panel();
       p.setBounds(10,10,500,500);
         p.setLayout(null);
         p.setOpaque(true);
    p.setBackground(Color.WHITE);
    text1.setBounds(160,30,100,20);
    p.add(text1);
    text2.setBounds(10,30,100,20);
      p.add(text2);
      text3.setBounds(300,30,100,20);
      p.add(text3);
      text4.setBounds(10,100,100,20);
      p.add(text4);
    text5.setBounds(160,100,100,20);
      p.add(text5);
      text6.setBounds(300,100,100,20);
      p.add(text6);
    JLabel l1=new JLabel("touti");
    l1.setBackground(Color.WHITE);
      l1.setBounds(10,10,80,15);
      add(p);
       class panel extends JPanel
           public  void paint(Graphics g) {
           super.paint(g);
           icon=new ImageIcon("c:/bachir.jpg");
            g.drawImage(icon.getImage(),0,0, this);
    public static void main(String args[])
       JFrame frm = new JFrame( "test panel back ground" );
            frm.setBounds( 100, 100, 800, 800 );
            frm.getContentPane().setLayout( new BorderLayout() );
        d pnl=new d();
            frm.getContentPane().add(pnl , BorderLayout.CENTER );
      frm.setIconImage(Toolkit.getDefaultToolkit().getImage("c:/java/oicon.gif"));
            frm.setVisible( true );
    }

    You seem to be mixing AWT and Swing. You should use all AWT or all Swing but not a mixture. Try changing
    public class d extends Container
    to
    public class d extends JPanel.
    P.S. Your choice of class name stinks! It does not describes the role the class plays and it does not meet the Sun recommended coding standards.
    Message was edited by:
    sabre150

  • Urgent!!!!!!!! JFrame+JPanel problem

    How can I add a JFrame to a JPanel? What kind of objects can be contained Frames in at all?
    Thanks in advance

    Hi
    You cant add JFrame,JWindow,JApplet,JDialog to any other component.
    These are top level component and can not be added to any other.
    Ashish

  • Painting on JPanel problem

    i am new in java and im practicing on GUI...
    i wrote this stupid GUI that draw shapes on a JPanel, when i minimize the window and maximize again shapes disapear, i have been told to use the paintComponent( ) instead of getGraphics( ) but i didnt know how since my program is made out of two class...
    i will provide the code so please help a newbie
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.image.BufferedImage;
    import java.awt.image.RasterFormatException;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    public class can extends JFrame {
        private JPanel pic = new JPanel();
        private JButton b1 = new JButton("Clear");
        private JButton b2 = new JButton("Quit");
        private JButton b3 = new JButton("Save");
        private JRadioButton r, c, s;
        private JPanel p = new JPanel();
        public can() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(800, 600);
            setTitle("Shape Drawer");
            setLayout(new BorderLayout());
            pic.setBackground(Color.white);
            pic.addMouseListener(new locationListener());
            this.add(pic, BorderLayout.CENTER);
            this.add(b1, BorderLayout.WEST);
            this.add(b2, BorderLayout.EAST);
            this.add(b3, BorderLayout.SOUTH);
            b1.addActionListener(new clearListener());
            b2.addActionListener(new quitListener());
            b3.addActionListener(new saveListener());
            r = new JRadioButton("rectangle");
            c = new JRadioButton("circle");
            s = new JRadioButton("square");
            ButtonGroup bg = new ButtonGroup();
            bg.add(r);
            bg.add(c);
            bg.add(s);
            r.setSelected(true);
            p.add(r);
            p.add(c);
            p.add(s);
            this.add(p, BorderLayout.NORTH);
        private class saveListener implements ActionListener {
             * Invoked when an action occurs.
            public void actionPerformed(ActionEvent e) {
                saveFile();
        private class clearListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                clear();
        private class quitListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                quit();
        private class locationListener implements MouseListener {
            public void mouseClicked(MouseEvent e) {
                shapes shape = new shapes();
                Graphics g = pic.getGraphics();
                if (r.isSelected()) {
                    shape.rect(g, e.getX() - 30, e.getY() - 20);
                if (c.isSelected()) {
                    shape.circles(g, e.getX() - 25, e.getY() - 25);
                if (s.isSelected()) {
                    shape.squares(g, e.getX() - 25, e.getY() - 25);
             * Invoked when a mouse button has been pressed on a component.
            public void mousePressed(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when a mouse button has been released on a component.
            public void mouseReleased(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when the mouse enters a component.
            public void mouseEntered(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when the mouse exits a component.
            public void mouseExited(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
        private void quit() {
            System.exit(0);
        private void clear() {
            pic.repaint();
        private void saveFile() {
            int count = 1;
            String fileName = "picture.jpeg";
            File file = new File(fileName);
            if (file.exists()) {
                System.out.println("hello motto");
                fileName = "picture"+count+".jpeg";
                System.out.println(fileName);
                count++;
                System.out.println(count);
            pic = (JPanel) getContentPane();
            int w = pic.getWidth();
            int h = pic.getHeight();
            BufferedImage image = (BufferedImage) pic.createImage(w, h);
            Graphics g = image.getGraphics();
            if (g.getClipBounds() != null) {
                g.setClip(0, 0, w, h);
            pic.paint(g);
            try {
                FileOutputStream out = new FileOutputStream(file);
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                encoder.encode(image);
                out.flush();
                out.close();
            } catch (IOException ioe) {
            catch (RasterFormatException rfe) {
        public static void main(String[] args) {
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            } catch (Exception e) {
                System.out.println("ERROR: " + e);
            can c = new can();
            c.setVisible(true);
    }this was the first class and this is the second class that define the shapes
    import java.awt.*;
    public class shapes {
        public void squares(Graphics g, int x, int y) {
            g.setColor(Color.BLUE);
            g.fillRect(x, y, 50, 50);
        public void rect(Graphics g, int x, int y) {
            g.setColor(Color.RED);
            g.fillRect(x, y, 60, 40);
        public void circles(Graphics g, int x, int y) {
            g.setColor(Color.GREEN);
            g.fillOval(x, y, 50, 50);
    }i dunno how and where to implement the paintComponent( ) in this situation , please help me... and im also having another problemin the saveFile( ) method in the can class, it doesnt increment the naming of the file if it already exists...
    please help me...

    Hey, there were a few design issues in your code so I hope you dont mind me re-coding a few section of it to bring out the usage of the paintComponent(Graphics g) method.
    Also, the save was not working correctly because of the localization of the variables count and filename. I moved them and them global it to work. Also you had to re-create the file instance in order for it to be saved correctly with the new name.
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    public class Can extends JFrame {
        private JPanel p = new JPanel();
        private JButton b1 = new JButton("Clear");
        private JButton b2 = new JButton("Quit");
        private JButton b3 = new JButton("Save");
        private JRadioButton r, c, s;
        private PicturePanel pic = new PicturePanel();  
        private boolean shdClear = false;
        public Can() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(800, 600);
            setTitle("Shape Drawer");
            setLayout(new BorderLayout());          
            JPanel buttonPanel = new JPanel();
                buttonPanel.add(b1);
                buttonPanel.add(b2);
                buttonPanel.add(b3);
            b1.addActionListener(new clearListener());
            b2.addActionListener(new quitListener());
            b3.addActionListener(new saveListener());      
            r = new JRadioButton("rectangle");       
            c = new JRadioButton("circle");
            s = new JRadioButton("square");       
            r.setSelected(true);
            p.add(r);
            p.add(c);
            p.add(s);
            ButtonGroup bg = new ButtonGroup();
                bg.add(r);
                bg.add(c);
                bg.add(s);
            getContentPane().add(pic, BorderLayout.CENTER);
            getContentPane().add(buttonPanel, BorderLayout.SOUTH );
            getContentPane().add(p, BorderLayout.NORTH);
        public class PicturePanel extends JPanel implements MouseListener {
            Shapes shape = new Shapes();
            MouseEvent e = null;
            BufferedImage backgroundImage = null;
            public PicturePanel() {
                super();
                setBackground(Color.white);
                addMouseListener(this);
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                if(e == null) {
                    return;
                if(shdClear) {
                    backgroundImage.getGraphics().dispose();
                    backgroundImage = null;
                if(backgroundImage == null) {
                    backgroundImage = new BufferedImage( getWidth(), getHeight(),
                        BufferedImage.TYPE_INT_RGB );
                    Graphics g2 = backgroundImage.getGraphics();
                        g2.setColor( getBackground() );
                        g2.fillRect(0,0, getWidth(), getHeight());
                    // added here for performance reasons
                    // could have been added above in the if(shdClear) section 
                    if(shdClear) {
                        shdClear = false;
                        return;
                Graphics g2 = backgroundImage.getGraphics();
                if (r.isSelected()) {
                    shape.rect(g2, e.getX() - 30, e.getY() - 20);
                if (c.isSelected()) {
                    shape.circles(g2, e.getX() - 25, e.getY() - 25);
                if (s.isSelected()) {
                    shape.squares(g2, e.getX() - 25, e.getY() - 25);
                if(backgroundImage != null) {
                    g.drawImage(backgroundImage, 0, 0, this);
            public void mouseClicked(MouseEvent e) {
                this.e = e;
                pic.repaint();
             * Invoked when a mouse button has been pressed on a component.
            public void mousePressed(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when a mouse button has been released on a component.
            public void mouseReleased(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when the mouse enters a component.
            public void mouseEntered(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when the mouse exits a component.
            public void mouseExited(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
        private class saveListener implements ActionListener {
             * Invoked when an action occurs.
            public void actionPerformed(ActionEvent e) {
                saveFile();
        private class clearListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {           
                clear();
        private class quitListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                quit();
        private void quit() {
            System.exit(0);
        private void clear() {
            shdClear = true;
            pic.repaint();
        int count = 1; // moved so as not be recreated each time
        String fileName = "picture.jpeg";
        private void saveFile() {
            File file = new File(fileName);
            while (file.exists()) {
                System.out.println("hello motto");
                fileName = "picture" + count + ".jpeg";
                System.out.println(fileName);
                count++;
                System.out.println(count);
                file = new File(fileName); // recreate the file
            //pic = (JPanel) getContentPane();
            int w = pic.getWidth();
            int h = pic.getHeight();
            BufferedImage image = (BufferedImage) pic.createImage(w, h);
            Graphics g = image.getGraphics();
            if (g.getClipBounds() != null) {
                g.setClip(0, 0, w, h);
            pic.paint(g);
            try {
                FileOutputStream out = new FileOutputStream(file);
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                encoder.encode(image);
                out.flush();
                out.close();
                JOptionPane.showMessageDialog(null, fileName + " Saved", "File Saved",
                JOptionPane.INFORMATION_MESSAGE);
            } catch (IOException ioe) {
            } catch (RasterFormatException rfe) {
        public static void main(String[] args) {
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            } catch (Exception e) {
                System.out.println("ERROR: " + e);
            Can c = new Can();
            c.setVisible(true);
    class Shapes {
        public void squares(Graphics g, int x, int y) {
            g.setColor(Color.BLUE);
            g.fillRect(x, y, 50, 50);
        public void rect(Graphics g, int x, int y) {
            g.setColor(Color.RED);
            g.fillRect(x, y, 60, 40);
        public void circles(Graphics g, int x, int y) {
            g.setColor(Color.GREEN);
            g.fillOval(x, y, 50, 50);
    }ICE

  • Simple JPanel problem

    In the below code I try to make a JPanel thats 300 * 300 pixels big where I can draw some shapes. Just to test the program so far I tryed adding a red line. When I run the program (compile is ok) I only get a small rectangular area with a white background but without the red line, the area that supposed to be the JPanel is way too small. What am I doing wrong ?
    import javax.swing.*;
    import java.awt.*;
    class test extends JFrame
         public Sheet sheet = new Sheet();
         public static void main(String[] arg)
              new test();     
         public test()
              Toolkit kit = getToolkit();
              Dimension screen = kit.getScreenSize();
              setBounds(screen.width/3, screen.height/3, 400, 400);
              getContentPane().setLayout(new BorderLayout());
              JPanel main = new JPanel();     
              getContentPane().add(main, BorderLayout.CENTER);
              main.add (sheet);
              setVisible (true);          
         public class Sheet extends JPanel
              public Sheet ()
                   setSize(300,300);
                   setBackground(Color.white);
                   setVisible (true);     
              public void paintComponent(Graphics g)
                   super.paintComponent(g);
                   g.setColor(Color.red);     
                   g.drawLine(1,1,300,300);
    }

    Of course not.
    As a default, a JPanel has a FlowLayout. In a flow layout, all components are added left to right, top to bottom in the center of the container. The flow layout ignores your size settings as well. As of these facts, a FlowLayout mostly isn't very useful.
    A BorderLayout stretches out your panel (when you add it to the center). The JPanel (LayoutManager) constructor takes a layout manager (such as BorderLayout), that's why I created main that way.
    When you want to have your panel exactly some size you can try BoxLayout, null or GridBagLayout.
    I hope this information will help you on your way.
    Greetings,
    Levi

  • Trivial JPanel problem, but cant around it!!

    i am trying to add a JPanel, in CENTER of another panel (which already has a toolbar in its NORTH). when i set the background of the panel (which i am trying to add)....nothing happens
    though when i set the background of the main panel, i can see the changed background color
    how do i fix this??

    Ye tat field is the primary key for the table, and
    you're right the function works fine when everything
    is entered in properly.
    Are you saying that there is no way that you are
    aware of catching this exception myself- I just have
    to leave it for the SQL catch, I have tried similar
    things on different pages and they are all giving me
    the same result.
    Huh?
    When the table is empty there is no exception - correct?
    When there is one entry in the table and another non-duplicate is entered there is no exception - correct?
    When there is one entry in the table and another duplicate is entered there is an exception - correct?
    If the answer to above are all yes, then that is exactly the behavior that should occur.
    Now most databases report a differences via the text of the exception, and so you parse that if you want to differentiate.

  • Updating JPanel Problem

    Hi everyone!
    I have the following problem:
    My application makes it possible to watch the movement of a few balls simultaniously. The problem is that every ball updates the panel after it draws itself. This makes great mess when the balls are more than one. Can you help me?
    Thanks in advance!

    Sounds like control design problem. You might try something like...
    Have each ball move in it's own thread. Set up a SwingUtilities.Timer to repaint all the balls at a given time interval, say 1/30th of a second, or whatever you can smoothly support on your hardware. Alternatively, you could have the timer update the position of the balls before it draws them. The right answer depends on your system and requirements.
    Happy balling!

  • JFrame/JPanel Problem

    Hi all,
    I'm having trouble chaging the backgound color of my JFrame. It contains a JList.
    MY Code:
    panel.setBackground(Color.black);
    Please help. Thanks

    What is panel? Is it your JFrame? I think you need to do getContentPane().setBackgroundColor()

  • Border Layout problem

    I have a JPanel set to BorderLayout. I have 2 JPanels inside it. One JPanel is set to the West and one to the East. They are both are set to GridBagLayout.
    The West Panel vertically centers and the East Panel is vertically aligned at the top. Why is this? I would like them both vertically aligned at the top.
    Any help would be appreciated.

    Have you tried to add a border to each JPanel just to see what space they truly take?
    The west JPanel problem might be caused by the fact that you forgot to give at least one of its sub components a vertical weighty of 1.0.
    Also, a GridLayout(1, 2) might be more appropriate for the main JPanel, just because that's what GridLayouts are for :) .
    When you're facing problems with JPanels, you can either use setOpaque(true) along with setBackground(Color.whatevercolor) or set a Border. That way, you can know whether it's the JPanel itself or its sub components that are not properly displayed.

  • Javaclassnotfound javax.swing.JPanel in a applet

    Hi,
    I have a applet which use a class which have the code
    import javax.swing.JPanel;
    public class WebPanel extends JPanel implements Runnable{
    Applet parent;
    i compile it with jdk1.2.2
    my problem is that when i try to run the applet on a Internet Explorer navigator it give me a
    javaclassnotfound javax.swing.JPanel
    problem.
    Javax.swing.JPanel is�nt in IExploter?
    Should i put the javax.swing.Jpanel class in the jar fije?
    Where i can find it?
    Thanks in advance.

    forgot to mention this...get the plug in here:
    http://java.sun.com/products/plugin/
    read the intstructions, u might have to do some 'applet conversion' ....u'll know what I mean when u install the plugin
    good luck

Maybe you are looking for

  • After Effects wont start; OSX Lion 10.7.5 with Creative Cloud

    When I try to start Adobe After Effect CC 2014 it crashes and I get this message out of all my CC programs this is the only one that doesnt work, can anyone tell me what I can to fix this issue?

  • How do I find a corrupted file in a backup folder on my computer?

    I have recently had to replace the battery in my iphone, but before doing so, I had backed up the phone about 3 times, all saying they were successful.  And then I had erased the phone(before I realised the battery was the problem).  However when I w

  • Switching between page layout and word processing

    I can't seem to switch between page layout and word processing view.  I've read all the posts on this and still can't figure out why I can't just type a document into Pages.  The only option I have in page layout view is to type into text boxes, whic

  • PHP Form Filtering

    Hey Guys, I'm curious as to some of the best solutions to help filter out spamming through a php form.  Should I add captcha?  Is there another way?  I want to be able to filter out the erroneous requests or advertising of selling email lists from th

  • Deploying external jar files in CE 7.1

    Hi All, I am using CE 7.1 SP01 NWDS to develop my applications. Now I want deploy one external jar files to J2ee engine. I know how to do the same in NWDS 2004s. But here the steps seems to be little bit different. I referred the following blog for d