Have GridLayout in JLayeredPane

Hi, I would like to have a JPanel with GridLayout as background and another image on top of it. So I think I have to add 2 JPanel into the JLayeredPane but it doesn't work. I wonder whether I can do it in fact, anybody know it? Thanks.
I have my code for your reference:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainFrame{
     public MainFrame(){
          initFrame();
     public void initFrame(){
          JFrame frame = new JFrame("Swing program");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          ImageIcon bgIcon = new ImageIcon("pic/background.jpg");
          JLabel[] bgLabel = new JLabel[4];
          for(int i=0; i<4; i++){
               bgLabel[i] = new JLabel(bgIcon);
               bgLabel.setBounds(50,50,200,200);
          JPanel bgPane = new JPanel(new GridLayout(2,2));
          bgPane.setPreferredSize(new Dimension(600, 600));
          for(int i=0; i<4; i++){
               bgPane.add(bgLabel[i]);
          ImageIcon charIcon = new ImageIcon("pic/character.jpg");
          JLabel charLabel = new JLabel(charIcon);
          charLabel.setBounds(10,10,100,100);
          JPanel charPane = new JPanel();
          charPane.setPreferredSize(new Dimension(100,100));
          charPane.add(charLabel);
          JLayeredPane layeredPane = new JLayeredPane();
          layeredPane.setPreferredSize(new Dimension(600, 600));
          layeredPane.add(bgPane, new Integer(1));
          layeredPane.add(charPane, new Integer(2));
          Container contentPane = frame.getContentPane();
          contentPane.add(layeredPane);
          frame.pack();
          frame.setVisible(true);

Error in code:for(int i=0; i<4; i++){
  bgPane.add(bgLabel);
}should befor(int i=0; i<4; i++){
  bgPane.add(bgLabel[ i]);
}

Similar Messages

  • Layering a series of Transparent images onto a JPanel or JLayeredPane

    Hello all -
    I am working on creating a viewfinder type component for a game engine I am developing. Currently, I am loading a BackBuffered image from an array and displaying it in a JPanel. This image essentially serves as the "background" of the viewfinder.
    What I would like to do is go one step further and after the background image is determined, load a series of transparent images and place those on top of the background, BEFORE the repaint() method is called. An example of this would be loading the background image, and then loading walls (or other sprites), firing the repaint() method, resulting in the rendering all the images at one time.
    I have looked into JLayeredPane, but am uncertain as to whether this is the correct avenue to pursue. Does anyone have any experience with this?
    Any assistance would be greatly appreciated.

    JLayeredPane is not the way to go. Just draw your images on a panel. If you want/need to do all the drawing before repainting, use a back buffer. See BufferedImage

  • JLayeredPane in JScrollPane!

    here I am again, I thought I had solved it but apparently not so I'm trying some other way. Now what I have is the JLayeredPane inside the JScrollPane but the problem is that if I don't do this:
    layeredPane.setPreferredSize(new Dimension(1500, 1500));this is okay but when I want to insert info beyond this dimension it gets invisible. so what I wanted is the layeredPane' size to be dynamic..can anyone help me please?
    thanx a lot really
    iland

    Constructor
    // JLayeredPane   
        jlayeredPane = new JLayeredPane();
        jspLayered = new JScrollPane(jlayeredPane);
        jlayeredPane.addComponentListener(this);
        add(jspLayered, BorderLayout.CENTER);
        jlayeredPane.setPreferredSize(new Dimension(1000, 1000));
        jlayeredPane.add(graph, JLayeredPane.DEFAULT_LAYER);
    public void componentResized(ComponentEvent e) {
        Component c = e.getComponent();
        graph.setSize(c.getSize());
        graph.validate();
        c.repaint();
      }can u tell me pleasewhere do i revalidate the scrollpane and how , i really don't know
    thanx iland

  • Problem with view visibility

    Hello Everybody,
    I have two webdynpro applications.
    Lets say:
    MyApp1 and MyApp2.
    I am calling interface view of MyApp2 from MyApp1 application.
    For this, I have provided link on the tree at left side. Based on this, MyApp2's view is showing at right side.
    If I click on some other link then it shows me some other views of the same application(MyApp1).
    Now, When I click on the link again to load view of the other application(MyApp2) it is showing me the view with the same status as it was previous.
    Instead of this, I want to show the defaultview of MyApp2 each time when i click on the link from MyApp1.
    One solution for this is:
    Set the lifecycle of the used component of as "Manual". And create component each time when I fired the plug for MyApp2->Interfaceview.
    But, from performance point of view, I am searching for alternative option if any.
    So, is there any option to achieve this without manually deleting and creating component.
    Thanks in Advance,
    Bhavik

    Hi,
    Let me explain whole scenario:
    I have two webdynpro applications
    1. MyApp1
    2. MyApp2
    In MyApp2 I have gridlayout viewset with one column and two rows.
    In this vewset, I have one view(MyView21) on top and empty view in the bottom as default.
    In MyApp1, I have Gridlayout with 2 columns and 1 row. On left side I have one view containing tree. And on right side I am showing different views based upon the value selected from tree.
    For some values, I am firing plug to Interface view of the MyApp2 and for some values, I am firing plug to the views of MyApp1(Means from same application).
    Now Flow:
    1. I am calling view of MyApp2. It will call some views of MyApp2 based upon some actions.
    2. Then I am calling view of MyApp1.
    3. Again, I am calling view of the MyApp2, Which i called previously.
    But, now it loads with the view where i was in the first step. I want to display MyView21 on top and Empty view in bottom.
    I guess now, It will clear the picture.
    Regards,
    Bhavik

  • Move elements in layout and bind the elements?

    Hi experts, I have sereval questions.
    1. In a view, I drag & drop a group to the layout and drap sereval elements on the group. But I can't move the elements to the next line. They were just arranged one after one and line after line. How can I move them as I want?
    2. Does it exist a "table" element for the layout? Where is it?
    3. Does it exist a "date select" button for the layout which allows me to see a calendar and select a date on clicking it? Where is it.
    4. I've  mapped and binded the context of Component Controller to my Window context. But when I want to map & bind Window Context to View Context, all of the elements of context are gray that I can't bind them to the UI elements on the layout. That's why? How can I bind them?
    Thank you a lot in advance!!!!!

    Hi
    1. In a view, I drag & drop a group to the layout and drap sereval elements on the group. But I can't move the elements to the next line. They were just arranged one after one and line after line. How can I move them as I want?
    You have to use Layouts, you have GridLayout, FlowLayout, MatrixLayout and RowLayout
    Layout property is there for Groups, Transparent Containers
    2. Does it exist a "table" element for the layout? Where is it?
    Table UI element is not for Layouts, you have to use the Layouts mentioned above
    3. Does it exist a "date select" button for the layout which allows me to see a calendar and select a date on clicking it? Where is it.
    Take an Input Field and bind it with a Cotnext Attribute which of type DATS or dataelement which is a date type, then you can see calender automatically
    4. I've mapped and binded the context of Component Controller to my Window context. But when I want to map & bind Window Context to View Context, all of the elements of context are gray that I can't bind them to the UI elements on the layout. That's why? How can I bind them?
    This should not happen, check this again
    Abhi

  • P2P Image sharing

    hi everybody,
    I am not familiar with socket programming and i am rushing to overcome the following problem(s):
    I have a client-server application that allow client and server to exchange text message concurrently using some pleasent GUI. now i would like to extend it so they can exchange text file as well as images/pictures. in other words the client should be able to see the server pic when connection is established and via versa.
    Client code
    //Client Application
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    public class Client1 extends Frame implements ActionListener,Runnable,KeyListener
         Socket s;
         BufferedReader br;
         BufferedWriter bw;
            TextField text,name;
            Button exit,clear;
            Label label1;
            List list;
            Panel p1,p2,sp21,sp22,jp=null;
         public void run()
              try{s.setSoTimeout(1);}catch(Exception e){}
              while (true)
                   try{
                   System.out.println("Message: " + br.readLine());
                            //list.add(br.readLine());
                   }catch (Exception h){}
                                    /*because after succesive typing the list get a
                                    scrollbar and to view what You typed; the scroller
                                    is required.Hence after item count=8 the first
                                    item is removed.
                             if(list.getItemCount()==7)
                             list.remove(0);
         public static void main(String arg[])
                    new Client1("Client1", "localhost");
                    //new Client1();
         //Constructor creation
            public Client1(String m,String host)
              super(m);
                                    /* Creating a main Panel "jp" ,adding to it two
                                    Panels p1,p2 all have GridLayout.
                                    to the Panel p2 adding two sub Panels sp21,sp22
                                    having FlowLayout. then adding main Panel "jp" to
                                    frame. The Clear Button to reedit the name first typed
                    //Panels creation
                  jp=new Panel();
                    p1=new Panel();
                    p2=new Panel();
                    sp21=new Panel();
                    sp22=new Panel();
                    jp.setLayout(new GridLayout(2,1));
                    p1.setLayout(new GridLayout(1,1));
                    p2.setLayout(new GridLayout(2,1));
                    sp21.setLayout(new FlowLayout());
                    sp22.setLayout(new FlowLayout());
                    exit = new Button("Exit");
                    clear = new Button("Clear");
                    exit.addActionListener(this);
                    clear.addActionListener(this);
                    list = new List(50);
                    text = new TextField(43);
                    name = new TextField(10);
                    label1=new Label("Enter Your Name");
                    name.addKeyListener(this);
                    text.addKeyListener(this);
                    p1.add(list);
                    sp21.add(text);
                    sp21.add(exit);
                    sp22.add(label1);
                    sp22.add(name);
                    sp22.add(clear);
                    p2.add(sp21);
                    p2.add(sp22);
                    jp.add(p1);
                    jp.add(p2);
                    this.add(jp);
                    setBackground(Color.orange);
                    setSize(380,300);
                    setLocation(400,0);
                    setVisible(true);
                    setResizable(false);
                    name.requestFocus();
              try{
                            /*Server and Client are assumed to have the same IP here
                            if they are different enter them instead of "127.0.0.1"
                            default is 127.0.0.1 here*/
                            s = new Socket(host,786);
                            br = new BufferedReader(new InputStreamReader(
                             s.getInputStream()));
                   bw = new BufferedWriter(new OutputStreamWriter(
                             s.getOutputStream()));
                   Thread th;
                   th = new Thread(this);
                   th.start();
              }catch(Exception e){}
         public void actionPerformed ( ActionEvent e)
                     if (e.getSource().equals(exit))
                    System.exit(0);
                    else if (e.getSource().equals(clear))
                            { name.setText(" ");
                             name.setEditable(true);
            public void keyPressed(KeyEvent ke)
            {        if(text.equals(ke.getSource()))
                            if(ke.getKeyCode()==KeyEvent.VK_ENTER)
                                  try{
                                     bw.write(name.getText()+"\n**>>"+text.getText());
                                     bw.newLine();bw.flush();
                                     }catch(Exception m){}
                                     list.setListData(name.getText()+">>"+text.getText());
                                     text.setText("");
                      if(name.equals(ke.getSource()))
                            if(ke.getKeyCode()==KeyEvent.VK_ENTER)
                                    name.setEditable(false);
                                    text.requestFocus();
            public void keyReleased(KeyEvent ke) { //something
            public void keyTyped(KeyEvent ke) { //something
    Server code
    //Server Application
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    public class Server1 extends Frame implements ActionListener,Runnable,KeyListener
         ServerSocket s;
         Socket s1;
         BufferedReader br;
         BufferedWriter bw;
         TextField text; // used for typing text that will be sending to another person u chat with
         TextField name; // to specify a nick name using for chat
         Button exit,clear; // exit is terminate the application, and clear is for clearing the text field
         Label label;
         List list;
         //Declaration of panels for the frame interface
         Panel p1=null;
         Panel p2=null;
         Panel sp21=null;
         Panel sp22=null;
         Panel jp=null;
         public void run()
              try{s1.setSoTimeout(1);}
              catch(Exception e){}
              while (true)
                   try
                   System.out.println("Message: " + br.readLine());
                        //list.add(br.readLine());
                   catch (Exception h){}
                   if(list.getItemCount()==7)
                        list.remove(0);
         //Creation of the constructor
         public Server1(String m)
              super(m);
              //Creation of the panels   
              jp=new Panel();
              p1=new Panel();
              p2=new Panel();
              sp21=new Panel();
              sp22=new Panel();
              jp.setLayout(new GridLayout(2,1));
              p1.setLayout(new GridLayout(1,1));
              p2.setLayout(new GridLayout(2,1));
              sp21.setLayout(new FlowLayout());
              sp22.setLayout(new FlowLayout());
              exit = new Button("Exit");
              clear = new Button("Clear");
              exit.addActionListener(this);
              clear.addActionListener(this);
              list = new List(50);
              text = new TextField(43);
              name = new TextField(10);
              label = new Label("Enter your name");
              name.addKeyListener(this);
              text.addKeyListener(this);
              p1.add(list);
              sp21.add(text);
              sp21.add(exit);
              sp22.add(label);
              sp22.add(name);
              sp22.add(clear);
              p2.add(sp21);
              p2.add(sp22);
              jp.add(p1);
              jp.add(p2);
              this.add(jp);
              setBackground(Color.orange);
              setSize(380,300);
              setLocation(0,0);
              setVisible(true);
              setResizable(false);
              name.requestFocus();
              try
                   s = new ServerSocket(786);
                   s1=s.accept();
                   br = new BufferedReader(new InputStreamReader(
                        s1.getInputStream()));
                   bw = new BufferedWriter(new OutputStreamWriter(
                        s1.getOutputStream()));
                   bw.write("Welcome");bw.newLine();bw.flush();
                      //Tread.allows our system to perfom several tasks, concurrently, meaning the ability of sending
                        //and receiving messages to and from one terminal and others.
                   Thread th;
                   th = new Thread(this);
                   th.start();
              catch(Exception e){}
         //Main method
         public static void main(String args[])
              new Server1("Server");
         //Function to handle each button clicked
         public void actionPerformed (      ActionEvent e)
              if (e.getSource().equals(exit)) // if clicked button is the exit
                   System.exit(0); // terminate the system
              else if (e.getSource().equals(clear)) //if clicked button is the clear
                   name.setText(" ");//clear field
                   name.setEditable(true);
         //This function is to handle user pressed key event
         public void keyPressed(KeyEvent ke)
              if(text.equals(ke.getSource())) // get text entered by the user
                   if(ke.getKeyCode()==KeyEvent.VK_ENTER) // if he presses ENTER key
                        try // catch errors
                             bw.write(name.getText()+">>"+text.getText());
                             bw.newLine();bw.flush();
                        catch(Exception m){} // exception handling
                        list.add(name.getText()+"\n*>>"+text.getText());
                        text.setText("");
              else if(name.equals(ke.getSource())) // get text entered by the user
                   if(ke.getKeyCode()==KeyEvent.VK_ENTER) // if he presses ENTER key
                        name.setEditable(false); // cut and paste the entered text from text field to text panel
                        text.requestFocus();
         public void keyReleased(KeyEvent ke)
              //something
         public void keyTyped(KeyEvent ke)
              //something
                                by the way, do i need to use ImageIO......
    please help me
    Thanks in advance

    What you need to do is to define a message format that can accommodate both text and arbitrary data. Then you send those messages across the hosts.
    For example you can use something smiler to HTTP request format. Which has a set of headers and a body. Each header contain various meta data about the body. Such as message type, content type, file name, content length...
    And the message body is actual data.
    At the receiving end you decide what to do with each message depending on the headers.
    If you want to send large files you should implement your messaging system in a way so it can send a file in multiple messages to be reassembled in the other end.
    If you define a java class for the message. You can use either serialization of some other mechanism like XML encoding to send it across the network.

  • JTable have no resize cursor under a JLayeredPane

    Hi,
    i have over my JScrollPane a JLayeredPane to show infotext.
    When the JLayeredPane is over the JScrollpane you can resize the column but the JTable show no resize Cursor.
    Does anybody know why?
    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JLayeredPane;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    public class NoResizeCursorDemo extends JFrame
      public NoResizeCursorDemo()
        JTable table = new JTable( new DefaultTableModel( new String[]{ "aaa", "bbb" }, 10 ) );
        JScrollPane scrollPane = new JScrollPane( table );
        InfoLayer layer = new InfoLayer( scrollPane );
        add( layer );
      public static void main( String[] args )
        NoResizeCursorDemo frame = new NoResizeCursorDemo();
        frame.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible( true );
      class InfoLayer extends JLayeredPane
        private final JComponent wrappedComponent;
        public InfoLayer( JComponent wrappedComponent )
          this.wrappedComponent = wrappedComponent;
          setLayout( null );
          add( wrappedComponent, JLayeredPane.DEFAULT_LAYER );
          setInfoText();
        private void setInfoText()
          add( new JLabel( "Info......" ), JLayeredPane.POPUP_LAYER );
          revalidate();
        @Override
        public Dimension getPreferredSize()
          return wrappedComponent.getPreferredSize();
        @Override
        public void doLayout()
          Dimension size = getSize();
          Component layers[] = getComponents();
          for ( Component layer : layers )
            layer.setBounds( 0, 0, size.width, size.height );
    }Thanks

    Hi,
    I had almost the same problem with JTable and JSplitPane, the components worked fine, but cursor did not change when require.
    I already had in place mouse events dispatching in my top layer. It passed all events to the components underneath (see example in [Glass Pane Demo Project|http://java.sun.com/docs/books/tutorial/uiswing/examples/components/GlassPaneDemoProject/src/components/GlassPaneDemo.java]; in my case the listener was the content panel of the top layer).
    And now here is the trick around the cursor. Within the custom dispatch method I've called the following:
    this.setCursor(comp.getCursor());
    where "this" is the content panel of the layer and comp is the component where mouse event passed to.
    Hope that helps!
    Regards,
    Sergey

  • Probs. with JLayeredPane & JFrames

    Hi!
    I have a serious problem with a JLayeredPane in a JFrame... it doesn�t show any of my components, just a grey background.
    I have tried almost every single hint and advise I have been able to find - with no luck. So here goes my code - please help - I�m really stuck.
    //GUI.java Authors: Lis Riediger & Dawn H. Hammer
    //Klassen der indeholder vores brugergr�nseflade
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class GUI extends JFrame
    private GUI_felt[] gui_f = new GUI_felt[40];
    private JPanel[] jp1 = new JPanel[40], jp2 = new JPanel[40];
    private JLayeredPane JLP;
    private Spil s;
    private JPanel pBraet, pHuse, pBrikker, pNord, pSyd, pVest, pOst, pCenter, lastCenter = null,
    Ost1, Ost2, Vest1, Vest2, Syd1, Syd2, Nord1, Nord2;
    //S�tter GUI'en op
    public GUI(String[] spillere)
    super("Matador");
    s = new Spil(spillere);
    //S�tter lag 0 op
    for (int i = 0; i <=39; i++)
    if (((s.getFelt(i)).getType()).compareTo("grund") == 0)
    gui_f[i] = new GUI_grund((Grund)s.getFelt(i));
    else if(s.getFelt(i).getType().compareTo("bryggeri") == 0)
    gui_f[i] = new GUI_bryggeri((Bryggeri)s.getFelt(i));
    else if(s.getFelt(i).getType().compareTo("faerge") == 0)
    gui_f[i] = new GUI_faerge((Faerge)s.getFelt(i));
    else if(s.getFelt(i).getType().compareTo("ddb") == 0)
    gui_f[i] = new GUI_ddb((DDB)s.getFelt(i));
    else if(s.getFelt(i).getType().compareTo("skat") == 0)
    gui_f[i] = new GUI_skat((Skat)s.getFelt(i));
    else
    gui_f[i] = new GUI_felt(s.getFelt(i));
    for (int i = 0; i <=39;i++)
    gui_f.addMouseListener(new mouseListener());
    gui_f[i].setBackground(new Color(0,128,0));
    pSyd = new JPanel(new GridLayout(1,11));
    pSyd.setSize(462,42);
    for (int i = 10; i >= 0;i--)
    pSyd.add(gui_f[i]);
    pVest = new JPanel(new GridLayout(9,1));
    pVest.setSize(42,378);
    for (int i = 19; i >= 11; i--)
    pVest.add(gui_f[i]);
    pNord = new JPanel(new GridLayout(1,11));
    pNord.setSize(462,42);
    for (int i = 20; i <= 30; i++)
    pNord.add(gui_f[i]);
    pOst = new JPanel(new GridLayout(9,1));
    pOst.setSize(42,378);
    for (int i = 31; i <= 39; i++)
    pOst.add(gui_f[i]);
    pCenter = new JPanel();
    pCenter.setSize(378,378);
    pCenter.setBackground(new Color(0,128,0));
    pBraet = new JPanel(new BorderLayout());
    pBraet.setSize(462,462);
    pBraet.setVisible(true);
    pBraet.setBackground(new Color(0,128,0));
    pBraet.add(pSyd, BorderLayout.SOUTH);
    pBraet.add(pVest, BorderLayout.WEST);
    pBraet.add(pNord, BorderLayout.NORTH);
    pBraet.add(pOst, BorderLayout.EAST);
    pBraet.add(pCenter, BorderLayout.CENTER);
    //S�tter lag 1 op
    for (int i = 0; i <= 39;i++)
    jp1[i] = new JPanel();
    jp1[i].add(new JLabel(new ImageIcon("layer.gif")));
    jp1[i].setSize(42,42);
    Syd1 = new JPanel(new GridLayout(1,11));
    Syd1.setSize(462,42);
    for (int i = 10; i >= 0;i--)
    pSyd.add(jp1[i]);
    Vest1 = new JPanel(new GridLayout(9,1));
    Vest1.setSize(42,378);
    for (int i = 19; i >= 11; i--)
    pVest.add(jp1[i]);
    Nord1 = new JPanel(new GridLayout(1,11));
    Nord1.setSize(462,42);
    for (int i = 20; i <= 30; i++)
    pNord.add(jp1[i]);
    Ost1 = new JPanel(new GridLayout(9,1));
    Ost1.setSize(42,378);
    for (int i = 31; i <= 39; i++)
    pOst.add(jp1[i]);
    pHuse = new JPanel(new BorderLayout());
    pHuse.setSize(new Dimension(500,500));
    pHuse.setVisible(true);
    pHuse.setBackground(new Color(0,128,0));
    pHuse.add(Syd1, BorderLayout.SOUTH);
    pHuse.add(Vest1, BorderLayout.WEST);
    pHuse.add(Nord1, BorderLayout.NORTH);
    pHuse.add(Ost1, BorderLayout.EAST);
    //S�tter lag 2 op
    jp2[0] = new JPanel();
    jp2[0].setSize(42,42);
    JLabel dimmer = new JLabel(new ImageIcon("spiller1.gif"));
    dimmer.setSize(42,42);
    jp2[0].add(dimmer);
    for (int i = 1; i <= 39;i++)
    jp2[i] = new JPanel();
    jp2[i].add(new JLabel(new ImageIcon("layer.gif")));
    Syd2 = new JPanel(new GridLayout(1,11));
    Syd2.setSize(462,42);
    for (int i = 10; i >= 0;i--)
    pSyd.add(jp2[i]);
    Vest2 = new JPanel(new GridLayout(9,1));
    Vest2.setSize(42,378);
    for (int i = 19; i >= 11; i--)
    pVest.add(jp2[i]);
    Nord2 = new JPanel(new GridLayout(1,11));
    Nord2.setSize(462,42);
    for (int i = 20; i <= 30; i++)
    pNord.add(jp2[i]);
    Ost2 = new JPanel(new GridLayout(9,1));
    Ost2.setSize(42,378);
    for (int i = 31; i <= 39; i++)
    pOst.add(jp2[i]);
    pBrikker = new JPanel(new BorderLayout());
    pBrikker.setSize(new Dimension(462,462));
    pBrikker.setVisible(true);
    pBrikker.setBackground(new Color(0,128,0));
    pBrikker.add(Syd1, BorderLayout.SOUTH);
    pBrikker.add(Vest1, BorderLayout.WEST);
    pBrikker.add(Nord1, BorderLayout.NORTH);
    pBrikker.add(Ost1, BorderLayout.EAST);
    JLP = new JLayeredPane();
    JLP.setPreferredSize(new Dimension(462,462));
    JLP.setVisible(true);
    JLP.add(pBraet,new Integer(0));
    JLP.add(pHuse, new Integer(1));
    JLP.add(pBrikker, new Integer(2));
    Container contentPane = getContentPane();
    contentPane.add(JLP);
    contentPane.setLayout(new BorderLayout());
    //Indre klasse der h�ndterer mouseEvents
    private class mouseListener extends MouseAdapter
    //Metode der svarer p� et musseklik
    public void mouseClicked(MouseEvent event)
    if (lastCenter != null) pCenter.remove(lastCenter);
    lastCenter = ((GUI_felt)event.getSource()).getCenterCard();
    pCenter.add(lastCenter);
    pCenter.updateUI();
    Sincerely,
    Trisse

    I can tell from looking at it that your code won't even compile, yet you say it runs, just doesn't give the right result. I found 8 syntax errors in the first two for loops alone. Please post the actual code next time.
    Now, onto the logic errors (assuming I understand what the code should be)
    1. Last code block in the constructor...you add a component to the content pane, THEN set the layout?
    2. You've got a bunch of setVisible(true) calls on JPanel objects....why?
    3. Please call your mouseListener class something else. It's confusing considering the Java interface MouseListener.
    4. Second for loop, assuming you mean to index into the gui_f array, create the Color object once outside the loop, then assign it within the loop. Otherwise, that loop alone is going to create 40 Color objects (plus another 40 implicitly, but that's a discussion for another time). You do the same thing with all those ImageIcon objects.
    5. Same assumption as #4, your mouseListener code is independent of the source object (it doesn't assume what's its source is), don't create a new listener object for every object. One listener instance can handle all the GUI_Felt objects.
    6. It looks like you're trying to use JLayeredPane when you want one of a number of panels to be visible given some circumstances. Don't use JLayeredPane, use a generic JPanel with the CardLayout.
    7. You've got WAY too much code for a constructor. Each of your primary panels should be its own class.
    8. Your call in the mouseListener to updateUI is wrong. If what you want is to change the layout of a container after its been displayed, use the revalidate call. This is also the primary reason you're not seeing anything. You're calling setVisible on all these JPanels, which tells them to lay out their child components, but they don't have any yet. THEN, you add components, which will never get laid out.
    9. You're setting the actual size of a bunch of components, then adding them to a container that has a BorderLayout. Don't..BorderLayout will ignore the sizing you're doing and use only the preferredSize.
    10. I'm pretty sure there's more, but work on this, then try again.
    PS: If after all that I don't get at least some DDs, I will be very unhappy.

  • How to make a JPanel with a GridLayout scroll

    I am using a JPanel to hold around 100 buttons. The JPanel is using GridLayout to organise these buttons in rows of 3 buttons per row. i.e. buttonPanel.setLayout(new GridLayout(33,3)); As there are so many buttons they obviously don't all fit in the viewable area of the screen. To get around this I am trying to use a JScrollPane on the buttonPanel to make it scroll but I can't get it to work. I have tried both creating a seperate JScrollPane object and adding the buttonPanel to it
    JScrollPane buttonScroll = new JScrollPane();
    buttonPanel.setLayout(new GridLayout(33,3));
    buttonPanel.setPreferredSize(new Dimension(380,400));
    buttonPanel.setMaximumSize(new Dimension(380,400));
    buttonScroll.add(buttonPanel);and also embeding everything into a new JPanel like:
    buttonHolder.add(new JScrollPane(buttonPanel),BorderLayout.CENTER);Neither way works. Any ideas. I've read about view port but not exactly sure what this is or if this will fix my problem.
    Help urgently required.

    Fixed layouts have their perils.
    We need to figure the size for the buttonScroll. Here's one way to approach this:
        topPanel
            messagePanel 400 x 400    buttonScroll unknown size
        inputPanel
            previewPane  600 x  80    sendButton   icon size (55 x 68, duke)
        For a fixed layout, find the size required for the buttonScroll by commenting out the
        two lines that add the buttons to buttonPanel and calling pack on the frame:
        frame size (pack w/no buttons)     743 x 570
        topPanel size                      735 x 400
        therefore, required size for
            buttonScroll is                335 x 400     (735 - 400, 400)
    After adding the buttons back in the final sizes become
    C:\jexp>java GUI
    frame width = 763       height = 570
    topPanel width = 755    height = 400I substituted a Duke image for your sendIcon so the sizes may differ but this should get you started...
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.Container.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.text.*;
    public class GUI extends JFrame
        Icon sendIcon = new ImageIcon(getClass().getResource("images/T4.gif"));
        Icon deleteIcon = new ImageIcon(getClass().getResource("images/T6.gif"));
        JButton sendButton = new JButton("Send",sendIcon);
        JButton deleteButton = new JButton("Delete",deleteIcon);
        JLabel statusBar = new JLabel();
        JMenu optionsMenu = new JMenu("Options");
        JMenu helpMenu = new JMenu("Help");
        JMenuBar menuBar = new JMenuBar();
        JMenuItem connectMenuItem = new JMenuItem("Connect");
        JMenuItem disconnectMenuItem = new JMenuItem("Disconnect");
        JMenuItem exitMenuItem = new JMenuItem("Exit");
        JMenuItem helpMenuItem = new JMenuItem("Online Help");
        JMenuItem aboutMenuItem = new JMenuItem("About");
        JPanel buttonPanel = new JPanel();
        JPanel inputPanel = new JPanel();
        JPanel messagePanel = new JPanel();
        JPanel topPanel = new JPanel();
        JPanel buttonHolder = new JPanel();
        JScrollPane buttonScroll = new JScrollPane(buttonPanel,20,30);
        JTextPane messageArea = new JTextPane();
        JTextPane previewPane = new JTextPane();
        public GUI()
            super("Chat Program");
            String userName = "user";
            statusBar.setText("Connected: " + userName);
            menuBar.add(optionsMenu);
            menuBar.add(helpMenu);
            setJMenuBar(menuBar);
            optionsMenu.add(connectMenuItem);
            optionsMenu.add(disconnectMenuItem);
            optionsMenu.add(exitMenuItem);
            helpMenu.add(helpMenuItem);
            helpMenu.add(aboutMenuItem);
            buttonPanel.setLayout(new GridLayout(0,3));
            for(int i = 0; i < 100; i++)
                buttonPanel.add(new JButton("Button " + (i + 1)));
            messageArea.setEditable(false);
            previewPane.setEditable(false);
            previewPane.setPreferredSize(new Dimension(600,80));
            previewPane.setMaximumSize(new Dimension(600,80));
            messagePanel.setLayout(new BorderLayout(10,10));
            messagePanel.add(new JScrollPane(messageArea),BorderLayout.CENTER);
            messagePanel.setPreferredSize(new Dimension(400,400));
            messagePanel.setMaximumSize(new Dimension(400,400));
            // w = 735 - 400, h = 400
            // does not take into account the width of the vertical scrollBar
            buttonScroll.setPreferredSize(new Dimension(335,400));       // *
            Box box = new Box(BoxLayout.X_AXIS);
            box.add(new JScrollPane(previewPane));
            box.add(sendButton);
            inputPanel.add(box,BorderLayout.CENTER);
            statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED));
            topPanel.setLayout(new BorderLayout(10,10));
            topPanel.add(messagePanel, BorderLayout.WEST);
            topPanel.add(buttonScroll, BorderLayout.EAST);
            Container content = getContentPane();
            content.add(topPanel,   BorderLayout.NORTH);
            content.add(inputPanel, BorderLayout.CENTER);
            content.add(statusBar,  BorderLayout.SOUTH);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
    //        setSize(?,?);       // 763, 570 (now we know)
            setLocation(200,200);
            setVisible(true);
            // collect size information
            System.out.println("frame width = " + getWidth() + "\t" +
                               "height = " + getHeight() + "\n" +
                               "topPanel width = " + topPanel.getWidth() + "\t" +
                               "height = " + topPanel.getHeight());
        public static void main(String[] args)
            new GUI();
    }

  • Java code to get integer values from a gridLayout to put into an array?

    I am writing a tictactoe game for a programming class. I made a grid of 3x3 layout and it alternates between putting an X when clicked and an O. I need to know how to retrieve what button off the grid was picked so I can create an array to check for win conditions...Or how to access the rowIndex and columnIndex of a selected button on the grid
    Thanks in advance
    Edited by: ryAnOnFire on May 23, 2010 6:10 PM

    import java.awt.*;
    import java.awt.Container;
    import javax.swing.*;
    import java.awt.event.*;
    public class TicTacToe
         JFrame theWindow;
         JButton theButton;
         Container thePane;
         JTextField theText;
         MyListener theListener;
         public JButton[][] grid = new JButton[3][3];
         public TicTacToe()
              theWindow = new JFrame("Tic Tac Toe");
              theWindow.setSize(250, 250);
              String empty = " ";
             theListener = new MyListener();
              JFrame frame = new JFrame("TicTacToe");
              Container thePane = theWindow.getContentPane();
              thePane.setLayout(new GridLayout (3,3,5,5));
              for(int i = 0; i < 3; i++)
                   for(int j =0; j < 3; j++)
                        grid[i][j] = new JButton(empty);
                        thePane.add(grid[i][j]);
                        grid[i][j].addActionListener(theListener);
              JButton blankSpot = new JButton(empty);
              blankSpot.setFont(new Font("Papyrus", Font.BOLD, 35));
              theWindow.setVisible(true);
         public static void main(String[] args)
              new TicTacToe();
    class MyListener implements ActionListener
              String[][] spots1 = new String[3][3];
              String[][] spots2 = new String[3][3];
              static int playerTurnCounter = 0;
               JButton[][] grid; // !! added
                // !! added
                public MyListener(JButton[][] grid)
                     this.grid = grid;
              public void actionPerformed(ActionEvent e)
                   JButton jb = (JButton)e.getSource();
                   if(playerTurnCounter % 2 == 0)
                        jb.setText("X");
                        for(int i = 0; i < grid.length; i++)
                             for(int j = 0; j < grid.length; j++)
                                  spots1[i][j] = grid[i][j].getText();
                        if((spots1[0][0].equals("X")))
                             JOptionPane.showMessageDialog(null, "TICTACTOE", "WIN", JOptionPane.PLAIN_MESSAGE);
                        //The problem seems to be occuring in the above block commented area
                   else
                        jb.setText("O");
                   jb.setEnabled(false);
                   playerTurnCounter ++;
    Compiler Error:
    C:\Documents and Settings\HP_Administrator\My Documents\TicTacToe.java:24: cannot find symbol
    symbol  : constructor MyListener()
    location: class MyListener
             theListener = new MyListener();
                           ^
    1 error
    Tool completed with exit code 1
    I'm just going to let you ponder over this as I do too...
    I have no idea...my minimal experience with ActionListeners is doing me nothing for this one.
    Edited by: ryAnOnFire on May 23, 2010 8:12 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • I have no idea where to start

    okay, hi! i'm trying to write a vending machine program for a class i'm taking. i have a text file with names, image URLs, and prices. I have a product class which is supposed to use filereader to read the fields in the text file. The product class is going to be loaded by the main VendMach class file, where i will have all of the main ui stuff written. The last file is the MoneyInOut class, which handles all of the money methods. i've got the majority of the UI file done, the text file is ready, and the money file is almost done...everything is hanging on whether or not i can write the product file. i have no idea where to start. any help would be greatly appreciated. i'm not looking for somebody else to write my code, but a point in the right direction would be great! here are the UI and text files:
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.NumberFormat;
    import java.util.StringTokenizer;
    // Still to be fixed:
    // 1. Purchase & Maintenance buttons.
    // 2. fix repaint of pictures, they don't display until a repaint is hit.
    // 3. fix the Quit from program, it doesn't work right.
    // 4. Put in the code for doing Maintenance.
    // 5. Button super.setSize
    // 6. Animate picture on selection.
    public class VendMach extends Applet implements ActionListener
    // Fonts for text and buttons.
    private Font boldSerif16 = new Font("Serif",Font.BOLD,16);
    private Font boldSerif24 = new Font("Serif",Font.BOLD,24);
    private Font boldItalicSerif24 = new Font("Serif",Font.BOLD+Font.ITALIC,24);
    private Font boldItalicSerif13 = new Font("Serif",Font.BOLD+Font.ITALIC,13);
    private Font boldItalicSerif40 = new Font("Serif",Font.BOLD+Font.ITALIC,40);
    //%% private Font boldItalicDialog16 = new Font("Dialog",Font.BOLD+Font.ITALIC,16);
    // Mode flag.
    private int mode = 0;
    // Panels for the buttons
    private Panel mainPanel = new Panel();
    private Panel cashPanel = new Panel();
    private Panel selPanel = new Panel();
    private Panel maintPanel = new Panel();
    // Product selection panel buttons
    private Button selBtn[] = new Button[6];
    // Cash customer puts in machine panel buttons
    private Button viewC = new Button("View The Products");
    private Button quit = new Button("Quit");
    private Button bNickle = new Button("Nickel");
    private Button bDime = new Button("Dime");
    private Button bQuarter = new Button("Quarter");
    private Button b$Paper = new Button("$1 Paper");
    private Button b$Coin = new Button("$1 Coin");
    private Label lCredit = new Label(" Credit:");
    private Label lMsg = new Label("");
    private Button bChange = new Button("Change Return");
    private Button purchase = new Button("Purchase");
    private Button maintenance = new Button("Maintenance");
    private Product productForSale [];
    private CashIn changeOH;
    private int $collected = 0;
    private double total$In = 0.00;
    private NumberFormat nf;
    private Image pic;
    private Image picAnim;
    private int prodSel = 999;
    private String line;
    private String f[] = new String[8];
    private int tokenCount;
    private int int3, int4, int5, int6, int7;
    private double dbl4;
    private StringTokenizer strings;
    private int dispense = 99;
    public void init()
    {  setLayout(new BorderLayout());
    productForSale = new Product[6];
    try
    {  BufferedReader inPut = new BufferedReader(new FileReader("Vend_Machine.txt"));
    while ((line=inPut.readLine()) != null)
    {  strings = new StringTokenizer(line,",");
    tokenCount = strings.countTokens();
    // Loop thru and retrieve each data element.
    for (int i=0; i<tokenCount; i++)
    f[i] = strings.nextToken();
    // Load the money.
    if (f[0].compareTo("M") == 0)
    {  int3 = Integer.parseInt(f[3]);
    int4 = Integer.parseInt(f[4]);
    int5 = Integer.parseInt(f[5]);
    int6 = Integer.parseInt(f[6]);
    int7 = Integer.parseInt(f[7]);
    changeOH = new CashIn(f[1],f[2],int3,int4,int5,int6,int7);
    // Load the products.
    if (f[0].compareTo("P") == 0)
    {  int3 = Integer.parseInt(f[3]);
    dbl4 = (new Double(f[4])).doubleValue();
    int5 = Integer.parseInt(f[5]);
    int6 = Integer.parseInt(f[6]);
    int7 = Integer.parseInt(f[7]);
    productForSale[int3] = new Product(f[1],f[2],dbl4,int5,int6,int7);
    inPut.close();
    catch(IOException e)
    {  e.printStackTrace();
    setBackground(Color.pink);
    setForeground(new Color(120,0,120));
    setFont(boldSerif16);
    cashPanel.setLayout(new GridLayout(10,1));
    cashPanel.add(viewC);
    cashPanel.add(quit);
    cashPanel.add(bNickle);
    cashPanel.add(bDime);
    cashPanel.add(bQuarter);
    cashPanel.add(b$Paper);
    cashPanel.add(b$Coin);
    cashPanel.add(lCredit);
    cashPanel.add(lMsg);
    cashPanel.add(bChange);
    add(cashPanel,"East");
    selPanel.setLayout(new GridLayout(1,6));
    for (int i=0; i<6; i++)
    {  selBtn[i] = new Button(productForSale.getName());
    selPanel.add(selBtn[i]);
    add(selPanel,"South");
    setBackground(Color.black);
    viewC.addActionListener(this);
    quit.addActionListener(this);
    bNickle.addActionListener(this);
    bDime.addActionListener(this);
    bQuarter.addActionListener(this);
    b$Paper.addActionListener(this);
    b$Coin.addActionListener(this);
    bChange.addActionListener(this);
    nf = NumberFormat.getCurrencyInstance();
    for (int i=0; i<6; i++)
    selBtn[i].addActionListener(this);
    } // =======>> END OF INIT METHOD
    // ** PAINT METHOD **
    public void paint(Graphics g)
    {  int xVal = 35;
    int yVal = 85;
    int xValAnim = 0;
    int yValAnim = 0;
    int c = 0;
    // Paint the product pictures on the vending machine.
    g.setColor(Color.cyan);
    g.setFont(boldItalicSerif24);
    g.drawString(changeOH.getLogo1(),115,40);
    g.setFont(boldItalicSerif13);
    g.drawString(changeOH.getLogo2(),200,60);
    for (int z=0; z<2; z++)
    {  xVal = 35;
    yVal = 85;
    c = 0;
    g.setColor(Color.black);
    g.fillRect(xVal,yVal,500,350);
    g.setColor(Color.yellow);
    for (int i=0; i<2; i++)
    {  for (int j=0; j<3; j++)
    {  g.setFont(boldSerif16);
    g.drawString(nf.format(productForSale[c].getPrice()),xVal+45,yVal-5);
    pic = getImage(getCodeBase(),productForSale[c].getPic());
    g.drawImage(pic,xVal,yVal,null);
    // If product is dispensed get ready to animate.
    if (c == dispense)
    {  xValAnim = xVal;
    yValAnim = yVal;
    picAnim = pic;
    xVal = xVal + 170;
    c++;
    yVal = yVal + 160;
    xVal = 35;
    // If product is dispensed, animate it.
    if (dispense < 99)
    {  for (int y=0; y<40; y++)
    {  g.setColor(Color.black);
    g.fillRect(xValAnim,yValAnim-9,125,125);
    g.setColor(Color.yellow);
    g.drawImage(picAnim,xValAnim,yValAnim,null);
    yValAnim = yValAnim + 10;
    pause(3);
    dispense = 99;
    if (mode == 0)
    {  pic = getImage(getCodeBase(),"OutStock.gif");
    g.drawImage(pic,300,300,null);
    g.setColor(Color.black);
    g.fillRect(1,1,500,300);
    g.setColor(Color.pink);
    g.setFont(boldItalicSerif40);
    g.drawString(changeOH.getLogo1(),10,150);
    g.setFont(boldItalicSerif24);
    g.drawString(changeOH.getLogo2(),160,250);
    mode++;
    } // =======>> END OF PAINT METHOD
    // ** ACTIONPERFORMED METHOD **
    public void actionPerformed(ActionEvent event)
    {  Object source = event.getSource();
    lMsg.setText(" Enter up to $1.00");
    // Customer puts money in the vending machine.
    // Customer paid a nickle
    if (source == bNickle && $collected < 96)
    {  changeOH.nickleIn();
    $collected = $collected + 5;
    // Customer paid a dime
    if (source == bDime && $collected < 91)
    {  changeOH.dimeIn();
    $collected = $collected + 10;
    // Customer paid a quarter
    if (source == bQuarter && $collected < 76)
    {  changeOH.quarterIn();
    $collected = $collected + 25;
    // Customer paid a paper dollar
    if (source == b$Paper && $collected == 0)
    {  changeOH.dollarPaperIn();
    $collected = $collected + 100;
    // Customer paid a coin dollar
    if (source == b$Coin && $collected == 0)
    {  changeOH.dollarCoinIn();
    $collected = $collected + 100;
    // Customer makes their product selection.
    for (int i=0; i<6; i++)
    {  if (source == selBtn[i])
    // Do nothing if customer selects item that isn't on-hand.
    if (productForSale[i].getOnHand() == 0)
    repaint();
    // We have product on-hand.
    else
    {  prodSel = i;
    // Tell customer to add more money if they don't have
    // enough in the machine to handle the purchase.
    if ($collected < (int) (productForSale[i].getPrice() * 100))
    { lMsg.setText("    Insert Money");
    // Customer has enough money in machine to cover purchase.
    else
    {  // Take cost of item from customer's money
    dbl4 = productForSale[i].getPrice() * 100;
    int4 = changeOH.giveChange($collected - (int)dbl4,0);
    // Tell customer to put exact amount in the machine
    // because there isn't enough change to handle purchase.
    if (int4 == 9)
    {  lMsg.setText("Exact Amount Only!");
    // **** Here the purchase was made and committed. ****
    else
    {  total$In = productForSale[i].getPrice() * 100;
    $collected = $collected - (int) total$In;
    productForSale[i].sellProduct();
    dispense = i;
    repaint();
    // If the last product item was sold, set picture to OutStock.gif.
    if (productForSale[i].getOnHand() <= 0)
    productForSale[i].setOutOfStock();
    if ((source == bChange || source == quit) && $collected > 0)
    {  $collected = changeOH.giveChange($collected,1);
    // Here we save the machine info file when customer asks
    // for their change back or quits the machine.
    // Customer has selected to Quit the vending machine program.
    // Quit the program.
    if (source == quit)
    System.exit(0);
    // These commands set up variables to show how much money
    // the customer has in the machine.
    total$In = $collected;
    total$In = total$In / 100;
    lCredit.setText(" Credit: " + nf.format(total$In));
    repaint();
    } // =======>> END OF ACTIONPERFORMED METHOD
    // ** PAUSE METHOD **
    public void pause(int i)
    {  for(long l = System.currentTimeMillis() + (long) i; System.currentTimeMillis() < l;);
    // =======>> END OF VENDMACH CLASS APPLET
    // ** CASHIN CLASS **
    class CashIn
    {  private String logo1;
    private String logo2;
    private int numProd;
    private int nickles;
    private int dimes;
    private int quarters;
    private int dollarsP;
    private int dollarsC;
    private int money;
    private double moneyVal;
    private int amtToChange = 0;
    private int hNickle;
    private int hDime;
    private int hQuarter;
    private int hpDollar;
    private int hcDollar;
    public CashIn(String l1, String l2, int p, int q, int d, int n, int dP)
    {  logo1    = l1;
    logo2 = l2;
    numProd = p;
    quarters = q;
    dimes = d;
    nickles = n;
    dollarsP = dP;
    dollarsC = 0;
    money = (n * 5) + (d * 10) + (q * 25) + (dP * 100);
    // Get total of money in machine.
    public double getCashIn()
    {  moneyVal = money;
    moneyVal = moneyVal / 100;
    return moneyVal;
    // Get machine record information.
    public String getLogo1()
    {  return logo1;
    public String getLogo2()
    {  return logo2;
    public int getNumProd()
    {  return numProd;
    public int getNickles()
    {  return nickles;
    public int getDimes()
    {  return dimes;
    public int getQuarters()
    {  return quarters;
    public int getDollarPaper()
    {  return dollarsP;
    public int getDollarCoins()
    {  return dollarsC;
    // Money comes into the machine
    public void nickleIn()
    {  nickles++;
    money = money + 05;
    public void dimeIn()
    {  dimes++;
    money = money + 10;
    public void quarterIn()
    {  quarters++;
    money = money + 25;
    public void dollarPaperIn()
    {  dollarsP++;
    money = money + 100;
    public void dollarCoinIn()
    {  dollarsC++;
    money = money + 100;
    // Give the customer their change.
    public int giveChange(int custMoney, int mode)
    {  hNickle   = nickles;
    hDime = dimes;
    hQuarter = quarters;
    hpDollar = dollarsP;
    hcDollar = dollarsC;
    amtToChange = custMoney / 100;
    for (int i=0; i<amtToChange; i++)
    {  // Give change in dollar coin if possible
    if (hcDollar > 0)
    {  hcDollar--;
    custMoney = custMoney - 100;
    // or else give change in paper dollar
    else
    {  if (hpDollar > 0)
    {  hpDollar--;
    custMoney = custMoney - 100;
    amtToChange = custMoney / 25;
    for (int i=0; i<amtToChange; i++)
    {  if (hQuarter > 0)
    {  hQuarter--;
    custMoney = custMoney - 25;
    amtToChange = custMoney / 10;
    for (int i=0; i<amtToChange; i++)
    {  if (hDime > 0)
    {  hDime--;
    custMoney = custMoney - 10;
    amtToChange = custMoney / 5;
    if (amtToChange > hNickle)
    {  mode = 9;
    for (int i=0; i<amtToChange; i++)
    {  hNickle--;
    custMoney = custMoney - 5;
    if (mode == 1)
    {  nickles   = hNickle;
    dimes = hDime;
    quarters = hQuarter;
    dollarsP = hpDollar;
    dollarsC = hcDollar;
    money = money - custMoney;
    if (mode == 9) custMoney = 9;
    return custMoney;
    } // =======>> END OF CASHIN CLASS
    // ** PRODUCT CLASS **
    class Product
    {  private String name;
    private String image;
    private String picUsed;
    private double price;
    private int onHand;
    private int sold;
    private int maint;
    public Product(String n, String i, double p, int o, int s, int m)
    {  name    = n;
    image = i;
    picUsed = i;
    price = p;
    onHand = o;
    sold = s;
    maint = m;
    // Reset picture used when product is out of stock.
    public void setOutOfStock()
    {  picUsed  = "OutStock.gif";
    // Get product information
    public String getName()
    {  return name;
    public String getImage()
    {  return image;
    public String getPic()
    {  return picUsed;
    public double getPrice()
    {  return price;
    public int getOnHand()
    {  return onHand;
    public int getQtySold()
    {  return sold;
    public int getMaintDate()
    {  return maint;
    // Sell one of the product.
    public void sellProduct()
    {  onHand--;
    sold++;
    // Set the product values.
    public void setName(String n)
    {  name = n;
    public void setImage(String i)
    {  image   = i;
    picUsed = i;
    public void setPrice(double p)
    {  price = p;
    public void setOnHand(int o)
    {  onHand = o;
    public void setQtySold(int s)
    {  sold = s;
    public void setMaintDate(int m)
    {  maint = m; }
    this is the text file
    p,Fritos,Images/FritoLay.gif,
    m,$.50,
    p,Dr. Pepper,Images/Dr.Pepper.gif,
    m,$.60,
    p,Pepsi,Images/Pepsi.gif,
    m,$.60,
    p,Coke,Images/CocaCola.gif,
    m,$.60,
    p,Seven-Up,Images/7-Up.gif,
    m,$.60,
    p,Sprite,Images/Sprite.gif,
    m,$.60,
    c,10,20,40,
    i know that the filereader is supposed to read the fields...i guess i just have a weak start on understanding and implementing arrays.

    I write this sample some time ago, you can use it to start a new project
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class CVM extends JFrame 
         JTextField mw = new JTextField("0");     
         JTextField hf = new JTextField("0");     
         JTextField ds = new JTextField("0");     
         JTextField lr = new JTextField("0");     
         JTextField py = new JTextField("0");     
         JTextField tp = new JTextField("0");     
         JTextField ch = new JTextField("0");     
    public CVM()
         super("Chocolate Vending Machine");
         setBounds(0,0,500,400);
         addWindowListener(new WindowAdapter()
         {      public void windowClosing(WindowEvent ev)
                   dispose();
                   System.exit(0);
         JPanel pan = new JPanel();
    //     pan.setLayout(new GridLayout(0,2,4,4));
         JPanel lp = new JPanel();
         lp.setBackground(Color.pink);
         lp.setLayout(new GridLayout(16,2,4,4));
         addButton(lp,"Milky Way    20$",mw);
         addButton(lp,"Hot Fudge    40$",hf);
         addButton(lp,"Dandy Shandy 50$",ds);
         addButton(lp,"Lovers Rock  80$",lr);
         addClearButton(lp);
         lp.add(new JLabel(""));
         lp.add(new JLabel(""));
         addPayButtons(lp);
         addMoneyBack(lp);
         pan.add(lp);
         setContentPane(pan);
         setVisible(true);
    private void addPayButtons(JPanel pan)
         JPanel lp = new JPanel();
         lp.setOpaque(false);
         lp.setLayout(new GridLayout(0,2,4,4));
         JButton b1 = new JButton("Pay 5");
         addPay(b1,5);
         b1.setMargin(new Insets(0,0,0,0));
         JButton b2 = new JButton("Pay 10");
         addPay(b2,10);
         b2.setMargin(new Insets(0,0,0,0));
         lp.add(b1);
         lp.add(b2);
         pan.add(lp);
         lp = new JPanel();
         lp.setOpaque(false);
         lp.setBackground(Color.cyan);
         lp.setLayout(new GridLayout(0,2,4,4));
         JButton b3 = new JButton("Pay 20");
         addPay(b3,20);
         b3.setMargin(new Insets(0,0,0,0));
         JButton b4 = new JButton("Pay 50");
         addPay(b4,50);
         b4.setMargin(new Insets(0,0,0,0));
         lp.add(b3);
         lp.add(b4);
         pan.add(lp);
         pan.add(new JLabel("    Payd"));
         pan.add(py);
    private void addPay(JButton bt, final int i)
         bt.addActionListener(new ActionListener()
         {     public void actionPerformed( ActionEvent e )
                   int n = Integer.parseInt(py.getText())+i;
                   py.setText(""+n);
                   calculate();
    private void addButton(JPanel pan, String s, final JTextField jt)
         JButton    bt = new JButton(s);
         bt.setHorizontalAlignment(SwingConstants.LEFT);
         bt.setMargin(new Insets(0,0,0,0));
         pan.add(bt);
         bt.addActionListener(new ActionListener()
         {     public void actionPerformed( ActionEvent e )
                   int i = Integer.parseInt(jt.getText())+1;
                   jt.setText(""+i);
                   calculate();
         jt.setHorizontalAlignment(SwingConstants.CENTER );
         jt.setEditable(false);
         jt.setBackground(Color.white);
         pan.add(jt);
    private void calculate()
         int nwi = Integer.parseInt(mw.getText()) * 20;       
         int hfi = Integer.parseInt(hf.getText()) * 40;  
         int dsi = Integer.parseInt(ds.getText()) * 50;  
         int lri = Integer.parseInt(lr.getText()) * 80;  
         int t   = nwi+hfi+dsi+lri;
         if (t >= 100) t = t - (t/10);
         tp.setText(""+t);
         int n = Integer.parseInt(py.getText());
         int c = n-t;
         ch.setText(""+c);
    private void addClearButton(JPanel pan)
         pan.add(new JLabel("    To pay"));
         pan.add(tp);     
         JButton    bt = new JButton("Clear");
         bt.setHorizontalAlignment(SwingConstants.CENTER);
         bt.setMargin(new Insets(0,0,0,0));
         pan.add(bt);
         bt.addActionListener(new ActionListener()
         {     public void actionPerformed( ActionEvent e )
                   mw.setText("0");       
                   hf.setText("0");  
                   ds.setText("0");  
                   lr.setText("0");  
                   tp.setText("0");  
         pan.add(new JLabel(""));
    private void addMoneyBack(JPanel pan)
         JButton    bt = new JButton("Money back");
         bt.setHorizontalAlignment(SwingConstants.CENTER);
         bt.setMargin(new Insets(0,0,0,0));
         pan.add(bt);
         bt.addActionListener(new ActionListener()
         {     public void actionPerformed( ActionEvent e )
                   py.setText("0");
                   ch.setText("0");
         pan.add(new JLabel(""));
         pan.add(new JLabel("    Change"));
         pan.add(ch);     
    public static void main( String[] args)
         new CVM();
    }Noah

  • Problem with drawLine and GridLayout Manager

    Hi
    I am writing a piece of software that lets you design a local area network. Currently I have a JPanel with a GridLayout of 10 squares by 10 squares. Each of these grid spaces is filled with a small custom component that is blank if empty or displaying the relevant graphic to the user if a node has been placed. The difficulty that I am having is that I want to be able to draw a section of cable between nodes. As an example, when the user places a Server and a client, I want them to be able to hold down SHIFT, select the two nodes, then press a key (probably 'c') to automatically generate a run of cable between the two nodes. The software achieves this by getting the co-ordinates of the center point of the two nodes and drawing a line between them using the graphics class drawLine() method. I have all of this working fine apart from the bit where the cable needs to be drawn. The reason is that I can only create a section of cable by creating a new component and then using g.drawLine(). Fair enough. However, I can only draw within the small grid section designated by the GridLayout manager in the JPanel. What I am asking is how would I go about getting the software to draw a line between two relative co-ordinates on the screen, disregarding any positioning that the GridLayout manager tries to impose. To put it another way, how would I go about getting the software to draw a line between two absolutety specified co-ordinates, as opposed to relative co-ordinates currently being used? Any help would be greatly appeciated, thanks

    Here's a way to draw lines between component centers irrespective of layouts.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    public class GridDrawing
        public static void main(String[] args)
            JLabel[] labels = new JLabel[100];
            JPanel loPanel = new JPanel(new GridLayout(0,10));
            for(int j = 0; j < labels.length; j++)
                labels[j] = new JLabel(String.valueOf(j + 1), JLabel.CENTER);
                labels[j].setBorder(BorderFactory.createEtchedBorder());
                loPanel.add(labels[j]);
            OverdrawPanel overdrawPanel = new OverdrawPanel();
            CableSelector selector = new CableSelector(overdrawPanel, loPanel);
            JPanel panel = new JPanel();
            OverlayLayout overlay = new OverlayLayout(panel);
            panel.add(overdrawPanel);
            panel.setLayout(overlay);
            panel.add(loPanel);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(panel);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class OverdrawPanel extends JPanel
        List cableList;
        public OverdrawPanel()
            cableList = new ArrayList();
            setOpaque(false);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.red);
            for(int j = 0; j < cableList.size(); j++)
                g2.draw((Line2D)cableList.get(j));
        public void addCable(Point2D p1, Point2D p2)
            Line2D line = new Line2D.Double(p1, p2);
            cableList.add(line);
            repaint();
        public void register(CableSelector cs)
            addMouseListener(cs);
    class CableSelector extends MouseAdapter
        OverdrawPanel overdrawPanel;
        JPanel loPanel;
        boolean firstPointSet;
        Point2D firstPoint;
        public CableSelector(OverdrawPanel op, JPanel lp)
            overdrawPanel = op;
            loPanel = lp;
            firstPointSet = false;
            overdrawPanel.register(this);
        public void mousePressed(MouseEvent e)
            Point p = e.getPoint();
            Component[] c = loPanel.getComponents();
            Rectangle r;
            for(int j = 0; j < c.length; j++)
                r = c[j].getBounds();
                if(r.contains(p))
                    if(!firstPointSet)
                        firstPoint = new Point2D.Double(r.getCenterX(), r.getCenterY());
                        firstPointSet = true;
                    else
                        Point2D p2 = new Point2D.Double(r.getCenterX(), r.getCenterY());
                        overdrawPanel.addCable(firstPoint, p2);
                        firstPointSet = false;
    }

  • How do I stretch a JButtonImage to use the whole cell in a GridLayout?

    Hi,
    I have a problem that is similar to what Edilmar_Alves had when posting the thread "I don't get to stretch an image in a JButton" in February 2009, though this is a bit different so I'm posting it in a new thread.
    I also want to put an image in a JButton (or similar) in such a way that the image covers the whole area of the JButton. I've downloaded the SubMacroForms package and I'm trying to use a JButtonImage, where I set the size of it to exactly the size of the image I use.
    It works if I just put the button in a JPanel using FlowLayout, but that's not what I really want. I need a 2 dimensional array of JButtonImages, since they will form the board of a game.Therefore I'm using a JPanel with GridLayout, to put the buttons in.
    The problem is that when the JButtonImage buttons are added to the cells of the GridLayout, they don't cover the whole area of the cells (there's space at the top and at the bottom). What can I do about this? It's absolutely crucial that I fix this problem, because I can't have any space between the buttons (e.g. the images on them) since they will be forming something similar to a chess board.
    Should I use some other layout or try to make my own Layout manager perhaps?
    Any kind of help would be greatly appreciated!
    Let me know if I should add any code.

    If you want to fill the component (JButton/JLabel/and AbstractButton subclass/any third party component that supports setIcon/getWidth/getHeight) IMO the easiest way is to subclass ImageIcon and override paintIcon to do what you want.public class StretchIcon extends ImageIcon {
      public StretchIcon(Image image) {
        super(image);
      // other constructor/s as desired that call into the corresponding ImageIcon constructor
      public void paintIcon(Component c, Graphics g, int x, int y) {
        if(imageObserver == null) {
          g.drawImage(image, 0, 0, c.getWidth(), c.getHeight(), c);
        } else {
          g.drawImage(image, 0, 0, c.getWidth(), c.getHeight(), imageObserver);
    }Alternatively you could write a class that implements Icon and wraps a ImageIcon.public class StretchIcon implements Icon {
      private ImageIcon icon;
      public StretchIcon(ImageIcon icon) {
        this.icon = icon;
      public void paintIcon(Component c, Graphics g, int x, int y) {
        if(icon.getImageObserver() == null) {
          g.drawImage(icon.getImage(), 0, 0, c.getWidth(), c.getHeight(), c);
        } else {
          g.drawImage(icon.getImage(), 0, 0, c.getWidth(), c.getHeight(), icon.getImageObserver());
      public int getIconWidth() {
        return icon.getIconWidth();
      public int getIconHeight() {
        return icon.getIconHeight();
    Note: All code typed here, may contain typos or otherwise need debugging.
    Depending on the layout in which this is to be used, you may want to return something else for the width and height.
    db

  • Displaying custom drawn panels in a panel with FlowLayout vs GridLayout

    I am having trouble to display my custom panels(on which I have drawn) in another panel with FlowLayout. When I use this layout only a small part of their top-left corner appears, when using the GridLayout they are displayed as should, all. Why is this? Is there any way around it?
    The following is the code:
    package diagramillustrator;
    import java.awt.*;
    import java.util.Vector;
    import javax.swing.*;
    public class ClassDiagram extends JPanel
        //fields
        //<editor-fold>
        //general info
        public String title = "class";
        public String name;
        public Vector interfaces;
        public Vector exceptions;
        public String superclass;
        public Vector subClasses;
        public boolean superClass;
        public boolean subClass;
        public String dPackage;
        public String dExtends;
        //variables
        public FieldStructure field;
        //methods
        public MethodStructure constructor;
        public MethodStructure metho;
        //</editor-fold>
        /** Creates a new instance of ClassDiagram */
        public ClassDiagram()
            super();
            super.setSize(132,75);
        protected void paintComponent(Graphics g)
           setBackground(Color.WHITE);
           Graphics2D g2d = (Graphics2D) g;
           super.paintComponent(g2d);
           g2d.setStroke(new BasicStroke(2f));
           g2d.drawRect(1,1,132,25);
           g2d.setFont(new Font("arial", Font.BOLD, 12));
           g2d.drawString(title, 4,18);
           g2d.setColor(Color.LIGHT_GRAY);
           g2d.fillRect(1,25,132,25);
           g2d.setColor(Color.BLACK);
           g2d.drawRect(1,25,132,25);
           g2d.setColor(Color.WHITE);
           g2d.fillRect(1,51,132,25);
           g2d.setColor(Color.BLACK);
           g2d.drawRect(1,50,132,25);
        public static void main(String[] args)
            JFrame f = new JFrame("Testing ClassDiagram");
            f.setSize(500,400);
            //layout shows it correctly
            JPanel panel1 = new JPanel(new GridLayout());
            //layout shows it incorrectly
            //JPanel panel1 = new JPanel(new FlowLayout());
            panel1.setSize(200,200);
            ClassDiagram c1 = new ClassDiagram();
            ClassDiagram c2 = new ClassDiagram();
            ClassDiagram c3 = new ClassDiagram();
            panel1.add(c1);
            panel1.add(c2);
            panel1.add(c3);
            f.add(panel1);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.show();
    }Here is the main method included in the class(the main method is used for testing here) where the adding etc is done.
    public static void main(String[] args)
            JFrame f = new JFrame("Testing ClassDiagram");
            f.setSize(500,400);
            //layout shows it correctly
            JPanel panel1 = new JPanel(new GridLayout());
            //layout shows it incorrectly
            //JPanel panel1 = new JPanel(new FlowLayout());
            panel1.setSize(200,200);
            ClassDiagram c1 = new ClassDiagram();
            ClassDiagram c2 = new ClassDiagram();
            ClassDiagram c3 = new ClassDiagram();
            panel1.add(c1);
            panel1.add(c2);
            panel1.add(c3);
            f.add(panel1);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.show();
        }Please help.
    Thanks,
    AndXer

    Layout managers.
    JPanel panel1 = new JPanel(new GridLayout());GridLayout divides the availabale space into equal cells and expands each child component to fill the cell.
    JPanel panel1 = new JPanel(new FlowLayout());FlowLayout attempts to show each child component at its preferred size. The preferredSize is determined by the layout manager in the process of laying out the children. For a graphic component, ie, a component with no child components, the request for the components preferredSize will return the default size which is 10,10 for JPanel. Therefore you will need to either set the preferredSize for the gtaphic component or override the getPreferredSize method and return the desired Dimension. Another limitation of FlowLayout is that it attempts to lay its children out in&#8211;line.
    GridBagLayout also respects the preferredSize of child components and offers more versatility.
    import java.awt.*;
    import javax.swing.*;
    public class CD extends JPanel
        public String title = "class";
        public CD()
            super();
            setPreferredSize(new Dimension(132,75));
            setBackground(Color.WHITE);
        protected void paintComponent(Graphics g)
            Graphics2D g2d = (Graphics2D) g;
            super.paintComponent(g2d);
            g2d.setStroke(new BasicStroke(2f));
            g2d.drawRect(1,1,130,25);
            g2d.setFont(new Font("arial", Font.BOLD, 12));
            g2d.drawString(title, 4,18);
            g2d.setColor(Color.LIGHT_GRAY);
            g2d.fillRect(1,25,130,25);
            g2d.setColor(Color.BLACK);
            g2d.drawRect(1,25,130,25);
            g2d.setColor(Color.WHITE);
            g2d.fillRect(1,51,130,25);
            g2d.setColor(Color.BLACK);
            g2d.drawRect(1,50,130,25);
        public static void main(String[] args)
            JPanel panel1 = new JPanel(new GridBagLayout());
            // This has little affect until after realization and
            // is then subject to its parent layout manager. Use
            // the preferredSize for better results.
            //panel1.setSize(200,200);
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(5,5,5,5);
            gbc.weightx = 1.0;
            gbc.weighty = 1.0;
            // Add some components
            int n = 5;
            // and specify columns
            int cols = 3;
            for(int j = 0; j < n; j++) {
                gbc.gridwidth = ((j+1) % cols == 0) ? GridBagConstraints.REMAINDER
                                                    : 1;
                panel1.add(new CD(), gbc);
            JFrame f = new JFrame("Testing ClassDiagram");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(panel1);
            f.setSize(500,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Can't get JLayeredPane to work

    Hi,
    I'm trying to use the JLayeredPane as part of a large application, but I can't get a small example to work... What else do I need to set before I can see my JLabel?
    package views;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JLayeredPane;
    public class Test extends JFrame {
          * @param args
         public static void main(String[] args) {
              new Test();
         public Test()
              super("Test");
              this.setVisible(true);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.setSize(new Dimension(200, 200));
              JLayeredPane pane = (JLayeredPane) this.add(new JLayeredPane());
              pane.add(new JLabel("Hello World"), new Integer(0));
              this.add(pane);
    }Edited by: TheDauntless on Oct 24, 2009 12:55 PM

    TheDauntless wrote:
    Thanks, that seems to work. You're welcome.
    I have a follow up question: How can I get my JLabel to take up the entire parents width & height?
    I usually use a GridBagLayout (with fill=horizontal, weightx=1, heightx=1, gridx=0, gridy=0), but I can't always get it to work. Is there a better way to make sure the size is 100%x100% ?I know that I use GridBagLayout, but only sparingly and only when other layouts (including nested layouts) won't work. I think that there are several in this same camp. In your situation, you could easily just use a BorderLayout and add the JLabel BorderLayout.CENTER.

Maybe you are looking for

  • Issue in MC.1

    Hello, In our system when the standard report MC.1 is run with drilldown as material, the last goods issue and last goods receipt fields for some materials are either blank or showing dates from 2003 / 2004. These are all rolling materials with many

  • Oracle 8i for Win98

    I have installed Oracle 8i successfully and now I need to create multiple databases. I have tried unsuccessfully to create additional databases in the default ORACLE_HOME. Can you do this or do I have to create another ORACLE_HOME for each database I

  • Which sql can get pl/sql's version?

    Hi, how to get PL/SQL's version? such as 2.1, 2.2, 2.3 or later. v$version can not tell me the acurate version. SQL> select * from v$version; BANNER Oracle9i Release 9.2.0.6.0 - 64bit Production PL/SQL Release 9.2.0.6.0 - ProductionThanks

  • CS4 accidental file deletion, programs won't start

    Due to Avast antivirus putting up a popup I didn't expect during email deletions, I accidentally deleted 1, maybe 2 files, and now can't boot most of my CS4 programs on Windows 7. The 64 bit version of Photoshop opens, stored in "program files", but

  • Did the Premiere CC update not work?

    I'm still unable to view my DNG files. What is the problem?