JLabel do not Appear On JPanel

Help! PPl I am upto my eyes in this problem and I cannot solve it.
I have a JFrame with BorderLayout on which I have 2 JPanels.The JPanel on the SOUTH of borderLayout is called secPanel and the one at the CENTER is called newPanel.
On newPanel I am basically trying to make a lot of squares appear some should be whit and some black which is based on a random calculation. I have put in a lot of time on this and it worked on the first go and now it does not seem to work after I changed some code which I cannot recall what I did wrong. Now all the calculcations work out fine and everything only the squares which are really JLabels with a single space character in them are not displayed . The main file proj.java and the file that contains class aSquare are give below can someone please have a look and tell me how can I do it RIGHT! PLEASE
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class proj
     public static void main(String args[])
          JFrame aFrame= new JFrame("This is a Test");
          aFrame.addWindowListener(new WindowAdapter()
          {public void windowClosing(WindowEvent e)
          {System.exit(0);
          aFrame.setSize(700,700);
          Container c = aFrame.getContentPane();
          //c.setBackground(Color.blue);
          JPanel secPanel = new JPanel();
          secPanel.setLayout(new GridLayout(1,3));
          secPanel.setBackground(Color.gray);
          secPanel.setOpaque(false);
          secPanel.setBorder(BorderFactory.createEtchedBorder());
          JButton first, second, third;
          first= new JButton("Initialise New Maze");
          second = new JButton("Random New Genes");
          third = new JButton("Run Halt Genes");
          secPanel.add(first);
          secPanel.add(second);
          secPanel.add(third);
          JPanel newPanel = new JPanel();
          newPanel.setLayout(null);
          newPanel.setOpaque(true);
          newPanel.setBorder(BorderFactory.createEtchedBorder());
          newPanel.setVisible(true);
          aSquare squares[][] = new aSquare[40][40];
          int xPos=5;
          int yPos=5;
          for(int i=0; i<40; i++)
               yPos= yPos+10;
               xPos=5;
               for(int j=0; j<40;j++)
                    xPos= xPos+10;
                    squares[i][j] = new aSquare(i,j);
                    if (nZrandom()%nZrandom()== 0 && nZrandom()%nZrandom() == 0)
                         squares[i][j].changeColor(Color.black);
                         System.out.println("MAde Black"+i+" "+j);
                    squares[i][j].setBounds(xPos, yPos,10,10);
                    System.out.println(xPos+" "+yPos);
                    newPanel.add(squares[i][j]);
               }//end for j
          }//end for i
          newPanel.setOpaque(false);
          c.add(newPanel,BorderLayout.CENTER);
          c.add(secPanel,BorderLayout.SOUTH);
          aFrame.setVisible(true);
          aFrame.show();
     }//end main
     public static int nZrandom()
          int randno =(int)(Math.random()*10);
          while (true)
               if (randno != 0)
                    return randno;
               }else
                    randno = (int)(Math.random()*10);
               }//end if
          }//end while
     }//end nZrandom
}//end class proj
CLASS aSquare
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class aSquare extends JLabel implements MouseListener
     private int x, y;
     private boolean wall, beenThere;
     public aSquare(int a,int b)
          super(" ");
          this.setOpaque(true);
          this.setBackground(Color.white);
          this.setToolTipText(String.valueOf(a)+","+String.valueOf(b));
          this.setVisible(true);
          this.addMouseListener(new MouseAdapter()
               public void mousePressed(MouseEvent e)
                    if (((JLabel)e.getSource()).getBackground().equals(Color.black))
                         ((JLabel)e.getSource()).setBackground(Color.white);
                    System.out.println("You are on the Label");
                    }else
                         ((JLabel)e.getSource()).setBackground(Color.white);
                         System.out.println("You are on the Label");
                    }//end if
          int x=a;
          int y=b;
          wall= false;
          beenThere= false;
     }//end constructor;
     public void changeColor(Color change)
          this.setBackground(change);
          if (change.equals(Color.cyan))
               this.setBeenThere(true);
          if(change.equals(Color.black))
               this.setWall(true);
     }//end changeColor
     public void mousePressed(MouseEvent me)
     public void mouseClicked(MouseEvent me)
     public void mouseReleased(MouseEvent me){}
     public void mouseEntered(MouseEvent me){}
     public void mouseExited(MouseEvent me){}
     public int getX()
     return this.x;
     public int getY()
     return this.y;
     public boolean getBeenThere()
     return this.beenThere;
     public void setBeenThere(boolean beenThere)
     this.beenThere = beenThere;
     public boolean getWall()
     return this.wall;
     public void setWall(boolean wall)
     this.wall = wall;
}//end class aSquare

