Menu Expansion in swing

Hai,
i want to keep the menu with expansion as in Microsoft Word menus so that only on clicking that ,the remaining menu items should get displayed.If anybody knows that,let me know how to do.
Thanks in advance.

Actually ,i want to keep some of the menu items to
be hidden initially and only on clicking the
expansion symbol in the menu ,they should be made
visible.Ahhh I see. That feature irritates the hell out of me personally. And I don't know how to do that or if it can be done. But now that you have described your problem more clearly I am sure someone can give you a more definitive answer.

Similar Messages

  • How to create file menu in the swing?

    How to create file menu or any menu in the swing?
    Please help me.

    How to create file menu or any menu in the
    swing?
    Please help me.By file menu, do you mean where you can choose a file to open or save to? If so, have you had a look at the File Chooser component? If not, please click on the link in the previous sentence to the Sun tutorial.
    Good luck
    /Pete

  • Expandable Menu in Java Swing app

    Hello JFriends,
    is it possible to create a expandable menu in java swing app? I am thinking of something like menu in MS Visio: http://img32.imageshack.us/i/menuip.jpg/
    It works like that: When user click on a bar it expands (with nice animation) and shows containing components.
    Or maybye there are components like that?
    Thanks in advance for Your reply and please forgive me if my english is bad.
    JRegards :-)

    Yes, such constructs are possible. There isn't a pre-made component exactly like that. The NetBeans IDE has a Window - named Palette - that's very similar. The code is open source.
    You can read about Java menus here:
    [http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html]

  • I need the action for menu in java swing

    hai friends
    have a peace day.
    i created a menu using swing, but i don't know how to give the action.
    eg: i created menu called FILE if i click this menu its goes to specify program
    please give any idea or sample code.
    thank u
    regards
    rex

    Hi,
    u have to implement ActionListener...when u r pressing menu item the events
    will come inside the ActionPerformed function.
    for example
    public class Menuexample implements ActionListener
    public Menuexample()
    filemenuiem=new MenuItem("File");
    filemenuiem.addActionListener(this);
    public void actionPerformed(ActionEvent ae) {
    if(ae.getSource==filemenuitem)
    regards
    pradeep

  • Hierarchal Menu Behavior in Swing

    When a user pops up a hierarchical menu, she should be able to drag directly to the desired item in that menu. The shortest path to the desired menu item is usually a diagonal path.
    Under Swing, the user must first drag horizontally into the hierarchical menu and then drag down that menu to select the item, otherwise the hierarchical menu closes. This is very disconcerting behavior for users who are expecting the normal platform behavior (the Mac and Windows allow direct [diagonal] dragging).
    I feel this is a significant problem, but I tried submitting it as a bug and didn't get much interest from Sun. Please post your agreement (or disagreement) to this topic so that I can build a stronger case. Thanks.

    Personally, I find it mildly amazing that Sun showed "no interest" in this issue. It's the lack of attention paid to exactly these sorts of seemingly minor, but actually extremely important, interface issues that has caused developers to look for alternatives to Swing. SWT, anyone?
    If Sun cares about the user experience they will pay attention to this issue, and others like it...

  • Calling runtime.exec in menu(swing)

    Hi all,
    I want to pop up a command (NT) window from a menu in java swing.
    1. However I am able to call from the menu, but was Not able to get the batch file (either .bat or .exe) to run in another window
    2. and all the output from the batch file did not printout to screen.
    any help?
    JMenuItem menuItem = null;
    startAction = new AbstractAction("Start") {
    public void actionPerformed(ActionEvent e) {
    displayResult("Starting Application...", e);
    Process JobProcess = null;
    try {
    // JobProcess = Runtime.getRuntime().exec("cmd.exe /c test.bat");
    //JobProcess = Runtime.getRuntime().exec("cmd /K start cmd /K test.bat");
    //JobProcess = Runtime.getRuntime().exec("cmd.exe /c test.bat"); //works
    JobProcess = Runtime.getRuntime().exec("test.bat"); // works
    JobProcess.waitFor();
    int i = JobProcess.exitValue();
    catch (Exception ex) {
    textArea.append(ex.getMessage());
    in the test.bat :
    echo "this is test" > test.txt
    thanks
    andrew

    I don't believe you can ues redirection (>) when executing a command. Your program must handle the output itself. Add code something like:
    String line;
    BufferedReader output = new BufferedReader( new InputStreamReader( JobProcess.getInputStream() ) );
    while ( (line = output.readLine()) != null )
              System.out.println( line );
    output.close();Note: the variable JobProcess should be renamed to jobProcess. The Java convention is to use uppercase for class names.

  • How to write a code for  open new txt file in swing

    hai all,
    now i do one project in java.that project's GUI is Swing. But i don't known swing (basic).So how to write a code for open new txt file and "Open window " in menu item on swing.that means when i click the "New" on menu that time open a new txt file. open also like that type.
    plz give me that code ! very urgent
    Advance Thanks !
    RSK

    Swing Tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/index.html
    Since you don't know the basic of swing read the tutorial, it is for your own good because it is useless if we provide you with a code you don't even understand and how it works.
    If you want a menu read the tutorial about using menus and for opening a file read using JFileChooser.
    note: don't use the word urgent because it implies that your problem is more important than others.

  • Apply MVC to a Swing app?

    Folks,
    I got inspired by this thread: http://forum.java.sun.com/thread.jspa?threadID=5244847&start=23&tstart=0
    and wrote the below version of MineSweeper (winmine.exe) in Swing as a learning exercise.
    I'm about half way through my TODO list, and the code is "getting ugly". For instance, It took me a couple of hours to figure out what needed to change in order to keep track of the remaining bombs.
    This leads me to believe that the best way forward might be to declare this version to be "The Prototype" and go back to torres.... taking what I've learned about the problems involved, and designing the whole thing from ground up, applying the MVC paradigm.
    But I'm really unsure of how go about doing that... I studied program design back in the heyday of pseudo-code and structure charts, and I was hoping for some free advise (pretty please) or maybe some practical exercises/tutorials on OO program design. I've read some theory, but to be honest, it just goes over my head... in one ear and out the other. I hope that exercise of applying the principles espoused in the theory to a concrete example will help me to bring the theory into focus... at the moment GOF is rattling around in my brain, but it refuses coalesce into a coherent picture.
    I have a rough design in mind... Please would anyone care to comment?
    The Model
    * A Field has Mine's
    * Field would contain a matrix of Mine's ... mines[col][row]
    * Mine would encapsulate the state of each mine, and expose the a low level set of mutators.
    The View
    * Form extends JFrame - the main form
    * Top JPanel - much like the existing one
    * Bottom JPanel
    .... I'm wondering if a JTable would work in place of the existing matrix of JPanels.
    .... or can this be done with a LayoutManager... I'm thinking GridBagLayout?
    * Can I use a JPanel instead of the existing JPanel contains a JButton?
    .... * I've got an issue with the existing MouseListener implementation. You have to hold
    .... the mouse still and click each button rather deliberately. This ruins the fluidity of
    .... the game-play, substantially reducing the players enjoyment. ie: it gives me the sh1ts.
    .... Please does anyone have any ideas? I've used enough swing/awt apps to know
    .... that this isn't an insoluble problem, but I've got no idea how to address it.
    The Controler
    * A Game class orchestrates the whole thing at the high level.
    ... + main - Creates a new Game and calls it's play method.
    ... - play - Creates and shows the gui on the EDT
    * The MineLayer lays Mine's for the MineSweeper to clean up.
    .... But I'm a but lost as to what should "own" the MineLayer and the MineSweeper.
    .... To me it makes sense for the Controler to kick of the View, but from then on
    .... we're event-driven by the View... so should the View "create and own" the
    .... MineLayer and the MineSweeper? or should they be created by the controler
    .... and passed into the constructor of the main form? This OO stuff always leaves me
    .... feeling a bit thick. Back in my day you just called functions. It was ugly and simple.
    .... OO is ugly and complicated.
    package krc.games;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import java.awt.EventQueue;
    import java.awt.Container;
    import java.awt.Color;
    import java.awt.Insets;
    import java.awt.Font;
    import java.awt.BorderLayout;
    import java.awt.image.ColorModel;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.ImageIcon;
    import javax.swing.border.LineBorder;
    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.io.File;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    // TODO:
    // * implement "you win"... track remaining bombs.                DONE
    // * show "not a bomb" at end of game.                            DONE
    // * display remaining bombs.                                     DONE
    // * display a clock.                                             DONE
    // * Resign/Refactor along MVC lines.
    //   M = A Field has Mine's
    //   V = The JFrame, some JPanels, a Grid?
    //   C = Game orchestrates. The MineLayer lays Mine's for the MineSweeper to clean up.
    // * beginner / intermediate / advanced / custom settings.
    //   - Find out how to use menu's in swing
    // * config board from command line args and/or properties file.
    //   - Use an XML Properties file.
    // * restart the same game. Reset the board with existing bombs. 
    //   - TOO EASY - remember the seed used passed to Random.
    // * high score.
    //   - CAPTURE: JOptionPane("Enter your name")
    //   - DISPLAY: A form with a grid
    //   - STORE  : Java only database
    // * save and load a game.
    //   - A de/serialization exercise.
    // * cheats - IDDKFA ;-)
    //   - keyboard listener to show bombs.
    import java.awt.image.BufferedImage;
    public class MineSweeperGame extends JFrame
      private static final long serialVersionUID = 0L;
      private static final int ROWS = 15;
      private static final int COLS = 30;
      private static final int BOMBS = (int)(ROWS * COLS / 4.5);
      private JLabel bombs = null; //count down the bombs
      private int bombsRemaining = BOMBS;
      private JLabel clock = null; //seconds since first click
      private int elapsedTime;
      private volatile boolean isClockRunning = false;
      private static final String DIR = "C:/Java/home/src/krc/games/";
      private static final BufferedImage FLAG_IMAGE     = loadImage(DIR+"/flag.jpg");
      private static final BufferedImage QUESTION_IMAGE = loadImage(DIR+"/question.jpg");
      private static final BufferedImage BOMB_IMAGE     = loadImage(DIR+"/bomb.jpg");
      private static final BufferedImage EXPLODED_IMAGE = loadImage(DIR+"/exploded_bomb.jpg");
      private static final BufferedImage NOT_BOMB_IMAGE = loadImage(DIR+"/not_bomb.jpg");
      // number colors
      private static final Color[] COLORS = {
        Color.black         // 0 not used
      , Color.blue          // 1 blue
      , new Color(0,153,153)// 4 darkGreen
      , Color.red           // 3 red
      , new Color(0,0,204)  // 4 darkBlue
      , new Color(153,0,0)  // 5 brown
      , Color.pink          // 6 pink
      , Color.orange        // 7 orange
      , Color.white         // 8 white
      , Color.magenta       // 9 magenta
      private static final Font FONT = new Font("Dialog", Font.BOLD, 12);
      private MouseListener mouseListener = new MouseAdapter() {
        public void mouseClicked(MouseEvent event) {
          if(!isClockRunning) startClock();
          Cell cell = ((Cell.Button)event.getSource()).getParentCell();
          if ( event.getButton() == MouseEvent.BUTTON1 ) {
            if (cell.isBomb()) {
              if ( cell.isMarkedAsBomb() ) {
                java.awt.Toolkit.getDefaultToolkit().beep();
              } else {
                cell.explode();
                youLost();
            } else {
              revealCell(cell);
          } else if ( event.getButton() == MouseEvent.BUTTON3 ) {
            cell.nextState();
      private class Cell extends JPanel {
        private static final long serialVersionUID = 0L;
        public static final int WIDTH = 17;
        public static final int HEIGHT = 17;
        public static final float Y_OFFSET = 13F;
        public static final float X_OFFSET = 5F;
        private class Button extends JButton {
          private static final long serialVersionUID = 0L;
          private final Cell parentCell;
          public Button(int width, int height, Cell parentCell) {
            this.parentCell = parentCell;
            this.setBounds(0, 0, width, height);
            this.setMargin(new Insets(1,1,1,1));
            this.setFont(new Font("Dialog",0,8));
            this.addMouseListener(mouseListener); // handle right button
          public void reset() {
            this.setText("");
            this.setVisible(true);
            this.setIcon(null);
          public Cell getParentCell() {
            return this.parentCell;
        private final Button button;
        private final int row, col;
        private boolean isBomb = false;
        private boolean isRevealed = false;
        private boolean isExploded = false;
        private int neighbours = 0;
        private ImageIcon[] stateIcons = new ImageIcon[] {
          null,  new ImageIcon(FLAG_IMAGE), new ImageIcon(QUESTION_IMAGE)
        private int state = 0;
        public static final int STATE_UNMARKED = 0;
        public static final int STATE_MARKED_AS_A_BOMB = 1;
        public static final int STATE_MARKED_AS_A_QUESTION = 2;
        Cell(int row, int col) {
          this.row = row;
          this.col = col;
          this.setBounds(col*WIDTH, row*HEIGHT, WIDTH, HEIGHT);
          this.setLayout(null);
          button = new Button(WIDTH, HEIGHT, this);
          this.add(button);
        public boolean isBomb() { return this.isBomb; }
        public void setBomb(boolean isBomb) { this.isBomb = isBomb; }
        public boolean isRevealed() { return this.isRevealed; }
        public void reveal() {
          if(this.isRevealed) return;
          this.button.setVisible(false);
          this.isRevealed = true;
        public void revealNotABomb() {
          button.setText("");
          button.setIcon(new ImageIcon(NOT_BOMB_IMAGE));
        public boolean isExploded() { return this.isExploded; }
        public void explode() {this.isExploded = true;}
        public int getNeighbours() { return this.neighbours; }
        public void setNeighbours(int neighbours) {this.neighbours = neighbours;}
        public void reset() {
          this.isRevealed = false;
          this.isBomb = false;
          this.isExploded = false;
          this.state = STATE_UNMARKED;
          this.button.reset();
        public boolean isMarkedAsBomb() {
          return this.state == Cell.STATE_MARKED_AS_A_BOMB;
        public void nextState() {
          boolean wasMarkedAsABomb = this.isMarkedAsBomb();
          this.state = (this.state+1) % 3;
          button.setIcon(stateIcons[this.state]);
          if (this.isMarkedAsBomb()) {
            setBombsRemaining(getBombsRemaining()-1);
            if (getBombsRemaining() == 0) {
              if (allMarkedBombsAreReallyBombs()) {
                youWon();
              } else {
                youLost();
          } else if (wasMarkedAsABomb) {
            setBombsRemaining(getBombsRemaining()+1);
        @Override
        public void paintComponent(Graphics g) {
          super.paintComponent(g);
          if ( this.isRevealed() ) {
            Graphics2D g2d = (Graphics2D) g;
            if (this.isExploded) {
              g2d.drawImage(EXPLODED_IMAGE, 0, 0, null);
            } else if (this.isBomb) {
              g2d.drawImage(BOMB_IMAGE, 0, 0, null);
            } else if (this.neighbours > 0) {
              g2d.setColor(COLORS[this.neighbours]);
              g2d.setFont(FONT);
              g2d.drawString(""+this.neighbours, X_OFFSET, Y_OFFSET);
      private Cell[][] cells = new Cell[ROWS][COLS];
      MineSweeperGame() {
        super();
        buildAndShowGUI();
      private void buildAndShowGUI() {
        this.setTitle("Miner");
        final int CELLS_X = Cell.WIDTH*COLS;
        final int WASTE_X = 6;
        final int WIN_WIDTH = CELLS_X+WASTE_X;
        final int CELLS_Y = Cell.HEIGHT*ROWS;
        final int WASTE_Y = 32;
        final int TOP_FRAME_Y = 34;
        final int WIN_HEIGHT = CELLS_Y+WASTE_Y+TOP_FRAME_Y;
        this.setSize(WIN_WIDTH, WIN_HEIGHT);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setResizable(false);
        Container pane = this.getContentPane();
        pane.setLayout(null);
        JPanel top = new JPanel();
        top.setBounds(0,0, WIN_WIDTH,TOP_FRAME_Y);
        top.setBorder(new LineBorder(Color.black));
        top.setLayout(null);
        bombs = new JLabel();
        bombs.setBounds(5,7, 23,17);
        bombs.setBorder(new LineBorder(Color.black));
        top.add(bombs);
        clock = new JLabel("0");
        clock.setBounds(WIN_WIDTH-35,7, 23,17);
        clock.setBorder(new LineBorder(Color.black));
        top.add(clock);
        pane.add(top);
        JPanel bot = new JPanel();
        bot.setLayout(null);
        bot.setBackground(Color.white);
        bot.setBounds(0, TOP_FRAME_Y+1, CELLS_X, CELLS_Y);
        for(int r=0; r<ROWS; r++) {
          for(int c=0; c<COLS; c++) {
            cells[r][c] = new Cell(r, c);
            bot.add(cells[r][c]);
        pane.add(bot);
        resetGame();
        this.setVisible(true);
      private void resetGame() {
        resetClock();
        resetCells();
        placeBombs();
        setBombsRemaining(BOMBS);
        countNeighbouringBombs();
      private void resetCells() {
        // reset all the cells
        for(int r=0; r<ROWS; r++) {
          for(int c=0; c<COLS; c++) {
            cells[r][c].reset();
      private void placeBombs() {
        // randomly place however many bombs in the minefield
        Random rand = new Random(System.currentTimeMillis());
        for(int i=0; i<BOMBS; i++) {
          while(true) {
            Cell cell = this.cells[rand.nextInt(ROWS)][rand.nextInt(COLS)];
            if (!cell.isBomb()) {
              cell.setBomb(true);
              cell.button.setText("b");
              break;
      // count the number of bombs neighbouring each cell
      private void countNeighbouringBombs() {
        for(int r=0; r<ROWS; r++) {
          for(int c=0; c<COLS; c++) {
            cells[r][c].setNeighbours(getNeighbourCount(r, c));
      // the number of bombs neighbouring the given cell
      private int getNeighbourCount(int row, int col) {
        int count = 0;
        int firstRow = Math.max(row-1, 0);
        int lastRow  = Math.min(row+1, ROWS-1);
        int firstCol = Math.max(col-1, 0);
        int lastCol  = Math.min(col+1, COLS-1);
        for(int r=firstRow; r<=lastRow; r++) {
          for(int c=firstCol; c<=lastCol; c++) {
            if( this.cells[r][c].isBomb ) count++;
        return count;
      public void setBombsRemaining(int bombsRemaining) {
        this.bombsRemaining = bombsRemaining;
        this.bombs.setText(""+this.bombsRemaining);
      public int getBombsRemaining() {
        return(this.bombsRemaining);
      private void showBombs() {
        for(int r=0; r<ROWS; r++) {
          for(int c=0; c<COLS; c++) {
            Cell cell = cells[r][c];
            if (cell.isBomb) {
              cell.reveal();
            } else if (cell.isMarkedAsBomb()) {
              cell.revealNotABomb();
      private boolean allMarkedBombsAreReallyBombs() {
        for(int r=0; r<ROWS; r++) {
          for(int c=0; c<COLS; c++) {
            Cell cell = this.cells[r][c];
            if (cell.isMarkedAsBomb() && !cell.isBomb() ) {
              return false;
        return true;
      private void revealCell(Cell cell) {
        if(cell.getNeighbours()==0) {
          revealCells(cell, new HashMap<Cell,Object>());
        } else {
          cell.reveal();
      private void revealCells(Cell cell, Map<Cell,Object> ancestors) {
        if (ancestors.containsKey(cell)) return;
        if (cell.isRevealed()) return;
        ancestors.put(cell, null);
        cell.reveal();
        if(cell.getNeighbours()==0) {
          int firstRow = Math.max(cell.row-1, 0);
          int lastRow  = Math.min(cell.row+1, ROWS-1);
          int firstCol = Math.max(cell.col-1, 0);
          int lastCol  = Math.min(cell.col+1, COLS-1);
          for(int r=firstRow; r<=lastRow; r++) {
            for(int c=firstCol; c<=lastCol; c++) {
              Cell x = cells[r][c];
              if (x == cell) continue;
              if( !x.isBomb() && !x.isRevealed() ) {
                revealCells(x, ancestors);
      private void youLost() {
        stopClock();
        showBombs();
        JOptionPane.showMessageDialog(this, "You Lost.", "Game Over", JOptionPane.WARNING_MESSAGE);
        resetGame();
      private void youWon() {
        stopClock();
        JOptionPane.showMessageDialog(this, "You Won. Congratulations.", "Game Over", JOptionPane.INFORMATION_MESSAGE);
        resetGame();
      private static BufferedImage loadImage(String filename) {
        try {
          return ImageIO.read(new File(filename));
        } catch (IOException e) {
          // the game will still kinda work, you just won't see this image.
          e.printStackTrace();
        return null;
      private void startClock() {
        isClockRunning = true;
        new Thread() {
          public void run() {
            while (isClockRunning) {
              clock.setText(""+(elapsedTime++));
              //repaint();
              try{Thread.sleep(1000);}catch(InterruptedException eaten){}
        }.start();
      private void stopClock() {
        this.isClockRunning = false;
      private void resetClock() {
        elapsedTime = 0;
        clock.setText("0");
      public static void main(String[] args) {
        try {
          EventQueue.invokeLater(
            new Runnable() {
              public void run() {
                MineSweeperGame game = new MineSweeperGame();
        } catch (Exception e) {
          e.printStackTrace();
    }Thanx in advance for any ideas.
    Cheers. Keith.
    Edited by: corlettk on Dec 23, 2007 6:15 AM - typos.

    For anyone who's interested... here's the latest (and complete, I think) version of the program.... there's quit a lot of code here, sorry. It should all compile first time... but you'll need to scrape your own set of images from minesweeper (ie: winmine.exe) and google for the wav files... It's a shame we can't post jar's or zip's here.
    MineSweeperGame.java
    package krc.games.sweeper;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JMenuBar;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.ButtonGroup;
    import java.awt.Color;
    import java.awt.Insets;
    import java.awt.Font;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.ImageIcon;
    import javax.swing.border.LineBorder;
    import java.io.File;
    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.util.HashMap;
    import java.util.Map;
    import krc.utilz.sound.WavePlayer;
    // TODO:
    // * implement "you win"... track remaining bombs.                    DONE
    // * show "not a bomb" at end of game.                                DONE
    // * display remaining bombs.                                         DONE
    // * display a clock.                                                 DONE
    // * Resign/Refactor along MVC lines.                                 NOT DONE
    //   M = A Field has Mine's
    //   V = The JFrame, some JPanels, a Grid?
    //   C = Controler orcestrates.
    // * beginner / intermediate / advanced / custom settings.            DONE
    //   - Find out how to use menu's in swing
    // * config board from command line args and/or properties file.      DONE
    //   - used a standard properties file
    // * restart the same game. Reset the board with existing bombs.      DONE
    //   - TOO EASY - remember the seed used passed to Random.
    // * high score.
    //   - CAPTURE: JOptionPane("Enter your name")
    //   - DISPLAY: A form with a grid
    //   - STORE  : Java only database
    // * save and load a game.
    //   - A de/serialization exercise.
    // * cheats
    //   until the first 0 is hit
    //   - ctrl-click - is bomb proof (costs 5 seconds)                   DONE
    //   - fifth click reveals the biggest patch of 0's                   DONE
    //   god mode
    //   - ctrl-alt-shift shows the position of all bombs.                DONE
    //     // search for "b" - uncomment that line)
    public class MineSweeperGame extends JFrame
      private static final long serialVersionUID = 0L;
      //these are read from properties files
      private GameSettings settings;
      private JFrame theFrame;
      private JLabel bombs = null; //count down the bombs
      private int bombsRemaining;
      private boolean replayCurrentGame = false;
      private long randomSeed = 0;
      private GameClock clock = null; //seconds since first click
      private static final String DIR = "C:/Java/home/src/krc/games/sweeper/";
      private static final String IMGDIR = DIR+"images/";
      private static final BufferedImage FLAG_IMAGE     = loadImage(IMGDIR+"flag.jpg");
      private static final BufferedImage QUESTION_IMAGE = loadImage(IMGDIR+"question.jpg");
      private static final BufferedImage BOMB_IMAGE     = loadImage(IMGDIR+"bomb.jpg");
      private static final BufferedImage EXPLODED_IMAGE = loadImage(IMGDIR+"exploded_bomb.jpg");
      private static final BufferedImage NOT_BOMB_IMAGE = loadImage(IMGDIR+"not_bomb.jpg");
      private static final String WAVDIR = DIR+"sounds/";
      // number colors
      private static final Color[] COLORS = {
        Color.black         // 0 not used
      , Color.blue          // 1 blue
      , new Color(0,153,153)// 4 darkGreen
      , Color.red           // 3 red
      , new Color(0,0,204)  // 4 darkBlue
      , new Color(153,0,0)  // 5 brown
      , Color.pink          // 6 pink
      , Color.orange        // 7 orange
      , Color.white         // 8 white
      , Color.magenta       // 9 magenta
      private static final Font FONT = new Font("Dialog", Font.BOLD, 12);
      private class GameMenuBar extends JMenuBar
        private static final long serialVersionUID = 0L;
        private ActionListener menuListener = new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            String action = event.getActionCommand().toLowerCase();
            if ("new".equals(action)) {
              hideAndDestroyGUI();
              buildAndShowGUI();
            } else if ("restart".equals(action)) {
              hideAndDestroyGUI();
              replayCurrentGame = true;
              buildAndShowGUI();
            } else if ( "beginner,intermediate,expert,custom".indexOf(action) > -1 ) {
              hideAndDestroyGUI();
              if ( "custom".equals(action) ) {
                CustomSettingsDialog dialog = new CustomSettingsDialog(theFrame, properties.get("custom"));
                settings = dialog.getSettings();
                dialog.dispose();
                properties.set(settings);
              } else {
                settings = properties.get(action);
              buildAndShowGUI();
            } else if ("exit".equals(action)) {
              setVisible(false);
              dispose();
            } else {
              java.awt.Toolkit.getDefaultToolkit().beep();
              System.out.println("Menu item ["+event.getActionCommand()+"] was pressed.");
        public GameMenuBar(String level) {
          JMenu menu = new JMenu("Game");
          menu.add(newJMenuItem("New", 'N'));
          menu.add(newJMenuItem("Restart", 'R'));
          menu.addSeparator();
          ButtonGroup group = new ButtonGroup();
          menu.add(newJRadioButtonMenuItem(group, "Beginner", level));
          menu.add(newJRadioButtonMenuItem(group, "Intermediate", level));
          menu.add(newJRadioButtonMenuItem(group, "Expert", level));
          menu.add(newJRadioButtonMenuItem(group, "Custom", level));
          menu.addSeparator();
          menu.add(newJMenuItem("Exit", 'X'));
          this.add(menu);
        private JMenuItem newJMenuItem(String text, char mneumonic) {
          JMenuItem item = new JMenuItem(text, mneumonic);
          item.addActionListener(this.menuListener);
          return item;
        private JRadioButtonMenuItem newJRadioButtonMenuItem(ButtonGroup group, String text, String level) {
          JRadioButtonMenuItem item = new JRadioButtonMenuItem(text);
          item.addActionListener(this.menuListener);
          group.add(item);
          if(text.equalsIgnoreCase(level)) item.setSelected(true);
          return item;
      private class Cell extends JPanel
        private static final long serialVersionUID = 0L;
        public static final int WIDTH = 17;
        public static final int HEIGHT = 17;
        public static final float Y_OFFSET = 13F;
        public static final float X_OFFSET = 5F;
        private class Button extends JButton {
          private static final long serialVersionUID = 0L;
          private final Cell parentCell;
          public Button(int width, int height, Cell parentCell) {
            this.parentCell = parentCell;
            this.setBounds(0, 0, width, height);
            this.setMargin(new Insets(1,1,1,1));
            this.setFont(new Font("Dialog",0,8));
            this.addMouseListener(mouseListener); // handles left & right button
          public void reset() {
            this.setText("");
            this.setVisible(true);
            this.setIcon(null);
          public Cell getParentCell() {
            return this.parentCell;
          public void removeMouseListener() {
            this.removeMouseListener(mouseListener);
        private final Button button;
        private final int row, col;
        private boolean isBomb = false;
        private boolean isRevealed = false;
        private boolean isExploded = false;
        private int neighbours = 0;
        public static final int STATE_UNMARKED = 0;
        public static final int STATE_MARKED_AS_A_BOMB = 1;
        public static final int STATE_MARKED_AS_A_QUESTION = 2;
        private int state = 0;
        private ImageIcon[] stateIcons = new ImageIcon[] {
          null,  new ImageIcon(FLAG_IMAGE), new ImageIcon(QUESTION_IMAGE)
        Cell(int row, int col) {
          this.row = row;
          this.col = col;
          this.setBounds(col*WIDTH, row*HEIGHT, WIDTH, HEIGHT);
          this.setLayout(null);
          button = new Button(WIDTH, HEIGHT, this);
          this.add(button);
        public boolean isBomb() { return this.isBomb; }
        public void setBomb(boolean isBomb) { this.isBomb = isBomb; }
        public boolean isRevealed() { return this.isRevealed; }
        public void reveal() {
          if(this.isRevealed) return;
          this.button.setVisible(false);
          this.isRevealed = true;
        public void revealNotABomb() {
          button.setText("");
          button.setIcon(new ImageIcon(NOT_BOMB_IMAGE));
        public boolean isExploded() { return this.isExploded; }
        public void explode() {this.isExploded = true;}
        public int getNeighbours() { return this.neighbours; }
        public void setNeighbours(int neighbours) {this.neighbours = neighbours;}
        public void reset() {
          this.isRevealed = false;
          this.isBomb = false;
          this.isExploded = false;
          this.state = STATE_UNMARKED;
          this.button.reset();
        public boolean isMarkedAsBomb() {
          return this.state == Cell.STATE_MARKED_AS_A_BOMB;
        public void nextState() {
          boolean wasMarkedAsABomb = this.isMarkedAsBomb();
          this.state = (this.state+1) % 3;
          button.setIcon(stateIcons[this.state]);
          if (this.isMarkedAsBomb()) {
            setBombsRemaining(getBombsRemaining()-1);
            if (getBombsRemaining() == 0) {
              if (allMarkedBombsAreReallyBombs()) {
                youWon();
              } else {
                youLost();
          } else if (wasMarkedAsABomb) {
            setBombsRemaining(getBombsRemaining()+1);
        public void removeMouseListener() {
          button.removeMouseListener();
        @Override
        public void paintComponent(Graphics g) {
          super.paintComponent(g);
          if ( this.isRevealed() ) {
            Graphics2D g2 = (Graphics2D) g;
            if (this.isExploded) {
              g2.drawImage(EXPLODED_IMAGE, 0, 0, null);
            } else if (this.isBomb) {
              g2.drawImage(BOMB_IMAGE, 0, 0, null);
            } else if (this.neighbours > 0) {
              g2.setColor(COLORS[this.neighbours]);
              g2.setFont(FONT);
              g2.drawString(""+this.neighbours, X_OFFSET, Y_OFFSET);
      private MouseListener mouseListener = null;
      private GameProperties properties = null;
      private Cell[][] cells = null;
      // this game is a "virgin" until the user finds the first 0.
      private boolean isVirgin = false;
      // when the user clears fifth square of a virgin game the
      // largest patch of 0's is automagically cleared.
      private int numCleared = 0;
      MineSweeperGame() {
        theFrame = this;
        this.properties = new GameProperties();
        this.settings = this.properties.get();
        buildAndShowGUI();
      private void setMouseListener(){
        this.mouseListener = new MouseAdapter() {
          public void mouseClicked(MouseEvent event) {
            clock.start();
            Cell cell = ((Cell.Button)event.getSource()).getParentCell();
            if ( event.getButton() == MouseEvent.BUTTON1 ) {
              if(event.isControlDown()) clock.skip(5);
              if (cell.isBomb()) {
                if ( cell.isMarkedAsBomb() ) {
                  java.awt.Toolkit.getDefaultToolkit().beep();
                } else if ( event.isControlDown() ) {
                  WavePlayer.play(WAVDIR+"ricochet.wav");
                } else {
                  WavePlayer.play(WAVDIR+"grenade.wav");
                  cell.explode();
                  youLost();
              } else {
                revealCell(cell);
                if ( isVirgin && ++numCleared==5 ) {
                  WavePlayer.play(WAVDIR+"smokin.wav");
                  revealTheBiggestFreePatch();
            } else if ( event.getButton() == MouseEvent.BUTTON3 ) {
              cell.nextState();
      private void hideAndDestroyGUI() {
        this.setVisible(false);
        for(int r=0; r<settings.rows; r++) {
          for(int c=0; c<settings.cols; c++) {
            cells[r][c].removeMouseListener(); // old mouse listeners send it crazy.
            cells[r][c] = null;
        this.getContentPane().removeAll();
        this.dispose();
      private void buildAndShowGUI() {
        final int CELLS_X = Cell.WIDTH*settings.cols;
        final int WASTE_X = 9;
        final int WIN_WIDTH = CELLS_X+WASTE_X;
        final int CELLS_Y = Cell.HEIGHT*settings.rows;
        final int WASTE_Y = 59;
        final int TOP_FRAME_Y = 34;
        final int WIN_HEIGHT = CELLS_Y+WASTE_Y+TOP_FRAME_Y;
        this.setTitle("Miner");
        this.setSize(WIN_WIDTH, WIN_HEIGHT);
        this.setResizable(false);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setJMenuBar( new GameMenuBar(this.settings.level) );
        this.getContentPane().setLayout(null);
        // the top panel
        JPanel top = new JPanel(null);
        top.setBounds(0,0, WIN_WIDTH-6,TOP_FRAME_Y);
        top.setBorder(new LineBorder(Color.black));
        // the remaining-bomb-counter (on the left)
        bombs = new JLabel();
        bombs.setBounds(5,7, 23,17);
        bombs.setBorder(new LineBorder(Color.black));
        top.add(bombs);
        // the time-counter (on the right)
        this.clock = new GameClock();
        clock.setBounds(WIN_WIDTH-35,7, 23,17);
        top.add(clock);
        this.getContentPane().add(top);
        // the bottom panel
        setMouseListener();
        JPanel bot = new JPanel();
        bot.setLayout(null);
        bot.setBackground(Color.white);
        bot.setBounds(0, TOP_FRAME_Y+1, CELLS_X, CELLS_Y);
        this.cells = new Cell[settings.rows][settings.cols];
        for(int r=0; r<settings.rows; r++) {
          for(int c=0; c<settings.cols; c++) {
            cells[r][c] = new Cell(r, c);
            bot.add(cells[r][c]);
        this.getContentPane().add(bot);
        resetGame();
        this.setVisible(true);
      private void resetGame() {
        clock.reset();
        resetCells();
        isVirgin = true;
        numCleared = 0;
        placeBombs();
        setBombsRemaining(settings.bombs);
        countNeighbouringBombs();
      // reset the state of all the cells to default "empty" values.
      private void resetCells() {
        for(int r=0; r<settings.rows; r++) {
          for(int c=0; c<settings.cols; c++) {
            cells[r][c].reset();
      // randomly place however many bombs in the minefield
      // if replay then reuses the same seed to reproduce the same mine layout.
      private void placeBombs() {
        if(!this.replayCurrentGame) this.randomSeed = System.currentTimeMillis();
        this.replayCurrentGame = false;
        Random rand = new Random(this.randomSeed);
        for(int i=0; i<settings.bombs; i++) {
          while(true) {
            Cell cell = this.cells[rand.nextInt(settings.rows)][rand.nextInt(settings.cols)];
            if (!cell.isBomb()) {
              cell.setBomb(true);
              //cell.button.setText("b");
              break;
      // count the number of bombs neighbouring each cell
      private void countNeighbouringBombs() {
        for(int r=0; r<settings.rows; r++) {
          for(int c=0; c<settings.cols; c++) {
            cells[r][c].setNeighbours(getNeighbourCount(r, c));
      // return the number of bombs neighbouring the given cell
      private int getNeighbourCount(int row, int col) {
        int count = 0;
        int firstRow = Math.max(row-1, 0);
        int lastRow  = Math.min(row+1, settings.rows-1);
        int firstCol = Math.max(col-1, 0);
        int lastCol  = Math.min(col+1, settings.cols-1);
        for(int r=firstRow; r<=lastRow; r++) {
          for(int c=firstCol; c<=lastCol; c++) {
            if( this.cells[r][c].isBomb ) count++;
        return count;
      public void setBombsRemaining(int bombsRemaining) {
        this.bombsRemaining = bombsRemaining;
        this.bombs.setText(""+this.bombsRemaining);
      public int getBombsRemaining() {
        return(this.bombsRemaining);
      private void showBombs() {
        for(int r=0; r<settings.rows; r++) {
          for(int c=0; c<settings.cols; c++) {
            Cell cell = cells[r][c];
            if (cell.isBomb) {
              cell.reveal();
            } else if (cell.isMarkedAsBomb()) {
              cell.revealNotABomb();
      private boolean allMarkedBombsAreReallyBombs() {
        for(int r=0; r<settings.rows; r++) {
          for(int c=0; c<settings.cols; c++) {
            Cell cell = this.cells[r][c];
            if (cell.isMarkedAsBomb() && !cell.isBomb() ) {
              return false;
        return true;
      private void revealCell(Cell cell) {
        if(cell.getNeighbours()==0) {
          revealCells(cell, new HashMap<Cell,Object>());
        } else {
          cell.reveal();
      private void revealTheBiggestFreePatch() {
        Map<Cell,Object> counted = new HashMap<Cell,Object>();
        int count = 0;
        int max = 0;
        Cell maxCell = null;
        for(int r=0; r<settings.rows; r++) {
          for(int c=0; c<settings.cols; c++) {
            Cell cell = this.cells[r][c];
            if(cell.getNeighbours()==0) {
              count = countNeighbouringZeros(cell, counted);
              if(count > max) {
                max = count;
                maxCell = cell;
        revealCell(maxCell);
      private int countNeighbouringZeros(Cell cell, Map<Cell,Object> counted) {
        int count = 0;
        if (counted.containsKey(cell)) return 0;
        counted.put(cell, null);
        if(cell.getNeighbours()==0) {
          count++;
          int firstRow = Math.max(cell.row-1, 0);
          int lastRow  = Math.min(cell.row+1, settings.rows-1);
          int firstCol = Math.max(cell.col-1, 0);
          int lastCol  = Math.min(cell.col+1, settings.cols-1);
          for(int r=firstRow; r<=lastRow; r++) {
            for(int c=firstCol; c<=lastCol; c++) {
              Cell x = cells[r][c];
              if (x == cell) continue;
              if (x.getNeighbours()==0) {
                count += countNeighbouringZeros(x, counted);
        return count;
      private void revealCells(Cell cell, Map<Cell,Object> ancestors) {
        if (ancestors.containsKey(cell)) return;
        if (cell.isRevealed()) return;
        ancestors.put(cell, null);
        cell.reveal();
        if(cell.getNeighbours()==0) {
          isVirgin = false;
          int firstRow = Math.max(cell.row-1, 0);
          int lastRow  = Math.min(cell.row+1, settings.rows-1);
          int firstCol = Math.max(cell.col-1, 0);
          int lastCol  = Math.min(cell.col+1, settings.cols-1);
          for(int r=firstRow; r<=lastRow; r++) {
            for(int c=firstCol; c<=lastCol; c++) {
              Cell x = cells[r][c];
              if (x == cell) continue;
              if( !x.isBomb() && !x.isRevealed() ) {
                revealCells(x, ancestors);
      private void youLost() {
        clock.stop();
        showBombs();
        //WavePlayer.play(WAVDIR+"msstartup.wav");
        Object[] options = { "Replay", "New Game" };
        int choice = JOptionPane.showOptionDialog(
            null
          , "Replay?"
          , "Game Over."
          , JOptionPane.DEFAULT_OPTION
          , JOptionPane.QUESTION_MESSAGE
          , null
          , options
          , options[0]
        if (choice == 0) {
          replayCurrentGame = true;
        resetGame();
      private void youWon() {
        clock.stop();
        WavePlayer.play(WAVDIR+"applause.wav");
        JOptionPane.showMessageDialog(this, "Congratulations. You Won!", "Game Over", JOptionPane.INFORMATION_MESSAGE);
        resetGame();
      private static BufferedImage loadImage(String filename) {
        try {
          return ImageIO.read(new File(filename));
        } catch (Exception e) { //IOExcecption
          // the game will still kinda work, you just won't see the images.
          e.printStackTrace();
        return null;
      public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(
          new Runnable() {
            public void run() {
              MineSweeperGame game = new MineSweeperGame();
    CustomSettingsDialog.java
    package krc.games.sweeper;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class CustomSettingsDialog extends JDialog implements ActionListener
      private static final long serialVersionUID = 0L;
      private static final int ROW_HEIGHT = 24;
      private static final int PAD = 5;
      private boolean isOk = false;
      GameSettings settings;
      private JPanel panel;
      private JTextField rowsTextField;
      private JTextField colsTextField;
      private JTextField bombsTextField;
      private JButton okButton;
      private JButton cancelButton;
      CustomSettingsDialog(JFrame parentFrame, GameSettings settings) {
        super(parentFrame, true);
        this.settings = settings;
        this.setTitle("Custom Miner");
        this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        this.setSize(250, 200);
        this.setResizable(false);
        panel = new JPanel();
        panel.setLayout(null);
        addLabel(0, "rows"); rowsTextField = addField(0, ""+settings.rows);
        addLabel(1, "cols"); colsTextField = addField(1, ""+settings.cols);
        addLabel(2, "bombs"); bombsTextField = addField(2, ""+settings.bombs);
        okButton = addButton(3,0, "Ok");
        cancelButton = addButton(3,1, "Cancel");
        rowsTextField.selectAll();
        rowsTextField.requestFocusInWindow();
        this.add(panel);
        this.setVisible(true);
      boolean isOk() {
        return this.isOk;
      GameSettings getSettings() {
        return this.settings;
      private void addLabel(int row, String caption) {
        JLabel label = new JLabel(caption);
        label.setBounds(PAD, PAD+((ROW_HEIGHT+PAD)*row), 80, ROW_HEIGHT);
        panel.add(label);
      private JTextField addField(int row, String text) {
        JTextField field = new JTextField();
        field.setBounds(80, PAD+((ROW_HEIGHT+PAD)*row), 100, ROW_HEIGHT);
        field.setText(text);
        panel.add(field);
        return(field);
      private JButton addButton(int row, int col, String caption) {
        JButton button = new JButton(caption);
        button.setBounds(20+(col*85), PAD+((ROW_HEIGHT+PAD)*row), 80, ROW_HEIGHT);
        button.addActionListener(this);
        panel.add(button);
        return(button);
      public void actionPerformed(ActionEvent event) {
        if ( okButton == event.getSource() ) {
          try {
            this.settings.level = "custom";
            this.settings.rows = Integer.parseInt(rowsTextField.getText());
            this.settings.cols = Integer.parseInt(colsTextField.getText());
            this.settings.bombs = Integer.parseInt(bombsTextField.getText());
            this.isOk = true;
            this.setVisible(false);
          } catch(NumberFormatException e) {
            JOptionPane.showMessageDialog(this, e.getMessage(), "NumberFormatException", JOptionPane.ERROR_MESSAGE);
        } else if ( cancelButton == event.getSource() ) {
          this.isOk = false;
          this.setVisible(false);
        } else {
          java.awt.Toolkit.getDefaultToolkit().beep();
          System.out.println("CustomSettingsDialog.actionPerformed: Unknown event source "+event.getSource());
    GameProperties.java
    package krc.games.sweeper;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    class GameProperties extends java.util.Properties
      private static final long serialVersionUID = 0L;
      private static final String FILENAME = "MineSweeperGame.properties";
      public GameProperties() {
        super();
        load();
      public GameSettings get(String level) {
        return new GameSettings(
            level
          , getInt(level+"_rows")
          , getInt(level+"_cols")
          , getInt(level+"_bombs")
      public GameSettings get() {
        return get(getProperty("level"));
      public void set(GameSettings settings) {
        setProperty("level", settings.level);
        setProperty(settings.level+"_rows", ""+settings.rows);
        setProperty(settings.level+"_cols", ""+settings.cols);
        setProperty(settings.level+"_bombs", ""+settings.bombs);
      public void load() {
        try {
          load(new FileReader(FILENAME));
        } catch (Exception e) {
          System.err.println("Failed to load properties from "+FILENAME+" - "+e);
          e.printStackTrace();
      public void save() {
        try {
          store(new FileWriter(FILENAME), FILENAME);
        } catch (Exception e) {
          System.err.println("Failed to save properties to "+FILENAME+" - "+e);
          e.printStackTrace();
      private int getInt(String key) {
        try {
          return Integer.parseInt(getProperty(key));
        } catch (Exception e) {
          e.printStackTrace();
          throw new RuntimeException("Failed to getPropertyAsInt("+key+") from "+FILENAME+" - "+e);
    GameSettings.java
    package krc.games.sweeper;
    class GameSettings
      public String level;
      public int rows;
      public int cols;
      public int bombs;
      GameSettings(String level, int rows, int cols, int bombs) {
        this.level = level;
        this.rows = rows;
        this.cols = cols;
        this.bombs = bombs;
    GameClock.java
    package krc.games.sweeper;
    import javax.swing.JLabel;
    import javax.swing.border.LineBorder;
    import java.awt.Color;
    class GameClock extends JLabel
      private static final long serialVersionUID = 0L;
      private volatile boolean isRunning = false;
      private volatile int elapsedTime;
      public GameClock() {
        super("0");
        elapsedTime = 0;
        this.setBorder(new LineBorder(Color.black));
      public void start() {
        if(isRunning) return;
        isRunning = true;
        new Thread() {
          public void run() {
            while (isRunning) {
              setText(""+(elapsedTime++));
              try{Thread.sleep(1000);}catch(InterruptedException eaten){}
        }.start();
      public void stop() {
        this.isRunning = false;
      public void skip(int seconds) {
        elapsedTime+=seconds;
      public void reset() {
        elapsedTime = 0;
        super.setText("0");
    MineSweeperGame.properties
    #MineSweeperGame.properties
    #Sat Dec 29 18:56:47 GMT+10:00 2007
    level=expert
    beginner_rows=9
    beginner_cols=9
    beginner_bombs=10
    intermediate_rows=16
    intermediate_cols=16
    intermediate_bombs=40
    expert_rows=16
    expert_cols=30
    expert_bombs=99
    custom_rows=30
    custom_cols=50
    custom_bombs=299-----
    BTW... I gave up on the whole refactor thing... I just couldn't work out how to cleanly separate the view from the model... and my design was getting mighty complicated.... bigger than ben hurr... So I decided to revert to the "hack" version, and do a little refactoring to try to split out the more-easily-split-out sections, and tada - I (mostly) got through the TODO list.
    Also... can anyone point me at a good serialization tutorial... sun's is a bit how's your dad.
    Thanx all.

  • How can i impement some simple menu bar into this code ?

    Hello all.
    I have a problem with my program. I wanna add a simple menu bar, but i don't have any idea how to do it.
    Here is code of my program:
    import java.awt.Menu;
    import javax.swing.event.MenuListener;
    import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter.DEFAULT;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.events.PaintEvent;
    import org.eclipse.swt.events.PaintListener;
    import org.eclipse.swt.graphics.GC;
    import org.eclipse.swt.graphics.Image;
    import org.eclipse.swt.layout.FillLayout;
    import org.eclipse.swt.widgets.Canvas;
    import org.eclipse.swt.widgets.Display;
    import org.eclipse.swt.widgets.Event;
    import org.eclipse.swt.widgets.Listener;
    import org.eclipse.swt.widgets.MenuItem;
    import org.eclipse.swt.widgets.Shell;
    public class SimpleGraphicEditor {
    public Display display;
    public Shell shell,shellmenu;
    public Canvas canvas;
    public Image imageBuffer;
    org.eclipse.swt.widgets.Menu menu;
    public Menu fileMenu, editMenu, viewMenu;
    int startx=0;
    int starty=0;
    int endx=0;
    int endy=0;
         public SimpleGraphicEditor() {
              display = new Display();
              shell = new Shell(display);
              createGUI();
              shell.open();
                   while(!shell.isDisposed()) {
                   if(!display.readAndDispatch()) {
                        display.sleep();
              } // end of simple grapphic editor
              private void createGUI() {
                   shell.setLayout(new FillLayout());
                   canvas = new Canvas(shell, SWT.BORDER);
                   menu = null;
                   shell.setText("Simple rec draw");
                   shell.setSize(500, 500);
                   shell.setMenuBar(menu);
                   canvas.addPaintListener(new PaintListener() {
                             public void paintControl(PaintEvent e) {
                             e.gc.drawImage(imageBuffer, 0, 0, 500, 500, 0, 0, 500, 500);      
                   imageBuffer = new Image(display, 500, 500);
                   Listener listener = new Listener() {
                        private boolean isDrawing;
                        private GC gc = new GC(imageBuffer);
                        private int oldX = 0;
                        private int oldY = 0;
                        private int newX = 0;
                        private int newY = 0;
                        private boolean isDeleting;
                        public void handleEvent(Event event) {
                             // System.err.println("type=" + event.type);
                             switch(event.type) {
                             case SWT.MouseDown:
                                  // System.err.println("button down");
                                  switch(event.button) {
                                  case 1:
                                       isDrawing = true;
                                       System.out.println("Start at:("+event.x+","+event.y);
                                       startx=event.x;
                                       starty=event.y;
                                       break;
                                  case 2:
                                       System.err.println("button2 down");
                                       break;
                                  case 3:
                                       isDeleting = true;
                                       gc.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
                                       break;
                                  break;
                             case SWT.MouseUp:
                                  // System.err.println("button up");
                                  switch(event.button) {
                                  case 1:
                                       isDrawing = false;
                                       // --- czyszczenie tablicy ---
                                       System.out.println("End at:("+event.x+","+event.y);
                                       int szerokosc=event.x-startx;
                                       int wysokosc=event.y-starty;
                                       //gc.drawRectangle(startx, starty, szerokosc,wysokosc);
                                       gc.setBackground(display.getSystemColor(SWT.COLOR_GREEN));
                                       gc.fillRectangle(startx, starty, szerokosc,wysokosc);
                                       canvas.redraw();
                                       break;
                                  case 2:
                                       System.err.println("button2 up");
                                       break;
                                  case 3:
                                       isDeleting = false;
                                       break;
                                  break;
                             case SWT.MouseMove:
                                  newX = event.x;
                                  newY = event.y;
                                  // System.err.println("mouse moved");
                                  if(isDrawing) {
                                                   // ----------- draw at hold  -----------------------------                    
                                       //gc.drawLine(oldX, oldY, newX, newY);
                                       int szerokosc=event.x-startx;
                                       int wysokosc=event.y-starty;
                                       gc.setForeground(display.getSystemColor(SWT.COLOR_BLACK));
                                       gc.drawText("x:"+event.x+", y:"+event.y+"  ", 0, 0);
                                       canvas.redraw();
                                       // ----- Clear the whole area -------------
                                       gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
                                       gc.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
                                       gc.fillRectangle(startx, starty, szerokosc+500, wysokosc+500);
                                       gc.fillRectangle(startx, starty, szerokosc-500, wysokosc-500);
                                       gc.fillRectangle(startx, starty, szerokosc+500, wysokosc-500);
                                       gc.fillRectangle(startx, starty, szerokosc-500, wysokosc+500);
                                       canvas.redraw();
                                       gc.setForeground(display.getSystemColor(SWT.COLOR_DARK_BLUE));
                                       gc.drawRectangle(startx, starty, szerokosc, wysokosc);
                                       canvas.redraw();
                                       int x = (oldX < newX) ? oldX : newX;
                                       int y = (oldY < newY) ? oldY : newY;
                                       int width = (oldX < newX) ? (newX-oldX) : (oldX - newX);
                                       int height = (oldY < newY) ? (newY-oldY) : (oldY - newY);
                                       if(width < 20) width = 20;
                                       if(height < 20) height = 20;
                                       canvas.redraw(x, y, width, height, true);
                                  } else if(isDeleting) {
                                       // Color c = gc.getBackground();
                                       // gc.setBackground(gc.getForeground());
                                       gc.fillRectangle(newX - 15, newY - 15, 30, 30);
                                       canvas.redraw(newX - 15, newY - 15, 30, 30, true);
                                       // gc.setBackground(c);
                                       break;
                             } // end switch caly
                             oldX = event.x;
                             oldY = event.y;
                   canvas.redraw();
                   canvas.addListener(SWT.MouseDown, listener);
                   canvas.addListener(SWT.MouseUp, listener);
                   canvas.addListener(SWT.MouseMove, listener);
              public static void main(String[] args) {
                   new SimpleGraphicEditor();
    }

    nitroduxe wrote:
    ok i add the following code:
    menu = new org.eclipse.swt.widgets.Menu(shell, SWT.BAR);
                   MenuItem fileItem = new MenuItem(menu, SWT.CASCADE);
                  fileItem.setText("menu1");
                  MenuItem editItem = new MenuItem(menu, SWT.CASCADE);
                  editItem.setText("menu2");
                  MenuItem viewItem = new MenuItem(menu, SWT.CASCADE);
                  viewItem.setText("menu3");
                  shell.setMenuBar(menu); // DODANIE MENUhow now i can add some submenu into menu1 and menu2 and menu3 ?
    Edited by: nitroduxe on Mar 9, 2010 10:23 AMI would start by reading the [menu tutorial|http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html].

  • Dock question:  Can I turn off the expansion/condensing effects of Fan and Grid view?

    Hi!
    Can I turn off the Dock menu expansion/condensing animations related to Fan and Grid view (and the condensing effect of List view)?  I find the expansion/condensing animations slow and detracting from an efficient workflow.  I would rather have menus pop up immediately so I can instinctively move the mouse cursor where I can anticipate a file to be located once grid/fan view window launches, rather than have to track the expansion animation with the mouse cursor so that I can select the desired file once it lands in its fixed position.
    Is there any known backdoor way to cease these showboating animations?
    For the dock to be such a major addition to the Mac OS (when compared to OS 9), I am surprised that there isn't greater customization for it.  Speaking of which, why can't we have the option of having more than one dock, for example?  I would like to have one mounted to the bottom of my screen for applications, but also have one on the left of my screen for commonly-accessed files and folders.
    I am all for stock settings that help to streamline features for users as a baseline, but the more tweakable options the better.  I pay a premium for Apple products; who are they to tell me I can have only one dock?!  ;p
    I've taken a look at Docker and Deeper, but neither delivered the goods.  Thanks so much!
    P.S.  I am still using Snow Leopard.  I haven't heard of new dock options for Lion, so please clarify if I am missing out on a Lion innovation.
    Thanks again!

    Take a look at Secrets, OnyX, or Tinker Tools. All of those have various undocumented preference settings that affect various animations.

  • Trouble with my dropdown menu

    I'm new to Java and I am getting pretty frustrated. I need a drop-down menu in my calculator and I'm probably doing this all wrong.
    When I compile my code, I don't get any errors but when I run it, I get:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at mortgagePaymentAmount.mortgagePaymentAmount(mortgagePaymentAmount.java:50)
    at mortgagePaymentAmount.<init>(mortgagePaymentAmount.java:27)
    at mortgagePaymentAmount$4.run(mortgagePaymentAmount.java:243)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:598)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:300)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:210)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:200)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:195)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:187)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    Here is my code. Can someone please help me out? Thank you.
    import java.lang.*;
    import java.text.DecimalFormat;
    import javax.swing.*;   
    public class mortgagePaymentAmount extends javax.swing.JFrame
      public mortgagePaymentAmount()
      mortgagePaymentAmount();
      private void mortgagePaymentAmount()
      /*From http://java.sun.com/docs/books/tutorial/uiswing/learn/index.html*/
      /*Fields for user to input data and labels on the side of the fields*/
      //Amount of mortgage
      loanAmountTextField = new javax.swing.JTextField();
      loanAmountLabel = new javax.swing.JLabel();
      //Term of mortgage
      monthsTextField = new javax.swing.JTextField();
      monthsLabel = new javax.swing.JLabel();
      //Interest rate
      interestTextField = new javax.swing.JTextField();
      interestLabel = new javax.swing.JLabel();
      menuBar = new javax.swing.JMenuBar();
      frame.setJMenuBar(menuBar);
      menu = new javax.swing.JMenu("Menu Label");
      item1 = new javax.swing.JMenuItem("Item Label 1");
      item2 = new javax.swing.JMenuItem("Item Label 2");  
      //Calculate
      calcButton = new javax.swing.JButton();
      calcButton.setText("Calculate");
      calcButton.addActionListener(new java.awt.event.ActionListener()
        public void actionPerformed(java.awt.event.ActionEvent evt)
        { calcButtonActionPerformed(evt); }
      //Reset
      resetButton = new javax.swing.JButton();
      resetButton.setText("Reset form");
      resetButton.addActionListener(new java.awt.event.ActionListener()
        public void actionPerformed(java.awt.event.ActionEvent evt)
        { resetButtonActionPerformed(evt); }
      //Quit
      quitButton = new javax.swing.JButton();
      quitButton.setText("Quit");
      quitButton.addActionListener(new java.awt.event.ActionListener()
        public void actionPerformed(java.awt.event.ActionEvent evt)
        { quitButtonActionPerformed(evt); }
      //Monthly payment amount display
      monthlyPaymentLabel = new javax.swing.JLabel();
      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
      //Title
      setTitle("Mortgage Calculator v2.3");
      //Labels for each field
      loanAmountLabel.setText("Amount of Mortgage (no commas)");
      monthsLabel.setText("Term of Mortgage (in years)");
      interestLabel.setText("% interest rate");
      monthlyPaymentLabel.setText("Monthly payment amount");
      //Layout of buttons using
      //http://java.sun.com/docs/books/tutorial/uiswing/examples/learn/CelsiusConverterProject/src/learn/CelsiusConverterGUI.java
      //as my template
      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(  //Horizontal positioning
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
          .addContainerGap()
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            //Loan amount field and label position
            .addGroup(layout.createSequentialGroup()
              .addComponent(loanAmountTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(loanAmountLabel))
             //Months field and label position
            .addGroup(layout.createSequentialGroup()
              .addComponent(monthsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(monthsLabel))
            //Interest field and label position 
            .addGroup(layout.createSequentialGroup()
              .addComponent(interestTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(interestLabel))
            //Menu bar
            .addGroup(layout.createSequentialGroup()
              .addComponent(menuBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(menuBar))
            //Calculate button           
            .addGroup(layout.createSequentialGroup()
              .addComponent(calcButton)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(monthlyPaymentLabel))
            //Reset button           
            .addGroup(layout.createSequentialGroup()
              .addComponent(resetButton)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(monthlyPaymentLabel))
            //Quit button           
            .addGroup(layout.createSequentialGroup()
              .addComponent(quitButton)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(monthlyPaymentLabel)))
          .addContainerGap(30, Short.MAX_VALUE)) //length
      layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {item2, item1, menu, menuBar, resetButton, quitButton, calcButton, loanAmountTextField, monthsTextField, interestTextField});   
      layout.setVerticalGroup( //Vertical positioning
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
          .addContainerGap()
          //Loan amount field and label position
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(loanAmountTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(loanAmountLabel))
          //Months field and label position         
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(monthsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(monthsLabel))
          //Interest field and label position 
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(interestTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(interestLabel))
          //Menu bar
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(menuBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(menuBar))
          //Calculate button           
          .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(calcButton)
            .addComponent(monthlyPaymentLabel))
          //Reset button
          .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(resetButton))
          //Quit button
          .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(quitButton))
        .addContainerGap(20, Short.MAX_VALUE)) //height
        pack(); 
      //Calculation action
      private void calcButtonActionPerformed(java.awt.event.ActionEvent evt)
      DecimalFormat df = new DecimalFormat("0.##");  //DecimalFormat derived from http://forum.java.sun.com/ to make no more than two decimal places.
      //My calcuations
      double months = ((Double.parseDouble(monthsTextField.getText())) * 12); //months calculated into years
      double loanAmount = (Double.parseDouble(loanAmountTextField.getText()) );
      double interest = ((Double.parseDouble(interestTextField.getText())) / 100); //interest decimal calculated into percentage
      double monthlyAmount = (loanAmount * (interest/12.0))/(1 - 1 /Math.pow((1 + interest/12.0), months));
      monthlyPaymentLabel.setText(df.format(monthlyAmount) + " Monthly payment amount");  //output
      //Reset action
      private void resetButtonActionPerformed(java.awt.event.ActionEvent evt)
      new mortgagePaymentAmount().setVisible(true);
      //Quit action
      private void quitButtonActionPerformed(java.awt.event.ActionEvent evt)
      System.exit(0);
      //Run the program
      public static void main(String args[])
      java.awt.EventQueue.invokeLater(new Runnable()
        public void run()
          new mortgagePaymentAmount().setVisible(true);
        //variables
        private javax.swing.JLabel loanAmountLabel;
        private javax.swing.JLabel monthsLabel;
        private javax.swing.JLabel interestLabel;
        private javax.swing.JFrame frame;
        private javax.swing.JMenuBar menuBar;
        private javax.swing.JMenu menu;
        private javax.swing.JMenuItem item1;
        private javax.swing.JMenuItem item2;
        private javax.swing.JButton calcButton;
        private javax.swing.JLabel monthlyPaymentLabel;
        private javax.swing.JTextField loanAmountTextField;
        private javax.swing.JTextField monthsTextField;
        private javax.swing.JTextField interestTextField;
        private javax.swing.JButton quitButton;
        private javax.swing.JButton resetButton;
    }

    Don't be scared of actually reading these stacktraces - a lot of the time they give you all you need to solve your problem. This one tells you that there's a NullPointerException at line 50 of your class - you're trying to do something to, or call a method on, something that doesn't exist.

  • Menus in Swing

    How do you respond to menu events in Swing?

    you add an action listener to the menu ... look up the swing help thread or the doc for ActionListener

  • How to trap menu actions

    I am trying to perform some as a result of click on menu(not menu item) using SWINGS.
    i tried by adding the menu to menu listener . i overwride menuselected() method, but each time i select the menu(ie using arrow keys) the event is rising...
    how to over come this??

    I think you want to use ActionListeners with the actionPerformed method instead:
    http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html#event
    If any of your menu items performs an action that is duplicated by another menu item or by a tool-bar button you should look into using Actions instead of plain ActionListener classes:
    http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html

  • Dialogs and JDK1.6.0_10

    Hm. I have seen this like four times now; a user opens a dialog in any form (JDialog or glasspane) on top of a JFrame, the EDT is blocked and a new event pump is installed to continue painting, as things should be. However the dialog is not drawn and the frame freezes since you cannot close the dialog. Has anyone else had such an experience?
    Naturally this happens very rarely, like once or twice a week (with an average of 25 active users at any time). But if it happens and I pull the stack trace, I do not see anything wrong. AFAIK from the trace, the dialog should have been visible... A stack trace is below:
    Full thread dump Java HotSpot(TM) Client VM (11.0-b15 mixed mode):
    "Foxtrot Multi Worker Thread Runner #1" daemon prio=6 tid=0x4d410400 nid=0x6d8 in Object.wait() [0x4edbf000..0x4edbfb14]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            at java.lang.Object.wait(Object.java:485)
            at foxtrot.workers.SingleWorkerThread.takeTask(SingleWorkerThread.java:132)
            - locked <0x07cbe9c8> (a foxtrot.workers.MultiWorkerThread)
            at foxtrot.workers.SingleWorkerThread.run(SingleWorkerThread.java:180)
            at java.lang.Thread.run(Unknown Source)
    "Thread-5 StateChecker" prio=6 tid=0x4d429400 nid=0x250 waiting on condition [0x4e35f000..0x4e35fd14]
       java.lang.Thread.State: TIMED_WAITING (sleeping)
            at java.lang.Thread.sleep(Native Method)
            at nl.reinders.Reinders.run(Reinders.java:2186)
            at java.lang.Thread.run(Unknown Source)
    "ESTOS Timeouter" prio=6 tid=0x4d432400 nid=0x7c waiting on condition [0x4e2bf000..0x4e2bfa94]
       java.lang.Thread.State: TIMED_WAITING (sleeping)
            at java.lang.Thread.sleep(Native Method)
            at org.tbee.util.ThreadUtil.sleepForced(ThreadUtil.java:244)
            at org.tbee.util.ThreadUtil.sleepForced(ThreadUtil.java:224)
            at nl.reinders.estos.EstosWrapper.timeouter(EstosWrapper.java:863)
            at nl.reinders.estos.EstosWrapper.access$100(EstosWrapper.java:47)
            at nl.reinders.estos.EstosWrapper$2.run(EstosWrapper.java:832)
            at java.lang.Thread.run(Unknown Source)
    "ESTOS Dispatcher" prio=6 tid=0x4d4a4800 nid=0x114 runnable [0x4e26f000..0x4e26fa14]
       java.lang.Thread.State: RUNNABLE
            at java.net.SocketInputStream.socketRead0(Native Method)
            at java.net.SocketInputStream.read(Unknown Source)
            at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
            at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
            at sun.nio.cs.StreamDecoder.read(Unknown Source)
            - locked <0x0742a760> (a java.io.InputStreamReader)
            at java.io.InputStreamReader.read(Unknown Source)
            at java.io.BufferedReader.fill(Unknown Source)
            at java.io.BufferedReader.readLine(Unknown Source)
            - locked <0x0742a760> (a java.io.InputStreamReader)
            at java.io.BufferedReader.readLine(Unknown Source)
            at nl.reinders.estos.EstosWrapper.dispatch(EstosWrapper.java:748)
            at nl.reinders.estos.EstosWrapper.access$000(EstosWrapper.java:47)
            at nl.reinders.estos.EstosWrapper$1.run(EstosWrapper.java:714)
            at java.lang.Thread.run(Unknown Source)
    "D3D Screen Updater" daemon prio=8 tid=0x4d32e000 nid=0xccc in Object.wait() [0x4dc4f000..0x4dc4fb14]
       java.lang.Thread.State: TIMED_WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            at sun.java2d.d3d.D3DScreenUpdateManager.run(Unknown Source)
            - locked <0x068fbc18> (a java.lang.Object)
            at java.lang.Thread.run(Unknown Source)
    "TimerQueue" daemon prio=6 tid=0x4d31c400 nid=0xe00 in Object.wait() [0x4dbff000..0x4dbffb94]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            at javax.swing.TimerQueue.run(Unknown Source)
            - locked <0x069f81d8> (a javax.swing.TimerQueue)
            at java.lang.Thread.run(Unknown Source)
    "AWT-EventQueue-1" prio=6 tid=0x4d23b800 nid=0xd64 in Object.wait() [0x4d69e000..0x4d69fd14]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            at java.lang.Object.wait(Object.java:485)
            at java.awt.EventQueue.getNextEvent(Unknown Source)
            - locked <0x068b8a20> (a org.tbee.swing.EventQueue)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
            at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
            at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
            at java.awt.Dialog$1.run(Unknown Source)
            at java.awt.Dialog$3.run(Unknown Source)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.awt.Dialog.show(Unknown Source)
            at java.awt.Component.show(Unknown Source)
            at java.awt.Component.setVisible(Unknown Source)
            at java.awt.Window.setVisible(Unknown Source)
            at java.awt.Dialog.setVisible(Unknown Source)
            at org.tbee.swing.jpa.JpaEntitySearchBuilder.searchDialog(JpaEntitySearchBuilder.java:1670)
            at org.tbee.swing.jpa.JpaEntitySearchBuilder.searchSingleDialog(JpaEntitySearchBuilder.java:1403)
            at org.tbee.swing.jpa.JpaObjectNavigatorBar$11.actionPerformed(JpaObjectNavigatorBar.java:239)
            at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
            at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
            at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
            at javax.swing.JToggleButton$ToggleButtonModel.setPressed(Unknown Source)
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
            at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
            at java.awt.Component.processMouseEvent(Unknown Source)
            at javax.swing.JComponent.processMouseEvent(Unknown Source)
            at java.awt.Component.processEvent(Unknown Source)
            at java.awt.Container.processEvent(Unknown Source)
            at java.awt.Component.dispatchEventImpl(Unknown Source)
            at java.awt.Container.dispatchEventImpl(Unknown Source)
            at java.awt.Component.dispatchEvent(Unknown Source)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
            at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
            at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
            at java.awt.Container.dispatchEventImpl(Unknown Source)
            at java.awt.Window.dispatchEventImpl(Unknown Source)
            at java.awt.Component.dispatchEvent(Unknown Source)
            at java.awt.EventQueue.dispatchEvent(Unknown Source)
            at org.tbee.swing.EventQueue.dispatchEvent(EventQueue.java:83)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
            at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
            at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
            at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
            at java.awt.EventDispatchThread.run(Unknown Source)
    "DestroyJavaVM" prio=6 tid=0x002b6800 nid=0x718 waiting on condition [0x00000000..0x0090fd4c]
       java.lang.Thread.State: RUNNABLE
    "AWT-Windows" daemon prio=6 tid=0x38df4000 nid=0x814 runnable [0x390bf000..0x390bfa94]
       java.lang.Thread.State: RUNNABLE
            at sun.awt.windows.WToolkit.eventLoop(Native Method)
            at sun.awt.windows.WToolkit.run(Unknown Source)
            at java.lang.Thread.run(Unknown Source)
    "AWT-Shutdown" prio=6 tid=0x38df2800 nid=0x138 in Object.wait() [0x3906f000..0x3906fb94]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            at java.lang.Object.wait(Object.java:485)
            at sun.awt.AWTAutoShutdown.run(Unknown Source)
            - locked <0x06893fa0> (a java.lang.Object)
            at java.lang.Thread.run(Unknown Source)
    "Java2D Disposer" daemon prio=10 tid=0x38df1800 nid=0xd6c in Object.wait() [0x3901f000..0x3901fb14]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            at java.lang.ref.ReferenceQueue.remove(Unknown Source)
            - locked <0x068a4478> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(Unknown Source)
            at sun.java2d.Disposer.run(Unknown Source)
            at java.lang.Thread.run(Unknown Source)
    "Low Memory Detector" daemon prio=6 tid=0x38d81800 nid=0xac runnable [0x00000000..0x00000000]
       java.lang.Thread.State: RUNNABLE
    "CompilerThread0" daemon prio=10 tid=0x38d92000 nid=0xf34 waiting on condition [0x00000000..0x38eef9bc]
       java.lang.Thread.State: RUNNABLE
    "Attach Listener" daemon prio=10 tid=0x38a7d000 nid=0xd18 runnable [0x00000000..0x00000000]
       java.lang.Thread.State: RUNNABLE
    "Signal Dispatcher" daemon prio=10 tid=0x38a7bc00 nid=0xa60 waiting on condition [0x00000000..0x00000000]
       java.lang.Thread.State: RUNNABLE
    "Finalizer" daemon prio=8 tid=0x38a6c000 nid=0x98c in Object.wait() [0x38bdf000..0x38bdfa94]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            at java.lang.ref.ReferenceQueue.remove(Unknown Source)
            - locked <0x065c2d40> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(Unknown Source)
            at java.lang.ref.Finalizer$FinalizerThread.run(Unknown Source)
    "Reference Handler" daemon prio=10 tid=0x38a67800 nid=0xac4 in Object.wait() [0x38b8f000..0x38b8fb14]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            at java.lang.Object.wait(Object.java:485)
            at java.lang.ref.Reference$ReferenceHandler.run(Unknown Source)
            - locked <0x065c2dc8> (a java.lang.ref.Reference$Lock)
    "VM Thread" prio=10 tid=0x38a62800 nid=0x5fc runnable
    "VM Periodic Task Thread" prio=10 tid=0x38cd3800 nid=0x9dc waiting on condition
    JNI global references: 2883
    Heap
    def new generation   total 9600K, used 4976K [0x02aa0000, 0x03500000, 0x065b0000)
      eden space 8576K,  55% used [0x02aa0000, 0x02f3f720, 0x03300000)
      from space 1024K,  23% used [0x03400000, 0x0343c910, 0x03500000)
      to   space 1024K,   0% used [0x03300000, 0x03300000, 0x03400000)
    tenured generation   total 127084K, used 56180K [0x065b0000, 0x0e1cb000, 0x32aa0000)
       the space 127084K,  44% used [0x065b0000, 0x09c8d388, 0x09c8d400, 0x0e1cb000)
    compacting perm gen  total 36096K, used 35877K [0x32aa0000, 0x34de0000, 0x36aa0000)
       the space 36096K,  99% used [0x32aa0000, 0x34da9560, 0x34da9600, 0x34de0000)
    No shared spaces configured.Do note that the AWT-EventQueue-1 has installed a new event pump like it should for a new JDialog. The org.tbee.swing.EventQueue does nothing more than examining mouse click and uses that to install a popup menu on any swing component (copy, paste, etc). It has been used unchanged for two years now. The change would be the JRE.
    I've rolled back to 1.6.0_01, since that is what was used before and I'll monitor if the problem goes away.

    Hi,
    I've experienced something very similar to what you describe under JRE 1.6.0_10. I've rolled back to 1.6.0_03 and this appears to work thus far. When displaying a JDialog sometimes the dialog contents do not paint - the border is drawn but the contents of the dialog are not. JButtons present on the dialog work when clicked but are not drawn. Operation continues as normal when the dialog is closed and if the user closes the dialog and re-opens it then the problem does not repeat. The problem is very intermittent, occuring every couple days.
    We're using XP on Dell Optiplex PCs in case there is some link to the hardware here?
    I'd be very grateful if you would let me know if you manage to identify the cause of this problem. I will of course do the same. I'd really like to be able to ship my software with JRE 1.6.0_10 or later as these releases fix a long standing bug in the JFileChooser.
    Best regards

  • How do i use objects from one class in anohter?

    Hey
    I have two GUI classes ShowWhiteGUI and BasketGUI and then a control class ShowWhite. The control class calls all the method from anohter class's which the GUI classes are gonna use.
    The basis idea with this script is it shall be a very very simpel Shop. Where you can add items to a basket and then show the items in a new window(BasketGUI).
    So here is the problem. I cant create an object in both GUI classes, because then im working with two sets of data, right? So how do i do this?
    Here is my code:
    ShowWhiteGUI
    * ShowWhiteGUI.java
    * Created on 5. februar 2008, 10:43
    package userclasses;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    * @author  Lille mus
    public class ShowWhiteGUI extends javax.swing.JFrame {
        private BasketGUI basketGUI;
        private ShowWhite control;
        /** Creates new form ShowWhiteGUI */
        public ShowWhiteGUI() {
            basketGUI = new BasketGUI();
            control = new ShowWhite();
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            aboutDialog = new javax.swing.JDialog();
            jLabel1 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
            itemIdField = new javax.swing.JTextField();
            productIdLabel = new javax.swing.JLabel();
            numberOfItems = new javax.swing.JLabel();
            productId = new javax.swing.JTextField();
            basketButton = new javax.swing.JButton();
            jLabel2 = new javax.swing.JLabel();
            showBasketButton = new javax.swing.JButton();
            jMenuBar1 = new javax.swing.JMenuBar();
            menu = new javax.swing.JMenu();
            jMenu1 = new javax.swing.JMenu();
            open = new javax.swing.JMenuItem();
            quit = new javax.swing.JMenuItem();
            jMenuItem1 = new javax.swing.JMenuItem();
            jMenu2 = new javax.swing.JMenu();
            help = new javax.swing.JMenuItem();
            about = new javax.swing.JMenuItem();
            javax.swing.GroupLayout aboutDialogLayout = new javax.swing.GroupLayout(aboutDialog.getContentPane());
            aboutDialog.getContentPane().setLayout(aboutDialogLayout);
            aboutDialogLayout.setHorizontalGroup(
                aboutDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 400, Short.MAX_VALUE)
            aboutDialogLayout.setVerticalGroup(
                aboutDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 300, Short.MAX_VALUE)
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Show White's Shop");
            setBackground(new java.awt.Color(0, 102, 255));
            jLabel1.setFont(new java.awt.Font("Baby Kruffy", 0, 36));
            jLabel1.setText("Snow White?s Shop");
            jTextArea1.setColumns(20);
            jTextArea1.setEditable(false);
            jTextArea1.setRows(5);
            jTextArea1.setText(control.getPrintAllStockItems());
            jScrollPane1.setViewportView(jTextArea1);
            productIdLabel.setText("Varenummer:");
            numberOfItems.setText("Antal:");
            basketButton.setText("L?g i kurv");
            basketButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    putInBasket(evt);
            showBasketButton.setText("Vis indk?bskurv");
            showBasketButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    showBasket(evt);
            menu.setLabel("Fil");
            jMenu1.setText("Menu");
            menu.add(jMenu1);
            open.setLabel("?bn");
            open.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    open(evt);
            menu.add(open);
            quit.setLabel("Luk");
            quit.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    quit(evt);
            menu.add(quit);
            jMenuItem1.setLabel("Gem");
            jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    save(evt);
            menu.add(jMenuItem1);
            jMenuBar1.add(menu);
            jMenu2.setLabel("Hj?lp");
            help.setLabel("Hj?lp");
            help.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    help(evt);
            jMenu2.add(help);
            about.setLabel("Om Show White Shop");
            jMenu2.add(about);
            jMenuBar1.add(jMenu2);
            setJMenuBar(jMenuBar1);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(37, 37, 37)
                            .addComponent(jLabel1))
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(productIdLabel)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(itemIdField, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(numberOfItems))
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(productId, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 65, Short.MAX_VALUE)
                                        .addComponent(basketButton))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(31, 31, 31)
                                        .addComponent(jLabel2)))
                                .addGroup(layout.createSequentialGroup()
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(showBasketButton)))))
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel2))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 49, Short.MAX_VALUE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(productIdLabel)
                                .addComponent(itemIdField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(numberOfItems)
                                .addComponent(productId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(showBasketButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 202, Short.MAX_VALUE)
                            .addComponent(basketButton)))
                    .addContainerGap())
            pack();
        }// </editor-fold>                       
        public void createBasketWindow(){
            basketGUI.setVisible(true);
        private void showBasket(java.awt.event.ActionEvent evt) {                           
            createBasketWindow();
        private void putInBasket(java.awt.event.ActionEvent evt) {                            
            Integer itemId = Integer.parseInt(itemIdField.getText());
            String petToAdd = control.getFindItem(itemId);
            System.out.println(petToAdd);
            control.setAddItemToBasket(itemId);
            basketGUI.addPetToBasket(petToAdd);     
        private void help(java.awt.event.ActionEvent evt) {                     
        private void save(java.awt.event.ActionEvent evt) {                     
            System.out.println("Gemmer fil");
        private void open(java.awt.event.ActionEvent evt) {                     
            System.out.println("?bn fil");
        private void quit(java.awt.event.ActionEvent evt) {                     
            System.exit(0);
        public ShowWhite getControl(){
            return control;
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ShowWhiteGUI().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JMenuItem about;
        private javax.swing.JDialog aboutDialog;
        private javax.swing.JButton basketButton;
        private javax.swing.JMenuItem help;
        private javax.swing.JTextField itemIdField;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JMenu jMenu1;
        private javax.swing.JMenu jMenu2;
        private javax.swing.JMenuBar jMenuBar1;
        private javax.swing.JMenuItem jMenuItem1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextArea jTextArea1;
        private javax.swing.JMenu menu;
        private javax.swing.JLabel numberOfItems;
        private javax.swing.JMenuItem open;
        private javax.swing.JTextField productId;
        private javax.swing.JLabel productIdLabel;
        private javax.swing.JMenuItem quit;
        private javax.swing.JButton showBasketButton;
        // End of variables declaration                  
    }BasketGUI:
    * Basket.java
    * Created on 5. februar 2008, 15:29
    package userclasses;
    import javax.swing.JTextArea;
    * @author  Lille mus
    public class BasketGUI extends javax.swing.JFrame {
        private String newline = "\n";
        private InvoiceGUI invoiceGUI;
        /** Creates new form Basket */
        public BasketGUI() {       
            initComponents();
            //invoiceGUI = new InvoiceGUI();
        public void addPetToBasket(String pet){
            jTextArea1.append(pet+newline);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            jLabel1 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
            jButton1 = new javax.swing.JButton();
            itemIdField = new javax.swing.JTextField();
            jLabel2 = new javax.swing.JLabel();
            removeItemButton = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Indk?bskurv");
            jLabel1.setText("Indk?bskurv");
            jTextArea1.setColumns(20);
            jTextArea1.setRows(5);
            jScrollPane1.setViewportView(jTextArea1);
            jButton1.setText("K?b og print kvittering");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    printInvoice(evt);
            jLabel2.setText("Slet varenr");
            removeItemButton.setText("Slet");
            removeItemButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    removeItemFromBasket(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(21, 21, 21)
                            .addComponent(jLabel1))
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 141, Short.MAX_VALUE)
                                    .addComponent(jButton1))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel2)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(itemIdField, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(removeItemButton)))))
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel1)
                    .addGap(20, 20, 20)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButton1)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 125, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(itemIdField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(removeItemButton))
                    .addContainerGap())
            pack();
        }// </editor-fold>                       
        private void removeItemFromBasket(java.awt.event.ActionEvent evt) {                                     
            Integer itemId = Integer.parseInt(itemIdField.getText());
        private void printInvoice(java.awt.event.ActionEvent evt) {                             
            //invoiceGUI.setVisible(true);
        public JTextArea getTextArea(){
            return jTextArea1;
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new BasketGUI().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JTextField itemIdField;
        private javax.swing.JButton jButton1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextArea jTextArea1;
        private javax.swing.JButton removeItemButton;
        // End of variables declaration                  
    }ShowWhite:
    * ShowWhite.java
    * Created on 13. februar 2008, 18:15
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package userclasses;
    * @author Lille mus
    public class ShowWhite {
        public Basket basket;
        public Stock stock;
        /** Creates a new instance of ShowWhite */
        public ShowWhite() {
            stock = new Stock();
            basket = new Basket();
        public String getFindItem(int itemId){
            String returnItem = stock.findItem(itemId);
            return returnItem;
        public void setAddItemToBasket(int itemId){
            basket.addItemToBasket(itemId);
        public String getPrintAllStockItems(){
            return stock.printAllStockItems();
        public String getShowBasket(){
             return basket.showBasket();
        public void setRemoveItemFromBasket(int itemId){
            basket.removeItemFromBasket(itemId);
    }

    okay i tried this, but it give me a nullpointerexeption:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at userclasses.ShowWhiteGUI.initComponents(ShowWhiteGUI.java:75)
    at userclasses.ShowWhiteGUI.<init>(ShowWhiteGUI.java:21)
    at userclasses.ShowWhite.<init>(ShowWhite.java:26)
    at userclasses.Main.<init>(Main.java:16)
    at userclasses.Main$1.run(Main.java:31)
    ShowWhite
    public class ShowWhite {
        public Basket basket;
        public Stock stock;
        private ShowWhiteGUI mainGUI;
        private BasketGUI basketGUI;
        /** Creates a new instance of ShowWhite */
        public ShowWhite() {
            stock = new Stock();
            basket = new Basket();
            mainGUI = new ShowWhiteGUI(this);
            basketGUI = new BasketGUI();
        public String getFindItem(int itemId){
            String returnItem = stock.findItem(itemId);
            return returnItem;
        public void setAddItemToBasket(int itemId){
            basket.addItemToBasket(itemId);
        public String getPrintAllStockItems(){
            return stock.printAllStockItems();
        public String getShowBasket(){
             return basket.showBasket();
        public void setRemoveItemFromBasket(int itemId){
            basket.removeItemFromBasket(itemId);
        public void createMainGUI(){
            mainGUI.setVisible(true);
        public BasketGUI getBasketGUI(){
            return basketGUI;
        public void setAddPetToBasket(String pet){
            basketGUI.addPetToBasket(pet);
    }ShowWhiteGUI:
    public class ShowWhiteGUI extends javax.swing.JFrame {
        private ShowWhite control;
        /** Creates new form ShowWhiteGUI */
        public ShowWhiteGUI(ShowWhite control) {
            initComponents();
            this.control = control;
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            aboutDialog = new javax.swing.JDialog();
            jLabel1 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
            itemIdField = new javax.swing.JTextField();
            productIdLabel = new javax.swing.JLabel();
            numberOfItems = new javax.swing.JLabel();
            productId = new javax.swing.JTextField();
            basketButton = new javax.swing.JButton();
            jLabel2 = new javax.swing.JLabel();
            showBasketButton = new javax.swing.JButton();
            jMenuBar1 = new javax.swing.JMenuBar();
            menu = new javax.swing.JMenu();
            jMenu1 = new javax.swing.JMenu();
            open = new javax.swing.JMenuItem();
            quit = new javax.swing.JMenuItem();
            jMenuItem1 = new javax.swing.JMenuItem();
            jMenu2 = new javax.swing.JMenu();
            help = new javax.swing.JMenuItem();
            about = new javax.swing.JMenuItem();
            javax.swing.GroupLayout aboutDialogLayout = new javax.swing.GroupLayout(aboutDialog.getContentPane());
            aboutDialog.getContentPane().setLayout(aboutDialogLayout);
            aboutDialogLayout.setHorizontalGroup(
                aboutDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 400, Short.MAX_VALUE)
            aboutDialogLayout.setVerticalGroup(
                aboutDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 300, Short.MAX_VALUE)
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Show White's Shop");
            setBackground(new java.awt.Color(0, 102, 255));
            jLabel1.setFont(new java.awt.Font("Baby Kruffy", 0, 36));
            jLabel1.setText("Snow White?s Shop");
            jTextArea1.setColumns(20);
            jTextArea1.setEditable(false);
            jTextArea1.setRows(5);
            jTextArea1.setText(control.getPrintAllStockItems());
            jScrollPane1.setViewportView(jTextArea1);
            productIdLabel.setText("Varenummer:");
            numberOfItems.setText("Antal:");
            basketButton.setText("L?g i kurv");
            basketButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    putInBasket(evt);
            showBasketButton.setText("Vis indk?bskurv");
            showBasketButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    showBasket(evt);
            menu.setLabel("Fil");
            jMenu1.setText("Menu");
            menu.add(jMenu1);
            open.setLabel("?bn");
            open.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    open(evt);
            menu.add(open);
            quit.setLabel("Luk");
            quit.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    quit(evt);
            menu.add(quit);
            jMenuItem1.setLabel("Gem");
            jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    save(evt);
            menu.add(jMenuItem1);
            jMenuBar1.add(menu);
            jMenu2.setLabel("Hj?lp");
            help.setLabel("Hj?lp");
            help.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    help(evt);
            jMenu2.add(help);
            about.setLabel("Om Show White Shop");
            jMenu2.add(about);
            jMenuBar1.add(jMenu2);
            setJMenuBar(jMenuBar1);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(37, 37, 37)
                            .addComponent(jLabel1))
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(productIdLabel)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(itemIdField, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(numberOfItems))
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(productId, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 65, Short.MAX_VALUE)
                                        .addComponent(basketButton))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(31, 31, 31)
                                        .addComponent(jLabel2)))
                                .addGroup(layout.createSequentialGroup()
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(showBasketButton)))))
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel2))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 49, Short.MAX_VALUE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(productIdLabel)
                                .addComponent(itemIdField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(numberOfItems)
                                .addComponent(productId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(showBasketButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 202, Short.MAX_VALUE)
                            .addComponent(basketButton)))
                    .addContainerGap())
            pack();
        }// </editor-fold>                       
        public void createBasketWindow(){
            control.getBasketGUI().setVisible(true);
        private void showBasket(java.awt.event.ActionEvent evt) {                           
            createBasketWindow();
        private void putInBasket(java.awt.event.ActionEvent evt) {                            
            Integer itemId = Integer.parseInt(itemIdField.getText());
            String petToAdd = control.getFindItem(itemId);
            System.out.println(petToAdd);
            control.setAddItemToBasket(itemId);
            control.setAddPetToBasket(petToAdd);     
        private void help(java.awt.event.ActionEvent evt) {                     
        private void save(java.awt.event.ActionEvent evt) {                     
            System.out.println("Gemmer fil");
        private void open(java.awt.event.ActionEvent evt) {                     
            System.out.println("?bn fil");
        private void quit(java.awt.event.ActionEvent evt) {                     
            System.exit(0);
        public ShowWhite getControl(){
            return control;
        // Variables declaration - do not modify                    
        private javax.swing.JMenuItem about;
        private javax.swing.JDialog aboutDialog;
        private javax.swing.JButton basketButton;
        private javax.swing.JMenuItem help;
        private javax.swing.JTextField itemIdField;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JMenu jMenu1;
        private javax.swing.JMenu jMenu2;
        private javax.swing.JMenuBar jMenuBar1;
        private javax.swing.JMenuItem jMenuItem1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextArea jTextArea1;
        private javax.swing.JMenu menu;
        private javax.swing.JLabel numberOfItems;
        private javax.swing.JMenuItem open;
        private javax.swing.JTextField productId;
        private javax.swing.JLabel productIdLabel;
        private javax.swing.JMenuItem quit;
        private javax.swing.JButton showBasketButton;
        // End of variables declaration                  
    }

Maybe you are looking for

  • ERROR MESSAGE WHEN CONNECTING IPOD TO PC

    My ipod shuffle has been working fine for over one year. Yesterday I went to connect the ipod to the docking station on the PC to charge it and an error message stating "USB device not recognized" pops up. The Ipod doesn't open up when itunes is open

  • How To: Turn Windows 8 Automatic Updates on or off

    My numerous advanced degrees are not helping me resolve how to process information via Toshiba Service Station. There is NO Download key tho I am asked to press it to process info for CyberLink Power DVD... .  Other updates (I guess) ask me to press

  • Ios6 unexpected auto reboot?Safari typing error?

    So I was texting with my friend today, when I sent a message to "A"friend, I then received message from "B"friend, and it appeared on top of the screen, so I touched the roll, it normally should take me to the message sent from "B". Instead the whole

  • Audible App for 808 PureView?

    Hi, I'm thinking of trying the 808 coming over from Android.  I have many books on my Audible app and use the app a lot.  I realise that previous Symbian phones did not work with Audible's file format (AA) due to Nokia not supporting it. Please tell

  • How to call LabVIEW ActiveX dlls into VB6

    I'm jumping in on a project written primarily in VB6. I'd much rather wirte code in LabVIEW so what I am looking for is some example code for calling LabVIEW activeX dlls into VB6. Does anyone have example code? I need to see how the LabVIEW librarie