Beginner of Swing

Hi, I am a beginner of java swing programming.
Now I am developing a campus project about sales order.
Recently, I have a problem for using JTable for update and delete
order record, could you send me some example to solve my problem?
Thank you.

Hi, if you can go through this tutorial that would be helpful for your project and it relieves much confusion later on.
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
Thanks,
Kalyan

Similar Messages

  • How to list/access swing components?

    hi all,
    Can anyone give me a clue, how can I access or simply list swing components I have on a frame, long after I created them. E.g. I'd like to change their setEnabled() attribute at a later time, not at creation time, but I don't know how to access them.
    Does Swing/AWT/JFC provides a component hierarchy? can someone share some code on this issue?
    Thanks for any help.
    Thomas

    I guess, you are saying the use of getComponent(int n)?
    Since I'm a beginner in Swing see my short code below:
    import java.awt.BorderLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JTextArea;
    public class EasyFrame {
        public EasyFrame() {
            super();
            startHere();
        public void startHere() {
            JFrame frame = new JFrame("SwingApplication");
            JButton button = new JButton("click here");
            JTextArea area = new JTextArea();
            frame.setSize(300, 200);
            frame.getContentPane().setLayout(new BorderLayout());
            frame.getContentPane().add(area, BorderLayout.CENTER);
            frame.getContentPane().add(button, BorderLayout.SOUTH);
            area.setText("Hello World");
            JMenuBar menuBar = new JMenuBar();
            JMenu menu = new JMenu("A Menu");
            menuBar.add(menu);
            JMenuItem menuItem = new JMenuItem("A text item");
            menu.add(menuItem);
            menu.addSeparator();
            menuItem = new JMenuItem("hello");
            menu.add(menuItem);
            JMenu subMenu = new JMenu("submenu");
            menuItem = new JMenuItem("sub1");
            subMenu.add(menuItem);
            menuItem = new JMenuItem("sub2");
            subMenu.add(menuItem);
            menu.add(subMenu);
            frame.getContentPane().add(menuBar, BorderLayout.NORTH);
            frame.show();
         public static void main(String[] args) {
         EasyFrame ef = new EasyFrame();
    }If I make a System.out.println(frame.getContentPane().getComponentCount());I get 3. But I should dig deeper (with getComponent(2)) to access JMenuBar. But this way I receive a AWT Component / not a JMenuBar Swing component to get its JMenu / and its JMenuItems. And I cannot make it cast to JMenuBar since this walk-through routine should be a universal while(isThereMoreCompenent){} procedure, I don't know when to cast to what (JMenu, JMenuItem, Button and so on).
    My problem is that how can I access the JMenuItems one by one, and change e.g. the setEnabled attribute of the "hello" menu?
    I hope you can make it clear to me.
    Please help if so.

  • Swing utilites

    Hi,
    I am beginner to swing. How to change cell focus in the JTable. Could you please guide me.
    I am using the below statement , when it focus its clear existing data in the field.
    table.changeSelection(row,column,false,false);
    I don't know why its happen.
    advance Thanks.

    If you are a beginner you should read the tutorial first, its very helpful, and it explains most of what you would need to know to get yourself going.
    [http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]

  • Problem on drawin a graph

    I'm a just beginner in Swing.I want to draw a graph on a frame.My problem is.....:in the o/p window graph is just become disable afterit came.it will reappear whwn we maximize thhe o/p window...my part of code is following:
    public void paint(Graphics g) {//main graph drawing part
              super.paint(g);
              Graphics2D g2 = (Graphics2D)g;
              g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              for(i=0;i<ss2;i++){//assigning the the values of FROM node and TO node
                   pf=p[Integer.parseInt(str2[i][0])];
                   pt[i]=p[Integer.parseInt(str2[i][2])];
              for(i=0;i<ss2;i++){//to print the value like a,b,c...
                   xf=pf[i].x;
                   yf=pf[i].y;
                   xt=pt[i].x;
                   yt=pt[i].y;
                   xm=(xf+xt*3)/4;
                   ym=((yf+yt*3)/4)-5;
                   sssss=str2[i][1].charAt(0);
                   g2.setColor(Color.black);
                   if(xf==xt&&yf==yt){
                        g2.drawArc(xf,yf,35,20,0,360);
                        g2.drawString(Character.toString(sssss),xf+15,yf+12);
                   else{
                        g2.drawLine(xf,yf,xt,yt);
                        g2.setColor(Color.black);
                        g2.drawString(Character.toString(sssss),xm,ym);
                        g2.fillOval(m,n,7,7);
              for(i=0;i<sc1;i++) {//for loop to draw the circle class to draw circles
                   int _x;
                   int _y;
                   _x=(p[i].x-10);
                   _y=(p[i].y-10);
                   if(str1[i][3].equals("1")){
                   g2.setColor(Color.PINK);
                   g2.fillOval(_x, _y,20,20);
                   x=0;y=0;
              else if(str1[i][3].equals("2")){
                   g2.setColor(Color.CYAN);
                   g2.fillOval(_x, y,20,20);x=0;_y=0;
              else if(str1[i][3].equals("4")){
                   g2.setColor(Color.YELLOW);
                   g2.fillOval(_x, y,20,20);x=0;_y=0;
              else{
                   g2.setColor(Color.ORANGE);
                   g2.fillOval(_x, y,20,20);x=0;_y=0;
              for(i=0;i<sc1;i++){//to put the node name like 1,2...i'll changed it to Q0,Q1,... later
                   g2.setColor(Color.BLACK);
                   g2.drawString(Integer.toString(i),p[i].x,p[i].y);

    Comments:
    If you had gone through the painting tutorial linked, you would know that custom painting is not normally performed on a JFrame. And knowing that, you would find no reason to extend JFrame.
    If you had taken a look at the API you would know that JFrame doesn't have a method paintComponent.
    If you had gone through the Swing tutorial linked, you would know about concurrency in Swing, and that the GUI should be launched on the EDT.
    So. With the wealth of knowledge already available in the tutorials, do you really think forum members should waste their time teaching you the basics? Please go through the changed code and post back what you conclude about the differences that make it work.
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class FrameTest {
       int px, py, ox, oy;
       JFrame frame;
       JPanel panel;
       FrameTest(String title, int x1, int y1, int x2, int y2){
          frame = new JFrame(title);
          px = x1;
          py = y1;
          ox = x2;
          oy = y2;
       private void makeUI() {
          panel = new JPanel() {
             public void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawLine(px, py, ox, oy);
          frame.setContentPane(panel);
          frame.setSize(300, 300);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setVisible(true);
       public static void main(String args[]) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                new FrameTest("Show", 10, 10, 100, 100).makeUI();
    }db

  • How can I access data in different panels?

    Hi,
    I'm a beginner in Swing and have a simple(?) question. Unfortunately I didn't find the answer by oneself so I hope you can help me.
    I have three classes. In the GUI.java class I build the JFrame and it's components. All components are added to the frame via panels that a separate classes.
    My problem is: how can I acces the values in PanelB when I call the actionPerfomed in PanelA? Or is that always a bad design? How can I make it better?
    GUI.java
    JFrame frame = new JFrame();
    PanelA panelA = new PanelA();
    PanelB panelB = new PanelB();
    frame.getContentPane().add(panelA);
    frame.getContentPane().add(panelB);PanelA.java
    private class ButtonCalculateAction implements ActionListener {
         public void actionPerformed(ActionEvent e){
              //calculate with valuesX and valuesY from Panel B
    JButton buttonCalculate;
    ...PanelB.java
    JList valuesX;
    JList valuesY;
    JButton addValueX;
    ...

    Here is the code for a Short, Self Contained, Correct (Compilable), Example
    GUI.java
    import java.awt.FlowLayout;
    import javax.swing.JFrame;
    public class GUI {
         public GUI(){
              JFrame frame = new JFrame();
              PanelA panelA = new PanelA();
              PanelB panelB = new PanelB();
              frame.getContentPane().setLayout(new FlowLayout());
              frame.getContentPane().add(panelA);
              frame.getContentPane().add(panelB);
              frame.setSize(400, 200);
              frame.setVisible(true);
         public static void main(String[] args) {
              GUI gui = new GUI();
    }PanelA.javaimport java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class PanelA extends JPanel {
         public PanelA(){
              this.setLayout(new FlowLayout());
              this.buttonCalculate = new JButton("Calculate");
              this.buttonCalculate.addActionListener(new ButtonCalculateAction());
              this.add(buttonCalculate);
              this.result = new JTextField("...");
              this.add(result);
         private class ButtonCalculateAction implements ActionListener {
              public void actionPerformed(ActionEvent e){
                   //calculate with values from PanelB. How??
                   //result = ?
         private JButton buttonCalculate;
         private JTextField result;
    }PanelB.java
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class PanelB extends JPanel {
         public PanelB(){
              this.addValueX = new JButton("Add X");
              this.addValueX.addActionListener(new ButtonAddAction());
              this.valuesXList = new DefaultListModel();
              this.valuesX = new JList();
              this.valuesX.setModel(valuesXList);
              this.add(addValueX);
              this.add(valuesX);
         private class ButtonAddAction implements ActionListener {
              public void actionPerformed(ActionEvent e){
                   valuesXList.addElement(47);
         private JList valuesX;
         private DefaultListModel valuesXList;
         private JButton addValueX;
    }

  • System tray functionality in java

    Hi friends,
    I wanted to know which is the best package to use for implementing the system tray functionality in java.
    I read about systray, jtray,trayicon etc. I saw that TrayIcon is included in jdk 1.6. Is there any other included package in swing which will do this?
    i am just a beginner in swing programming.
    Thanks in advance.

    i would say not. as far as i can remember you can't directly set icons on a AWT MenuItem.
    and you shouldn't mix awt and swing components and most of the time can't do it anyway.
    however, if you have your own MenuItem i recon you could overwrite paint and paint the icons,
    i.e. images yourself using graphics2D methods.
    if you want to dig deeper into it, there are some good tutorials on paint:
    [http://java.sun.com/products/jfc/tsc/articles/painting/]
    might be worth, if you really want to have images and icons on your menuitems.
    i have never done this myself for awt components, but it should work.
    just found something interesting though:
    [http://atunes.svn.sourceforge.net/viewvc/atunes/aTunes_HEAD/src/net/sourceforge/atunes/gui/views/controls/JTrayIcon.java?view=markup]
    apparently, using this class, which derives from the normal TrayIcon, you can set a JPopupMenu and therefore use normal swing components.
    i did not try it though, but it looks very promising.
    Edited by: produggt on 20.08.2008 22:08

  • Help trying to create multiple rectangles

    Hi, I'm trying to create a five-in-a-row game, and I need lots of rectangles, forming a kind of a net. I've figured out a bit, but the thing is that every new rectangle seems to erase all the former ones, so in the end there's just the last one. I use this code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class luffare extends JApplet {
    ruta rutor[] = new ruta[400];
    public void init() {
    for(int a=0;a<20;a++){
    for(int b=0;b<20;b++){
         rutor[a*20+b] = new ruta(a*10, b*10);
         //rutor[a*20+b].setBackground(Color.white);
    getContentPane().add(rutor[a*20+b]);
    class ruta extends JPanel implements MouseListener, MouseMotionListener{
    Rectangle rect;
    public ruta(int xPos, int yPos){
    rect = new Rectangle(xPos, yPos, 10, 10);
    addMouseMotionListener(this);
    addMouseListener(this);
    public void paintComponent(Graphics g){
    Graphics2D g2 = (Graphics2D)g;
    g2.draw(rect);
    public void mouseReleased(MouseEvent e){}
    public void mousePressed(MouseEvent e){}
    public void mouseDragged(MouseEvent e){}
    public void mouseMoved(MouseEvent e){}
    public void mouseClicked(MouseEvent e){}
    public void mouseExited(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    I'm really stuck here, can anybody help?
    regards,
    M?ns Wide

    Hey, I'm no Swing expert, actually I'm very much a beginner in Swing! I suggest you go through the Swing tutorials
    {color:#0000ff}http://java.sun.com/docs/books/tutorial/uiswing/index.html{color}
    and learn about the multitude of features that can be useful to you.
    After that, if you have any problems related to Swing, please post in the Swing forum where you will get advice from real experts.
    This works, using setBounds(...) with null Layout --I've added the position number to each Ruta (size increased to 20 X 20 for that) so you can see where they go.
    file Luffare.javapackage manswide;
    import java.awt.*;
    import javax.swing.*;
    public class Luffare extends JApplet
        Ruta rutor[] = new Ruta[400];
        public void init ()
            setLayout (null);
            for(int a = 0; a < 20; a++)
                for(int b = 0; b < 20; b++)
                    rutor[a * 20 + b] = new Ruta (a * 20 + b);
                    getContentPane ().add (rutor[a * 20 + b]);
                    rutor[a * 20 + b].setBounds (a * 20, b * 20, 20, 20);
    }file Ruta.javapackage manswide;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    class Ruta extends JPanel implements MouseListener, MouseMotionListener
        Rectangle rect;
        int id;
        public Ruta (int newId)
            id = newId;
            setBorder (LineBorder.createBlackLineBorder ());
            addMouseMotionListener (this);
            addMouseListener (this);
        public void paintComponent (Graphics g)
            Graphics2D g2 = (Graphics2D)g;
            g2.setFont (new Font("Arial", 1, 9));
            g2.drawString (Integer.toString (id), 2, 10);
        public void mouseReleased (MouseEvent e) {}
        public void mousePressed (MouseEvent e) {}
        public void mouseDragged (MouseEvent e) {}
        public void mouseMoved (MouseEvent e) {}
        public void mouseClicked (MouseEvent e) {}
        public void mouseExited (MouseEvent e) {}
        public void mouseEntered (MouseEvent e) {}
    }It's good practise to place each java class in its own file.
    db
    -- To post code, use the code button or type the code tags -- [code]CODE[/code] is displayed as CODE

  • Swing beginner JOptionPane question

    Hi
    my question is:
    When I construct an input dialog like this:
    JOptionPane.showInputDialog(null, "enter something here");
    by default the buttons available are OK and Cancel. How do I capture the Cancel button being clicked to make the system exit?
    I know I can call System.exit(0) but how do I do that when clicking Cancel?
    Thanks for any help

    JOptionPane.showInputDialog(null, "enter something here") returns a string, if the user clicks cancel then it returns null. so you can do something like this...
    String str = JOptionPane.showInputDialog(null, "enter something here");
    if(str != null){/*do 'ok' stuff*/;}
    else{/*do cancel stuff*/;}hope that helps

  • Swing and jmf

    can u please have a look to the attached file
    i know that this involves the jmf API but I have the feeling that has to do more with swing, thats whay I post my question here
    this simple application is based on the MDI.java example of the jmf web
    pages
    I also added a slider and want to set the playback rate for the player from
    there if possible
    that is I want everytime that I move the slider and the value is biggerthan
    50 the rate to be reduced according to a simple calculation that converts
    the slider value to a value between 0 an1 for the rate...
    so all i want to do is pass the slider value to the player everytime that
    the slider changes value and this is bigger than 50
    the attached file can do that only when the player starts playing the
    file,,,,
    after the player has started and the rate is set I cant change it even if
    the slider moves
    when I tried to do that from within the stateChanged method of the slider I
    was getting a Nullpointer exception because of the EventDispatching thread,
    so I thought to take this piece of code out of there (create the setnewrate
    method in the jmframe instead),,,,but then of course doesnt work like I
    would want,,,,,
    do I have to register the class that implements the frame for the player as
    a ChangeListener on the slider to achieve that, is something like that
    possible....
    I know that swing is not supposed to be thread safe, so maybe this is what
    the problem is after all...any suggestions to that direction?
    Can u please have a look??
    I am a beginner so any help would really be very much appreciated
    thanx :)
    maria
    .....and the attached file
    I think the problem is with the stateChanged method for the Jslider...
    I am getting a null pointerexception because of the eventdispatching thread
    pls ignore any silly mistakes I am a completely newbie in java
    myAppfr2.java
    import javax.media.*;
    import com.sun.media.ui.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.Vector;
    import javax.swing.border.Border.*;
    import java.util.Hashtable;
    public class myAppfr2 extends Frame {
    * VARIABLES
    JMFrame jmframe = null;
    JDesktopPane desktop;
    FileDialog fd = null;
    CheckboxMenuItem cbAutoLoop = null;
    Player player ;
    //Player newPlayer = null;
    String filename;
    boolean stopped;
    public my_slider test_slider;//put it here so I can use it by name by all code
    float rate;
    * MAIN PROGRAM / STATIC METHODS
    public static void main(String args[]) {
    //if (args.length > 0)
         //rate=Float.parseFloat(args[0]);
    myAppfr2 mdi = new myAppfr2();
    static void Fatal(String s) {
    MessageBox mb = new MessageBox("JMF Error", s);
    * METHODS
    public myAppfr2() {
    super("VHE Demo");
    // Add the desktop pane
    setLayout( new BorderLayout() );
    desktop = new JDesktopPane();
    desktop.setDoubleBuffered(true);
         desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);//makes dragging faster
    add("Center", desktop);
    setMenuBar(createMenuBar());
    setSize(640, 480);
    setVisible(true);
         test_slider = new my_slider("networkutil");
         createnetworkutil();
         try {
         UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel") ;
    } catch (Exception e) {
    System.err.println("Could not initialize personal look and feel");
    addWindowListener( new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    System.exit(0);
    Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, new Boolean(true));
    private MenuBar createMenuBar() {
    ActionListener al = new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    String command = ae.getActionCommand();
    if (command.equals("Open")) {
    if (fd == null) {
    fd = new FileDialog(myAppfr2.this, "Open File",
    FileDialog.LOAD);
    fd.setDirectory("~/movies");
    fd.show();
    if (fd.getFile() != null) {
    String filename = fd.getDirectory() + fd.getFile();
    openFile("file:" + filename);
    } else if (command.equals("Exit")) {
    dispose();
    System.exit(0);
    MenuItem item;
    MenuBar mb = new MenuBar();
    // File Menu
    Menu mnFile = new Menu("File");
    mnFile.add(item = new MenuItem("Open"));
    item.addActionListener(al);
    mnFile.add(item = new MenuItem("Exit"));
    item.addActionListener(al);
    // Options Menu
    Menu mnOptions = new Menu("Options");
    cbAutoLoop = new CheckboxMenuItem("Auto replay");
    cbAutoLoop.setState(true);
    mnOptions.add(cbAutoLoop);
    mb.add(mnFile);
    mb.add(mnOptions);
    return mb;
    //create slider and add it to desktop
    public void createnetworkutil(){
    test_slider.pack();
    desktop.add(test_slider);
    test_slider.setVisible(true);
    * Open a media file.
    private void openFile(String filename) {
    String mediaFile = filename;
    Player player = null;
    // URL for our media file
    URL url = null;
    try {
    // Create an url from the file name and the url to the
    // document containing this applet.
    if ((url = new URL(mediaFile)) == null) {
    Fatal("Can't build URL for " + mediaFile);
    return;
    // Create an instance of a player for this media
    try {
    player = Manager.createPlayer(url);
    } catch (NoPlayerException e) {
    Fatal("Error: " + e);
    } catch (MalformedURLException e) {
    Fatal("Error:" + e);
    } catch (IOException e) {
    Fatal("Error:" + e);
    if (player != null) {
    this.filename = filename;
    JMFrame jmframe = new JMFrame(player, filename);
    desktop.add(jmframe);
    class JMFrame extends JInternalFrame implements ControllerListener {
    public Player mplayer;
    Component visual = null;
    Component control = null;
    int videoWidth = 0;
    int videoHeight = 0;
    int controlHeight = 30;
    int insetWidth = 10;
    int insetHeight = 30;
    // boolean firstTime = true;
    public JMFrame(Player player, String title) {
    super(title, true, true, true, true);
    getContentPane().setLayout( new BorderLayout() );
    //setSize(320, 10);
    setLocation(200, 25);
    setVisible(true);
    mplayer = player;
    mplayer.addControllerListener((ControllerListener) this);
    mplayer.realize();
    addInternalFrameListener( new InternalFrameAdapter() {
    public void internalFrameClosing(InternalFrameEvent ife) {
    mplayer.close();
    public void controllerUpdate(ControllerEvent ce) {
    // System.out.println("controllerUpdate");
    //SwingUtilities.isEventDispatchThread();
    if (ce instanceof RealizeCompleteEvent) {
    mplayer.prefetch();
    } else if (ce instanceof PrefetchCompleteEvent) {
    if (visual != null)
    return;
         //setnewrate();
         //rate=mplayer.getRate();
         System.out.println( mplayer.getRate());
    if ((visual = mplayer.getVisualComponent()) != null) {
    Dimension size = visual.getPreferredSize();
    videoWidth = size.width;
    videoHeight = size.height;
    getContentPane().add("Center", visual);
    } else
    videoWidth = 320;
    /*if ((control = mplayer.getControlPanelComponent()) != null) {
    controlHeight = control.getPreferredSize().height;
    getContentPane().add("South", control);
    setSize(videoWidth + insetWidth,
    videoHeight + controlHeight + insetHeight);
    validate();
    mplayer.start();
    } else if (ce instanceof StartEvent){
         if (test_slider.netutil==0) {
         mplayer.stop();
         } else if (ce instanceof EndOfMediaEvent && cbAutoLoop.getState()) {
    mplayer.setMediaTime(new Time(0));
              boolean stopped=true;
              mplayer.prefetch();
              mplayer.start();
              stopped=false;
    class my_slider extends JInternalFrame implements ChangeListener{
    //Set up parameters.
    int netini=50;
    public int netutil=netini;
    public my_slider(String windowTitle) {
    super(windowTitle, false, false, false, false);
    getContentPane().setLayout(new BorderLayout());
    setLocation(25,25);// for the internal frame that contains the slider
    setVisible(true); //..same
    //Create the slider(the component included in "my_slider" internal frame
         JSlider mslider = new JSlider(JSlider.VERTICAL,
    0, 100, netini);
    mslider.addChangeListener((ChangeListener) this);
    mslider.setMajorTickSpacing(10);
    mslider.setPaintTicks(true);
    //Create the label table.
    Hashtable labelTable = new Hashtable();
    labelTable.put(new Integer( 0 ),
    new JLabel("0%") );
    labelTable.put(new Integer( 25 ),
    new JLabel("25%") );
    labelTable.put(new Integer( 50 ),
    new JLabel("50%") );
    labelTable.put(new Integer(75),
    new JLabel("75%") );
         labelTable.put(new Integer( 100),
    new JLabel("100%") );     
    mslider.setLabelTable(labelTable);
    mslider.setPaintLabels(true);
    mslider.setBorder(
    BorderFactory.createEmptyBorder(0,0,0,10));
         //Put everything in the content pane.
    getContentPane().add(mslider, BorderLayout.CENTER);
    public void stateChanged(ChangeEvent e) { //System.out.println("stateChanged");
    // SwingUtilities.isEventDispatchThread();
    if (e instanceof ChangeEvent){
    JSlider source = (JSlider)e.getSource();
    if (!source.getValueIsAdjusting()) {
    netutil= (int)source.getValue();
         System.out.println(netutil);
              if (jmframe.mplayer!=null) {
         jmframe.mplayer.setRate((float)(netutil/(netutil+(0.3*netutil))));
              if (jmframe.mplayer.getTargetState() <Player.Started)
         jmframe.mplayer.prefetch();
    i am stuck so any help would be really very much appreciated

    did you ever resolve this.
    I may be having similar problems
    I have an JMF application running under webstart. It runs ok in Java 1.3
    Now I am trying to get ti to run under Java 1.4. The attached error is rather useless,
    but by guess at what is happening is that the JMF control has some .awt. stuff included
    but that Java 1.4 emulates .awt. in swing. But something was not set and the default does not
    work.
    This error messages does not appear in the 1.3 run
    Any suggestions would be greatly appriatated.
    1.4 result:
    mg version 2.1.1a
    player created com.sun.media.content.unknown.Handler@3a1834
    ctr com.sun.media.PlaybackEngine$BitRateA@4a9a7d
    ctr com.sun.media.BasicJMD[panel0,0,0,512x200,invalid,layout=java.awt.BorderLayout]
    duration? javax.media.Time@6b5666 sec = 9.223372036854776E9
    time unknown javax.media.Time@754699
    will realize the player
    realize
    javax.media.TransitionEvent[source=com.sun.media.content.unknown.
    Handler@3a1834,previous=Unrealized,current=Realizing,
    target=Realized]
    start smxBADS
    bass start
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at javax.swing.plaf.metal.MetalLookAndFeel.getControlInfo(Unknown Source)
    at javax.swing.plaf.metal.MetalScrollButton.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintWithBuffer(Unknown Source)
    at javax.swing.JComponent._paintImmediately(Unknown Source)
    at javax.swing.JComponent.paintImmediately(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at javax.swing.plaf.metal.MetalLookAndFeel.getControlInfo(Unknown Source)
    at javax.swing.plaf.metal.MetalScrollButton.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintWithBuffer(Unknown Source)
    at javax.swing.JComponent._paintImmediately(Unknown Source)
    at javax.swing.JComponent.paintImmediately(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    realize done
    panel found java.awt.Panel[panel1,0,0,0x0,invalid] java.awt.Panel[panel2,4,216,292x30,layout=java.awt.FlowLayout]
    press a button
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at javax.swing.plaf.metal.MetalLookAndFeel.getControlInfo(Unknown Source)
    at javax.swing.plaf.metal.MetalScrollButton.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintWithBuffer(Unknown Source)
    at javax.swing.JComponent._paintImmediately(Unknown Source)
    at javax.swing.JComponent.paintImmediately(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    1.3 result
    mg version 2.1.1a
    player created com.sun.media.content.unknown.Handler@354749
    ctr com.sun.media.PlaybackEngine$BitRateA@5b484d
    ctr com.sun.media.BasicJMD[panel3,0,0,512x200,invalid,layout=java.awt.BorderLayout]
    duration? javax.media.Time@46d228 sec = 9.223372036854776E9
    time unknown javax.media.Time@f7386
    will realize the player
    realize
    javax.media.TransitionEvent[source=com.sun.media.content.unknown.
    Handler@354749,previous=Unrealized,current=Realizing,
    target=Realized]
    start smxBADS
    bass start
    javax.media.DurationUpdateEvent[source=com.sun.media.content.unknown.Handler@354749,duration=javax.media.Time@55c0f9
    javax.media.Time@55c0f9
    javax.media.RealizeCompleteEvent[source=com.sun.media.content.unknown.Handler@354749,previous=Realizing,current=Realized,target=Realized]
    realized complete
    prefetch
    realize done
    controlComp com.sun.media.ui.DefaultControlPanel[,0,0,74x21,invalid,layout=java.awt.BorderLayout]
    add controlComp 21 java.awt.Panel[panel4,10,-12,258x47,invalid]
    javax.media.TransitionEvent[source=com.sun.media.content.unknown.Handler@354749,previous=Realized,current=Prefetching,target=Prefetched]
    start smxBADS
    bass start
    running ok from here on

  • Learning Swing - Can't get JLabel to appear in JFrame

    Hi,
    I'm a complete beginner to Java. I'm taking a course that's moving way too fast, in my opinion, and we're currently studying Swing. I've likely missed a lot of basic basic Java fundamentals due to the speed of this class, so if I'm making a ridiculous mistake, please let me know.
    I'm trying to create the following:
    +"Create a GUI interface using the Swing API. Use the JOptionPane class to create a dialog box to ask the+
    +user for the University Name. Create a JFrame that has a label with the University name and create your+
    +own logo. The window should have the capability of inputting first name , last name, and id for a student+
    +in text fields. Once the id is entered open another dialog box with the student information."+
    I'm pretty much done, I'm just having issues getting the output from the first JFrame to appear in the second JFrame. When I create a new JFrame, the title I specify appears, but the normal syntax for a JLabel just isn't working and I'm not sure why.
    I suspect it has something to do with the general structure of my program rather than my syntax. ...I know I'm missing a lot of fundamentals that I should have developed, thanks to the way the course I'm in is structured.
    I'm posting two .java files. The first, called GUIFrame.java is the class that basically does everything, it calls JOptionPane, opens the first and second JFrames, and uses ActionEvent and ActionListener to read text from the text fields. The second .java file is called GUITest.java and all it does is instantiate GUIFrame and sets the JFrame parameters.
    If anyone has any suggestions, at all, about how to fix this, or especially how to structure these better... Any suggestion would be greatly appreciated.
    CODE:
    import javax.swing.JFrame; //provides basic window features
    import javax.swing.JOptionPane; //simple GUI input/output
    import javax.swing.JLabel; //displays text and images
    import javax.swing.Icon; //interface used to manipulate images
    import javax.swing.ImageIcon; //loads images
    import java.awt.FlowLayout; // specifies how components are arranged
    import javax.swing.SwingConstants; //common constants used with Swing
    import javax.swing.JTextField;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class GUIFrame extends JFrame
         private JLabel line1;
         private JLabel line2;
         private JLabel line3;
         private JLabel line4;
         private JTextField textField1;
         private JTextField textField2;
         private JTextField textField3;
         //This method prompts the user in a JOptionPane for the university's name.
         public static String obtainUniversityName()
              //Obtain user input from JOptionPane input dialog for universityName.
              String uName = JOptionPane.showInputDialog(null,"Enter the University's name","University Name",JOptionPane.QUESTION_MESSAGE);
              return uName;     
         //This method creates an image icon if possible, or it will print an error and return null
         protected ImageIcon createImageIcon(String path,String description)
              java.net.URL imgURL = getClass().getResource(path);
              if (imgURL != null)
                   return new ImageIcon(imgURL, description);
              } else {
                   System.err.println("Couldn't find file: " + path);
                   return null;
         public GUIFrame()
              //Create a new JFrame for the university info to be placed in
              //The title of the window is also declared here
              super(obtainUniversityName());
              //Sets way things are arranged
              setLayout(new FlowLayout());
              //Grabs logo and aligns it with "Welcome to the University"
              ImageIcon logo = createImageIcon("girl.gif","This is a logo");
              line1 = new JLabel("Welcome to the University", logo, JLabel.CENTER);
              add(line1);
              //"First Name" + Text Field
              line2 = new JLabel("First Name");
              add(line2);
              textField1 = new JTextField(10);
              add(textField1);
              //"Last Name" + Text Field
              line3 = new JLabel("Last Name");
              add(line3);
              textField2 = new JTextField(10);
              add(textField2);
              //"Student ID" + Text Field
              line4 = new JLabel("Student ID");
              add(line4);
              textField3 = new JTextField(10);
              add(textField3);
              //Register event handlers
              TextFieldHandler handler = new TextFieldHandler();
              textField1.addActionListener(handler);
              textField2.addActionListener(handler);
              textField3.addActionListener(handler);
         private class TextFieldHandler implements ActionListener
              public void actionPerformed(ActionEvent event)
                   String fname = "";
                   String lname = "";
                   String stuid = "";
                   //When user presses enter in any text field, these set values for input into text field
                   if(event.getSource()==textField1)
                        fname = String.format("First Name: %s", event.getActionCommand());
                             else if(event.getSource()==textField2)
                                  lname=String.format("Last Name: %s", event.getActionCommand());
                                       else if(event.getSource()==textField3)
                                            stuid=String.format("Student ID: %s", event.getActionCommand());
                                                 else
                                                      System.out.println("ERROR! You didn't fill in atleast one of the text boxes...");
                   //Creates a new JFrame with title "Student Info"          
                   JFrame frame2 = new JFrame("Student Info");
                   //Sets way things are arranged
                   setLayout(new FlowLayout());
                   //Temporary - Tests to see that processing of text field events occurs correctly
                   System.out.println(fname);
                   System.out.println(lname);
                   System.out.println(stuid);               
                   //Puts data into JLabels for display in new JFrame
                   JLabel label1=new JLabel(fname);
                   add(label1);
                   JLabel label2=new JLabel("Can you see this!?");
                   add(label2);          
                   JLabel label3=new JLabel(stuid);
                   add(label3);
                   //Sets parameters, size, close, visibility, etc, for new JFrame
                   frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frame2.setSize(275,210);
                   frame2.setVisible(true);
              }//end void actionPerformed
         }//end TextFieldHandler
    }//end GUIFrame
    ==================================================================================
    import javax.swing.JFrame; //provides basic window features
    public class GUITest
         public static void main(String args[])
              //Calls on GUIFrame class. Instantiates.
              GUIFrame guiFrame = new GUIFrame();
              //Set the window to exit when closed
              guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Size the window
              guiFrame.setSize(275,210);
              //Center the window on the screen
              guiFrame.setLocationRelativeTo(null);
              //Make the window visible
              guiFrame.setVisible(true);
    }

    Thanks so much for the quick response. Yeah, I guess I'm a bit oblivious, I guess I missed that it was supposed to be another JOptionPane.
    I fixed that and got rid of all the second JFrame stuff. Thank you.
    And you're right, now that I can see my output, it's obvious I have serious issues in the actionPerformed() method with the ActionListener. I guess it's just a simple question of how to take what's in all three boxes and output to JOptionPane. Simple logic I guess.
    I don't completely understand the ActionListener. I've read my textbook about it and looked at a few online resources, but I don't have a complete understanding.
    How then, would I be able to use the ActionListener to get the text from all three text fields?
    The way it is now, as you correctly predicted, it waits for enter to be inputted from each text field and whichever text field you hit enter in, despite what's in the other text fields, is the only thing that is outputted to the string in the JOptionPane.
    Do you have a suggestion for that?
    Thanks again.
    CODE:
    import javax.swing.JFrame; //provides basic window features
    import javax.swing.JOptionPane; //simple GUI input/output
    import javax.swing.JLabel; //displays text and images
    import javax.swing.Icon; //interface used to manipulate images
    import javax.swing.ImageIcon; //loads images
    import java.awt.FlowLayout; // specifies how components are arranged
    import javax.swing.SwingConstants; //common constants used with Swing
    import javax.swing.JTextField;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class GUIFrame extends JFrame
         private JLabel line1;
         private JLabel line2;
         private JLabel line3;
         private JLabel line4;
         private JTextField textField1;
         private JTextField textField2;
         private JTextField textField3;
         //This method prompts the user in a JOptionPane for the university's name.
         public static String obtainUniversityName()
              //Obtain user input from JOptionPane input dialog for universityName.
              String uName = JOptionPane.showInputDialog(null,"Enter the University's name","University Name",JOptionPane.QUESTION_MESSAGE);
              return uName;     
         //This method creates an image icon if possible, or it will print an error and return null
         protected ImageIcon createImageIcon(String path,String description)
              java.net.URL imgURL = getClass().getResource(path);
              if (imgURL != null)
                   return new ImageIcon(imgURL, description);
              } else {
                   System.err.println("Couldn't find file: " + path);
                   return null;
         public GUIFrame()
              //Create a new JFrame for the university info to be placed in
              //The title of the window is also declared here
              super(obtainUniversityName());
              //Sets way things are arranged
              setLayout(new FlowLayout());
              //Grabs logo and aligns it with "Welcome to the University"
              ImageIcon logo = createImageIcon("girl.gif","This is a logo");
              line1 = new JLabel("Welcome to the University", logo, JLabel.CENTER);
              add(line1);
              //"First Name" + Text Field
              line2 = new JLabel("First Name");
              add(line2);
              textField1 = new JTextField(10);
              add(textField1);
              //"Last Name" + Text Field
              line3 = new JLabel("Last Name");
              add(line3);
              textField2 = new JTextField(10);
              add(textField2);
              //"Student ID" + Text Field
              line4 = new JLabel("Student ID");
              add(line4);
              textField3 = new JTextField(10);
              add(textField3);
              //Register event handlers
              TextFieldHandler handler = new TextFieldHandler();
              textField1.addActionListener(handler);
              textField2.addActionListener(handler);
              textField3.addActionListener(handler);
         private class TextFieldHandler implements ActionListener
              public void actionPerformed(ActionEvent event)
                   String fname = "";
                   String lname = "";
                   String stuid = "";
                   //When user presses enter in any text field, these set values for input into text field
                   if(event.getSource()==textField1)
                        fname = String.format("First Name: %s", event.getActionCommand());
                             else if(event.getSource()==textField2)
                                  lname=String.format("Last Name: %s", event.getActionCommand());
                                       else if(event.getSource()==textField3)
                                            stuid=String.format("Student ID: %s", event.getActionCommand());
                                                 else
                                                      System.out.println("ERROR! You didn't fill in atleast one of the text boxes...");
                   String out = fname + "\n" + lname + "\n" + stuid;
                   JOptionPane.showMessageDialog(null,out);
              }//end void actionPerformed
         }//end TextFieldHandler
    }//end GUIFrame
    import javax.swing.JFrame; //provides basic window features
    public class GUITest
         public static void main(String args[])
              //Calls on GUIFrame class. Instantiates.
              GUIFrame guiFrame = new GUIFrame();
              //Set the window to exit when closed
              guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Size the window
              guiFrame.setSize(275,210);
              //Center the window on the screen
              guiFrame.setLocationRelativeTo(null);
              //Make the window visible
              guiFrame.setVisible(true);
    }Edited by: heathercmiller on Apr 5, 2008 8:56 AM

  • 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.

  • A doubt in SWING event handling

    Hi all,
    I'm a beginner in JAVA studying SWING. I learned that if we want to handle an event for a event source(say JButton) we should implement corresponding Event Listener(say ActionListener) .
    I also understood that we should register the Listener with that event source.
    With that knowledge I tried this program
    import javax.swing.*;
    import java.awt.event.*;
    public class SimpleGui2 implements MouseListener,ActionListener {
       SimpleGui2 insGui;
       JButton button= new JButton("Click me");
         public static void main(String[] args) {
              SimpleGui2 gui = new SimpleGui2();
              gui.start();
       public void start() {
            JFrame frame = new JFrame();
            //button.addMouseListener(this);   
            //button.addActionListener(this);
            button.addActionListener(insGui);
            frame.getContentPane().add(button);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300,300);
            frame.setVisible(true);
       public void actionPerformed(ActionEvent ae) {
            button.setText("Triggered");
       public void mouseClicked(MouseEvent me) {
          button.setText("I have been clicked");
       public void mouseEntered(MouseEvent me) { }
       public void mouseExited(MouseEvent me) { }
       public void mousePressed(MouseEvent me) { }
       public void mouseReleased(MouseEvent me) { }  
    }but It's is not working as I expected.
    or precisely why when we clicked the actionPerformed/mouseClicked method is not invoked ?
    if i change the same with argument "this" it's working .
    I guess "this" refers to current object (which is also of type SimpleGui2 which implemented ActionListener)
    Can any one please clarify me what happens behind the scenes ?
    Thanks in advance

    first of all, you never initialize insGui. YOu just declare it, and never use it.
    SimpleGui2 insGui;However, you dont need it anyways. As you suspected, using 'this' when you add your actionListener is what you need.
    button.addActionListener(insGui);
    Can any one please clarify me what happens behind the scenes ?Well my professor always said it was 'black magic'. All I know is that you click a button with an event listener, and an event is fired doing whatever you want it to do. For example, if I want my event to print "Hey" then when I click the button, "Hey" is printed. Simple enough eh? You will probably find a better answer using Google though. It's amazing.

  • Very confused beginner here...

    Hello everyone. I'm new to the board here. I am currently a junior meteorology major with a minor in computer science at Millersville University. To incorporate both my minor and major, I decided to make a computer program that scrolls weather watches and warnings across the bottom of a computer screen (much like they do on television). I am a beginner at Java, only using it for a few months. I really feel like I have bitten off more than I can chew with this program. However, I am dedicated in working through this problem. Below is a copy of the code I am using for this. I keep getting errors, however. I had it working perfectly, besides the fact that a) it never updated and b) it would never scroll more than one watch or warning, meaning it would just loop one over and over. I have also included the errors that I receive during this. Any help would be greatly appreciated. I am sorry if the code looks a bit trashy and disorganized. These are just some things, being a rookie, that I am going to have to learn how to clean up. Thanks
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.Timer;
    import javax.swing.*;
    import java.applet.Applet;
    import java.applet.AudioClip;
    import java.net.*;
    import de.nava.informa.core.ChannelIF;
    import de.nava.informa.core.ItemIF;
    import de.nava.informa.impl.basic.ChannelBuilder;
    import de.nava.informa.parsers.FeedParser;
    public class WxScroll extends JFrame implements ActionListener {
         private static final long serialVersionUID = 1L;
         int count = 0;
         JLabel scrollLabel;
         String scroll, watwarstring, text;
         Label label;
         ItemIF item;
         Component newText;
         String watwar[];
         String newscroll, oldText;
         ChannelIF channel;
         Collection items;
         final TimerTask task;
         java.util.Timer timercheck;
         ChannelBuilder channelb;
         URL url;
         public WxScroll() {
              final Color red = new Color(255, 0, 0);
              final Color yellow = new Color(255, 255, 0);
              final Color orange = new Color(255, 165, 0);
              final Color darkred = new Color(205, 38, 38);
              final Color orangered = new Color(255, 69, 0);
              final Color darkmagenta = new Color(139, 0, 139);
              final Color blueviolet = new Color(138, 43, 226);
              final Color lime = new Color(50, 205, 50);
              final Color goldenrod = new Color(205, 155, 29);
              final Color deeppink = new Color(255, 20, 147);
              final Color lightsteelblue = new Color(176, 196, 222);
              final Color yellowgreen = new Color(154, 205, 50);
              final Color limegreen = new Color(34, 139, 34);
              final Color burlywood = new Color(222, 184, 135);
              final Color paleturquoise = new Color(102, 139, 139);
              final Color springgreen = new Color(0, 238, 118);
              final Color seagreen = new Color(46, 139, 87);
              final Color greenyellow = new Color(127, 255, 0);
              final Color steelblue = new Color(54, 100, 139);
              final Color royalblue = new Color(65, 105, 225);
              final Color hotpink = new Color(255, 105, 180);
              final Color tan = new Color(205, 133, 63);
              final Color skyblue = new Color(135, 206, 250);
              final Color palevioletred = new Color(219, 112, 147);
              final Color slateblue = new Color(0, 127, 255);
              final Color coral = new Color(255, 127, 0);
              final Color cornflower = new Color(100, 149, 237);
              final Color maroon = new Color(176, 48, 96);
              try {
                   URL url = new URL("file:misslebeep2.wav");
                   AudioClip ac = Applet.newAudioClip(url);
                   ac.play();
              } catch (Exception e) {
              timercheck = new java.util.Timer();
              task = new TimerTask() {
                   public void run() {
                        try {
                             channel = FeedParser
                                       .parse(
                                                 channelb = new ChannelBuilder(),
                                                 url = new URL(
                                                           "http://www.weather.gov/alerts/wwarssget.php?zone=COZ041"));
                        catch (Exception e) {
                             System.out.println("exception");
                        finally {
                             items = channel.getItems();
                             scrollLabel = new JLabel(newscroll);
                             for (Iterator i = items.iterator(); i.hasNext();) {
                                  count++;
                                  ItemIF item = (ItemIF) i.next();
                                  scroll = item.getDescription();
                                  newscroll += scroll
                                            .replaceAll("<br>", " ")
                                            .replaceAll(
                                                      "Issuing Weather Forecast Office Homepage",
                                            .replaceAll("</a>", " ")
                                            .replaceAll(
                                                      "<a href=http://www.nws.noaa.gov/er/ctp>",
                             if (newscroll.contains("There are no active"))
                                  scrollLabel.setVisible(false);
                             else {
                                  scrollLabel.setBackground(red);
                                  if (newscroll.contains("Tornado warning".toUpperCase()))
                                       scrollLabel.setBackground(red);
                                  if (newscroll.contains("Severe thunderstorm warning"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(orange);
                                  if (newscroll.contains("Flash Flood Warning"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(darkred);
                                  if (newscroll
                                            .contains("Blizzard Warning".toUpperCase()))
                                       scrollLabel.setBackground(orangered);
                                  if (newscroll.contains("ice storm warning"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(darkmagenta);
                                  if (newscroll.contains("short term".toUpperCase()))
                                       scrollLabel.setBackground(burlywood);
                                  if (newscroll.contains("heavy snow warning"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(blueviolet);
                                  if (newscroll.contains("heavy sleet warning"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(skyblue);
                                  if (newscroll.contains("flood warning".toUpperCase()))
                                       scrollLabel.setBackground(lime);
                                  if (newscroll.contains("high wind warning"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(goldenrod);
                                  if (newscroll
                                            .contains("red flag warning".toUpperCase()))
                                       scrollLabel.setBackground(deeppink);
                                  if (newscroll.contains("wind chill warning"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(lightsteelblue);
                                  if (newscroll.contains("freeze warning".toUpperCase()))
                                       scrollLabel.setBackground(Color.cyan);
                                  if (newscroll.contains("snow watch".toUpperCase()))
                                       scrollLabel.setBackground(Color.cyan);
                                  if (newscroll.contains("flood statement".toUpperCase()))
                                       scrollLabel.setBackground(yellowgreen);
                                  if (newscroll.contains("tornado watch".toUpperCase()))
                                       scrollLabel.setBackground(yellow);
                                  if (newscroll.contains("severe thunderstorm watch"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(palevioletred);
                                  if (newscroll.contains("flash flood watch"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(limegreen);
                                  if (newscroll.contains("freezing rain".toUpperCase()))
                                       scrollLabel.setBackground(slateblue);
                                  if (newscroll
                                            .contains("freezing drizzle".toUpperCase()))
                                       scrollLabel.setBackground(slateblue);
                                  if (newscroll.contains("sleet advisory".toUpperCase()))
                                       scrollLabel.setBackground(slateblue);
                                  if (newscroll.contains("winter weather advisory"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(burlywood);
                                  if (newscroll.contains("wind chill advisory"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(paleturquoise);
                                  if (newscroll.contains("heat advisory".toUpperCase()))
                                       scrollLabel.setBackground(coral);
                                  if (newscroll.contains("flood advisory".toUpperCase()))
                                       scrollLabel.setBackground(springgreen);
                                  if (newscroll.contains("snow advisory".toUpperCase()))
                                       scrollLabel.setBackground(paleturquoise);
                                  if (newscroll.contains("wind advisory".toUpperCase()))
                                       scrollLabel.setBackground(tan);
                                  if (newscroll.contains("frost advisory".toUpperCase()))
                                       scrollLabel.setBackground(cornflower);
                                  if (newscroll.contains("flood watch".toUpperCase()))
                                       scrollLabel.setBackground(seagreen);
                                  if (newscroll.contains("blizzard watch".toUpperCase()))
                                       scrollLabel.setBackground(greenyellow);
                                  if (newscroll.contains("winter storm watch"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(steelblue);
                                  if (newscroll.contains("winter storm warning"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(hotpink);
                                  if (newscroll.contains("high wind watch".toUpperCase()))
                                       scrollLabel.setBackground(goldenrod);
                                  if (newscroll.contains("excessive heat watch"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(maroon);
                                  if (newscroll.contains("freeze watch".toUpperCase()))
                                       scrollLabel.setBackground(royalblue);
                                  if (newscroll
                                            .contains("wind chill watch".toUpperCase()))
                                       scrollLabel.setBackground(royalblue);
                                  if (newscroll.contains("excessive heat watch"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(maroon);
                                  if (newscroll.contains("excessive heat watch"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(maroon);
                                  if (newscroll.contains("excessive heat watch"
                                            .toUpperCase()))
                                       scrollLabel.setBackground(maroon);
                                  scrollLabel.setFont(new Font("Arial", Font.BOLD, 40));
                                  getContentPane().add(scrollLabel, BorderLayout.SOUTH);
                                  scrollLabel.setOpaque(true);
                                  scrollLabel.setForeground(Color.white);
         // create 2nd timer. give time of 1000ms.
         // event.getsource...in action performed
         timercheck.scheduleAtFixedRate(task, 1000, 10000);
         Timer timer = new Timer(120,this);
         //javax.swing.Timer timer = new javax.swing.Timer(120, this);
         timer.start();
         public void actionPerformed(ActionEvent event) {
              oldText = scrollLabel.getText();
              StringBuffer newText = new StringBuffer(oldText.substring(1) + oldText.substring(0, 1));
              String text = newText.toString();
              scrollLabel = new JLabel (text);
              //scrollLabel.setText(newText.toString());
         public static void main(String[] args) {
              Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
              int y = (14 * screen.height) / 15;
              WxScroll frame = new WxScroll();
              JLabel title = new JLabel("WxScroll");
              JPanel titlePanel = new JPanel();
              titlePanel.setPreferredSize(new Dimension(0, 0));
              titlePanel.add(title);
              frame.setLocation(0, y);
              // paint component method, drawstring,
              frame.setUndecorated(true);
              frame.setAlwaysOnTop(true);
              frame.getContentPane().add(titlePanel);
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
    }The errors i receive are:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
         at WxScroll.actionPerformed(WxScroll.java:289)
         at javax.swing.Timer.fireActionPerformed(Unknown Source)
         at javax.swing.Timer$DoPostEvent.run(Unknown Source)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(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)

    I don't know. There are classes your code requires (e.g., everything in the de.nava.informa packages) that I don't have, so I can't really compile or run your code.
    I will say this: it's a confused mess. There's too much code and too little abstraction. This is typical of beginning object-oriented programmers.
    When you start seeing LOTS of repeated stuff like this:
                      if (newscroll.contains("Tornado warning".toUpperCase()))
                         scrollLabel.setBackground(red);
                      }alarm bells should start ringing in your head. It appears that a Map with a String as key and Color as value is wanted. I can make all that code collapse into something MUCH smaller. If I externalize all those awful Color declarations into a File that's read on startup (e.g., taking in the key message and the RGB values and initializing the Map), now I have something that I can change more easily. AND there's less code to manage.
    I see URLs, applet, TimerTask, HTML - the kitchen sink.
    I can't tell you what this class is about.
    Be lazier - write less code. That's what good programmers do.
    Try to think more abstractly.
    %

  • Shall i use Swing or AWT for creating a chessboard applet??

    Hi,
    I need to build an applet which should dislpay a chessboard where i should
    be able to move the pieces around, read in a game analysis, etc...
    I am a beginner and i would like some advice on if i should use swing or awt?
    Which one is it easier to work with in terms of dispaying the pieces, moving the pieces and achieving other more challenging functionalities?
    Is it good idea to mix both of them? i.e have a japplet and use a canvas for displaying the board??
    Any advice would be much obliged.

    I used to think AWT
    And someone told me Swing was better..and that all of the Drag-n-Drop stuff doesn't work well with AWT.
    I have to admit that I used AWT up until a project about 3 months ago--I liked it better, but Swing does seem to have more builtins for handling the things you would need to for the Chess Board. Not that you CAN'T do them with AWT, but that they are harder to do with AWT.
    As far as reading in game analysis, etc..that really is independent of Swing/AWT

  • PDF Display INSIDE a SWING app.

    Is there a way to display PDF inside a JPanel (or whatever ;-) ? I know Adobe made a Bean but no support was added since two years (if i am right). PDFGo could be a solution but it seems slow and not really nice...
    Other solutions ?
    Anyone has already done such thing ?
    Thanks.
    Phil

    Hi,
    we are using the bean in an 1.3.1 environment and it works pretty well...
    you can see how we implemented it by looking into the code a bit...Don't worry about the maintainer class..its just part of our gui framework.
    Regards.,
    rookie_no2
    package de.fiscus.sfs.akte;
    import com.adobe.acrobat.*;
    import com.adobe.acrobat.gui.*;
    import de.fiscus.sfs.akte.internal.AkteHelpset;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.FocusEvent;
    import java.awt.*;
    import java.io.StringWriter;
    import java.io.PrintWriter;
    import java.util.*;
    import javax.swing.*;
    import de.fiscus.mw.bnof.*;
    import de.fiscus.mw.transfer.*;
    import de.fiscus.sfs.druck.druckauftrag.TODruckAuftrag;
    * Diese Form realisiert die Anzeige eines einzelnen Aktenelementes in einer Nur-Lese-Ansicht.
    * Dazu zeigt die Form die PDF-Viewer-Bean, deren Inhalt durch ein an den Viewer �bergebenes
    * Byte-Array bestimmt wird, an.
    * <p>
    * @version %version: 7 %
    * @see BNOForm
    public class AkteneintragPDFForm extends AkteneintragBNOForm implements ViewerCommand{
      Viewer ivViewer = null;
      // Komponenten, die vom JBuilder erzeugt wurden
      BorderLayout borderLayout1 = new BorderLayout();
      BorderLayout borderLayout2 = new BorderLayout();
      JPanel jPanel1 = new JPanel();
      JPanel jPanelButtonBar = new JPanel();
      GridBagLayout gridBagLayout1 = new GridBagLayout();
      GridLayout gridLayout1 = new GridLayout();
      /** Konstruktor. Initialisiert die Form. Es wird lediglich die Methode
       *  <code>jbInit</code> gerufen, um die grafische Repr�sentation der Form zu
       *  erzeugen.
       *  @see jbInit
      public AkteneintragPDFForm() {
        try  {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      /** Definiert die grafische Repr�sentation der Form.
       *  @return void
       *  @exception Exception : technischer Fehler aufgetreten
      private void jbInit() throws Exception {
        this.setComponentName("Druckvorschau"+AkteHelpset.cvARBEITS_BESTANDSANZEIGE);
        //Funktionalit�t der pdf-Bean
        try{
          ivViewer = new Viewer();
          //Setzen der Skalierung auf die Breite des Frames
          ivViewer.setProperty("Default_Zoom_Type","FitWidth");
          //Abschalten der gesamten Shortcut-Funktionalit�t
          Properties prop = CommandRegistry.getKeymaps();
          prop.clear();
          //Einschalten bestimmter Shortcut-Funkionalit�ten
          prop.putAll(getAllowedShortcuts());
          //Nicht ben�tigte Commands abschalten
          CommandRegistry.setDisallowedCommands(getDisallowedCommands());
        catch (Exception e) {
          e.printStackTrace();
        this.setMaintainer(new AkteneintragPDFForm.FormMaintainer(ivViewer));
        this.setPreferredSize(new Dimension(700, 600));
        this.setLayout(borderLayout1);
        this.add(ivViewer, borderLayout1.CENTER);
        jPanelButtonBar.setLayout(borderLayout2);
        jPanelButtonBar.add(getButtonBar(), borderLayout2.EAST);
        //this.add(this.getButtonBar(), borderLayout1.SOUTH);
        this.add(jPanelButtonBar, borderLayout1.SOUTH);
        Die nicht ben�tigten Commands (ViewerCommand) werden hier in einem String-Array zusammengefa�t und zur�ckgegeben
        @return String [] gesammelte Commands
      private String [] getDisallowedCommands () {
        return new String [] {PageOnly_K, Thumbnails_K, ShowBookmarks_K, HideBookmarks_K, ToggleBookmarks_K,
                              Window_K, Open_K, OpenURL_K, Close_K, GeneralPrefs_K, About_K, Reload_K, Find_K,
                              FindAgain_K, DocInfo_K, ListBindings_K, PrintSetup_K, FirstPage_K,
                              PrevPage_K, NextPage_K, LastPage_K, PageUp_K, PageDown_K, LineUp_K, LineDown_K,
                              SinglePage_K, OneColumn_K, TwoColumn_K, TwoColumnLeft_K, TwoColumnRight_K,
                              ActualSize_K, FitPage_K, FitVisible_K, FitWidth_K, FitVisibleWidth_K, FitHeight_K,
                              FitVisibleHeight_K, FitVisibleHeight_K, FullScreen_K, ToFullScreen_K, FromFullScreen_K,
                              ToggleFullScreen_K, OpenHelpFile_K, OpenLicenseFile_K, EditUndo_K, EditDelete_K,
                              EditCopy_K, EditCut_K, EditPaste_K, EditSelectAll_K, Print_K};
        Erlaubte Shortcuts werden hier in einer Properties zur�ckgegeben. Die existierenden Commands sind
        durch den Aufruf CommandRegistry.getKeymaps() ersichtlich.
        @return Properties gesammelte Shortcuts
      private Properties getAllowedShortcuts () {
        Properties prop = new Properties();
        prop.put("Page_Down", "PageDown");
        prop.put("Page_Up", "PageUp");
        return prop;
      public Viewer getPDFViewer () {
        return ivViewer;
      * INNER CLASS - FormMaintainer --- Beginn                                   *
      public class FormMaintainer extends AkteneintragBNOFormMaintainer {
        private Viewer ivViewer = null;
        public FormMaintainer (Viewer ivViewer) {
          this.ivViewer = ivViewer;
         * F�gt den Inhalt des �bergebenen Byte-Arrays in den Viewer ein.
         * @param byte [] Byte-Array mit dem Inhalt des darzustellenden pdf-Files
        public void setPdfContent (byte [] bArray) {
          try{
            ivViewer.setDocumentByteArray(bArray);
          catch (Exception e) {
            e.printStackTrace();
         * CALLBACK: Diese Methode wird vom BNOFramework nach der Initialisierung
         * der Form gerufen. Diese Implementierung initialisiert die Toolbar der
         * Form. Anschlie�end wird die Methode <code>refresh</code> gerufen, um
         * die Form neu darzustellen.
         * @return void
         *  @see refresh
        protected void handleSetup() {
          super.handleSetup();
          refresh();
         * �berschreibt die Methode der Superklasse. Sorgt daf�r, da� bei einem Klick auf den
         * Schlie�en-Button die pdf-Bean ordnungsgem�� beendet wird.
         * @param ActionEvent e
        protected void handleCancel (ActionEvent e){
          ivViewer.deactivate();
          super.handleCancel(e);
         * �berschreibt die Methode in der Superklasse. Dient dazu, den Event f�r einen vorhandenen
         * Drucken-Button in der AkteneintragPDFForm entsprechend zu behandeln
         * @param e ActionEvent, das das ausgel�ste Ereignis enth�lt
         * @exception Exception
        protected void handleActionPerformed (ActionEvent e) throws java.lang.Exception {
          if (e.getActionCommand().equals(BNOActionEvent.cvPRINT)){
            //ALT:
            //ivViewer.execMenuItem(ViewerCommand.Print_K);
            BNOFormMaintainer bnoFM = this.getParentMaintainer();
            final AkteneintragBearbeiten ab = (AkteneintragBearbeiten)this.getDataSource();
            final TODokumentDruckInfo toDruckInfo = ab.getDruckInformation();
            TOAkteneintrag toAE = null;
            //Abfangen der Exception notwendig. Tritt auf, wenn eine Druckvorschau vorhanden ist,
            //der Akteneintrag gel�scht wird und versucht wird, auf der ge�ffnetten Druckvorschau
            //diesen gel�schten Akteneintrag zu drucken
            try{
              toAE = ab.getAkteneintrag();
            catch (AkteException ae){
              throw new AkteException (true, "AkteneintragNotFoundException", new Object [] {"M�glicherweise wurde der Akteneintrag gel�scht"});
            final TOAkteneintrag selectedTO = toAE;
            AkteneintragDruckDialogForm form = new AkteneintragDruckDialogForm(ab.provideDienstpostenBefragen());
            BNODataAccessor data = new BNODataAccessor("", "") {
              public Object handleGetData () throws de.fiscus.mw.util.FiscusException, java.rmi.RemoteException {
                return toDruckInfo;
              public void handleSetData (Object o) throws de.fiscus.mw.util.FiscusException, java.rmi.RemoteException {
                TODokumentDruckInfo toDruckInfo = (TODokumentDruckInfo)o;
                ab.printDokument(toDruckInfo);
                if (selectedTO.getStatus()==(AkteneintragStatus.IM_BESTAND.getValue())){
                  ab.printDokumentImBestand(toDruckInfo);
                else {
                  ab.printDokumentPreview(toDruckInfo);
            //form.setButtonBar(AkteneintragBNOForm.cvDRUCKVORSCHAU_OK_ABBRECHEN);
            form.setButtonBar(AkteneintragBNOForm.cvOK_ABBRECHEN);
            BNOOpenWindowParameters owp = BNOOpenWindowParameters.createForSecondaryWindow(form, data, this, null, true);
            BNOWindow w = BNOFactory.createWindow(owp);
          else super.handleActionPerformed(e);
        * Initialisiert die Maintainerhierarchie richtungsm��ig von den
        * �bergeordneten Maintainern zu den untergeordneten Maintainern.
        public void reInitialize() {
          super.reInitialize();
          refresh();
        /** Diese Methode wird verwendet, um die Form neu darzustellen. Dazu wird die
         *  zuvor erzeugte Viewer-Bean aktiviert, soda� sie dargestellt werden kann.
         *  @return void
        public void refresh() {
          try{
            ivViewer.activate();
          catch (Exception e) {
            e.printStackTrace();
      * INNER CLASS - FormMaintainer --- Ende                                     *
    }

Maybe you are looking for