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);
}

Similar Messages

  • Components Not Showing In JPanel

    I am trying to make a program that I can give to friends and family to help them keep track of their banking accounts and the such (It's nothing big I'm making, just something to do in my spare time). I've coded all the data classes and such (Transaction, Account, Type, etc) and am now working on the GUI. I've made them before so I created this bit of code. The problem is, whenever I run the program, I only get the frame and JMenuBar. The rest is white space where my JPanel should be. The panel is there, I've tried setting the background color to black and the entire frame follows suit accordingly, but all the objects I've added aren't there? I know I'm missing something painfully obvious, so if anyone out there would help out I would be much obliged.
    * @(#)TFrame.java
    * @author T^&*( W*(%^&$
    * @version 2.00 2009/9/23
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TFrame extends JFrame {
         private Account account;
         public TFrame(Account opened) {
              account = opened;
              setTitle("xxxx-xxxx-xxxx-" + account.getAccountNumber());
              setSize(800,500);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
         // Creates MenuBar
              JMenuBar menuBar = new JMenuBar();
              JMenu file = new JMenu("File");
              file.setMnemonic(KeyEvent.VK_F);
              JMenuItem save = new JMenuItem("Save",KeyEvent.VK_S);
              save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
              file.add(save);
              JMenuItem load = new JMenuItem("Load",KeyEvent.VK_L);
              load.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.ALT_MASK));
              file.add(load);
              JMenuItem print = new JMenuItem("Print",KeyEvent.VK_P);
              print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ActionEvent.ALT_MASK));
              file.add(print);
              file.addSeparator();
              menuBar.add(file);
         // Finishes MenuBar
              setJMenuBar(menuBar);
         // Creates the RadioPanel that switches type
              JPanel radioPanel = new JPanel();
              radioPanel.setLayout(new FlowLayout());
              ButtonGroup bg = new ButtonGroup();
              JRadioButton deposit = new JRadioButton("Deposit");
              deposit.setMnemonic(KeyEvent.VK_D);
              deposit.setActionCommand("Deposit");
              JRadioButton withdraw = new JRadioButton("Withdraw");
              deposit.setMnemonic(KeyEvent.VK_W);
              deposit.setActionCommand("Withdraw");
              JRadioButton all = new JRadioButton("All");
              deposit.setMnemonic(KeyEvent.VK_A);
              deposit.setActionCommand("All");
              bg.add(deposit);
              bg.add(withdraw);
              bg.add(all);
              deposit.addActionListener(TransactionPane.INSTANCE);
              withdraw.addActionListener(TransactionPane.INSTANCE);
              all.addActionListener(TransactionPane.INSTANCE);
         // Finishes the RadioPanel
         // Creates the TransactionPane
              TransactionPane.INSTANCE = new TransactionPane(account);
         // Finishes TransactionPane
         // Creates the ActionPane
              JPanel actionPane = new JPanel();
              actionPane.setLayout(new GridLayout(2,3));
              JButton addButton = new JButton("Add");
              JButton removeButton = new JButton("Remove");
              JButton printButton = new JButton("Print");
              JButton saveButton = new JButton("Save");
              JPanel pages = new JPanel();
                   JButton lastButton = new JButton("<-");
                   JButton nextButton = new JButton("->");
                   pages.setLayout(new GridLayout(1,2));
                   pages.add(lastButton);
                   pages.add(nextButton);
              JButton exitButton = new JButton("Exit");
              actionPane.add(addButton);
              actionPane.add(printButton);
              actionPane.add(pages);
              actionPane.add(removeButton);
              actionPane.add(saveButton);
              actionPane.add(exitButton);
         // Finishes the ActionPane
         // Creates the TPanel
              TPanel tPanel = new TPanel(account);
              tPanel.add(radioPanel, BorderLayout.NORTH);
              tPanel.add(TransactionPane.INSTANCE, BorderLayout.CENTER);
              tPanel.add(actionPane, BorderLayout.SOUTH);
              getContentPane().add(tPanel, BorderLayout.CENTER);
         // Finishes the TPanel
              pack();
              setVisible(true);
    * @(#)TPanel.java
    * @author
    * @version 1.00 2009/9/24
    import java.awt.*;
    import javax.swing.*;
    public class TPanel extends JPanel {
         private Account account;
         public TPanel(Account acc) {
              account = acc;
              setPreferredSize(new Dimension(800,480));
    }

    ok
    Edited by: Caarmel on Sep 25, 2009 1:12 AM

  • The JPanel did not show when the menu is selected

    My program consists a JMenu bar with sub menu items. When the user select on the menu items a panel with the gridbag layout will show with all the labels.but the panel did not show. Can anyone show the problem for me ?
    AdminFrameMain.java
    public class AdminFrameMain
         private DisplayMenuBar menubar;
         private DisplayToolBar toolbar;
         private DisplayStatusBar statusbar;     
         public AdminFrameMain()
              JFrame frame = new JFrame("S-League Administration Management System");
              Toolkit kit = frame.getToolkit();
              Dimension windowsize =kit.getScreenSize();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Container content = frame.getContentPane();
              content.setLayout(new BorderLayout());
              menubar = new DisplayMenuBar(frame,content);
              toolbar = new DisplayToolBar(content);
              statusbar = new DisplayStatusBar(content);
              frame.setSize(800,600);
              frame.setVisible(true);
         public static void main(String [] args){
              AdminFrameMain tm = new AdminFrameMain();
    DisplayMenuBar.java
    public class DisplayMenuBar
         private JMenu addMenu,addTeamMenu;
         private JMenuBar bar = new JMenuBar();
         private JToolBar toolbar = new JToolBar();
         private JMenuItem addTeamItem;
         private JFrame setFrame;
         private Container setContent;
         private AddTeamManagement addTeamMang;
         public DisplayMenuBar(JFrame frame,Container c)
              setFrame = frame;
              setContent = c;
              SetMenuBar();
         public void SetMenuBar()
         setFrame.setJMenuBar(bar);
         addMenu = new JMenu("Add");
         //file menu items list
         //Add sub menu
         addTeamMenu = new JMenu("Team Management");
         addMenu.add(addTeamMenu);
         //Add sub menu items
         addTeamMenu.add(addTeamItem = new JMenuItem("Add Team"));
         addTeamMenu.setMnemonic('T');     
         addTeamItem.setMnemonic('T');
         //team items listener
         //addTeamItem.addActionListener(taskcommand);          
         addTeamItem.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                   AddTeamManagement addTeamMang = new AddTeamManagement(setFrame,setContent);
         bar.add(addMenu);
    AddTeamManagement.java
    public class AddTeamManagement
         private JPanel addTeamPanel;
         private JFrame frame;
         private JButton createTeamBt,resetTeamBt;
         private Container addTeamContent;
         private JTextArea teamDescTextArea,teamIndpTextArea;
         private JTextField teamNameField;
         private JLabel teamID,teamDesc,teamInfo,numOfPlayers,teamZone,playersNum;
         private GridBagLayout gridBag;
         private GridBagConstraints constraints;
         public AddTeamManagement(JFrame f,Container c)
              System.out.println("add team mg");
              addTeamPanel = new JPanel();
              frame = f;
              addTeamContent = c;
              gridBag = new GridBagLayout();
              addTeamPanel.setLayout(gridBag);
              addTeamPanel.setBackground(Color.pink);
              constraints = new GridBagConstraints();
              teamID = new JLabel("Team ID:");
              teamDesc = new JLabel("Team Description:");
              teamInfo = new JLabel("Team Info:");
              numOfPlayers = new JLabel("No Of Players:");
              playersNum = new JLabel("15 Maximun");
              teamZone = new JLabel("Team Zone:");
              constraints.fill = constraints.VERTICAL;
              constraints.weightx = 1;
              constraints.weighty = 0;
              addComponent(teamID,0,0,1,1);
              constraints.fill = constraints.VERTICAL;
              constraints.weightx = 1;
              constraints.weighty = 0;
              addComponent(teamDesc,1,0,1,1);
              constraints.fill = constraints.VERTICAL;
              constraints.weightx = 1;
              constraints.weighty = 0;
              addComponent(teamInfo,2,0,1,1);
              constraints.fill = constraints.VERTICAL;
              constraints.weightx = 1;
              constraints.weighty = 0;
              addComponent(numOfPlayers,3,0,1,1);
              constraints.fill = constraints.VERTICAL;
              constraints.weightx = 1;
              constraints.weighty = 0;
              addComponent(teamZone,4,0,1,1);
              System.out.println("showing");
              addTeamContent.add(addTeamPanel,BorderLayout.CENTER);
         public void addComponent(Component component,int row,int column,int width,int height)
              System.out.println("adding c");
              constraints.gridx = column;
              constraints.gridy = row;
              constraints.gridwidth = width;
              constraints.gridheight = height;
              gridBag.setConstraints(component,constraints);
              addTeamPanel.add(component);
              addTeamPanel.setVisible(true);
    }

    Hello,
    you are missing only one link, just add following line to your actionPerformed method of DisplayMenuBar class and all problem will be solved
    setContent.validate();
    Actually, Swing component does not updated automatically. when you do any changes to the component layout it will set that component as invalidated component. To update the view you need to call validate() method defined in JComponent class.
    Virus

  • I add components to contentPane, but JFrame still does not show them

    I converted a small game I was making from AWT to Swing.(The game is just MineSweeper.) I made all the necessary adjustments like, Button to JButton and add() to getContentPane().add(), but when I show the JFrame, it does not show any components that I added. I have run test programs to see if I am adding the components correctly and they work.
    I print out the number of components contained in the frame by using getComponentCount() and the number is correct. It just will not show up in the JFrame. I have tried everything I can think of, no matter how strange and it still will not show the components.
    I have attached all the code to the bottom of this message. Can someone please take a look and see what I am missing.
    Thanks.
    Here's the code. The main file is at the end and is the one causing the problems. All the rest is just support stuff and should not be relavent, but I included it in case I missed something there.
    //Timer is just a custom timer
    import java.util.Date;
    public class Timer {
         Date curr;
         public Timer() {
              curr=new Date();
         public void start() {
              curr=new Date();
         public int getSeconds() {
              return (int)(((new Date().getTime())-curr.getTime())/1000);
    //Cover subclasses JButton for initial look
    import java.awt.*;
    import javax.swing.*;
    public class Cover extends JButton {
         Dimension size;
         public Cover() {
              super("");
              size=new Dimension(20,20);
              setSize(size);
         public Cover(String l) {
              super("");
              size=new Dimension(20,20);
              setSize(size);
         public void setSize(Dimension s) {
              super.setSize(size);
         public Dimension getPreferredSize() {
              return size.getSize();
         public Dimension getMinimumSize() {
              return size.getSize();
         public Dimension getMaximumSize() {
              return size.getSize();
    //Flag subclasses JButton to flag a mine
    import java.awt.*;
    import javax.swing.*;
    public class Flag extends JButton {
         Dimension size;
         public Flag() {
              super("F");
              size=new Dimension(20,20);
         public Flag(String l) {
              super("F");
              size=new Dimension(20,20);
         public void setSize(Dimension s) {
              super.setSize(size);
         public Dimension getPreferredSize() {
              return size.getSize();
         public Dimension getMinimumSize() {
              return size.getSize();
         public Dimension getMaximumSize() {
              return size.getSize();
    //Reveal subclasses JPanel to show what's underneath
    import java.awt.*;
    import javax.swing.*;
    public class Reveal extends JPanel {
         Dimension size;
         int number;
         Color color[];
         public Reveal(int n) {
              super();
              size=new Dimension(20,20);
              number=n;
              color=new Color[10];
              color[0]=Color.black;
              color[1]=Color.orange;
              color[2]=Color.cyan;
              color[3]=Color.yellow;
              color[4]=Color.green;
              color[5]=Color.magenta;
              color[6]=Color.blue;
              color[7]=Color.pink;
              color[8]=Color.darkGray;
              color[9]=Color.red;
              //for(int x=0;x<10;x++) {
              //     System.out.println(x+"="+color[x]);
              setBackground(Color.black);
         public void paintComponent(Graphics g) {
              int width=getWidth();
              int height=getHeight();
              FontMetrics fm=g.getFontMetrics();
              int fw=0;
              int fh=fm.getAscent();
              g.setColor(color[number]);
              if(number==9) {
                   fw=fm.stringWidth("M");
                   g.drawString("M",width/2-(fw/2),height/2+(fh/2));
              else if(number!=0) {
                   fw=fm.stringWidth(""+number);
                   g.drawString(""+number,width/2-(fw/2),height/2+(fh/2));
              g.setColor(Color.white);
              g.drawRect(1,1,width-2,height-2);
              //System.out.println("number="+number);
         public void setNumber(int n) {
              number=n;
         public int getNumber() {
              return number;
         public Dimension getPreferredSize() {
              return size.getSize();
         public Dimension getMinimumSize() {
              return size.getSize();
         public Dimension getMaximumSize() {
              return size.getSize();
    //MineSweeper just launches the program and subclasses JFrame
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MineSweeper extends JFrame implements ComponentListener {
         public MineSweeper(String s) {
              super(s);
              addComponentListener(this);
         public void quit() {
              System.exit(0);
         public void componentHidden(ComponentEvent e){}
         public void componentMoved(ComponentEvent e){}
         public void componentResized(ComponentEvent e){
              System.out.println("resized");
              MineSweeper temp=(MineSweeper)e.getSource();
              System.out.println("count="+temp.getContentPane().getComponentCount());
         public void componentShown(ComponentEvent e){}
         public static void main(String args[]) {
              MineSweeper t=new MineSweeper("Inside Moves");
              t.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              GameManager manager=new GameManager(t);
    //GameManager is the main program. This is where the JFrame is realized
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class GameManager implements MouseListener, ActionListener, Runnable {
         JPanel display;
         JPanel gameInfo;
         MineSweeper screen;
         JButton reset;
         JTextField tMine,time;
         Container pane;
         int clickX,clickY;
         int minesLeft;
         int gridX[],gridY[],mine[];
         static final int MAX_X=30;
         static final int MAX_Y=24;
         static final int MAX_MINE=667;
         JComponent grid[][];
         int board[][];
         int number[][];
         final static int OB=64;
         final static int BLANK=0;
         final static int MINE=1;
         final static int REVEAL=128;
         int level;
         final static int EASY=0;
         final static int MEDIUM=1;
         final static int HARD=2;
         final static int CUSTOM=3;
         int state;
         final static int START=1;
         final static int PLAYING=2;
         final static int DONE=3;
         Timer timer;
         int timeDisp;
         public GameManager(MineSweeper s) {
              screen=s;
              pane=screen.getContentPane();
              pane.setLayout(new BorderLayout());
              display=new JPanel();
              gameInfo=new JPanel(new GridLayout(1,3));
              reset=new JButton("Reset");
              tMine=new JTextField(20);
              time=new JTextField("0",20);
              grid=new JComponent[MAX_X+2][MAX_Y+2];
              board=new int[MAX_X+2][MAX_Y+2];
              number=new int[MAX_X+2][MAX_Y+2];
              gridX=new int[4];
              gridY=new int[4];
              mine=new int[4];
              level=EASY;
              gridX[0]=8;
              gridY[0]=8;
              mine[0]=10;
              gridX[1]=16;
              gridY[1]=16;
              mine[1]=40;
              gridX[2]=30;
              gridY[2]=16;
              mine[2]=99;
              gridX[3]=0;
              gridY[3]=0;
              mine[3]=0;
              minesLeft=mine[level];
              tMine.setText(""+minesLeft);
              state=START;
              timer=new Timer();
              reset.addActionListener(this);
              setup();
              Thread t=new Thread(this);
              t.start();
              /*System.out.println("count="+pane.getComponentCount());
              Component cc[]=pane.getComponents();
              for(int i=0;i<cc.length;i++) {
                   System.out.println("cc="+cc);
         public void setup() {
              boolean done;
              for(int x=0;x<=gridX[level]+1;x++) {
                   for(int y=0;y<=gridY[level]+1;y++) {
                        if(x==0 || x==gridX[level]+1 || y==0 || y==gridY[level]+1) {
                             board[x][y]=OB;
                             number[x][y]=-1;
                        else {
                             board[x][y]=BLANK;
              for(int i=0;i<mine[level];i++) {
                   done=false;
                   while(!done) {
                        int x=(int)((Math.random()*gridX[level])+1.0);
                        int y=(int)((Math.random()*gridY[level])+1.0);
                        if(board[x][y]==BLANK) {
                             board[x][y]=MINE;
                             done=true;
                             //System.out.println("Mine x="+x+" y="+y);
              for(int y=1;y<=gridY[level];y++) {
                   System.out.print("\n");
                   for(int x=1;x<=gridX[level];x++) {
                        number[x][y]=0;
                        if(board[x][y]==MINE) {
                             number[x][y]=9;
                             System.out.print(""+number[x][y]);
                             continue;
                        else {
                             //System.out.println("For board pos x="+x+" y="+y);
                             for(int i=-1;i<=1;i++) {
                                  for(int j=-1;j<=1;j++) {
                                       //System.out.print(""+board[x+i][y+j]);
                                       if(board[x+i][y+j]!=OB && board[x][y]==BLANK) {
                                            number[x][y]+=board[x+i][y+j];
                                  //System.out.print("\n");
                             System.out.print(""+number[x][y]);
              System.out.print("\n");
              screen.setVisible(false);
              display.removeAll();
              pane.removeAll();
              display.setLayout(new GridLayout(gridY[level],gridX[level]));
              for(int y=1;y<=gridY[level];y++) {
                   for(int x=1;x<=gridX[level];x++) {
                        Cover temp=new Cover();
                        //System.out.println("new button="+temp);
                        grid[x][y]=temp;
                        //System.out.println("display="+display.add(temp));
                        //display.add(temp);
                        temp.addMouseListener(this);
              //System.out.println("count="+display.getComponentCount());
              screen.setSize(gridX[level]*20,gridY[level]*20+30);
              pane.add(gameInfo,BorderLayout.NORTH);
              pane.add(display,BorderLayout.CENTER);
              minesLeft=mine[level];
              timeDisp=0;
              tMine.setText(""+minesLeft);
              time.setText(""+timeDisp);
              state=START;
              //System.out.println("gameInfo="+gameInfo);
              //System.out.println("display="+display);
              //screen.pack();
              screen.setVisible(true);
         void revealAround(int x,int y) {
              int index;
              Reveal tempRev=new Reveal(number[x][y]);
              grid[x][y]=tempRev;
              board[x][y]=(board[x][y]|REVEAL);
              index=(x-1)+((y-1)*gridX[level]);
              display.remove(index);
              display.add(tempRev,index);
              if(number[x][y]==0) {
                   for(int i=-1;i<=1;i++) {
                        for(int j=-1;j<=1;j++) {
                             if(!(i==0 && j==0)) {
                                  if((board[x+i][y+j]&REVEAL)!=REVEAL && board[x+i][y+j]!=OB) {
                                       revealAround(x+i,y+j);
         void startTimer() {
              timer.start();
         public void run() {
              while(true) {
                   if(state==PLAYING) {
                        if(timer.getSeconds()>timeDisp) {
                             timeDisp=timer.getSeconds();
                             time.setText(""+timeDisp);
                   else {
                        try {
                             Thread.sleep(1000);
                        catch (InterruptedException e) {
         public void actionPerformed(ActionEvent e) {
              if(e.getActionCommand().equals("Reset")) {
                   setup();
         public void mouseClicked(MouseEvent e) {
              if(state==START) {
                   startTimer();
                   state=PLAYING;
              if(state==PLAYING) {
                   Component tempComp=(Component)e.getSource();
                   boolean found=false;
                   int index=0;
                   int buttonPressed=e.getModifiers();
                   for(int x=1;x<=gridX[level];x++) {
                        if(found) {
                             break;
                        for(int y=1;y<=gridY[level];y++) {
                             if(tempComp==grid[x][y]) {
                                  clickX=x;
                                  clickY=y;
                                  found=true;
                                  break;
                   index=(clickX-1)+((clickY-1)*gridX[level]);
                   if(buttonPressed==InputEvent.BUTTON1_MASK && !(grid[clickX][clickY] instanceof Flag)) {
                        Reveal tempRev=new Reveal(number[clickX][clickY]);
                        grid[clickX][clickY]=tempRev;
                        board[clickX][clickY]=board[clickX][clickY]|REVEAL;
                        display.remove(index);
                        display.add(tempRev,index);
                   else if(buttonPressed==InputEvent.BUTTON3_MASK) {
                        if(display.getComponent(index) instanceof Cover) {
                             Flag tempFlag=new Flag();
                             grid[clickX][clickY]=tempFlag;
                             display.remove(index);
                             display.add(tempFlag,index);
                             tempFlag.addMouseListener(this);
                             minesLeft--;
                        else if(display.getComponent(index) instanceof Flag) {
                             Cover tempCov=new Cover();
                             grid[clickX][clickY]=tempCov;
                             display.remove(index);
                             display.add(tempCov,index);
                             tempCov.addMouseListener(this);
                             minesLeft++;
                        tMine.setText(""+minesLeft);
                   if(number[clickX][clickY]==0) {
                        revealAround(clickX,clickY);
                   screen.setVisible(true);
         public void mousePressed(MouseEvent e) {}
         public void mouseReleased(MouseEvent e) {}
         public void mouseEntered(MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}

    setBounds() is only used for absolute positioning. I
    am using layout managers, so it should no be used.
    Thanks for you reply.Oh I get I did not look at your source code enought... can you post only the part that is bugy!?!?!
    JRG

  • Showing a JPanel

    I'm trying to show a JPanel in my JFrame. Not sure how to accomplish this as I'm new to Swing. Here's my code attached below... Also can you recommend a good book to understand all this.
    public class RMAViewer {
         private static RMAViewer      theApp;
         private static RMAFrame      rmaFrame;
         private static Container      window;
         JPanel aboutPanel = new JPanel();
         public void init() {
              window = new RMAFrame("RMA Inventory Control");
              Toolkit theKit = window.getToolkit();
              Dimension wndSize = theKit.getScreenSize();
              window.setBounds(wndSize.width/4, wndSize.height/4,
         wndSize.width/2, wndSize.height/2);
              window.setVisible(true);
         public static void main(String[] args) {
              theApp = new RMAViewer();
              theApp.init();     
    public class RMAFrame extends JFrame {
         private JMenuBar menuBar = new JMenuBar();
         private JMenuItem closeMenu, scanMenu, aboutMenu;
         private JPanel aboutPanel = new JPanel();
         private Container contentPane = getContentPane();
         private JLabel label = new JLabel("JLabel");
         public RMAFrame(String title) {
              setTitle(title);
              setJMenuBar(menuBar);
              JMenu fileMenu = new JMenu("File");
              JMenuItem closeMenu = fileMenu.add("Close");
              JMenu toolsMenu = new JMenu("Tools");
              JMenuItem scanMenu = toolsMenu.add("Scan");
              JMenu helpMenu = new JMenu("Help");
              JMenuItem aboutMenu = helpMenu.add("About");
              menuBar.add(fileMenu);
              menuBar.add(toolsMenu);
              menuBar.add(helpMenu);     
              enableEvents(AWTEvent.WINDOW_EVENT_MASK);     //enable window events
              aboutPanel.add(new AboutPanel()); doesn't show this.
              aboutPanel.add(label); // shows this.
              aboutPanel.setSize(200,200);
              aboutPanel.setVisible(true);
              setContentPane(aboutPanel);
         //Handle the window events
         protected void processWindowEvent(WindowEvent e) {
              if(e.getID() == WindowEvent.WINDOW_CLOSING) {
                   dispose();               //release resources
                   System.exit(0);          //exit the program
              super.processWindowEvent(e);
    public class AboutPanel extends JPanel {
         Border edge = BorderFactory.createRaisedBevelBorder();
         private JButton okBut;
         private JLabel aboutLabel = new JLabel("RMA Inventory Tracking System");
         private ImageIcon memoryIcon = new ImageIcon("c:/resin/webapps/rma/WEB-INF/classes/com/pdp/memory.gif");
         private JLabel iconLabel = new JLabel(memoryIcon);
         Box boxLayout = Box.createVerticalBox();
         private javax.swing.JButton getbtnOK() {
         if (okBut == null) {
              try {
                   okBut = new javax.swing.JButton();
                   okBut.setName("btnOK");
                   okBut.setMnemonic('o');
                   okBut.setText(" OK ");
                   okBut.setSize(100,100);
                   okBut.setEnabled(true);
                   okBut.setBorder(edge);
                   //okBut.addActionListener(this);
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return okBut;
         public JPanel AboutPanel() {
         JPanel aboutPanel = new JPanel();     
              aboutLabel.setFont(new java.awt.Font("Arial", Font.BOLD, 24));
              boxLayout.add(Box.createVerticalStrut(30));
              aboutLabel.setHorizontalAlignment(SwingConstants.CENTER);
              revLabel.setHorizontalAlignment(SwingConstants.CENTER);
              boxLayout.add(aboutLabel);
              boxLayout.add(iconLabel);
              boxLayout.add(Box.createVerticalStrut(30));
              boxLayout.add(getbtnOK());
              aboutPanel.add(boxLayout);     
              return aboutPanel;
    private void handleException(java.lang.Throwable exception) {
              /* Uncomment the following lines to print uncaught exceptions to stdout */
              // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
              // exception.printStackTrace(System.out);
    }

    Try setContentPane (new AboutPanel ());Kind regards,
    Levi

  • Separator is not showing up in the JList that is set in the TextField

    Hi,
    This problem is really weird and I am tired trying to find the problem and so thought i ll ask u guys... i cant see any problem in the code below.. but when i run it the separator that i want if some condition is true it just dsnt come... i did debug it and it does actually go in the if condition but the separator is not showing up... i dont kno y...
    I am pasting the code of the JList renderer SearchListCellRenderer that implements ListCellRenderer.......it has only one method....
    public Component getListCellRendererComponent(JList list, Object value,
                   int     index, boolean isSelected, boolean cellHasFocus) {
              JLabel label = null;
              if (value != null){
                   label = new JLabel();/*(JLabel) defaultRenderer.getListCellRendererComponent(list, value, index,
                   isSelected, cellHasFocus);*/
                   if(!anatomySeparator && anatomyMap.containsKey(value.toString().toLowerCase())){
                        label.setVerticalTextPosition(SwingConstants.BOTTOM);
                        label.setPreferredSize(new Dimension(300, 80));
                        label.setText("<html><body>" + "<p style='color:white;'><b>--------------Anatomy--------------</b></p>" + "<p style='color:white;'><b>" + value.toString() + "</b></p></body></html>");
                        anatomySeparator = true;
                        logger.debug("in anatomy");
                   }else if(!diseaseSeparator && diseaseMap.containsKey(value.toString().toLowerCase())){
                        label.setVerticalTextPosition(SwingConstants.BOTTOM);
                        label.setPreferredSize(new Dimension(300, 80));
                        label.setText("<html><body>" + "<p style='color:white;'><b>---------------Diseases----------------</b></p>" + "<p style='color:white;'><b>" + value.toString() + "</b></p></body></html>");
                        diseaseSeparator = true;
                        logger.debug("in disease");
                   }else if(!propSeparator && observationMap.containsKey(value.toString().toLowerCase())){
                        label.setVerticalTextPosition(SwingConstants.BOTTOM);
                        label.setPreferredSize(new Dimension(300, 80));
                        label.setText("<html><body>" + "<p style='color:white;'><b>-----------Observations----------------</b></p>" + "<p style='color:white;'><b>" + value.toString() + "</b></p></body></html>");
                        propSeparator = true;
                        logger.debug("in observation");
                   }else{
                        label.setPreferredSize(new Dimension(300, 30));
                        label.setText("<html><body><p style='color:white;'><b>" + value.toString() + "</b></p></body></html>");
              return label;
    If i see the output the list in the JList is bold also in the condition i have the label size larger so in some values the label is actually large than others... that means it does go in the if condition... but the separator that i have there it just dsnt show up... i dnt kno wat is wrong... can anyone pls help me with this????
    This is how i set the autocopleter text field with the Jlist and its renderer... if that is of some help.....
    JList list = new JList();
    JPopupMenu popup = new JPopupMenu();
    JTextComponent textComp;
    private static final String AUTOCOMPLETER = "AUTOCOMPLETER"; //NOI18N
    public SearchListCellRenderer renderer;
    public AutoCompleter(JTextComponent comp){
    textComp = comp;
    textComp.putClientProperty(AUTOCOMPLETER, this);
    JScrollPane scroll = new JScrollPane(list);
    scroll.setBorder(null);
    list.setFocusable( false );
    list.setBackground(Color.DARK_GRAY);
    list.setForeground(Color.WHITE);
    renderer = new SearchListCellRenderer();
    list.setCellRenderer(renderer);
    scroll.getVerticalScrollBar().setFocusable( false );
    scroll.getHorizontalScrollBar().setFocusable( false );
    popup.setBorder(BorderFactory.createLineBorder(Color.black));
    popup.add(scroll);
    if(textComp instanceof JTextField){
    textComp.registerKeyboardAction(showAction, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), JComponent.WHEN_FOCUSED);
    textComp.getDocument().addDocumentListener(documentListener);
    }else
    textComp.registerKeyboardAction(showAction, KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, KeyEvent.CTRL_MASK), JComponent.WHEN_FOCUSED);
    textComp.registerKeyboardAction(upAction, KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), JComponent.WHEN_FOCUSED);
    textComp.registerKeyboardAction(hidePopupAction, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_FOCUSED);
    popup.addPopupMenuListener(new PopupMenuListener(){
    public void popupMenuWillBecomeVisible(PopupMenuEvent e){
    public void popupMenuWillBecomeInvisible(PopupMenuEvent e){
    textComp.unregisterKeyboardAction(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));
    public void popupMenuCanceled(PopupMenuEvent e){
    list.setRequestFocusEnabled(false);
    }

    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • Background not displaying in JPanel

    I have tried virtually every method I can find on this site to display a jpg in a panel yet while it compiles fine the background does not show up. Can anybody please take a look at this code and try to figure out where I went wrong? Thank you
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Image;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    import java.io.File;
    import java.io.*;
    public class Main implements ActionListener {
    JFrame f1,login;
    JLabel LID,LPW,LTitle;
    JTextField TID,TPW;
    JButton BLogin;
    JPanel PTitle,IDPanel,PWPanel,LPanel,PL;
    ImageIcon background;
    public Main() {
    CreateLogin();
    login.setVisible(true);
    public static void main(String[] args) {
    new Main();
    public void CreateLogin(){
    login=new JFrame("Guelph-Humber Mark Program");
    login.setSize(150,300);
    Container LContainer = login.getContentPane();
    LPanel=new JPanel(new BorderLayout());
    LPanel.setOpaque(false);
    //Adds title bar
    PTitle=new JPanel(new FlowLayout());
    PTitle.setOpaque(false);
    LTitle=new JLabel("LOGIN");
    PTitle.add(LTitle);
    LPanel.add(PTitle,"North");
    //Center Portion
    background = new ImageIcon("bg.jpg");
    PL=new JPanel(){
    public void paintComponent(Graphics g) {//Overrides default JPanel paintcomponent method to draw the background
    Dimension d = getSize();
    g.drawImage(background.getImage(), 0, 0, d.width, d.height, null);
    setOpaque(false);
    super.paintComponent(g);
    PL.setLayout(new GridLayout(2,1));
    IDPanel=new JPanel();
    IDPanel.setOpaque(false);
    LID=new JLabel("ID:");
    TID=new JTextField(12);
    IDPanel.add(LID);
    IDPanel.add(TID);
    PWPanel=new JPanel();
    PWPanel.setOpaque(false);
    LPW=new JLabel("Password:");
    TPW=new JTextField(12);
    PWPanel.add(LPW);
    PWPanel.add(TPW);
    PL.add(IDPanel);
    PL.add(PWPanel);
    LPanel.add(PL,"Center");
    //South portion
    BLogin=new JButton("Login");
    BLogin.addActionListener(this);
    LPanel.add(BLogin,"South");
    LContainer.add(LPanel);
    //Window adapter to close program when frames closes
    login.addWindowListener( new WindowAdapter() {public void windowClosing(WindowEvent evt) {System.exit(0);}});
    public void actionPerformed(ActionEvent e) {
    if(e.getSource()==BLogin){
    }

    1) Use the "code" tags when posting code so the posted code retains its original formatting.
    2) Learn the Java Naming conventions. None of your variable names follow standards and its very confusing to read. Variable names should start with a lower case character (class names start with an upper case character)
    3) The order of your code in the paintComponent(...) method is correct.
    4) Your code works for me, so I'm guessing you are just not finding your image.

  • Why is the GUI not showing when i run it

    Why is it not showing the container
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class Progress extends JFrame {
         private String path;
         private JPanel topLeftPanel;
         private JPanel labelPanel;
         private JTextField pathField;
         public Progress()
              this.setTitle("PROGRESS Message Viewer");
              this.setSize(800, 600);
              Container contentPane = this.getContentPane( );
              // Technique for centering a frame on the screen.
              Dimension frameSize = this.getSize();
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              this.setLocation((screenSize.width - frameSize.width)/2,
                               (screenSize.height - frameSize.height)/2);
              topLeftPanel = new JPanel();
              topLeftPanel.setLayout(new GridLayout(1, 2));
              labelPanel = new JPanel();
              labelPanel.setLayout(new GridLayout(4, 1));
              JLabel l = new JLabel("Please enter the path to log file:  ");
              l.setForeground(Color.black);
              labelPanel.add(l);
              topLeftPanel.add(labelPanel);
              pathField = new JTextField(80);
              ActionListener aListener = new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        // Retrieve the path.
                        char[] pathFieldText = pathField.getText().toCharArray();
                        path = new String(pathFieldText).trim();
              pathField.addActionListener(aListener);
              contentPane.add(topLeftPanel);
              contentPane.add(pathField);
         public static void main(String []args){
              Progress p = new Progress();
    }

    Swing related questions should be posted in the Swing forum.
    Read the BoderLayout API documentation. If you don't specify a constraint then by default the component is added to the "CENTER". However only a single component can be displayed in any given area of the BorderLayout. So the second add(...) method replaces the first component added.
    Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use Layout Managers for more information.

  • Ebay searches not showing images

    When viewing my messages from ebay in hotmail the images are not showing up until I refresh at least two or three plus times. Why is this?

    just work on getting one simple image to .jar OK
    e.g. this should .jar OK (after changing image names)
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      Image img;
      public void buildGUI()
        try
          java.net.URL url = new java.net.URL(getClass().getResource("Test.gif"), "Test.gif");
          if(url != null) img = javax.imageio.ImageIO.read(url);
        catch(Exception e){}//swallow exception - handled in paintComponent
        JPanel p = new JPanel(){
          public void paintComponent(Graphics g){
            super.paintComponent(g);
            if(img != null) g.drawImage(img,100,100,this);
            else g.drawString("this space for rent",100,100);
        JFrame f = new JFrame();
        f.getContentPane().add(p);
        f.setSize(400,300);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }put the image in the same folder, make .jar, then try the .jar on another pc
    if all OK, change code to locate image file in subfolder, make .jar, then try the .jar on another pc
    if all OK now, modify main program accordingly.
    note: in .jars, capitalization of the image file names counts
    e.g. in my above example, if I change Test.gif to test.gif, the image is not drawn

  • Jar file not showing images

    Hi
    When I make a runable jar file, my images it not showing if I try it on another computer. I searched the net and most people seems to use URLs instead ImageIO. But that doesnt help me either. Then I get the error message: Uncaught error fetching image:
    java.lang.NullPointerException
    Code is below. I hope someone can tell me what I should do.
        private Show show;
        private final int unit = 32;    // size of the images
    //    private BufferedImage free;
        private Image free;
        private BufferedImage booked;
        private BufferedImage toBeBooked;
        private BufferedImage ableToEdit;
        public TheaterOverview(Show show)
            this.show = show;
    //        try
    //            free = ImageIO.read(new File("src/images/user_alt2.png"));
    //            booked = ImageIO.read(new File("C:/Documents and Settings/Mads/Programmering/Eclipse/workspace/BioBooking/src/images/user_alt.png"));
    //            toBeBooked = ImageIO.read(new File("C:/Documents and Settings/Mads/Programmering/Eclipse/workspace/BioBooking/src/images/user.png"));
    //            ableToEdit = ImageIO.read(new File("C:/Documents and Settings/Mads/Programmering/Eclipse/workspace/BioBooking/src/images/user-yellow.png"));
    //        catch (Exception e)
    //            System.out.println("Not able to read images " + e);
            try
                URL myurl = this.getClass().getResource("images/user_alt2.png");
                Toolkit tk = this.getToolkit();
                free = tk.getImage(myurl);
    //            free = ImageIO.read(new File("images/user_alt2.png"));
                booked = ImageIO.read(new File("images/images/user_alt.png"));
                toBeBooked = ImageIO.read(new File("images/images/user.png"));
                ableToEdit = ImageIO.read(new File("images/images/user-yellow.png"));
            catch (Exception e)
                System.out.println("Not able to read images " + e);
         * The paint method. Checks what the status is of each seat and draws them accordingly.
        public void paint(Graphics g)
            Show show = getShow();
            int numberOfRows = show.getTheater().getNumberOfRows();
            int numberOfSeatsInRow = show.getTheater().getSeatsPerRow();
            for (int i = 0; i < numberOfRows; i++)
                for (int j =0; j < numberOfSeatsInRow; j++)
                    Seat seat = getShow().getRow(i).getSeat(j);
                    if(seat.isAbleToEdit())
                        g.drawImage(ableToEdit, j*unit+1, i*unit+1, null);
                    else if (seat.isBooked())
                        g.drawImage(booked, j*unit+1, i*unit+1, null);
                    else if (!seat.isBooked() && !seat.isSelected())
                        g.drawImage(free, 0, 0, this);
                    else if (seat.isSelected())
                        g.drawImage(toBeBooked, j*unit+1, i*unit+1, null);
        }

    just work on getting one simple image to .jar OK
    e.g. this should .jar OK (after changing image names)
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      Image img;
      public void buildGUI()
        try
          java.net.URL url = new java.net.URL(getClass().getResource("Test.gif"), "Test.gif");
          if(url != null) img = javax.imageio.ImageIO.read(url);
        catch(Exception e){}//swallow exception - handled in paintComponent
        JPanel p = new JPanel(){
          public void paintComponent(Graphics g){
            super.paintComponent(g);
            if(img != null) g.drawImage(img,100,100,this);
            else g.drawString("this space for rent",100,100);
        JFrame f = new JFrame();
        f.getContentPane().add(p);
        f.setSize(400,300);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }put the image in the same folder, make .jar, then try the .jar on another pc
    if all OK, change code to locate image file in subfolder, make .jar, then try the .jar on another pc
    if all OK now, modify main program accordingly.
    note: in .jars, capitalization of the image file names counts
    e.g. in my above example, if I change Test.gif to test.gif, the image is not drawn

  • Gui labels and buttons not showing...

    I am using Java to create a gui and so far I have everything working.
    But there is a section of code thats not working out and Ill post the whole file here (not very big) to let you guys see whats going on. The issue lies in the action listner where I state "if a text feild is empty, display the option pane, else show the following" and its not showing the labels and buttons.
    Help?
    package student.information.search;
    import javax.swing.JFrame;
    import java.awt.GridBagLayout;
    import javax.swing.WindowConstants;
    import java.awt.Rectangle;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import java.awt.ActiveEvent;
    import java.awt.Frame;
    import java.awt.GridBagConstraints;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    import student.information.readonly.ReadOnlyStudentForm;
    public class StudentSearch extends Frame implements ActionListener
       JTextField textField = new JTextField();
       JFrame frame = new JFrame();
       JPanel contentPane = (JPanel) frame.getContentPane();
       GridBagLayout gridBagLayout = new GridBagLayout();
        public StudentSearch()
            gridBagLayout.columnWidths = new int[]{20, 0, 12, 137, 17};
            gridBagLayout.rowHeights = new int[]{26, 0, 6, 0, 20};
            gridBagLayout.columnWeights = new double[]{1, 0, 0, 0, 0};
            gridBagLayout.rowWeights = new double[]{0, 0, 0, 0, 1};
            contentPane.setLayout(gridBagLayout);
            JButton button = new JButton();
            button.setText("Search");
            button.addActionListener(this);
            contentPane.add(button, new GridBagConstraints(3, 3, 1, 1, 0.0, 0.0, 13, 0, new Insets(0, 0, 0, 0), 0, 0));
            textField.setColumns(8);
            contentPane.add(textField, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0, 768, 2, new Insets(0, 0, 0, 0), 0, 0));
            JLabel label = new JLabel();
            label.setText("Student Seach");
            contentPane.add(label, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, 256, 0, new Insets(0, 0, 0, 0), 0, 0));
            frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            frame.setTitle("Student Search");
            frame.setBounds(new Rectangle(500, 0, 500, 320));
            frame.setVisible(true);
       public void actionPerformed( ActionEvent arg0)
            if (textField.getText().equals(""))
              JOptionPane.showConfirmDialog(null, "Please enter a value in the search feild", "Error", JOptionPane.OK_CANCEL_OPTION); 
            else
               //Show the text fields here and the user information. 
                 *  While there are students for this search, change the text fields to Name, Last Name and ID and have a button called
                 *  View that when clicked allows for you to view all that students information.
                JLabel firstName = new JLabel();
                firstName.setText("Label");
                contentPane.add(firstName, new GridBagConstraints(5, 5, 1, 1, 0.0, 0.0, 768, 0, new Insets(0, 0, 0, 0), 0, 0));
                JLabel lastName = new JLabel();
                lastName.setText("Label");
                contentPane.add(lastName, new GridBagConstraints(3, 5, 1, 1, 0.0, 0.0, 256, 0, new Insets(0, 0, 0, 0), 0, 0));
                JLabel studentID = new JLabel();
                studentID.setText("Label");
                contentPane.add(studentID, new GridBagConstraints(1, 5, 1, 1, 0.0, 0.0, 256, 0, new Insets(0, 0, 0, 0), 0, 0));
                JButton viewStudentInformation = new JButton();
                viewStudentInformation.setText("Search");
                viewStudentInformation.addActionListener(new ActionListener()
                        public void actionPerformed(ActionEvent e)
                               //For viewing individual student information
                                new ReadOnlyStudentForm();
                contentPane.add(viewStudentInformation, new GridBagConstraints(7, 3, 1, 1, 0.0, 0.0, 13, 0, new Insets(0, 0, 0, 0), 0, 0));
    }

    In general when adding or removing components for a visible GUI you need to use:
    panel.add(...);
    panel.revalidate();
    panel.repaint();

  • In GlassPane Wait cusor is not showing ?

    Hello all,
    I want show wait cursor and disable all the mouse input outside the application.Please help.
    In my code , I am using glasspane object to do it, but it is not showing wait cusor and it is accepting mouse event outside the application.
    Please help.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class TestGlass extends JFrame     implements ActionListener{
         private JButton closeButton;
         private Container c;
         MyGlassPane myGlassPane;
    //constructor -1
         public TestGlass()     {
              init();
              createGUI();
    //init
         void init()     {
              closeButton = new JButton("Close Me");
              c = getContentPane();
              myGlassPane = new MyGlassPane();
    //GUI
         void createGUI()     {
              setTitle("glass Pane Test");
              c.setLayout(new FlowLayout());
              c.add(closeButton);
              closeButton.addActionListener(this);
              addWindowListener     (     new WindowAdapter()     {
                                                 public void windowClosed(WindowEvent we)     {
                                                      closeApplication();
              //glass pane
              setGlassPane(myGlassPane);
              pack();
              setSize(400,300);
    //close
         void closeApplication()     {
              System.exit(0);
    //action handler
         public void actionPerformed(ActionEvent e)     {
              closeApplication();
    //main
         public static void main(String args[])     {
              new TestGlass().show();
    class MyGlassPane extends JComponent     {
         public MyGlassPane()     {
              //setSize(800,600);
              //setCursor(new Cursor(Cursor.WAIT_CURSOR));
              addMouseListener(     new MouseAdapter()     {
                                            public void mouseExited(MouseEvent me) {
                                                 setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

    Hi,
    in your subclass of JFrame you have to useCursor waitCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
    Component gp = getRootPane().getGlassPane();
    gp.setCursor(waitCursor);
    gp.setVisible(true); to get the glass pane.

  • Popup menu does not show in JTextField

    I have a JPanel with a popup menu that works perfectly, as long as the right mouse button is clicked on the JPanel. However the popup menu does not show if the right mouse button is clicked on a JTextField that is within the JPanel.
    What has to be done that the popup menu shows always?
    this.addMouseListener(new java.awt.event.MouseAdapter()
    public void mouseReleased(MouseEvent e)
    this_mouseReleased(e);
    protected void this_mouseReleased(MouseEvent e)
    if (e.isPopupTrigger())
    popPopup.show(this, e.getX(), e.getY());

    There are up to 20 JTextFields in the JPanels an the application has a lot of JPanels of course. Adding the listener to each and every JTextField means a lot of extra code. Is there really no generic solution to this problem???

  • Not show horizontal srollbar when decrease table size

    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class SimpleTableDemo extends JPanel {
         final Object[][] data = {
                   { "Mary", "Campione", "ooooooooooooooooooooooooooo", "5" },
                   { "Alison", "Huml", "Rowing", "3" },
                   { "Kathy", "Walrath", "Chasing toddlers", "2" },
                   { "Mark", "Andrews", "Speed reading", "20" },
                   { "Angela", "Lih", "Teaching high school", "4" } };
         final Object[] columnNames = { "First Name", "Last Name", "Sport",
                   "Est. Years Experience" };
         public SimpleTableDemo() {
              JTable table = new JTable(data, columnNames);
              // Create the scroll pane and add the table to it.
              JScrollPane scrollPane = new JScrollPane(table);
              scrollPane.setPreferredSize(new Dimension(400, 100));
              // Add the scroll pane to this panel.
              setLayout(new GridLayout(1, 0));
              add(scrollPane);
         public static void main(String[] args) {
              JFrame frame = new JFrame("SimpleTableDemo");
              frame.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              frame.getContentPane().add("Center", new SimpleTableDemo());
              // frame.setSize(400, 125);
              frame.pack();
              frame.setVisible(true);
    }When I decrease table size the vertical scrollbar show, but horizontal srollbar NOT show. Why?

    When I decrease table size the vertical scrollbar show, but horizontal srollbar NOT show. Why? Because the table automatically resizes the width of each column.
    If you don't want this behaviour then set the setAutoResizeMode(...) method to off.

  • ITunes does not show up on apple tv 1st gen.

    i have a 1st gen apple tv with the 160 gig HD. recently, it will not show the itunes site. Under teh movies tab there are my movies and trailers and that's it. Does anyone know how to get the itunes store back on apple tv?

    Known issue currently, you'll need to wait for the fix.

Maybe you are looking for

  • Some sites cannot be accessed after Mountain Lion

    Since I have downloaded Mountain Lion I cannot access the sites of my employer anymore (www.superiorenergy.com) Also I cannot access our portal for the intranet and not receive my email via Outlook and webmail. It seems that always when "superiorener

  • Ipod touch locked up while syncing tried to reset it didn't work

    the screen shows the itunes logo (music) and the usb connector. Tried resetting by holding down the on/off button at top cornedr and home button below square and it didn't work. still see same graphics? Help!!

  • SSRS vs BIRT Report

    Hi, Can any one let me know what is the difference between BIRT and SSRS interms of technical features. what all features avialble for creating the Dashboard which is not available in BIRT. Thanks Prashant

  • Reference symbol not found,  __1cDstdEcerr_

    I have a shared library(eg: x.so) which uses std::cerr for output. When another program attempts to load x.so via dlopen(), the program get a relocation error complaining symbol __1cDstdEcerr_ not found in x.so. Where is the symbol, __1cDstdEcerr_, d

  • Can't login password protected site in Windows XP !

    i use iWeb to make a password protected web page and publish to .Mac. I test it at home using my iMac G5 with Safari and Firefox, everything is ok. when i am at office today, i test it by using Windows XP PC with Firefox and IE, it just keep asking m