Semitransparent Panel on fullscreened jPanel

help me to make the AircraftCockpit a senitransparent jPanelimport java.awt.Color;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class RBStrategy implements Runnable
     private JFrame frame;
     static boolean onlyScreen = true;
     static Screen screen;
     static AircraftCockPit aircraftCockPit;
     public RBStrategy(JFrame frame, Screen screen)
          // store argument GUI elements
          this.frame = frame;
          this.screen = screen;
     public static void main(String[] args)
          JFrame frame = new JFrame();
          frame.setUndecorated(true);
          screen = new Screen();
          frame.getContentPane().add(screen);
          GraphicsEnvironment.getLocalGraphicsEnvironment().
               getDefaultScreenDevice().setFullScreenWindow(frame);
          screen.setLayout(null);
          aircraftCockPit = new AircraftCockPit(screen);
//          screen.add(aircraftCockPit);
//          screen.add(aircraftCockPit);
//          aircraftCockPit.setVisible(true);
          frame.addKeyListener(new KeyListener()
               public void keyPressed(KeyEvent event) {
                    int c = event.getKeyCode();
                    if(screen.active)     {
                         int scroll = screen.gridSize>>2;
                         if (c == KeyEvent.VK_LEFT)
                              screen.positionX=screen.positionX-scroll;
                              screen.tryX=screen.tryX+scroll;
                         if (c == KeyEvent.VK_RIGHT)
                              screen.positionX=screen.positionX+scroll;
                              screen.tryX=screen.tryX-scroll;
                         if (c == KeyEvent.VK_UP)
                              screen.positionY=screen.positionY+scroll;
                              screen.tryY=screen.tryY-scroll;
                         if (c == KeyEvent.VK_DOWN)
                              screen.positionY=screen.positionY-scroll;
                              screen.tryY=screen.tryY+scroll;
                         if (c == KeyEvent.VK_G)
                              screen.grid=!screen.grid;
               public void keyReleased(KeyEvent event) {
                    int c = event.getKeyCode();
//                    char c=event.getKeyChar();
                    System.out.print(c);
                    if (c == KeyEvent.VK_E)
                         System.out.println("e pressed");
                    if (c == KeyEvent.VK_M)
                         System.out.println("e pressed");
                    if (c == KeyEvent.VK_P)
                         System.out.println("p pressed");
                    if (c == KeyEvent.VK_C)
                         System.out.println("c pressed");
                         aircraftCockPit.show=!aircraftCockPit.show;
                    if (c == KeyEvent.VK_O)
                         onlyScreen = !onlyScreen;
                         aircraftCockPit.show=onlyScreen;
                         aircraftCockPit.show=onlyScreen;
                    if (c == KeyEvent.VK_ESCAPE)
                         System.exit(0);
               public void keyTyped(KeyEvent event) {}
          new RBStrategy(frame, screen).run();
     public void run()
          do
               long time = System.currentTimeMillis();
               String output;
               try
                    Thread.sleep(1000);
               catch (InterruptedException ie)
                    ie.printStackTrace(System.err);
          while (true);
class Screen
     extends JPanel
     implements
          Runnable,
          MouseListener,
          MouseMotionListener,
          MouseWheelListener,
          KeyListener {
               int scale;
               int positionX=0, positionY=0;
               int originX, originY;
               static int height,width;
               Color backgroundColor = Color.BLACK;
               Color gridColor = new Color(141,17,208);
               Thread t;
               final String name = "Screen";
               boolean active = true;
               boolean grid = true;
               int unit=4;
               int gridSize;
               final String fontName = "SansSerif";
               final int fontStyle = Font.BOLD;
               final int fontSize = 14;
               Font fontScale;
               double scaling=1;
               static int tryX,tryY;
               int mouseX=-100,mouseY=-100;
               int prevmouseX=mouseX,prevmouseY=mouseY;
               boolean progressing = true;
               Screen()     {
                    scale = 4;
                    gridSize=unit<<scale;
                    this.setBackground(backgroundColor);
                    this.start();
                    this.addMouseListener(this);
                    this.addKeyListener(this);
                    this.addMouseWheelListener(this);
                    this.addMouseMotionListener(this);
                    Icon icon = new ImageIcon("1.jpg");
                    LineBorder matteicon = new LineBorder(Color.DARK_GRAY,4);
//                    MatteBorder matteicon = new MatteBorder(19,25,19,25,icon);
                    this.setBorder(matteicon);
                    fontScale = new Font(fontName, fontStyle, fontSize);
             public void stop()     {
                  progressing = false;
                  t.stop();
             public void start()     {
                  progressing = true;
                  t = new Thread(this, name);
                  System.out.println("Screen start called");
                  t.start();
             protected void paintComponent(Graphics g)     {
                       super.paintComponent(g);
                       height = this.getHeight();
                       width=this.getWidth();
                         originX=width>>1;
                         originY=height>>1;
                         if(grid)     {
                              g.setColor(this.gridColor);
//                              System.out.println("han"+gridSize);     
                              for(int i=-(positionX%gridSize);i <= width;i=i+gridSize)     {
                                   g.drawLine(i,0,i,height);
//                                   System.out.println("han"+i);     
                              for(int i=positionY%gridSize;i <= height;i=i+gridSize)     {
                                   g.drawLine(0,i,width,i);
               g.setColor(Color.WHITE);
               g.drawLine(0,originY+positionY,width,originY+positionY);
               g.drawLine(originX-positionX,0,originX-positionX,height);
               g.setFont(fontScale);
               int me;          // for not junglling the scale label
               if(scale<=4)
                    me =4-scale;
               else
                    me=0;
               for(int i=-(positionX%gridSize);i <= width;i=i+(gridSize<<me))     {
                    g.drawString("X "+(int)((i-originX+positionX)/scaling),i-9,15);
               for(int i=positionY%gridSize;i <= height;i=i+(gridSize<<me))     {
                    g.drawString("Y"+(-(int)((i-originY-positionY)/scaling)),0+2,i+12);
               g.setColor(Color.WHITE);
               g.drawString("["+tryX+","+tryY+"]",mouseX,mouseY);
               public int getXCoordinate(int absoluteX)     {
                    int x;
                    x=(int)((absoluteX-originX+positionX)/scaling);
                    return(x);
               public int getYCoordinate(int absoluteY)     {
                    int y;
                    y=(int)((-absoluteY+originY+positionY)/scaling);
                    return(y);
               public void zoomOut()     {
                    if (scale==1)
                         return;
                    scale--;
                    gridSize=unit<<scale;
                    scaling = Math.pow(2,scale-4);
                    positionX=tryX;
                    positionY=tryY;
               public void zoomIn()     {
                    if (scale==5)
                         return;
                    scale++;
                    gridSize=unit<<scale;
                    scaling = Math.pow(2,scale-4);
                    positionX=tryX;
                    positionY=tryY;
               public void mousePositionChanged()     {
                    tryX=getXCoordinate(mouseX);
                    tryY=getYCoordinate(mouseY);
               public void mouseWheelMoved(MouseWheelEvent e)     {
                    System.out.println("wheel");
                    int kk=e.getUnitsToScroll();
                    if (kk>0)     {
                         zoomOut();
                    if (kk<0)     {
                         zoomIn();
                    this.repaint();
                    System.out.println("kk"+kk);
               public void keyReleased(KeyEvent e)     {
                    this.gridColor=Color.RED;
                    System.out.println("keyrel");
               public void keyTyped(KeyEvent e)     {
               public void keyPressed(KeyEvent e)     {
               public void mouseMoved(MouseEvent e)     {
                    mouseX=e.getX();
                    mouseY=e.getY();
                    tryX=getXCoordinate(mouseX);
                    tryY=getYCoordinate(mouseY);
               public void mouseReleased(MouseEvent e)     {
               public void mousePressed(MouseEvent e)     {
               public void mouseExited(MouseEvent e)     {
               public void mouseEntered(MouseEvent e)     {
               public void mouseClicked(MouseEvent e)     {
               public void mouseDragged(MouseEvent e)     {
               public void run()     {
                    try     {
                         while(progressing)     {
                              if(prevmouseX!=tryX || prevmouseY!=tryY)
                                   this.mousePositionChanged();
                              prevmouseX=tryX;
                              prevmouseY=tryY;
                              //System.out.println(prog);
                              this.repaint();
          //                    System.out.println("Interrupted");
                              Thread.sleep(1);
                    }catch     (InterruptedException e)     {
                         System.out.println("ssssssssssssInterrupted");
class AircraftCockPit
     extends JPanel
     implements MouseListener, MouseMotionListener, KeyListener, Runnable {
          boolean show = true;
          boolean progressing=true;
          static int ii=50,dii=1;
          static int jj=40, djj=-1;
          boolean inside=false;
          int i=0;     
          Thread t;
          Screen screen;
          AircraftCockPit(Screen s)     {
               this.add(new JButton("kapil"));
               screen = s;
               this.setBackground(new Color(0,25,0));
               this.setBounds(s.getWidth()*3/4,s.getHeight()>>2,s.getWidth()>>2,s.getHeight()*9/20);
               s.add(this);
               this.start();
          public void stop()     {
               progressing = false;
               t.stop();
          public void start()     {
               progressing = true;
               t = new Thread(this);
               System.out.println("Screen start called");
               t.start();
          protected void paintComponent(Graphics g)     {
                    super.paintComponent(g);
               if(!inside)     {
                    g.setColor(Color.YELLOW);
                         g.drawString("Puruer1 CockPit",ii,jj);
                         ii=ii+ dii;
                         jj=jj+djj;
                         if(ii==0 || ii>this.getWidth()-85)
                              dii=-dii;
                    if(jj==10 || jj>this.getHeight())
                         djj=-djj;
          public void keyReleased(KeyEvent e)     {
          public void keyTyped(KeyEvent e)     {
          public void keyPressed(KeyEvent e)     {
          public void mouseMoved(MouseEvent e)     {
          public void mouseReleased(MouseEvent e)     {
          public void mousePressed(MouseEvent e)     {
          public void mouseExited(MouseEvent e)     {
               inside=false;
          public void mouseEntered(MouseEvent e)     {
               inside=true;
          public void mouseClicked(MouseEvent e)     {
          public void mouseDragged(MouseEvent e)     {
          public void focusGained(FocusEvent e)     {
          public void focusLost(FocusEvent e)     {
          public void run()     {
               try     {
                    while(progressing)     {
                         this.setBounds((screen.getWidth()*3/4)+i,screen.getHeight()>>2,(screen.getWidth()>>2)-i,screen.getHeight()*9/20);
                         if(!this.show && this.getWidth()>=0 )
                              i=i+1;
                         if(this.show && this.getWidth()<=screen.getWidth()>>2)
                              i=i-1;
                         this.repaint();
//                         this.setVisible(this.show);
     //                    System.out.println("Interrupted");
                         Thread.sleep(2);
               }catch     (InterruptedException e)     {
                    System.out.println("ssssssssssssInterrupted");
}

In the future Swing related questions should be posted into the Swing forum.
You need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",
see http://homepage1.nifty.com/algafield/sscce.html, that demonstrates the incorrect behaviour. This is way too
much code for us to wade through.

Similar Messages

  • Semitransparent Panel & jComponent not visible

    Problem:jButton is not visible & CockPitPanel should be semitransparent import java.awt.Color;
    import java.awt.GraphicsEnvironment;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JFrame;
    public class RBStrategy implements Runnable
         private JFrame frame;
         static boolean onlyScreen = true;
         static Screen screen;
         static AircraftCockPit aircraftCockPit;
         public RBStrategy(JFrame frame, Screen screen)
              this.frame = frame;
              this.screen = screen;
         public static void main(String[] args)
              JFrame frame = new JFrame();
              screen = new Screen();
              frame.setUndecorated(true);
              frame.getContentPane().add(screen);
              GraphicsEnvironment.getLocalGraphicsEnvironment().
                   getDefaultScreenDevice().setFullScreenWindow(frame);
              screen.setLayout(null);
              aircraftCockPit = new AircraftCockPit(screen);
              new RBStrategy(frame, screen).run();
         public void run()
              do
                   String output;
                   try
                        Thread.sleep(1000);
                   catch (InterruptedException ie)
                        ie.printStackTrace(System.err);
              while (true);
    class Screen
         extends JPanel
         implements
              Runnable {
                   boolean progressing = true;
                   Thread t;
                   Screen()     {
                        this.add(new JButton("ButtonScreen"));
                        this.setBackground(Color.BLACK);
                        this.start();
                 public void stop()     {
                      progressing = false;
                      t.stop();
                 public void start()     {
                      progressing = true;
                      t = new Thread(this);
                      t.start();
                 protected void paintComponent(Graphics g)     {
                           super.paintComponent(g);
                           g.setColor(Color.red);
                           for(int i=0;i<this.getHeight();i=i+10)     {
                                     g.drawLine(0,i,this.getWidth(),i);
                   public void run()     {
                        try     {
                             while(progressing)     {
                                  this.repaint();
                                  Thread.sleep(1);
                        }catch     (InterruptedException e)     {
                             System.out.println("Interrupted");
    class AircraftCockPit
         extends JPanel
         implements  Runnable {
              boolean progressing=true;     
              Thread t;
              JButton jButton;
              Screen screen;
              AircraftCockPit(Screen s)     {
                   screen = s;
                   jButton=new JButton("ButtonCockPit");
                   jButton.setBounds(30,30,40,40);
                   this.setBackground(Color.GRAY);
                   this.setBounds(s.getWidth()*3/4,s.getHeight()>>2,s.getWidth()>>2,s.getHeight()*9/20);
                   s.add(this);
                   this.start();
              public void stop()     {
                   progressing = false;
                   t.stop();
              public void start()     {
                   progressing = true;
                   t = new Thread(this);
                   t.start();
              protected void paintComponent(Graphics g)     {
                        super.paintComponent(g);
              public void run()     {
                   try     {
                        while(progressing)     {
                             this.repaint();
                             Thread.sleep(2);
                   }catch     (InterruptedException e)     {
                        System.out.println("Interrupted");
    }

    As I suggested in your last posting, the size of the Screen panel is (0, 0). Since the size of the AircraftCockpit is based on the size of the Screen it is also (0, 0). So there is nothing to paint.
    Did you add a few System.out.println(...) statements to verify this?

  • List of various line panels in a JPanel

    Hi,
    I'd like to code a panel which can contain various amounts of other panels which can be considered as "line elements". They consist of a JLable and JTextfield and are all of the same height.
    I'd like the main panel at a specified fixed size so I chosed a BoxLayout and Y-Axis and I've put it into a JScrollpane.
    Now real fun starts. When I have only two "line panels" in it, they will be streched to fit the size and when it contains more than the Scrollpane's viewport, the JScrollbars show up only if the panel's size is greater than the viewport. What happens if there are more line elements than the main panel can keep, I don't know.
    How can I solve this problem having a list of various line elements which keep their size and JScrollbars which show up if necessary? If there might be a better way to do that, please tell me!!!
    I wrote this demo-version (2 classes):
    The main class with frame and main panel:
    package gui;
    import javax.swing.BoxLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.WindowConstants;
    public class PanOptions extends javax.swing.JPanel{
         private static final long serialVersionUID = 5833715021796955215L;
         private PanLine panLine1;
         private PanLine panLine2;
         private PanLine panLine7;
         private PanLine panLine6;
         private PanLine panLine5;
         private PanLine panLine4;
         private PanLine panLine3;
         private JScrollPane scrollPane;
         private JPanel panel;
         * Auto-generated main method to display this
         * JPanel inside a new JFrame.
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              frame.getContentPane().add(new PanOptions());
              frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
          * ctor.
         public PanOptions(){
              initGUI();
         private void initGUI() {
              panel = new JPanel();
              try {
                        this.setPreferredSize(new java.awt.Dimension(623, 140));
                   BoxLayout thisLayout = new BoxLayout( panel, javax.swing.BoxLayout.Y_AXIS);
                   panel.setLayout(thisLayout);
                        scrollPane = new JScrollPane();
                        this.add(scrollPane);
                        scrollPane.setViewportView( panel);
                             panLine1 = new PanLine();
                             panel.add(panLine1);
                             panLine2 = new PanLine();
                             panel.add(panLine2);
    //                    /* if the following part is commented the other two panels will be stretched?!
                             panLine3 = new PanLine();
                             panel.add(panLine3);
                             panLine4 = new PanLine();
                             panel.add(panLine4);
                             panLine5 = new PanLine();
                             panel.add(panLine5);
                             panLine6 = new PanLine();
                             panel.add(panLine6);
                             panLine7 = new PanLine();
                             panel.add(panLine7);
                        scrollPane.setSize(613, 140);
                        scrollPane.setPreferredSize(new java.awt.Dimension(613, 140));
              } catch (Exception e) {
                   e.printStackTrace();
    }The line element class:
    package gui;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    public class PanLine extends javax.swing.JPanel {
         private static final long serialVersionUID = 4932310577246348201L;
         private JLabel label;
         private JTextField tf;
          * Ctor
         public PanLine() {
              super();
              initGUI();
          * Inits GUI.
         private void initGUI() {
              try {
                   GridBagLayout thisLayout = new GridBagLayout();
                   thisLayout.rowWeights = new double[] {0.0,0.1};
                   thisLayout.rowHeights = new int[] {7,20};
                   thisLayout.columnWeights = new double[] {0.0,0.0,0.0,0.0,0.0};
                   thisLayout.columnWidths = new int[] {7,370,7,206,7};
                   this.setLayout(thisLayout);
                   this.setPreferredSize(new java.awt.Dimension(600, 27));
                        label = new JLabel();
                        this.add(label, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                        label.setText( "blablalba");
                        tf = new JTextField();
                        this.add(tf, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                        tf.setText( "blablalba");
              } catch (Exception e) {
                   e.printStackTrace();
    }

    Hi,
    I read thru the tuto and tried several things. I still have issues with the BoxLayout. For some strange reason glueing the excess space with Box.createVerticalGlue() doesn't work (at least I couldn't get it to work). So far I fixed the layout setting a maximum size for the line elements.
    To tell you the truth I don't really like this solution somehow - why does the glue not work in MY application? It seemed to be so easy in the tutorial and I can remember BoxLayout always having been nice to me?!
    This is just the modified main class, the elements are the same.. I'd like to get rid of having to set a max size for the element panels.
    package gui;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.WindowConstants;
    public class PanOptions01 extends javax.swing.JPanel{
         private static final long serialVersionUID = 5833715021796955215L;
         private PanLine panLine1;
         private PanLine panLine2;
         private PanLine panLine7;
         private PanLine panLine6;
         private PanLine panLine5;
         private PanLine panLine4;
         private PanLine panLine3;
         private JScrollPane scrollPane;
         private JPanel panel;
         * Auto-generated main method to display this
         * JPanel inside a new JFrame.
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              frame.getContentPane().add(new PanOptions01());
              frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
          * ctor.
         public PanOptions01(){
              initGUI();
         private void initGUI() {
              panel = new JPanel();
              try {
                        this.setPreferredSize(new java.awt.Dimension(623, 140));
                   BoxLayout thisLayout = new BoxLayout( panel, javax.swing.BoxLayout.Y_AXIS);
                   panel.setLayout(thisLayout);
                             panLine1 = new PanLine();
                             panel.add(panLine1);
    // it's only possible with lines like this:
                             panLine1.setMaximumSize(new java.awt.Dimension(610, 27));
                             panLine2 = new PanLine();
                             panel.add(panLine2);
    // it's only possible with lines like this:
                             panLine2.setMaximumSize(new java.awt.Dimension(610, 27));
                        /* if the following part is commented the other two panels will be stretched?!
                             panLine3 = new PanLine();
                             panel.add(panLine3);
                             panLine4 = new PanLine();
                             panel.add(panLine4);
                             panLine5 = new PanLine();
                             panel.add(panLine5);
                             panLine6 = new PanLine();
                             panel.add(panLine6);
                             panLine7 = new PanLine();
                             panel.add(panLine7);
    // this has rather no effect - why???
                        panel.add( Box.createVerticalGlue());
                        scrollPane = new JScrollPane();
                        this.add(scrollPane);
                        scrollPane.setSize(613, 140);
                        scrollPane.setPreferredSize(new java.awt.Dimension(613, 140));
                        scrollPane.setViewportView( panel);
                        panel.setPreferredSize(new java.awt.Dimension(610, 150));
              } catch (Exception e) {
                   e.printStackTrace();
    }

  • How to lock panels in fullscreen mode

    Hi all
    This might be a silly question, but since I converted from CS3 on Windows to CS5 on Mac I´ve been unable to do the following with the layout:
    I want the panels to be locked to the main window in full screen mode, so that when I open and work with files, they don´t get partly hidden behind the tool panels. I have searched and searched but to no avail.
    Help much appreciated?

    Ah Ah!
    Looks like you haven't yet seen this from the Adobe MAX event, two days ago:
    http://tv.adobe.com/watch/max-2010-keynotes/adobe-max-2010-keynote-day-1-welcome-to-the-re volution-creative-tooling/ (let load, then start at 1:30) very KPT/Metacreation-like, right?
    More seriously, I also wished to have the area below the toolbar to be a mixing palette.

  • Best technique for laying out a JPanel with sub panels...

    Okay, you're probably going to think this is a nit-picky question, but I seem to do it different each time I have to solve this problem, and neither of them feels like they're obviously the "right" way to do things, so I'm asking for how you all do them.
    Suppose I'm making a panel that's going to have several other panels on it. For example, let's say that the main JPanel is going to use BorderLayout and then there's going to be a sub-panel with a bunch of radiobuttons.. and another with some textboxes, and another with some jbuttons, etc.
    There are a few ways you can do it:
    Method #1
    1 Instantiate main JPanel
    2 Instantiate a sub-panel
    3 add() the sub-panel to the main (before it has anything)
    4 Populate the sub-panel with compnents
    5 Repeat 2-4 for all other sub-panels
    Method #2
    1 Instatiate main JPanel
    2 Instantiate a sub-panel
    3 add() it to the main panel
    4 repeat 2-3 for all sub-panels
    5 populate the first sub-panel with components
    6 Repeat #5 for all sub-panels
    Method #3
    1 Instantiate a sub-panel
    2 Populate the sub-panel with components
    3 Repeat 1-2 for all sub-panels
    4 Instantiate main JPanel
    5 Add populated sub-panel to main JPanel
    6 Repeat #5 for all sub-panels
    Method #4 (same as Method #1 except #3 and #4 are switched)
    1 Instantiate main JPanel
    2 Instantiate a sub-panel
    3 Populate the sub-panel with components
    4 add() populated sub-panel to main panel
    5 repeat 2-4 for all sub-panels
    They'll all work just fine when you initially write them. What I'm after is the one which:
    1) Is the most readable later, and
    2) Is easiest to make changes to if you want to change the way your overall panel looks (ie, least chance of having something go wrong because you didn't realize that you need to make a change in two different places in the code instead of one, etc).
    Of these methods, do any of them strike you as either "Sure, that's the only way to really do it!" or "Oh man, if you did it *that* way, you're in for major headaches"?
    Thanks in advance,
    - Joe

    Well, my code generally would look something like this:
    add(createToolBar(), BorderLayout.NORTH);
    add(createApplicationPanel(), BorderLayout.CENTER);
    add(createStatusBar(), BorderLayout.SOUTH);The createApplicationPanel might then be broken down into sub methods depending on the complexity of the application.
    So I guess that would be your method 4.
    The key point to remember is that you want create and add all the components and panels BEFORE you do your frame.pack() and frame.setVisible(), then you shouldn't have any layout problems.

  • How to make Fullscreen Applet

    Hello ,
    I am making slid show but need to be have full screen option . I searched for some example to find best way to do this task . I found this code but it`s not make full screen option when i am try to add to my code . I need someone to guide me for which way is best and high performance for this task .
    Thanks

    Sorry code is here , sorry if is not good .
    package slidshow;
    import javax.swing.*;
    import java.awt.*;
    import java.net.*;
    import java.io.*;
    public class Display extends JApplet {
         private Window mainWindow;
         private JPanel topPanel;
         private Panel bottomPanel;
         private URL myURL;
         private JEditorPane editorPane;
         public void init() {
              mainWindow = new Window(new Frame());
              // Get screen resolution and set mainWindow to fullscreen
              Dimension ss = Toolkit.getDefaultToolkit().getScreenSize();
              mainWindow.setBounds(0, -128, ss.width, ss.height + 256);
              //set up main window layout
              mainWindow.setLayout(new BorderLayout());
              /** Get bounds of screen so we can ultimately split the
                   window into two horizontally.
              GraphicsConfiguration gc = mainWindow.getGraphicsConfiguration();
              Rectangle bounds = gc.getBounds();
              double topPanelHeight = (ss.height * 0.5)+128;
              double bottomPanelHeight = (ss.height * 0.5);
              //Window size should be an integer (i.e whole number)
              int intTopHeight = (int)Math.round(topPanelHeight);
              int intBottomHeight = (int)Math.round(bottomPanelHeight);
              //Create Top Panel
              topPanel = new JPanel();
              topPanel.setPreferredSize(new Dimension(ss.width, intTopHeight));
              topPanel.setBackground(Color.blue);// May make this tranparent in the future
              topPanel.setLayout(new BorderLayout());
              //find out what the current directory structure is
              String codeBase = getCodeBase().toString();
              // Get page to load into top panel.
              try{
                   myURL = new URL(codeBase + "hi.html");
              } catch (MalformedURLException mue) {
                   System.out.println("Improper URL: " + mue.toString());
              // Create Editor Pane for top panel
              try {
                editorPane = new JEditorPane(myURL);
                editorPane.setBorder(null);
                editorPane.setEditable(false);
              } catch(IOException ioe) {
                System.err.println("Error displaying " + myURL);
              //Create JScrollPane, and place EditorPane in it.
              JScrollPane js = new JScrollPane(editorPane);
              js.setBorder(null);
              //Add Scroll pane to top panel
              topPanel.add(js, BorderLayout.CENTER);
              //Create bottom panel
              bottomPanel = new Panel();
              bottomPanel.setBackground(Color.black);
              bottomPanel.setPreferredSize(new Dimension(ss.width, intTopHeight));
              // add panels to window
              mainWindow.add(topPanel, BorderLayout.NORTH);
              mainWindow.add(bottomPanel, BorderLayout.CENTER);
              // make this visible
              mainWindow.setVisible(true);
    And now I notice your screen name, I recall you made a very odd reply to an ongoing thread in which I am also participating. What was with that? Sorry I didn`t understand what is your question ?

  • Need help:JPanel not being displayed in the JFrame

    Hello,
    I have a class called ConstructRoom.java which extends JFrame and another class called DimensionsPanel.java which extends JPanel. In the ConstructRoom class I use the following theContainer.add(new DimensionsPanel());, so I can display my JPanel. Well I get the JFrame but no JPanel. When the this call is made the DimensionsPanel.java code is cycled through, Where has my JPanel gone to?
    If I change the DimensionPanel.java extend JFrame and add the the JFrame code. Then I get the JFrame and the JPanel.
    Whats going on here?
    Thanks

    I made some of the changes with no luck. Here is some of the code:
    ---------from ConstructRoom.java--------
    //Imports
    public class ConstructRoom extends JFrame
    //----Member objects and varibles
    private static String theTitle; //Varible for title of frame
    private JFrame theFrame; //Object for the JFrame
    // ----------------------------------------------------------- ConstructRoom
    public ConstructRoom(String theTitle)
    super(theTitle); //JFrame super class
    theFrame = new JFrame("My frame");
    Container theContainer = theFrame.getContentPane(); //Frame container
    theContainer.setLayout(new FlowLayout());
    theContainer.add(new DimensionsPanel());
    theFrame.pack();
    theFrame.setBounds(10,10,400, 400);
    theFrame.addWindowListener(new WindowHandler());
    theFrame.setVisible(true);
    }//end ConstructRoom(String theTitle)
    // -------------------------------------------------------------------- main
    public static void main(String args[])
    ConstructRoom theRoom = new ConstructRoom(theTitle);
    }//end main(String args[])
    //----WindowHander
    }//end class ConstructRoom extends JFrame
    --------from DimensionsPanel.java
    //Imports
    public class DimensionsPanel extends JPanel
    //----Member objects and varibles
    private JPanel dimensionsPanel; //The main panel to hold all info
    private Box panelBox; //Box for all boxes which is added to the JPanel
    private Box furnListBox; //Box for all related items of the furnList
    private Box dimensionsBox; //Box for all dimensions (x, y, z)
    private Box xFieldBox; //Box for all related items of the xField
    private Box yFieldBox; //Box for related items of the yField
    private Box zFieldBox; //Box for related items of the zField
    private Box buttonsBox; //Box for all buttons
    private Box clearBox; //Box for related clear button items
    private Box buildBox; //Box for related build button items
    private JLabel furnListLabel; //Label for the furnList comboBox
    private JLabel xFieldLabel; //Label for the xField
    private JLabel yFieldLabel; //Label for yField
    private JLabel zFieldLabel; //Label for zField
    private JTextField xField; //Text field to enter the x dimension
    private JTextField yField; //Text field to enter the y dimension
    private JTextField zField; //Text field to enter the z dimension
    private JComboBox furnList; //List of selectable furniture objects
    private JButton clearButton; //Clear button
    private JButton buildButton; //Build button
    // --------------------------------------------------------- DimensionsPanel
    public DimensionsPanel()
    //----Setting up dimensions panel
    dimensionsPanel = new JPanel();
    dimensionsPanel.setLayout(new BorderLayout());
    dimensionsPanel.setPreferredSize(new Dimension(150,150));
    dimensionsPanel.setBorder(new TitledBorder(new EtchedBorder(),
    "Select Furniture and Enter Dimensions"));
    //----Initializing GUI components
    furnListLabel = new JLabel("Select from list ");
    furnList = new JComboBox();
    xFieldLabel = new JLabel("Enter Width ");
    xField = new JTextField();
    yFieldLabel = new JLabel("Enter Height ");
    yField = new JTextField();
    zFieldLabel = new JLabel("Enter Depth ");
    zField = new JTextField();
    buildButton = new JButton("Build Object");
    clearButton = new JButton("Clear Object");
    //-----Setting up the combo box and adding items
    furnList.addActionListener(new ComboProcessor());
    furnList.addItem(" "); //Default item
    furnList.addItem("Color Cube");
    furnList.setMaximumRowCount(6); //Max number of items before scrolling
    furnList.setSelectedItem(" "); //Set initial to default item
    //--Add the furnList to its box for placement in the JPanel
    furnListBox = Box.createHorizontalBox();
    furnListBox.add(Box.createHorizontalStrut(5));
    furnListBox.add(furnListLabel); //Adding the combo box label
    furnListBox.add(furnList); //Adding the combo box
    furnListBox.add(Box.createHorizontalStrut(5)); //Spacing
    //-------------------------------- Start Dimensions Components
    //----Setting up the xField
    xField.setEnabled(false); //Disabled at start
    xField.setFocusTraversalKeysEnabled(false); //Disabling the Tab Key
    //----Adding the event listeners
    xField.addActionListener(new XTextProcessor()); //Enter Key
    xField.addMouseListener(new ClickProcessor()); //Mouse Click
    //--Add the xField to its box for placement in the dimensionsBox
    xFieldBox = Box.createHorizontalBox();
    xFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
    xFieldBox.add(Box.createGlue()); //Take up extra space
    xFieldBox.add(xFieldLabel); //Adding the text field label
    xFieldBox.add(xField); //Adding the text field
    xFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
    //----Setting up the yfield
    yField.setEnabled(false); //Disabled at start
    yField.setFocusTraversalKeysEnabled(false); //Disabling TAB KEY
    //----Adding the event listeners
    yField.addActionListener(new YTextProcessor()); //Enter Key
    yField.addMouseListener(new ClickProcessor()); //Mouse Click
    //--Add the yField to its box for placement in the dimensionsBox
    yFieldBox = Box.createHorizontalBox();
    yFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
    yFieldBox.add(Box.createGlue()); //Take up extra space
    yFieldBox.add(yFieldLabel); //Adding the text field label
    yFieldBox.add(yField); //Adding the text field
    yFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
    //----Setting up the zfield
    zField.setEnabled(false); //Disabled at start
    zField.setFocusTraversalKeysEnabled(false); //Disabling TAB KEY
    //----Adding the event listeners
    zField.addActionListener(new ZTextProcessor()); //Enter Key
    zField.addMouseListener(new ClickProcessor()); //Mouse Click
    //--Add the zField to its box for placement in the dimensionsBox
    zFieldBox = Box.createHorizontalBox();
    zFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
    zFieldBox.add(Box.createGlue()); //Take up extra space
    zFieldBox.add(zFieldLabel); //Adding the text field label
    zFieldBox.add(zField); //Adding the text field
    zFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
    //----Adding all dimension components to the dimensionsBox
    dimensionsBox = Box.createVerticalBox();
    dimensionsBox.add(xFieldBox); //Adding the xFieldBox
    dimensionsBox.add(Box.createVerticalStrut(10)); //Spacing
    dimensionsBox.add(yFieldBox); //Adding the yFieldBox
    dimensionsBox.add(Box.createVerticalStrut(10)); //Spacing
    dimensionsBox.add(zFieldBox); //Adding the zFieldBox
    //-------------------------------- End Dimension Components
    //----Setting up the clearButton
    clearButton.setEnabled(false); //Disabled at start
    //----Adding the event listener
    clearButton.addActionListener(new ClearProcessor());
    //--Add the clear button to its box for placement
    clearBox = Box.createHorizontalBox();
    clearBox.add(Box.createHorizontalStrut(5)); //Spacing
    clearBox.add(clearButton); //Adding the clearButton
    //----Setting up the buildButton
    buildButton.setEnabled(false); //Disabled at start
    //--Add the action listener here
    buildBox = Box.createHorizontalBox();
    buildBox.add(buildButton); //Adding the buildButton
    buildBox.add(Box.createHorizontalStrut(5)); //Spacing
    //----Adding both buttons the buttonsBox
    buttonsBox = Box.createHorizontalBox();
    buttonsBox.add(clearBox); //Adding the clearBox
    buttonsBox.add(Box.createHorizontalStrut(10)); //Spacing
    buttonsBox.add(buildBox); //Adding the buildBox
    //----Create the JPanel (dimensionsPanel)
    //--Creating the main box to be added to the JPanel
    panelBox = Box.createVerticalBox();
    panelBox.add(furnListBox); //Adding the furnListBox components
    panelBox.add(Box.createVerticalStrut(10)); //Spacing
    panelBox.add(dimensionsBox); //Adding the dimensionBox components
    panelBox.add(Box.createVerticalStrut(10)); //Spacing
    panelBox.add(buttonsBox); //Adding the buttonsBox components
    panelBox.add(Box.createVerticalStrut(10)); //Spacing
    dimensionsPanel.add(panelBox); //Adding all components to the JPanel
    System.out.println("end dimensionpanel");
    }//end DimensionsPanel()
    //------ActionListeners
    }//end class DimensionsPanel extends JPanel

  • GridBagLayout and Panel Border problem

    I have 3 panels like
    A
    B
    C
    and the C panel has a Mouse Listener that on a mouseEntered creates a border around the same panel and on a mouseExited clears that border.
    When this border is created the A and B panels go up a little bit .. they move alone when the border is created.
    Is there any way to fix this problem? Is there any way to get the panels static?
    the code is close to the following:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.border.TitledBorder;
    import java.awt.event.*;
    import java.text.NumberFormat;
    public class Game extends JFrame implements MouseListener
    JPanel game, options, top, down, middle;
    NumberFormat nf;
    public Game() {
    super("Game");
    nf = NumberFormat.getPercentInstance();
    nf.setMaximumFractionDigits(1);
    JPanel center = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = gbc.BOTH;
    gbc.weighty = 1.0;
    gbc.weightx = 0.8;
    center.add(getGamePanel(), gbc);
    gbc.weightx = 0.104;
    center.add(getOptionsPanel(), gbc);
    Container cp = getContentPane();
    // use the JFrame default BorderLayout
    cp.add(center); // default center section
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setSize(700,600);
    // this.setResizable(false);
    setLocationRelativeTo(null);
    setVisible(true);
    addComponentListener(new ComponentAdapter()
    public void componentResized(ComponentEvent e)
    showSizeInfo();
    showSizeInfo();
    private void showSizeInfo()
    Dimension d = getContentPane().getSize();
    double totalWidth = game.getWidth() + options.getWidth();
    double gamePercent = game.getWidth() / totalWidth;
    double optionsPercent = options.getWidth() / totalWidth;
    double totalHeight = top.getHeight() + middle.getHeight() + down.getHeight();
    double topPercent = top.getHeight() / totalHeight;
    double middlePercent = middle.getHeight() / totalHeight;
    double downPercent = down.getHeight() / totalHeight;
    System.out.println("content size = " + d.width + ", " + d.height + "\n" +
    "game width = " + nf.format(gamePercent) + "\n" +
    "options width = " + nf.format(optionsPercent) + "\n" +
    "top height = " + nf.format(topPercent) + "\n" +
    "middle height = " + nf.format(middlePercent) + "\n" +
    "down height = " + nf.format(downPercent) + "\n");
    private JPanel getGamePanel()
    // init components
    top = new JPanel(new BorderLayout());
    top.setBackground(Color.red);
    top.add(new JLabel("top panel", JLabel.CENTER));
    middle = new JPanel(new BorderLayout());
    middle.setBackground(Color.green.darker());
    middle.add(new JLabel("middle panel", JLabel.CENTER));
    down = new JPanel(new BorderLayout());
    down.setBackground(Color.blue);
    down.add(new JLabel("down panel", JLabel.CENTER));
    // layout game panel
    game = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weightx = 1.0;
    gbc.fill = gbc.BOTH;
    gbc.gridwidth = gbc.REMAINDER;
    gbc.weighty = 0.2;
    game.add(top, gbc);
    gbc.weighty = 0.425;
    game.add(middle, gbc);
    gbc.weighty = 0.2;
    game.add(down, gbc);
    down.addMouseListener(this);
    return game;
    private JPanel getOptionsPanel()
    options = new JPanel(new BorderLayout());
    options.setBackground(Color.pink);
    options.add(new JLabel("options panel", JLabel.CENTER));
    return options;
    // mouse listener events
         public void mouseClicked( MouseEvent e ) {
    System.out.println("pressed");
         public void mousePressed( MouseEvent e ) {
         public void mouseReleased( MouseEvent e ) {
         public void mouseEntered( MouseEvent e ) {
    Border redline = BorderFactory.createLineBorder(Color.red);
    JPanel x = (JPanel) e.getSource();
    x.setBorder(redline);
         public void mouseExited( MouseEvent e ){
    JPanel x = (JPanel) e.getSource();
    x.setBorder(null);
    public static void main(String[] args ) {
    Game exe = new Game();
    exe.show();
    }

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    import java.text.NumberFormat;
    public class Game extends JFrame implements MouseListener{
      JPanel game, options, top, down, middle;
      NumberFormat nf;
      public Game() {
        super("Game");
        nf = NumberFormat.getPercentInstance();
        nf.setMaximumFractionDigits(1);
        JPanel center = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = gbc.BOTH;
        gbc.weighty = 1.0;
        gbc.weightx = 0.8;
        center.add(getGamePanel(), gbc);
        gbc.weightx = 0.104;
        center.add(getOptionsPanel(), gbc);
        Container cp = getContentPane();
        // use the JFrame default BorderLayout
        cp.add(center); // default center section
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(700,600);
        // this.setResizable(false);
        setLocationRelativeTo(null);
        setVisible(true);
        addComponentListener(new ComponentAdapter(){
            public void componentResized(ComponentEvent e){
            showSizeInfo();
        showSizeInfo();
      private void showSizeInfo(){
        Dimension d = getContentPane().getSize();
        double totalWidth = game.getWidth() + options.getWidth();
        double gamePercent = game.getWidth() / totalWidth;
        double optionsPercent = options.getWidth() / totalWidth;
        double totalHeight = top.getHeight() + middle.getHeight() + down.getHeight();
        double topPercent = top.getHeight() / totalHeight;
        double middlePercent = middle.getHeight() / totalHeight;
        double downPercent = down.getHeight() / totalHeight;
        System.out.println("content size = " + d.width + ", " + d.height + "\n" +
            "game width = " + nf.format(gamePercent) + "\n" +
            "options width = " + nf.format(optionsPercent) + "\n" +
            "top height = " + nf.format(topPercent) + "\n" +
            "middle height = " + nf.format(middlePercent) + "\n" +
            "down height = " + nf.format(downPercent) + "\n");
      private JPanel getGamePanel(){
        // init components
        top = new JPanel(new BorderLayout());
        top.setBackground(Color.red);
        top.add(new JLabel("top panel", JLabel.CENTER));
        middle = new JPanel(new BorderLayout());
        middle.setBackground(Color.green.darker());
        middle.add(new JLabel("middle panel", JLabel.CENTER));
        down = new JPanel(new BorderLayout());
        down.setBackground(Color.blue);
        down.add(new JLabel("down panel", JLabel.CENTER));
        // layout game panel
        game = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.weightx = 1.0;
        gbc.fill = gbc.BOTH;
        gbc.gridwidth = gbc.REMAINDER;
        gbc.weighty = 0.2;
        game.add(top, gbc);
        gbc.weighty = 0.425;
        game.add(middle, gbc);
        gbc.weighty = 0.2;
        game.add(down, gbc);
        down.addMouseListener(this);
        return game;
      private JPanel getOptionsPanel(){
        options = new JPanel(new BorderLayout());
        options.setBackground(Color.pink);
        options.add(new JLabel("options panel", JLabel.CENTER));
        return options;
      public void mouseClicked( MouseEvent e ) {
        System.out.println("pressed");
      public void mousePressed( MouseEvent e ) {
      public void mouseReleased( MouseEvent e ) {
      public void mouseEntered( MouseEvent e ) {
        Border redline = new CalmLineBorder(Color.red);
        JPanel x = (JPanel) e.getSource();
        x.setBorder(redline);
      public void mouseExited( MouseEvent e ){
        JPanel x = (JPanel) e.getSource();
        x.setBorder(null);
      public static void main(String[] args ) {
        Game exe = new Game();
        exe.setVisible(true);
    class CalmLineBorder extends LineBorder{
      public CalmLineBorder(Color c){
        super(c);
      public CalmLineBorder(Color c, int thick){
        super(c, thick);
      public CalmLineBorder(Color c, int thick, boolean round){
        super(c, thick, round);
      public Insets getBorderInsets(Component comp){
        return new Insets(0, 0, 0, 0);
    }

  • JPanel won't display my custome component

    Hi,
    I made a custome component class that in its paint method at this stage is suppose to paint a white rectangle on screen. However the when I add this custome component to my JPanel it doesn't show up. Does anybody have a solution for this?
    My code for the custome component is,
    public spaceMediaDisplayObject(mediaObject mo){
         x = mo.getSpaceX();
         y = mo.getSpaceY();
         height = mo.getHeight();
         width = mo.getWidth();
         name = mo.getName();
         System.out.println("Constructor");
         this.repaint();
    public void paint(Graphics g){
         System.out.println("Draw");
         g.setColor(Color.white);
         g.drawRect(x, y, height, width);
    And the fragment of code I am using to try and display in on the panel is as follows,
    spaceMediaDisplayObject smdo = new spaceMediaDisplayObject(toDisplay);
         spaceBodyPanel.add(smdo);
    Please help if able.

    If it's null then you need to set the size of each component explicitly:
    JPanel panel = new JPanel(null);
    Component customComponent = new CustomComponent();
    panel.add(customComponent);
    customComponent.setBounds(0, 0, 100, 100); // For exampleA simple layout manager could be used to make the component fill the panel, for example:
    JPanel panel = new JPanel(new GridLayout(1, 1));
    panel.add(new CustomComponent());Hope this helps.

  • Adding Components to a JPanel not working correctly

    I'm trying to build a JFrame that contains a parent JPanel that will hold a JPanel used to display a message view, a vertical strut and a JPanel that holds VCR-like buttons to cycle through the messages.
    My parent JPanel uses a BorderLayout and the Border is a TitledBorder which tells which product you are viewing (i.e., Message 1 of 5). I build the message JPanel, vertical strut and button JPanel and add them all in order to the parent JPanel which then gets added to the rootContentPane of the JFrame. All that appears is the parent JPanel's TitledBorder, the strut and the button JPanel. Using JSwat, I've been able to determine that the message JPanel has 0 for both its height and width after adding the message components to the JPanel.
    I create the message JPanel with a BorderLayout and an OvalBorder as copied from Manning Press's Swing book (which works fine in other JFrames that I have built), then add other components as necessary to the individual messages (mostly items around the edges with a central display for the actual message). What I can't figure out is why the height and width of the message JPanel isn't growing as I add components.
    I had previously used the same code to display a single message (minus the parent JPanel, strut and button JPanel) where I added the border panels (northPanel, eastPanel, southPanel and westPanel) created in createMsgPanel() directly to the contentPane and it worked perfectly, so I know that the code that adds the message works fine. Then, the requirements changed (go figure) and I had to display multiple messages from the same screen.
    Here's what I've got:
    public class Layout
                 extends JFrame
                 implements ActionListener
       private MissionData missionData;
       private JPanel messagePanel = null;
       private int index = 0;
       private int numMsgs = 0;
       private JPanel mainPanel = null;
       private JPanel buttonPanel = null;
       private TitledBorder titledBorder = null;
       Layout ()
       public Layout (MissionData msn)
          super ();
          missionData = msn;
          setSize (640, 640);
          setIconImage (new ImageIcon ("Icon.jpg").getImage());
          setTitle (((Message) (missionData.messages.elementAt(0))).name);
          numMsgs = missionData.messages.size();
          titledBorder = new TitledBorder (
                            new LineBorder (Color.BLACK),
                            "Message " + String.valueOf (index + 1) +
                            " of " + String.valueOf (numMsgs),
                            TitledBorder.LEFT,
                            TitledBorder.TOP);
          mainPanel = new JPanel ();
          mainPanel.setLayout (new BorderLayout());
          mainPanel.setBorder (new CompoundBorder (titledBorder,
                                                   new EmptyBorder (
                                                      new Insets (3, 3, 3, 3))));
          messagePanel = new JPanel();
          messagePanel.setLayout (new BorderLayout ());
          messagePanel.setBorder (new CompoundBorder (
                                     new EmptyBorder (50, 50, 50, 50),
                                     new OvalBorder (20, 20, Color.white)));
          messagePanel.setBackground (Color.black);
          createButtonPanel ();
          createMsgPanel ((Message) missionData.messages.elementAt (0));
          mainPanel.add (messagePanel);
          mainPanel.add (Box.createVerticalStrut (20));
          mainPanel.add (buttonPanel);
          Container mainContentPane = getContentPane();
          mainContentPane.add (mainPanel);
       private void createMsgPanel (Message msg)
          MessageType msgType = null;
          if (msg.getFunctionalAreaDesignator(0) == Message.GENERAL_INFO)
             if (msg.getMessageNumber(0) == 1)
                msgType = FREE_TEXT;
          else if (msg.getFunctionalAreaDesignator(0) == Message.SUPPORT)
             if (msg.getMessageNumber(0) == 33)
                msgType = CAS;
             else if (msg.getMessageNumber(0) == 34)
                msgType = OSR;
          // Setup NORTH Panel of Display
          JPanel northPanel = new JPanel (new GridLayout (2, 6));
          northPanel.setBackground (Color.black);
          northPanel.add (new JTIMLabel ("", false));
          northPanel.add (new JTIMLabel ("<html>RECV</html>", false));
          if (msgType == CAS)
             northPanel.add (new JTIMLabel ("<html>PCLR</html>", false));
             northPanel.add (new JTIMLabel ("<html>MSN</html>", false));
             northPanel.add (new JTIMLabel ("<html>SAVE</html>", false));
          else if (msgType == OSR)
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
          else if (msgType == FREE_TEXT)
             northPanel.add (new JTIMLabel ("<html>ERASE</html>", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("<html>BRDCST</html>", false));
          northPanel.add (new JTIMLabel ("<html>SEND</html>", false));
          northPanel.add (new JTIMLabel ("", false));
          northPanel.add (new JTIMLabel ("", false));
          if (msgType == CAS)
             northPanel.add (new JTIMLabel ("<html>CAS</html>", false));
          else if (msgType == OSR)
             northPanel.add (new JTIMLabel ("<html>OSR</html>", false));
          else if (msgType == FREE_TEXT)
             northPanel.add (new JTIMLabel ("<html>FTXT</html>", false));
          if (msgType == FREE_TEXT)
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
          else
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("<html>CAS</html>", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
             northPanel.add (new JTIMLabel ("", false));
          messagePanel.add (northPanel, BorderLayout.NORTH);
          // Setup EAST Box of Display
          Box eastBox = new Box (BoxLayout.Y_AXIS);
          if (msgType == CAS)
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("<html>F<br>T<br>X<br>T</html>", false));
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("<html>O<br>S<br>R</html>", false));
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("<html>D<br>P<br>I<br>P</html>", false));
             eastBox.add (Box.createGlue());
          else if (msgType == FREE_TEXT)
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("", false));
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("", false));
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("", false));
             eastBox.add (Box.createGlue());
             eastBox.add (new JTIMLabel ("", false));
             eastBox.add (Box.createGlue());
          eastBox.add (new JTIMLabel ("<html>W<br>L<br>C<br>O</html>", false));
          eastBox.add (Box.createGlue());
          eastBox.add (new JTIMLabel ("<html>C<br>N<br>T<br>C<br>O</html>",
                                        false));
          eastBox.add (Box.createGlue());
          messagePanel.add (eastBox, BorderLayout.EAST);
          // Setup SOUTH Panel of Display
          JPanel southPanel = new JPanel (new GridLayout (2, 5));
          southPanel.setBackground (Color.black);
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("<html>ON</html>", false));
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("", false));
          if (msgType == CAS)
             southPanel.add (new JTIMLabel ("<html>USE</html>", false));
             southPanel.add (new JTIMLabel ("<html>RCALL</html>", false));
          else if ((msgType == OSR) || (msgType == FREE_TEXT))
             southPanel.add (new JTIMLabel ("", false));
             southPanel.add (new JTIMLabel ("", false));
          southPanel.add (new JTIMLabel ("<html>MENU</html>", false));
          southPanel.add (new JTIMLabel ("<html>VMF</html>", false));
          if (msgType == CAS)
             southPanel.add (new JTIMLabel ("<html>NETS</html>", false));
          else if ((msgType == OSR) || (msgType == FREE_TEXT))
             southPanel.add (new JTIMLabel ("<html>CAS</html>", false));
          southPanel.add (new JTIMLabel ("", false));
          messagePanel.add (southPanel, BorderLayout.SOUTH);
          // Setup WEST Box of Display
          JTIMLabel incrLabel = null;
          JTIMLabel decrLabel = null;
          Box westBox = new Box (BoxLayout.Y_AXIS);
          if (msgType == FREE_TEXT)
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("", false));
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("", false));
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("", false));
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("<html>N<br>E<br>X<br>T</html>", false));
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("<html>P<br>R<br>E<br>V</html>", false));
          else
             westBox.add (Box.createGlue());
             westBox.add (new JTIMLabel ("<html>U<br>F<br>C</html>", false));
             westBox.add (Box.createGlue());
             if (msgType == CAS)
                westBox.add (new JTIMLabel ("<html>/\\</html>", false));
                westBox.add (Box.createGlue());
                westBox.add (new JTIMLabel ("<html>\\/</html>", false));
                westBox.add (Box.createGlue());
                incrLabel = new JTIMLabel ("<html>I<br>N<br>C<br>R</html>", false);
                westBox.add (incrLabel);
                westBox.add (Box.createGlue());
                decrLabel = new JTIMLabel ("<html>D<br>E<br>C<br>R</html>", false);
                westBox.add (decrLabel);
                westBox.add (Box.createGlue());
          messagePanel.add (westBox, BorderLayout.WEST);
          // Create CENTER Box to display message bodies
          GriddedPanel centerBox = new GriddedPanel ();
          centerBox.setBackground (Color.black);
          messagePanel.add (centerBox, BorderLayout.CENTER);
          if (msgType == CAS)
             new CASDisplay (msg, centerBox, incrLabel, decrLabel);
          else if (msgType == OSR)
             new OSRDisplay (msg, centerBox);
          else if (msgType == FREE_TEXT)
             new FreeTextDisplay (msg, centerBox);
       private void createButtonPanel ()
          // build the button panel
          buttonPanel = new JPanel ();
          buttonPanel.setLayout (new BoxLayout (buttonPanel, BoxLayout.X_AXIS));
          buttonPanel.setBorder (new LineBorder (Color.BLACK));
          // Create and add the buttons
          buttonPanel.add (createButton ("FIRST_BUTTON"));
          buttonPanel.add (createButton ("PREV_BUTTON"));
          buttonPanel.add (createButton ("NEXT_BUTTON"));
          buttonPanel.add (createButton ("LAST_BUTTON"));
       private JButton createButton (String buttonName)
          JButton button = new JButton ();
          button.addActionListener (this);
          button.setActionCommand (buttonName);
          Image image = null;
          String tooltip = "Press to go to the ";
          if (buttonName.equals ("FIRST_BUTTON"))
             image = new ImageIcon ("firstArrowIcon.gif").getImage();
             tooltip += "First";
          else if (buttonName.equals ("PREV_BUTTON"))
             image = new ImageIcon ("previousArrowIcon.gif").getImage();
             tooltip += "Previous";
          else if (buttonName.equals ("NEXT_BUTTON"))
             image = new ImageIcon ("nextArrowIcon.gif").getImage();
             tooltip += "Next";
          else if (buttonName.equals ("LAST_BUTTON"))
             image = new ImageIcon ("lastArrowIcon.gif").getImage();
             tooltip += "Last";
          tooltip += " message in the lst";
          button.setToolTipText (tooltip);
          button.setIcon (new ImageIcon (image.getScaledInstance (36, 36, Image.SCALE_FAST)));
          return button;
       public void actionPerformed (ActionEvent e)
          if (e.getActionCommand ().equals ("FIRST_BUTTON"))
             index = 0;
          else if (e.getActionCommand ().equals ("PREV_BUTTON"))
             if (index > 0)
                index--;
          else if (e.getActionCommand ().equals ("NEXT_BUTTON"))
             if (index < numMsgs - 1)
                index++;
          else if (e.getActionCommand ().equals ("LAST_BUTTON"))
             index = numMsgs - 1;
          titledBorder.setTitle ("Message " + String.valueOf (index + 1) +
                                 " of " + String.valueOf (numMsgs));
          createMsgPanel ((Message) missionData.messages.elementAt (index));
       private static class MessageType
                            extends EnumeratedType
                            implements Serializable
          final static long serialVersionUID = 1;
          protected MessageType (int value, String desc)
             super (value, desc);
       private static MessageType FREE_TEXT =
          new MessageType (0, "Free Text");
       private static MessageType CAS =
          new MessageType (1, "Call Accounting System");
       private static MessageType OSR =
          new MessageType (2, "Occupational Survey Report");
    }

    That's all well and good, but I've had more times that not where
    people want the entire program, not bits and pieces.Then you missed the whole point of that link.
    We don't want to see bits and pieces of code. We want to see an executable program, but we want an executable program the demonstrates the incorrect behaviour without all the unnecessary code. 90% of the code you posted was not related to your problem. That is we what you do to some basic debugging and remove the parts of code that are not related to the problem so we can concentrate on the code that is related to the problem.

  • Creating an image from a panel

    Hi everybody,
    I have a panel which extends JPanel, and wrote an image() method to extract the drawn image off the panel. For some reason, though, when I call this method, I get a dialog with a black box centered in it, and not the appropriate image.
    My SSCCE is as follows:
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import javax.swing.ImageIcon;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    public class MyPanel extends JPanel {
        private BufferedImage image;
        public BufferedImage image() {
            int x = getWidth();
            int y = getHeight();
            //image = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
            image = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            SwingUtilities.paintComponent( g2, this, new JPanel(), 0, 0, x, y );
            g2.dispose();
            return image;
        public static void main( String args[] ) {
             MyPanel canvas = new MyPanel() {
                  public void paintComponent( Graphics g ) {
                       Graphics2D g2 = (Graphics2D)g;
                       for( int i = 1; i <= 20; i++ ) {
                            int pos = i*50;
                            g2.drawString( "This is a test", pos, pos );
             JDialog test = new JDialog();
            JLabel label = new JLabel( new ImageIcon( canvas.image() ) );
            JScrollPane scroller = new JScrollPane( label );
            scroller.setPreferredSize( new Dimension( 500, 500 ) );
            test.add( scroller );
            test.pack();
            test.setVisible( true );
    }I'm pretty sure it has something to do with the sizing of the image and the timing of the repainting--when I uncomment the commented line in image(), I get an error saying width and height can't be less than or equal to 0. But anyway, I need to paint and then show an image of what was painted, not the actual painted panel--that's what I'm having trouble with. If anyone could help me out, I'd appreciate it. Can anyone help me fix this, please?
    Thanks,
    Jezzica85
    Edited by: jezzica85 on Jun 1, 2009 6:16 AM

    Odd choice to both have the panel with a getImage() method, and also override paintComponent(Graphics).
    Here is an alternate form of your code.
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class MyPanel extends JPanel {
      private BufferedImage image;
      public BufferedImage image() {
        int x = 200;
        int y = 200;
        image = new BufferedImage(x,y, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        g2.setColor(Color.yellow);
        g2.fillRect(0,0,x,y);
        g2.setColor(Color.black);
        for( int i = 1; i <= 20; i++ ) {
          int pos = i*50;
          g2.drawString( "This is a test", pos, pos );
        g2.dispose();
        return image;
      public static void main( String args[] ) {
        Runnable r = new Runnable() {
          public void run() {
            MyPanel canvas = new MyPanel();
            JDialog test = new JDialog();
            JLabel label = new JLabel( new ImageIcon( canvas.image() ) );
            JOptionPane.showMessageDialog(null, label);
            JScrollPane scroller = new JScrollPane( label );
            scroller.setPreferredSize( new Dimension( 500, 500 ) );
            JOptionPane.showMessageDialog(null, scroller);
        EventQueue.invokeLater(r);
    }

  • How can I hide a JPanel?

    I have some JPanels and using the mouse motion listeners you can scribble on them. I want to be able to switch between these panels but the problem is the drawings get wiped off when I use repaint() and frame.add(panel).
    Any ideas how else I could try doing this?

    Ok thanks everyone. I've taken the MyPanel class from here http://java.sun.com/docs/books/tutorial/uiswing/painting/step3.html
    class MyPanel extends JPanel {
        private int squareX = 50;
        private int squareY = 50;
        private int squareW = 20;
        private int squareH = 20;
        public MyPanel() {
            setBorder(BorderFactory.createLineBorder(Color.black));
            addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    moveSquare(e.getX(),e.getY());
            addMouseMotionListener(new MouseAdapter() {
                public void mouseDragged(MouseEvent e) {
                    moveSquare(e.getX(),e.getY());
        private void moveSquare(int x, int y) {
            int OFFSET = 1;
            if ((squareX!=x) || (squareY!=y)) {
                repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
                squareX=x;
                squareY=y;
                repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
        public Dimension getPreferredSize() {
            return new Dimension(250,200);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);      
            g.drawString("This is my custom Panel!",10,20);
            g.setColor(Color.RED);
            g.fillRect(squareX,squareY,squareW,squareH);
            g.setColor(Color.BLACK);
            g.drawRect(squareX,squareY,squareW,squareH);
    }Now if I use this class to make two panels, how can I hide one and bring the other one up and vice versa, using two buttons? setVisible() still doesn't work properly.
    Here's the whole code.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.SwingUtilities;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.BorderFactory;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.MouseMotionAdapter;
    public class PanelTest extends JFrame {
        private MyPanel panelOne;
        private MyPanel panelTwo;
        private BorderLayout layoutManager;
        private PanelTest() {
            layoutManager = new BorderLayout();
            this.setLayout(layoutManager);
            panelOne = new MyPanel();
            panelTwo = new MyPanel();
            panelOne.add(new JLabel("This is Panel One"));
            panelTwo.add(new JLabel("This is Panel Two"));
            setCurrentPanel(panelOne);
            JButton switchButton = new JButton("Switch");
            switchButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if(getCurrentPanel() == panelOne) {
                        setCurrentPanel(panelTwo);
                    } else {
                        setCurrentPanel(panelOne);
            this.getContentPane().add(switchButton, BorderLayout.SOUTH);
            this.pack();
            this.setVisible(true);
        private void setCurrentPanel(MyPanel panel) {
            this.getContentPane().add(panel, BorderLayout.CENTER);
            panel.revalidate();
            panel.repaint();
        private JPanel getCurrentPanel() {
            return (JPanel)layoutManager.getLayoutComponent(BorderLayout.CENTER);
        public static void main(String[] args) {
            new PanelTest();
    class MyPanel extends JPanel {
        private int squareX = 50;
        private int squareY = 50;
        private int squareW = 20;
        private int squareH = 20;
        public MyPanel() {
            setBorder(BorderFactory.createLineBorder(Color.black));
            addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    moveSquare(e.getX(),e.getY());
            addMouseMotionListener(new MouseAdapter() {
                public void mouseDragged(MouseEvent e) {
                    moveSquare(e.getX(),e.getY());
        private void moveSquare(int x, int y) {
            int OFFSET = 1;
            if ((squareX!=x) || (squareY!=y)) {
                repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
                squareX=x;
                squareY=y;
                repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
        public Dimension getPreferredSize() {
            return new Dimension(250,200);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);      
            g.setColor(Color.RED);
            g.fillRect(squareX,squareY,squareW,squareH);
            g.setColor(Color.BLACK);
            g.drawRect(squareX,squareY,squareW,squareH);
    }Edited by: atom.bomb on Mar 30, 2010 11:25 AM

  • Problem with displaying panel in a JFrame

    This application is supposed to display the actual month in a calendar with the current day in a red background.
    When running initially I get the frame with nothing in it, but if I resize it everything is displayed perfectly.
    I've played with the size of the JFrame and repaints methods but they are not woiking.
    I'll appreciate any information that you can give me
    thx
    Gustavo
    import javax.swing.*;
    import java.util.*;
    import java.awt.event.*;
    import java.awt.*;
    public class Assign2 extends JFrame
         private GregorianCalendar cal,temp;
         private int maxDay,minDay,firstDay,curDate;
         private String dayWeek[] = {"Sunday","Monday","Tuesday","Wednesday",
              "Thursday","Friday","Saturday"};
         private String month[] = {"January","February","March","April","May","June","July",
              "August","September","October","November","December"};
         JTextArea calDays[];
         private JPanel upper,lower,lowerDays,lowerGregorianCalendar;
         private JMenu file;
         private JMenuItem newDate,exit;
         private JMenuBar bar;
         private String banner;
         private JLabel dateBanner;
         public Assign2()
              // INITIALIZING CAL ( CALENDAR IS AN ABSTRACT CLASS, THAT'S WHY
              // THE KEYWORD NEW CAN NOT BE USED TO INITIALIZE
              cal = new GregorianCalendar();
              temp = new GregorianCalendar();
              // SETTING UP THE MENUBAR AND MENUITEMS
              bar = new JMenuBar();
              setJMenuBar(bar);
              file = new JMenu("File");
              bar.add(file);
              newDate = new JMenuItem("New Date");
              exit = new JMenuItem("Exit");
              file.add(newDate);
              file.add(exit);
              // CREATION AND INITIALIZATION OF THE MAIN CONTAINER
              // ITS LAYOUT MANAGER IS BORDERLAYOUT.
              // THERE WILL BE TWO ELEMENTS IN IT. THE BANNER WILL BE LOCATED IN
              // THE NORTH SIDE AND THE CALENDAR WILL BE LOCATED IN THE SOUTH SIDE
              Container c;
              c = getContentPane();
              c.setLayout ( new BorderLayout(5,5) );
              // INITIALIZING THE UPPER PANEL
              // THE BANNER WILL BE LOCATED THERE
              // ITS LAYOUT MANAGER WILL BE FLOWLAYOUT
              upper = new JPanel ( new FlowLayout(FlowLayout.LEFT) );
              // SETTING THE BANNER WITH THE CURRENT DATE
              banner = new String (month[cal.get(GregorianCalendar.MONTH)] + " " +
                   String.valueOf(cal.get(GregorianCalendar.DATE)) + "," + String.valueOf(cal.get(GregorianCalendar.YEAR)) );
              dateBanner = new JLabel(banner);
              upper.add(dateBanner);//ADDING THE BANNER TO THE UPPER PANEL
              // GETTING LIMITS TO BUILD THE CALENDAR USING FOR LOOPS
              // GETTING THE MAXIMUM NUMBER OF DAYS FOR A GIVEN DATE
              maxDay = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
              minDay = 0; // 0 is the equivalent of the first day of the month
              curDate = cal.get(GregorianCalendar.DATE);
              firstDay = firstDayOfMonth ( cal,temp ); //GETTING THE NUMERIC VALUE OF THE FIRST DAY
                                                           //OF THE MONTH: SUNDAY=1,MONDAY=2, AND SO ON
              // SETTING UP THE LAYOUT MANAGER FOR THE INFERIOR PANELS
              lower = new JPanel ( new BorderLayout() );
              lowerDays = new JPanel ( new GridLayout(1,7));
              lowerGregorianCalendar = new JPanel ( new GridLayout(5,7,5,5) );
              // PUTTING THE DAYS OF THE WEEK IN THE CALENDAR
              for ( int i=0 ; i<7 ; i++ )
                   lowerDays.add(new JLabel(dayWeek));
              lower.add(lowerDays,BorderLayout.NORTH);//ADDING THE DAYS OF THE WEEK TO THE LOWER PANEL
              // BUILDING THE CALENDAR USING THE PRIOR DEFINED LIMITS AND A FOR LOOP
              calDays = new JTextArea [50];//EVERY DAY OF THE CALENDAR IS A TEXT AREA
              for ( int i=0 ; i < (maxDay + firstDay) ; i++ )
                   calDays[i] = new JTextArea ( 3,3 );
                   calDays[i].setEditable(false);
                   if ( (i-firstDay) != curDate-1)
                        calDays[i].setBackground(Color.yellow);
                   else
                        calDays[i].setBackground(Color.red);
                   if ( i >= firstDay )
                        calDays[i].setText(String.valueOf(i-firstDay+1) );
                   lowerGregorianCalendar.add(calDays[i]);
              lower.add(lowerGregorianCalendar);
              c.add(upper,BorderLayout.NORTH);//ADDING THE UPPER PANEL TO THE CONTAINER
              c.add(lower,BorderLayout.SOUTH);
              setVisible(true);
              setSize(500,400);
         // THIS METHOD RETURNS THE EQUIVALENT OF THE FIRST DAY OF THE MONTH
         // SUNDAY=1,MONDAY=2 AND SO ON
         public int firstDayOfMonth ( GregorianCalendar cal, GregorianCalendar temp )
              // CREATING A TEMPORAL CALENDAR AND INITIALIZING IT WITH THE CAL VALUE
              //GregorianCalendar temp= temp.getInstance();
              // SETTING TEMP TO THE FIRST DAY OF THE MONTH
              temp.set(cal.get(GregorianCalendar.YEAR), cal.get( GregorianCalendar.MONTH) , 1 );
              // RETURNING THE NUMERIC VALUE OF THE FIRST DAY OF THE MONTH
              // SUNDAY=1,MONDAY=2, AND SO ON
              return temp.get(GregorianCalendar.DAY_OF_WEEK);
         public static void main ( String args[] )
              Assign2 app = new Assign2();
              app.reSize(550,450);
              app.addWindowListener(
                   new WindowAdapter()
                        public void windowClosing (WindowEvent e)
                             System.exit(0);

    Gustavo,
    I'm in the middle of writing such a calendar, but I've modularized things a bit. I start with a JFrame like you, and then add to it a class "CalendarPanel" built from a JPanel which holds all the buttons, combo boxes, etc.
    But try this: just after instantiating your JFrame object, call its show() method.

  • Arranging objects on a JPanel (Not sure how to use Layouts)

    Hey guys,
    It was suggested to me to use layouts to arrange Jbuttons fields and such. I tryed following the Java tutorial on the topic but I can't seem to follow it. If someone might look at my code and give me some pointers to arrange it. I'm not too familiar with the arrangement of objects, and what I do know is from BlueJ. This is is my code. Thanks in advance.
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JTextArea;
    public class SonnetTest {
        public static void main(String[] args) {
             JFrame frame = new JFrame();
             frame.setResizable(false);
             //Creates a new PoemGenerator object
             final PoemGenerator vanorden = new PoemGenerator();
             //Sets the standard width of the fields
             final int FIELD_WIDTH = 20;
             //Initializes the input fields for author and title
             final JTextField authorField = new JTextField(FIELD_WIDTH);
             final JTextField titleField = new JTextField(FIELD_WIDTH);
             //Labels the input fields
             final JLabel titleLabel = new JLabel("Title");
             final JLabel authorLabel = new JLabel("Author");
             //Initializes the display area
             final JTextArea display = new JTextArea();
             display.setText(vanorden.verse);
             display.setEditable (false);
              //Initializes the submit and new poem buttons
             JButton submitButton = new JButton("Submit");
             JButton newPoemButton = new JButton("New Poem");
             //Constructs the panel      
             JPanel panel = new JPanel();
             panel.add(display);
             panel.add(authorLabel);
             panel.add(authorField);
             panel.add(titleLabel);
             panel.add(titleField);
             panel.add(submitButton);
             panel.add(newPoemButton);
             frame.add(panel);
             submitButton.setSize(5000,50);
             //Creates a listener to be used when the submit button is pressed
             class CheckAnswerListener implements ActionListener{
                  public void actionPerformed(ActionEvent event){
                       String authorGuess = authorField.getText();
                       //Compares the input with the correct (ignoring case)
                       if(authorGuess.compareToIgnoreCase(vanorden.Poet) == 0){
                            display.setText("Correct!");
                       else{
                            display.setText("Incorrect, the poet's name is " + vanorden.Poet + ".");
             ActionListener listener = new CheckAnswerListener();
             submitButton.addActionListener(listener);
             //Creates a listener to be used when the new poem button is pressed
             class NewPoemListener implements ActionListener{
                  public void actionPerformed(ActionEvent event){
                       PoemGenerator vanorden = new PoemGenerator();
                       display.setText(vanorden.verse);     
             ActionListener listener2 = new NewPoemListener();
             newPoemButton.addActionListener(listener2);
             //Sets the panel's size
             frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
        //Sets the variables to be used as dimensions for the window
        private static final int FRAME_WIDTH = 500;  //Good width for input fields
        private static final int FRAME_HEIGHT = 100;
    }

    Thank you. I put each of the components into its on panel, just for the sake of experimentation. The thing is though that only one panel shows up. How do I arrange them? I keep getting the error:
    cannot find symbol method setLayout(java.awt.GridLayout)
    Here is my revised code. Thanks for putting up with me.
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JTextArea;
    public class SonnetTest {
        public static void main(String[] args) {
             JFrame frame = new JFrame();
             frame.setResizable(false);
             //Creates a new PoemGenerator object
             final PoemGenerator vanorden = new PoemGenerator();
             //Sets the standard width of the fields
             final int FIELD_WIDTH = 20;
             //Initializes the input fields for author and title
             final JTextField authorField = new JTextField(FIELD_WIDTH);
             final JTextField titleField = new JTextField(FIELD_WIDTH);
             //Labels the input fields
             final JLabel titleLabel = new JLabel("Title");
             final JLabel authorLabel = new JLabel("Author");
             //Initializes the display area
             final JTextArea display = new JTextArea();
             display.setText(vanorden.verse);
             display.setEditable (false);
              //Initializes the submit and new poem buttons
             JButton submitButton = new JButton("Submit");
             JButton newPoemButton = new JButton("New Poem");
             //Constructs the panel      
             JPanel panel = new JPanel();
             panel.add(display);
             JPanel panel2 = new JPanel();
             panel2.add(authorLabel);
             JPanel panel3 = new JPanel();
             panel3.add(authorField);
             JPanel panel4 = new JPanel();
             panel4.add(titleLabel);
             JPanel panel5 = new JPanel();
             panel5.add(titleField);
             JPanel panel6 = new JPanel();
             panel6.add(submitButton);
             JPanel panel7 = new JPanel();
             panel7.add(newPoemButton);
             frame.add(panel);
             frame.add(panel2);
             frame.add(panel3);
             frame.add(panel4);
             frame.add(panel5);
             frame.add(panel6);
             frame.add(panel7);
             submitButton.setSize(5000,50);
             //Creates a listener to be used when the submit button is pressed
             class CheckAnswerListener implements ActionListener{
                  public void actionPerformed(ActionEvent event){
                       String authorGuess = authorField.getText();
                       //Compares the input with the correct (ignoring case)
                       if(authorGuess.compareToIgnoreCase(vanorden.Poet) == 0){
                            display.setText("Correct!");
                       else{
                            display.setText("Incorrect, the poet's name is " + vanorden.Poet + ".");
             ActionListener listener = new CheckAnswerListener();
             submitButton.addActionListener(listener);
             //Creates a listener to be used when the new poem button is pressed
             class NewPoemListener implements ActionListener{
                  public void actionPerformed(ActionEvent event){
                       PoemGenerator vanorden = new PoemGenerator();
                       display.setText(vanorden.verse);     
             ActionListener listener2 = new NewPoemListener();
             newPoemButton.addActionListener(listener2);
             //Sets the panel's size
             frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
        //Sets the variables to be used as dimensions for the window
        private static final int FRAME_WIDTH = 260;  //Good width for input fields
        private static final int FRAME_HEIGHT = 200;
    }

  • Panel size

    How do you change the size of a panel or even a pane?

    You can also use setBounds(int x, int y, int width, int height) for a Panel or a JPanel. The component you add your Panel or JPanel to should have no layout set if you will use the setBounds() method.
    For example,
    JPanel myPanel = new JPanel();
    Container c = getContentPane();
    c.setLayout(null);
    c.add(myPanel);
    myPanel.setBounds(0, 0, 100, 100);
    Berk.

Maybe you are looking for