There seems to be some problem in getting the label to display at the proper location on the JPanel cos I just wrote short code in which I pasted a JLabel and one instance of my class aSquare here renamed to Alab .
the label get displayed at the proper location but the instance of class Alab does not . I went through the code line by line but I cannot understand it at all.. U have been very kind and patient.. can u gimme a hand with this one...
thanks again..
here is the small code
//code
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class LabelTry
     public static void main(String args[])
          JFrame aFrame= new JFrame("This is a Test");
          aFrame.addWindowListener(new WindowAdapter()
          {public void windowClosing(WindowEvent e)
          {System.exit(0);
          aFrame.setSize(500,500);
          Container c = aFrame.getContentPane();
          JPanel secPanel = new JPanel();
          secPanel.setLayout(null);
          secPanel.setBackground(Color.gray);
          secPanel.setOpaque(true);
          secPanel.setBorder(BorderFactory.createEtchedBorder());
          JLabel aLabel = new JLabel(" ");
          aLabel.setBounds(200,200,10,10);
          aLabel.setBackground(Color.black);
          aLabel.setOpaque(true);
          aLabel.setVisible(true);
          Alab bLabel = new Alab(1,2);
          bLabel.setBounds(200,200,10,10);
          bLabel.setBackground(Color.black);
          bLabel.setOpaque(true);
          bLabel.setVisible(true);
          secPanel.add(aLabel);
          secPanel.add(bLabel);
          c.add(secPanel, BorderLayout.CENTER);
          aFrame.setVisible(true);
     }//end main
}//end class LabelTry
CLASS ALAB //WHICH IS NOTHING BUT class aSquare
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class Alab extends JLabel implements MouseListener
     private int x, y;
     private boolean wall, beenThere;
     public Alab(int a,int b)
          super(" ");
          this.setOpaque(true);
          this.setBackground(Color.white);
          this.setToolTipText(String.valueOf(a)+","+String.valueOf(b));
          this.setVisible(true);
          this.addMouseListener(new MouseAdapter()
               public void mousePressed(MouseEvent e)
                    if (((JLabel)e.getSource()).getBackground().equals(Color.black))
                         ((JLabel)e.getSource()).setBackground(Color.white);
                    System.out.println("You are on the Label");
                    }else
                         ((JLabel)e.getSource()).setBackground(Color.white);
                         System.out.println("You are on the Label");
                    }//end if
          int x=a;
          int y=b;
          wall= false;
          beenThere= false;
     }//end constructor;
     public void changeColor(Color change)
          this.setBackground(change);
          if (change.equals(Color.cyan))
               this.setBeenThere(true);
          if(change.equals(Color.black))
               this.setWall(true);
     }//end changeColor
     public void mousePressed(MouseEvent me)
     public void mouseClicked(MouseEvent me)
     public void mouseReleased(MouseEvent me){}
     public void mouseEntered(MouseEvent me){}
     public void mouseExited(MouseEvent me){}
     public int getX()
     return this.x;
     public int getY()
     return this.y;
     public boolean getBeenThere()
     return this.beenThere;
     public void setBeenThere(boolean beenThere)
     this.beenThere = beenThere;
     public boolean getWall()
     return this.wall;
     public void setWall(boolean wall)
     this.wall = wall;
}//end class aSquare

Similar Messages

  • Jlist not appearing in jpanel

    I'm just messing around trying to get a JList to show work, but it won't show up. I've been going off the JList tutorial at http://java.sun.com/docs/books/tutorial/uiswing/components/list.html
    but I don't know what I'm doing wrong.
         private class FileListPanel extends JPanel{
              public FileListPanel(){
                   String[] arr = {";laskdfj","asdf"};
                   JList fileList = new JList(arr);
                   add(fileList);
                   fileList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
                   fileList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
                   fileList.setVisible(true);
                   fileList.setVisibleRowCount(-1);
                   fileList.setSelectedIndex(1);
                   JScrollPane listScroller = new JScrollPane(fileList);
                   listScroller.setPreferredSize(new Dimension(100,100));
                   listScroller.setAlignmentX(LEFT_ALIGNMENT);
         }and I'm calling that from the constructor for the class using
    Container gcp = getContentPane();
    gcp.setLayout(new BorderLayout());
    gcp.add(new FileListPanel(), BorderLayout.CENTER);
    ...

    In situations like this, you're shooting yourself in the foot if you don't post a SSCCE. Demo:
    import java.awt.*;
    import javax.swing.*;
    public class JListExample {
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable(){
                public void run() {
                    launch();
        static void launch() {
            String[] data = {"aaa","bbb","ccc","ddd","eee",
                "fff","ggg","hhh","iii","jjj"};
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(new JScrollPane(new JList(data)));
            f.setSize(100,100);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }And in the future, please post Swing questions to the Swing forum.

  • ScrollBars are not appearing on my JScrollPane

    I have a JPanel which I add a JScrollPane to -
    controlPanel = new JPanel();
    controlPanel.setPreferredSize(new Dimension(900, 100));
    JScrollPane cpScroll = new JScrollPane(controlPanel);I have added this JScrollPane to my Frame -
    frame.add(cpScroll, BorderLayout.SOUTH);I add a few JLabels to my Jpanel and increase the height of my JPanel as I add labels.
    The problem I am having is that the scroll pane is not appearing even if I make the height of the panel huge. However the strange thing is that it will appear if I make the Panel very wide.
    Does anyone know what could be causing the problem or how I could solve it. Thanks.

    compare yours to this, see if there's anything different
    import javax.swing.*;
    import java.awt.*;
    class Testing extends JFrame
      public Testing()
        setLocation(400,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel controlPanel = new JPanel(new GridLayout(10,1));
        for(int x = 0; x < 10; x++) controlPanel.add(new JLabel(""+x));
        controlPanel.setPreferredSize(new Dimension(400, 300));
        JScrollPane cpScroll = new JScrollPane(controlPanel);
        cpScroll.setPreferredSize(new Dimension(300, 150));
        getContentPane().add(cpScroll, BorderLayout.SOUTH);
        pack();
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • Buttons not  appearing (setVisible used)

    I have four buttons.
    This is what i want:
    1)At the begining run=debug=visible
    next=exit2=not visible
    2)When i click debug run=debug=invisible
    next=exit2=visible
    But it's not doing (2)correctly.
    instead it does debug run=debug=invisible
    next and exit2 do not appear.
    Any idea why?
    Here is the code:
    public class PC extends JApplet
    { public void init()
      { Executionionhandler a=new Executionionhandler();
        run=new JButton("Run");
        run.setEnabled(false);
        run.setMinimumSize(new Dimension(110,40));
        run.setPreferredSize(new Dimension(110,40));
        run.setMaximumSize(new Dimension(110,40));
        run.addActionListener(a);
        Debughandler b=new Debughandler();
        debug=new JButton("Debug");
        debug.setMinimumSize(new Dimension(100,40));
        debug.setPreferredSize(new Dimension(100,40));
        debug.setMaximumSize(new Dimension(100,40));
        debug.addActionListener(b);
        Right2=new JPanel();
        Right2.setBackground(Color.cyan);
        Right2.setMinimumSize(new Dimension(395,40));
        Right2.setPreferredSize(new Dimension(395,40));
        Right2.setMaximumSize(new Dimension(395,40));
        Right2.setLayout(new BoxLayout(Right2,BoxLayout.X_AXIS));
        Right2.add(run);
        Right2.add(debug);
        Nexthandler Ne=new Nexthandler();
        next=new JButton("NEXT");
        next.setVisible(false);
        next.addActionListener(Ne);
        Exithandler2 EX2=new Exithandler2();
        exit2=new JButton("EXIT DEBUG");
        exit2.setVisible(false);
        exit2.addActionListener(EX2);
        Right3=new JPanel();
        Right3.setBackground(Color.cyan);
        Right3.setMinimumSize(new Dimension(210,40));
        Right3.setPreferredSize(new Dimension(210,40));
        Right3.setMaximumSize(new Dimension(210,40));
        Right3.setLayout(new FlowLayout());
        Right3.add(next);
        Right3.add(exit2);
      private class Debughandler implements ActionListener
      { public void actionPerformed(ActionEvent event)
        { next.setVisible(true);
          exit2.setVisible(true);
          run.setVisible(false);
          debug.setVisible(false);
          boolean check2=false;
          for(int i=0;i<MemorySize&& check2==false ;i++)
          { if(MemoryContent.getText().length()>0)
    { start2=i;
    check2=true;
    private class Exithandler2 implements ActionListener
    { public void actionPerformed(ActionEvent event)
    { next.setVisible(false);
    exit2.setVisible(false);
    run.setVisible(true);
    debug.setVisible(true);

    Here they are
    import javax.swing.*;
    //import javax.swing.table.AbstractTableModel;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    //import javax.swing.JTable;
    //import javax.swing.table.TableColumn;
    //import javax.swing.DefaultCellEditor;
    //import javax.swing.table.TableCellRenderer;
    //import javax.swing.table.DefaultTableCellRenderer;
    //import javax.swing.JScrollPane;
    //import javax.swing.JComboBox;
    //import javax.swing.JFrame;
    //import javax.swing.SwingUtilities;
    //import javax.swing.JOptionPane;
    public class PC extends JApplet
    { private int MemorySize=100,km,Limit,copy92,m,start1,start2;
      private boolean Stop=false;
      private JTextField MemoryContent[];
      private JLabel MemoryAddress[],MemoryAdd1,MemoryAdd2,calculator1,calculator2;
      private JPanel Memory1,Memory2,Memory3,Memory,Right,Right1,Right2,
              Right3,mainpane;
      private JScrollPane scrollPane1;
      private JButton load,save,clear,exit,run,debug,next,exit2;
      private File fileName;
      public void init()
      { Executionionhandler a=new Executionionhandler();
        run=new JButton("Run");
        run.setEnabled(false);
        run.setMinimumSize(new Dimension(110,40));
        run.setPreferredSize(new Dimension(110,40));
        run.setMaximumSize(new Dimension(110,40));
        run.addActionListener(a);
        Debughandler b=new Debughandler();
        debug=new JButton("Debug");
        debug.setMinimumSize(new Dimension(100,40));
        debug.setPreferredSize(new Dimension(100,40));
        debug.setMaximumSize(new Dimension(100,40));
        debug.addActionListener(b);
        Right2=new JPanel();
        Right2.setBackground(Color.cyan);
        Right2.setMinimumSize(new Dimension(395,40));
        Right2.setPreferredSize(new Dimension(395,40));
        Right2.setMaximumSize(new Dimension(395,40));
        Right2.setLayout(new BoxLayout(Right2,BoxLayout.X_AXIS));
        Right2.add(run);
        Right2.add(debug);
        Nexthandler Ne=new Nexthandler();
        next=new JButton("NEXT");
        next.setVisible(false);
        next.addActionListener(Ne);
        Exithandler2 EX2=new Exithandler2();
        exit2=new JButton("EXIT DEBUG");
        exit2.setVisible(false);
        exit2.addActionListener(EX2);
        Right3=new JPanel();
        Right3.setBackground(Color.cyan);
        Right3.setMinimumSize(new Dimension(210,40));
        Right3.setPreferredSize(new Dimension(210,40));
        Right3.setMaximumSize(new Dimension(210,40));
        Right3.setLayout(new FlowLayout());
        Right3.add(next);
        Right3.add(exit2);
        private class Debughandler implements ActionListener
      { public void actionPerformed(ActionEvent event)
        { next.setVisible(true);
          exit2.setVisible(true);
          run.setVisible(false);
          debug.setVisible(false);
          boolean check2=false;
          for(int i=0;i<MemorySize&& check2==false ;i++)
          { if(MemoryContent.getText().length()>0)
    { start2=i;
    check2=true;
    private class Exithandler2 implements ActionListener
    { public void actionPerformed(ActionEvent event)
    { next.setVisible(false);
    exit2.setVisible(false);
    run.setVisible(true);
    debug.setVisible(true);

  • Problem in panel  - its not appear

    Hi to all;
    Here there is three panels . First Panel has label , when you press it you will go to the second panel . In the second panel there is a boutton when you press it third panel must be appeared but it is not appear .
    why this ? please show me the correct way .
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class TestPro extends JFrame {
        private JPanel panel = new JPanel();
        private JLabel label1;
        private MyMouseListener myMouseListener;
        private TestPanel testPanel;
        public TestPro() {
            myMouseListener = new MyMouseListener();
            testPanel = new TestPanel();
            label1 = new JLabel("Start");
            label1.setFont(new Font("Monospaced", Font.BOLD, 30));
            label1.addMouseListener(myMouseListener);
            panel.add(label1);
            getContentPane().add(panel);
        public static void main(String[] args) {
            TestPro testPro = new TestPro();
            testPro.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            testPro.setResizable(false);
            testPro.setSize(new Dimension(600, 600));
            testPro.setLocationRelativeTo(null);
            testPro.setVisible(true);
        private class MyMouseListener extends MouseAdapter {
            @Override
            public void mouseEntered(MouseEvent e) {
                super.mouseEntered(e);
                label1.setForeground(Color.red);
            @Override
            public void mouseExited(MouseEvent e) {
                super.mouseExited(e);
                label1.setBackground(Color.BLACK);
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                panel.setVisible(false);
                getContentPane().add(testPanel);
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Box;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    class TestPanel extends JPanel {
        private Box box;
        private JLabel label = new JLabel("New Panel");
        private JButton button = new JButton("Go>>>>>");
        private MyactionListener myactionListener;
        private AnotherPanel anotherPanel;
        public TestPanel() {
            myactionListener = new MyactionListener();
            anotherPanel = new AnotherPanel();
            box = Box.createVerticalBox();
            box.add(label);
            button.addActionListener(myactionListener);
            box.add(Box.createVerticalStrut(5));
            box.add(button);
            add(box);
        private class MyactionListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
                anotherPanel.setVisible(true);
                add(anotherPanel);
    import java.awt.Font;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    class AnotherPanel extends JPanel {
        private JLabel label=new JLabel("Another panel");
        public AnotherPanel() {
            label.setFont(new Font("Monospaced", Font.BOLD, 30));
            add(label);
    }Thanks in advance .
    Edited by: 804610 on Oct 22, 2010 6:29 PM

    Thanks for your reply .
    but in class TestPanel i did this :
        private class MyactionListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
                anotherPanel.setVisible(true);
                anotherPanel.revalidate();
                anotherPanel.repaint();
                add(anotherPanel);
        }but also the anotherPanel not appear when i press button . why?
    hint: I want when i press button the TestPanel disappear .
    thanks
    Edited by: 804610 on Oct 22, 2010 7:03 PM

  • Creating a gridlayout of jlabels and jbuttons in a JPanel

    The assignment:
    "Create a JPanel that contains an 8x8 checkerboard. Make all of the red squares JButtons and be sure to add them to the JPanel. Make all of the black squares JLabels and add them to the JPanel. Don't forget, you must use the add method to attach the JPanel to the JApplet's contentPane but that there is no contentPane for a JPanel. Be sure to set up any interfaces to handle the JButtons. Use a GridLayout to position and size each of the components instead of absolute locations and sizes."
    This assignment introduces the JPanel to me for the first time, I have not seen what the JDialog and JFrame are.
    What I have:
    import java.awt.*;
    import javax.swing.*;
    * Class CheckerBoard - write a description of the class here
    * @author (your name)
    * @version (a version number)
    public class CheckerBoard extends JPanel
        JButton redSquare;
        JLabel blackSquare;
         * Called by the browser or applet viewer to inform this JApplet that it
         * has been loaded into the system. It is always called before the first
         * time that the start method is called.
        public void init()
            JPanel p = new JPanel();
            setLayout(new GridLayout(8,8));
            setSize(512,512);
            ImageIcon red = new ImageIcon("GUI-006-RedButton.png");
            ImageIcon black = new ImageIcon("GUI-006-BlackSquare.png");
            blackSquare = new JLabel(black);
            blackSquare.setSize(64,64);
            redSquare = new JButton(red);
            redSquare.setSize(64,64);
            for (int i = 0; i < 64; i++) {
                if ((i % 2) == 1)
                    add(blackSquare);
                else
                   add(redSquare);
            // this is a workaround for a security conflict with some browsers
            // including some versions of Netscape & Internet Explorer which do
            // not allow access to the AWT system event queue which JApplets do
            // on startup to check access. May not be necessary with your browser.
            JRootPane rootPane = this.getRootPane();   
            rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
    }After successfully compiling it when I try to run it there appears to be nothing to run. I've tried messing around with content panes but I'm not sure if I need to add one for this assignment at all.

    Some suggestions:
    1) First and foremost, read about JPanels, JApplets, and JFrames. None of the help you can get here will substitute for your applying yourself towards this, absolutely none, and judging by your code, you have your work cut out for you.
    2) Don't have your JPanel initialize with an init method, that's what Applets and JApplets do. Instead have it initialize with a proper constructor.
    3) I'm wondering if your "workaround" code belongs in the JApplet that contains the JPanel and not in the JPanel. It has nothing to do with the JPanel's mission. For instance, what if you later decide to place this panel into a JFrame?
    4) Avoid "setSize", and if at all possible, use "setPreferredSize" instead. You are working with LayoutManagers who do the size setting. You are best served by suggesting the size to them.
    5) Please ask specific questions. Just dumping your code without a question is considered quite rude here. We are all volunteers. If you want our free advice, you really should be considerate enough to make it easy for us to help you.
    Good luck.
    Edited by: Encephalopathic on Dec 21, 2007 6:14 PM

  • Choice list does not appear

    Hi everyone!
    I have added a choice list to my Applet and it compiled without any kind of erros, but once I view the Applet on appletviewer or on my browser I can't see it.
    I have created a Panel to display the choice list so that it didn't interfere with the other elements of the Applet. I used a setLayout(null) to display it on the position I was expecting it to, but it does not appear anywhere. Would anyone be able to give me a hint on this issue? I would be grateful.
    Regards,
    Saulo

    would be easier if you post your codesnippet, but here's some general info.
    1. get the container: Container contentpane = getContentPane();
    2. create a panel: JPanel panel = new JPanel();
    3. create your elements you actually want to appear (example):
    JLabel label = new JLabel("hello world");
    4. add the label to the panel: panel.add(label); //you can use LayoutManagers for layout
    5. add the panel to the contentpane: contentpane.add(panel);
    6 call setContentPane(contentpane);

  • Button not appearing (obvious fix most likely (no errors))

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    public class ChatClient
      private TextArea output;
      private TextField input;
      private Button sendButton;
      private Button quitButton;
      private JButton button;
      private ImageIcon image;
      private ImageIcon image1;
      private Panel p1;
      private Frame frame;
      private Panel p2;
      public ChatClient()
        output = new TextArea(10,50);
        input = new TextField(50);
        frame = new Frame("Chat Room");
        sendButton = new Button("Send");
        quitButton = new Button("Quit");
        button = new JButton(image);
        image = new ImageIcon("c:/aztecsun.jpg");
        image1 = new ImageIcon("c:/aztecsun.jpg");
        p1 = new Panel();
        p2 = new Panel();
      public void launchFrame()
               button.setContentAreaFilled(false);
               button.setBorderPainted(false);
               button.setFocusPainted(false);
               button.setPressedIcon(image1);
               p1.add(sendButton);
               p1.add(quitButton);
               p2.add(button);
             // Use the Border Layout for the frame
             frame.setLayout(new BorderLayout());
             frame.add(output, BorderLayout.WEST);
             frame.add(input, BorderLayout.SOUTH);
             frame.add(p1, BorderLayout.EAST);
             frame.add(p2, BorderLayout.CENTER);
             // Add the button panel to the center
             frame.pack();
             frame.setVisible(true);
             //frame.addWindowListener(this);
             sendButton.addActionListener(new sendHandler());
             input.addActionListener(new inputHandler());
             button.addActionListener(new azteca());
             quitButton.addActionListener(new ActionListener()
                  public void actionPerformed(ActionEvent ae)
                       System.exit(0);
             frame.addWindowListener(new WindowAdapter()
                  public void windowClosing(WindowEvent we)
                       System.exit(0);
      /*     class windowTerminate implements WindowListener
                public void windowClosing(WindowEvent we)
                     System.exit(0);
                public void windowDeactivated(WindowEvent we)
                public void windowIconified(WindowEvent we)
                public void windowDeiconified(WindowEvent we)
                public void windowActivated(WindowEvent we)
                public void windowOpened(WindowEvent we)
                public void windowClosed(WindowEvent we)
       class azteca implements ActionListener
              public void actionPerformed(ActionEvent ae)
                   if(ae.getSource() == button)
                        String text = input.getText();
                        output.setText(output.getText() + text + "/n");
                        input.setText("");
           public void copyText()
                String text = input.getText();
                output.setText(output.getText() + text + "\n");
                input.setText("");
           class sendHandler implements ActionListener
                public void actionPerformed(ActionEvent ae)
                     copyText();
           class inputHandler implements ActionListener
                public void actionPerformed(ActionEvent ae)
                     copyText();
      public static void main(String[] args)
        ChatClient c = new ChatClient();
        c.launchFrame();
    }I'm practicing with events/buttons with icons and the button is not appearing...
    Yes the image is in the correct directory... (for the obvious fix type of people)...
    But yeah...
    Thanks!

    I know the fix but I do not know how to do it... I haven't added the image button correctly therefore it is not appearing, but I lack the necessary skills to fix the problem.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    public class ChatClient
      private JTextArea output;
      private JTextField input;
      private JButton sendButton;
      private JButton quitButton;
      private JButton button;
      private ImageIcon image;
      private ImageIcon image1;
      private JPanel p1;
      private JFrame frame;
      private JPanel p2;
      public ChatClient()
        output = new JTextArea(10,50);
        input = new JTextField(50);
        frame = new JFrame("Chat Room");
        sendButton = new JButton("Send");
        quitButton = new JButton("Quit");
        button = new JButton(image);
        image = new ImageIcon("c:/aztecsun.jpg");
        image1 = new ImageIcon("c:/aztecsun.jpg");
        p1 = new JPanel();
        p2 = new JPanel();
      public void launchFrame()
               button.setContentAreaFilled(false);
               button.setBorderPainted(false);
               button.setFocusPainted(false);
               button.setPressedIcon(image1);
               p1.add(sendButton);
               p1.add(quitButton);
               p2.add(button);
             // Use the Border Layout for the frame
             frame.setLayout(new BorderLayout());
             frame.add(output, BorderLayout.WEST);
             frame.add(input, BorderLayout.SOUTH);
             frame.add(p1, BorderLayout.EAST);
             frame.add(p2, BorderLayout.CENTER);
             // Add the button panel to the center
             frame.pack();
             frame.setVisible(true);
             //frame.addWindowListener(this);
             sendButton.addActionListener(new sendHandler());
             input.addActionListener(new inputHandler());
             button.addActionListener(new azteca());
             quitButton.addActionListener(new ActionListener()
                  public void actionPerformed(ActionEvent ae)
                       System.exit(0);
             frame.addWindowListener(new WindowAdapter()
                  public void windowClosing(WindowEvent we)
                       System.exit(0);
      /*     class windowTerminate implements WindowListener
                public void windowClosing(WindowEvent we)
                     System.exit(0);
                public void windowDeactivated(WindowEvent we)
                public void windowIconified(WindowEvent we)
                public void windowDeiconified(WindowEvent we)
                public void windowActivated(WindowEvent we)
                public void windowOpened(WindowEvent we)
                public void windowClosed(WindowEvent we)
       class azteca implements ActionListener
              public void actionPerformed(ActionEvent ae)
                   if(ae.getSource() == button)
                        String text = input.getText();
                        output.setText(output.getText() + text + "/n");
                        input.setText("");
           public void copyText()
                String text = input.getText();
                output.setText(output.getText() + text + "\n");
                input.setText("");
           class sendHandler implements ActionListener
                public void actionPerformed(ActionEvent ae)
                     copyText();
           class inputHandler implements ActionListener
                public void actionPerformed(ActionEvent ae)
                     copyText();
      public static void main(String[] args)
        ChatClient c = new ChatClient();
        c.launchFrame();
    }Edited by: Trizi on Mar 25, 2008 11:52 AM

  • Vertical scrollbar does not appear

    Hi all!
    Here is my problem.
    I have a JPanel on a JScrollPane (called: container).
    I have an other class which extends JPanel (called: component).
    I have a JButton which adds a new from component to container on every click. (container's layout is null, and I use the setBounds method on component).
    After every adding I've just set a new height to the container (setSize(container.getWidth(), container.getHeigth()+100)), but vertical scrollBars of JScrollPane does not appear.
    I tried to call the revalidate, repaint methods on the container but it did not work.
    Please help me!

    Which JScrollPane constructor are you using? If you're using one that does not specify scrollbar policy parameters, horizontal and vertical scrollbars only appear if the component's contents are larger than the view. You can of course set a JScrollPane's scollbar policies by calling the appropriate mutator methods: setVerticalScrollBarPolicy and setHorizontalScrollBarPolicy.

  • JComponent not showing in JPanel

    I've tried the add() method but nothing is displayed when I try to add Test to GraphicsTest. How should I be adding it? Can someone show me? I've included the code I'm using.
    This is my way and it's not working. Can someone show me or make me aware of what the problem actually is?
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JPanel;
    public class GraphicsTest extends JPanel
        private Graphics2D g2d;
        private String state;
        private int x, y;
        GraphicsTest()
            Test t = new Test();
            t.setVisible(true);
            add(t);
        @Override
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            g2d = (Graphics2D) g;
            g2d.setColor(Color.BLACK);
            g2d.drawString("STATE: " + state, 5, 15);
            g2d.drawString("Mouse Position: " + x + ", " + y, 5, 30);
            g2d.setColor(Color.red);
            Rectangle2D r2d = new Rectangle2D.Double(x, y, 10, 10);
            g2d.draw(r2d);
            g2d.dispose();
        public void setState(String state) { this.state = state; }
        public String getState() { return state; }
        public void setX(int x) { this.x = x; repaint(); }
        public void setY(int y) { this.y = y; repaint(); }
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JComponent;
    public class Test extends JComponent
        @Override
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(Color.red);
            g2d.drawString("Hello", 50, 50);
            g2d.dispose();
    }

    The object in Test ("hello") is not appearing.
    import java.awt.EventQueue;
    //import java.awt.event.MouseEvent;
    //import java.awt.event.MouseListener;
    //import java.awt.event.MouseMotionListener;
    import javax.swing.JFrame;
    public class MainWindow
        public static void main(String[] args)
            new MainWindow();
        JFrame frame;
        GraphicsTest gt = new GraphicsTest();
        MainWindow()
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    frame = new JFrame("Graphics Practice");
                    frame.setSize(680, 420);
                    frame.setVisible(true);
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    //                gt.addMouseListener(new MouseListener() {
    //                    public void mouseClicked(MouseEvent e) {}
    //                    public void mousePressed(MouseEvent e) {}
    //                    public void mouseReleased(MouseEvent e) {}
    //                    public void mouseEntered(MouseEvent e) {
    //                        gt.setState("Mouse has entered");
    //                    public void mouseExited(MouseEvent e) {
    //                        gt.setState("Mouse has not entered");
    //                gt.addMouseMotionListener(new MouseMotionListener() {
    //                    public void mouseDragged(MouseEvent e) {}
    //                    public void mouseMoved(MouseEvent e) {
    //                        gt.setX(e.getX());
    //                        gt.setY(e.getY());
                    frame.add(gt);
    }

  • JScrollPane is not appeared.

    Hi,
    I want to use JScrollPane.
    However in my program scrollbar is not appeared.
    What is wrong?
    Thanks.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ImageViewFrame extends JFrame {
    public static void main(String[] args) {
         ImageViewFrame frame = new ImageViewFrame();
         frame.show();
    ImageViewFrame() {
         setSize(300, 300);
         addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent evt) {
              System.exit(0);
         JPanel panel = new JPanel();
         panel.setSize(1000, 1000);
         JScrollPane scrollPane = new JScrollPane(panel);
         getContentPane().add(scrollPane, BorderLayout.CENTER);

    I add a line, "panel.setPreferredSize(new Dimension(1000, 1000));"
    It works well.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ImageViewFrame extends JFrame {
    public static void main(String[] args) {
         ImageViewFrame frame = new ImageViewFrame();
         frame.show();
    ImageViewFrame() {
         setSize(300, 300);
         addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent evt) {
              System.exit(0);
         JPanel panel = new JPanel();
         panel.setSize(1000, 1000);
         panel.setPreferredSize(new Dimension(1000, 1000));
         JScrollPane scrollPane = new JScrollPane(panel);
         getContentPane().add(scrollPane, BorderLayout.CENTER);

  • Update of jlabel does not happen when i wait for thread to finish (join())

    gurus please help.
    I have a main application which in actionevent calls a thread, that thread calls parent method to update ths status in jlabel, but when i use thread.join() to wait for process to complete, the jlabel does not get updated, please tell me how can i update the jlabel, i have to wait for thread to finish and during run i need to update the jlabel.
    thanks

    hi camickr and gurus:
    here is the code:
    notice after pressing the Process button, the label is being updated but its not working. I called the processnow() method directly and also by thread, but in thread I have to wait until it finishes using join() but still does not work, please help. Thanks
    package label;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.text.*;
    import javax.swing.border.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class thePanel extends JDialog {
      private DefaultTableModel tableModel = null;
      private JTable theTable = new JTable();
      private JScrollPane scrollPane = new JScrollPane();
    JPanel tPanel = new JPanel();
      private Border mainBorder;
      private BorderLayout borderLayout1 = new BorderLayout();
      private BorderLayout borderLayout2 = new BorderLayout();
      private BorderLayout borderLayout3 = new BorderLayout();
      private BorderLayout borderLayout4 = new BorderLayout();
      private JPanel statusPanel = new JPanel();
      private JPanel buttonPanel = new JPanel();
      private JPanel lowerPanel = new JPanel();
      private JLabel statusBar = new JLabel();
      private JButton processButton = new JButton("Process");
      public JButton closeButton = new JButton("Close");
      boolean image = true;
      theProcess processThread;
      Vector tableData = new Vector();
      ImageIcon Image = new ImageIcon("image.gif");
      ImageIcon oImage= new ImageIcon("oimage.gif");
      boolean errorOcurred=false;
      String statusMessage;
      public thePanel() {
        try {
         jbInit();
        } catch(Exception e) {
          e.printStackTrace();
      private void jbInit() throws Exception {
        tPanel.setPreferredSize(new Dimension(800,424));
        mainBorder = new TitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED)," ");
        statusPanel.setBorder(BorderFactory.createEtchedBorder());
        tPanel.setBorder(mainBorder);
        tPanel.setLayout(borderLayout1);
        scrollPane.getViewport().add(theTable, null);
        tPanel.add(scrollPane,  BorderLayout.CENTER);
        // status
        statusPanel.setLayout(borderLayout2);
        statusPanel.setBorder(BorderFactory.createEmptyBorder());
        statusBar.setAlignmentX((float) 0.5);
        statusBar.setBorder(BorderFactory.createLoweredBevelBorder());
        statusBar.setMaximumSize(new Dimension(600, 21));
        statusBar.setMinimumSize(new Dimension(600, 21));
        statusBar.setPreferredSize(new Dimension(600, 21));
        statusPanel.add(statusBar, BorderLayout.SOUTH);
        // buttons
        processButton.setPreferredSize(new Dimension(70,25));
        processButton.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            process_actionPerformed(e);
        closeButton.setPreferredSize(new Dimension(70,25));
        buttonPanel.setLayout(borderLayout3);
        buttonPanel.setBorder(BorderFactory.createRaisedBevelBorder());
        buttonPanel.add(processButton,BorderLayout.WEST);
        buttonPanel.add(new JPanel());
        buttonPanel.add(closeButton,BorderLayout.EAST);
        // lower panel
        lowerPanel.setLayout(borderLayout4);
        lowerPanel.setBorder(BorderFactory.createEmptyBorder());
        lowerPanel.add(statusPanel, BorderLayout.WEST);
        lowerPanel.add(buttonPanel, BorderLayout.EAST);
        tPanel.add(lowerPanel, BorderLayout.SOUTH);
        theTable.setAutoCreateColumnsFromModel(true);
        theTable.setColumnSelectionAllowed(false);
        theTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        theTable.getTableHeader().setReorderingAllowed(false);
    getContentPane().add(tPanel);pack();
        getinfo();
    show();
      private void prepairTable(){
        tableModel = new DefaultTableModel(){
                          public boolean isCellEditable(int row, int col)
                            { return false; }};
        tableModel.addColumn("text 1");
        tableModel.addColumn("text 2");
        tableModel.addColumn("text 3");
        tableModel.addColumn("text 4");
        tableModel.addColumn("text 5");
        theTable.setModel(tableModel);
      } // end method (prepairTable)
      public void refreshTable() {
        prepairTable();
      public void getinfo() {
        try {
            refreshTable();
            tableModel.addRow(new Object[]{"3465465555","0123456789",new Date(1135022905196L),"0100000","errror message","sssssss"});
            tableModel.addRow(new Object[]{"8949344562","0324354549",new Date(1134511763683L),"0166600","errror mes666e","ddddddd"});
    setStatusMessage("ready to process, select record and click Process button to process record");
          errorOcurred = false;
        } catch (Exception ex) {
          errorOcurred = true;
          ex.printStackTrace();
        } // End try
      private void process_actionPerformed(ActionEvent e) {
        try {
          if(theTable.getSelectedRows().length > 0) {
    //        processThread = null;
    //        processThread = new theProcess(this);
    //        processThread.start();
    processnow();
            System.out.println("........finished now.........");
          } else {
        } catch (Exception ex) {
          ex.printStackTrace();
      public void processnow() {
        try {
          int[] selectedRows = null;
          int totalSelected = 0;
          setStatusMessage("processing " + totalSelected + " selected records...");Thread.sleep(1500);
          selectedRows = theTable.getSelectedRows();
          totalSelected = selectedRows.length;
          for(int i = 0; i < totalSelected ; i++){
            setStatusMessage("processing " + (i+1) + " of " + totalSelected + " selected records...");
            System.out.println(".......................row: "+selectedRows);
    Thread.sleep(2500);
    System.out.println("........fins...........");
    errorOcurred = false;
    } catch (Exception ex) {
    errorOcurred = true;
    ex.printStackTrace();
    } // End try
    public void setStatusMessage(String message) {
    statusMessage=message;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    if(image)
    statusBar.setIcon(Image);
    else
    statusBar.setIcon(oImage);
    statusBar.setText(statusMessage);
    statusBar.update(statusBar.getGraphics());
    public static void main(String[] args){
    new thePanel();
    } // class
    package label;
    import java.lang.Runnable;
    public class theProcess implements Runnable {
    private thePanel parent;
    public theProcess(thePanel xparent){
    parent = xparent;
    } // end constructor
    public void start() {
    try {
    Thread thisThread = new Thread(this);
    thisThread.start();
    thisThread.join();
    } catch(Exception ex) {
    ex.printStackTrace();
    } // end method (start)
    public void run(){
    try {
    parent.processnow();
    } catch (Exception ex){
    ex.printStackTrace();
    } // end try
    } // end method (run)
    } // end class

  • Html page does not appear???

    I am designin a hepl page.I've written the code as follows
    but the html does not appear.Instead the panel holding the
    html is plain white.Why is this so?
    P.S: i am able to view the html in a explorer.
    Font demoFont = new Font("Serif", Font.PLAIN, 14);
        quotePane = null;
        scrollPane3 = null;
        s=null;
           try
        { s="file:\\myjava\\HELP.html";
          URL url = new URL(s);
             quotePane = new JEditorPane(url);
             quotePane.setEditable(false);
          scrollPane3 = new JScrollPane(quotePane);
             scrollPane3.setMinimumSize(new Dimension(390,490));
          scrollPane3.setPreferredSize(new Dimension(390,490));
          scrollPane3.setMaximumSize(new Dimension(390,490));
             if (DEBUG)
          { System.out.println(quotePane.getText());
               quotePane.setText(quotePane.getText());
        catch (java.io.IOException e)
        { scrollPane3 = new JScrollPane(new JTextArea("Can't find HTML file."));
             scrollPane3.setFont(demoFont);
        htmlTextPane = new JPanel();
         htmlTextPane.add(scrollPane3);
            /*htmlTextPane.setBorder(BorderFactory.createCompoundBorder(
                          BorderFactory.createTitledBorder("HTML Text"),
                          BorderFactory.createEmptyBorder(0, 5, 5, 5)
        //helppane=new JPanel();
        //htmlTextPane.setBackground(Color.magenta);
        HelpFrame=new JFrame("Help Index");
        HelpFrame.addWindowListener(new WindowAdapter()
                                 public void windowClosing(WindowEvent e)
                                   HelpFrame.setVisible(false);
        HelpFrame.getContentPane().add(htmlTextPane);
        HelpFrame.pack();
        HelpFrame.setSize(400,500);
        Container c=getContentPane();
        c.add(mainpane);

    More info ...
    Can we see the whole program please.

  • JComboBox - selection down arrow not appearing

    Hi All,
    I am writing a swing application which uses a JComboBox with a Vector<String> as it's constructor arguments. This JComboBox is then added to a JPanel derived class which is in turn added to a JFrame. The JComboBox works fine but the selection down arrow does not appear for some reason.
    So I built a quick test application (in a similar fashion) and the JComboBox also works fine but this time the selection down arrow does appear.
    I can't figure out what I'm doing different. Can anyone tell me the circumstances under which the down arrow will / will not appear in a JComboBox?
    Thanks,
    Dougall

    Hi,
    The reason I had used this approach is that sometime I wish the content pane to hold a JPanel type component (only) and sometimes a JTable type (only). I had (foolishly perhaps) assumed that this would not be possible with a standard layout manager.
    As es5f2000 suggests I shall investigate a CardLayout manager.
    If this does not succeed I shall keep the present system which currently works fine (maybe performance issues?). The bounds and size of the parent container are both work fine so long as I remember to call .validate() on the new component being added to the JFrame.
    The JFrame itself is specifically set to be a fixed non-resizable size, surely this is a case in which although not recommended, it's ok to use absolute positioning?
    Thanks again,
    Dougall

  • I am trying to set up Sharing amongst several computers on my home network.  I have followed all the setup instructions but after completion Sharing does not appear in my iTunes window (on any of the computers I've set up).  There is no explanation why.

    I have been trying to set up Sharing between two computers on my network. I did this once and it worked.  However, when I try to set this up now the Sharing feature does not appear on the left side of the iTunes window (on either computer).  There is no explanation as to why not.  Is this a configuration problem, a network problem or what?   Can it be fixed?  I have tried turning sharing off and back on on both computers but to no avail.  What am I missing?  Thanks for any help you can provide.

    Hey innerev2003,
    Thanks for the question, and welcome to Apple Support Communities.
    If, while searching through your past purchases, items are unavailable to download and show a "Purchased" button, they are still on your computer. It may be best to search your iTunes library by clicking Music, then use the search bar at the top right.
    If you are completely sure the items are no longer in your library, try signing out of the iTunes Store, and then back in.
    iTunes 11 for Windows: Manage your iTunes Store account
    http://support.apple.com/kb/PH12507
    Thanks,
    Matt M.

Maybe you are looking for