Graphics Giving me NullPointerException in my swings program

hiii
I have used Graphics to draw the histogram of an image on a blank file and then display it. I am getting a NullPointerException at the line where i call getGraphics().
My code is as follows:-
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.awt.image.*;
import javax.swing.*;
public class hist extends JFrame
     JPanel panel = new JPanel(new BorderLayout());
     JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    JScrollPane PictBox = new JScrollPane();
    JScrollPane HistBox = new JScrollPane();
     String ImageName = "pug.jpg"; //Enter Image to be opened here
     Image image = Toolkit.getDefaultToolkit().getImage(ImageName);
     Image histImage;     
     public hist()
          super("HISTOGRAM OF AN IMAGE");
          getContentPane().add(panel);
          panel.add(splitPane, BorderLayout.CENTER);
        splitPane.setResizeWeight(0.5); // Set the divider in the center
        JLabel originalImage = new JLabel(new ImageIcon(ImageName));
        histImage = createImage(240,320);
        splitPane.setLeftComponent(PictBox);     //this is the original image container
        splitPane.setRightComponent(HistBox);   //this is the Histogram image container
        PictBox.getViewport().add(originalImage);     //Image is added here
        getHistogram();
        displayNewImage();
     public void getHistogram()
          PixelGrabber grabber;
          int width=0,height=0;
          int i,j;
          int sizeofImage=0; //Original Dimensions
          int dataCopy[],data[];
          int ThreeDimImage[][][],ThreeDimImage1[][][];
//STEP 1:- FETCH THE PIXELS TO WORK WITH      
        try
              grabber = new PixelGrabber(image, 0, 0, -1, -1, true);
              if (grabber.grabPixels())
                    width = grabber.getWidth();
                     height = grabber.getHeight();
                     sizeofImage = width * height;
                data = (int[]) grabber.getPixels(); //Pixel values stored in array data
                //Next I make a copy of array data[] as array dataCopy[]
                dataCopy = new int[sizeofImage];
                for(i=0; i<sizeofImage; i++)
                     dataCopy[i] = data;          
//STEP 2:- CONVERT PIXELS FROM 1d ARRAY to 3d ARRAY
     //Create a 3d Array to store Alpha-Red-Green-Blue, storing a byte for each.
     //Remaining 24 bits of each integer set to zero.
     ThreeDimImage = new int[height][width][4];
//      ThreeDimImage1 = new int[height][width][4];
     //Next we perform transfer of actual RGB data from the packed 1d array, to the 3d array.
     int element = 0;
     for(i=0; i<height; i++)
          for(j=0; j<width; j++)
               ThreeDimImage[i][j][0] = (dataCopy[element] >> 24) & 0xFF; //ALPHA COMPONENT          
               ThreeDimImage[i][j][1] = (dataCopy[element] >> 16) & 0xFF; //RED COMPONENT                    
               ThreeDimImage[i][j][2] = (dataCopy[element] >> 8 ) & 0xFF; //GREEN COMPONENT                    
               ThreeDimImage[i][j][3] = (dataCopy[element] ) & 0xFF;     //BLUE COMPONENT          
               element++;
//DRAWING THE HISTOGRAM
               Graphics g = histImage.getGraphics();
               g.setColor(Color.white);
               g.fillRect(0,0,320,240);
               g.setColor(Color.black);
               g.drawRect(10,10,310,230);
               g.setColor(Color.red);
               int xCoord=230;
               int yCoord=10;
               int[] grayLevelImage = new int[height*width];
               int histogram[] = new int[256];
               element=0;
               for(i=0; i<height; i++)
          for(j=0; j<width; j++)
               grayLevelImage[element] = (int)(
                                                       (0.30 * ThreeDimImage[i][j][1]) +
                                                       (0.59 * ThreeDimImage[i][j][2]) +
                                                       (0.11 * ThreeDimImage[i][j][3])
               element++;
     for(i=0;i<256;i++)
          histogram[i]=0;     
     int currentpixel=0;
     for(i=0;i<sizeofImage;i++)
          currentpixel = grayLevelImage[i];
          histogram[currentpixel]++;
     int valueToPlot=0;
     for(i=0;i<256;i++)
          if(histogram[i]==0)
               valueToPlot=0;     //If ther is no pixel of the concernd intensity then print nothn on the histogrm
          else     
               valueToPlot = (histogram[i]/334)+2;     //otherwise print atleast a 2 pixel tall line
          g.drawLine(xCoord,yCoord,xCoord,(yCoord - valueToPlot));     
          xCoord++;
     g.dispose();
     /*element=0;
     for(i=0; i<height; i++)
          for(j=0; j<width; j++)
               ThreeDimImage1[i][j][0] = 255;
               ThreeDimImage1[i][j][1] = grayLevelImage[element];
               ThreeDimImage1[i][j][2] = grayLevelImage[element];
               ThreeDimImage1[i][j][3] = grayLevelImage[element];
               element++;
     //PART 4 - CONVERT PROCESSED 3d ARRAY BACK TO 1d ARRAY
               element = 0;
               for( i=0; i<height; i++)
                    for( j=0; j<width; j++)
                         dataCopy[element] = (
                                                  ((ThreeDimImage1[i][j][0] << 24) & 0xFF000000) |
                         ((ThreeDimImage1[i][j][1] << 16) & 0x00FF0000) |
                         ((ThreeDimImage1[i][j][2] << 8) & 0x0000FF00) |
                         ((ThreeDimImage1[i][j][3]) & 0x000000FF)
                         element++;     
//PART 5:- REGENERATE A MODIFIED IMAGE
               histImage = createImage( new MemoryImageSource(width,height,dataCopy,0,width) );
catch (InterruptedException e1)
     e1.printStackTrace();
//DISPLAY NEW IMAGE     
     public void displayNewImage()
          //FINALLY DISPLAY THE NEW IMAGE
          JLabel histogram = new JLabel(new ImageIcon(histImage));
          HistBox.getViewport().add(histogram);     //Inverted image is added here
     public static void main (String[] args)
          hist h1 = new hist();
          h1.setSize(1000,700);
          h1.setExtendedState(MAXIMIZED_BOTH);
          h1.setVisible(true);

As I said! You do your drawing in the paintComponent(Graphics g) method of some component. Something along the lines of this example
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class TestColors extends JFrame
    public TestColors()
        super("Colors");
        final JPanel panel = new JPanel()
                setPreferredSize(new Dimension(640, 480));
                setBackground(new Color(0xffffdf));
            public void paintComponent(Graphics g)
                super.paintComponent(g);
                final int r = 20;
                final int r2 = r/4;
                final int w = getWidth() - r - 1;
                final int h = getHeight() - r - 1;
                final Random random = new Random(12321);
                for (int i = 0; i < 1000; i++)
                    g.setColor(new Color(random.nextFloat(), random.nextFloat(), random.nextFloat()));
                    final int x = random.nextInt(w);
                    final int y = random.nextInt(h);
                    for (int j = 0; j < r2; j++)
                        g.drawRect(x+j, y+j, r-j-j, r-j-j);
        getContentPane().add(new CompassPoint(), BorderLayout.NORTH);
        getContentPane().add(new CompassPoint(), BorderLayout.EAST);
        getContentPane().add(panel, BorderLayout.CENTER);
        getContentPane().add(new CompassPoint(), BorderLayout.WEST);
        getContentPane().add(new CompassPoint(), BorderLayout.SOUTH);
        pack();
    private static class CompassPoint extends JPanel
        private CompassPoint()
            setBackground(Color.WHITE);
            setPreferredSize(new Dimension(100,100));
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            final int h = getHeight();
            final int w = getWidth();
            final double deltac = 1.0/w;
            for (int x = 0; x < w;)
                final float color = (float)(1.0-deltac*x);
                g.setColor(getColor(color));
                for (int j = 0; j < 1; j++)
                    g.drawLine(x,0,x,h);
                    x++;
        protected Color getColor(float color)
            if (color < 0.5)
                color = (float)(1.0-2.0*color);
            else
                color = (float)(2.0*color-1.0);
            return new Color(color, color, 1.0f);
    public static void main(String[] args)
        TestColors test = new TestColors();
        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        test.setLocationRelativeTo(null);
        test.setVisible(true);
}The point is that the paintComponent() method gets called whenever a repaint is required. For example, if you re-size the frame or de-iconize the application then the paintComponent() method gets called so that the content is re-drawn.

Similar Messages

  • Keyboard-lock of swing program on Linux box

    We are developing swing program on Linux, and we often meet keyboard-lock issues.
    I try to simplify some of them to small programs, and still meet keyboard-lock.
    Here I post two programs to show the error:
    //---first ----------------------------------------------
    package test;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class KeyLock extends JFrame {
      JPanel contentPanel = new JPanel();
      JPanel wizardToolPan = new JPanel();
      JButton btnBack = new JButton("Back");
      JButton btnNext = new JButton("Next");
      JButton btnAbout = new JButton("About");
      public static final String aboutMsg =
              "<html>  This program will help to find keyboard lock problems, two way to reproduce:<br><br>" +
              "1 - press Alt+N to navigate next, and don't release keys untill there are no more next page, <br>" +
              "then try Alt+B to navigate back and also don't release keys untill page 0,<br>" +
              "repeat Alt+N and Alt+B again and again, keyboard will be locked during navigating. <br><br>" +
              "2 - press Alt+A in main window, it will popup an about dialog,<br>" +
              "then press down space key and don't release, <br>" +
              "the about dialog will be closed and opened again and again,<br>" +
              "keyboard will be locked sooner or later." +
              "</html>";
      public KeyLock() {
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setTitle("Keyboard lock test");
        getContentPane().setLayout(new BorderLayout());
        btnBack.setMnemonic('B');
        btnBack.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            KeyLock.this.goBack(e);
        btnNext.setMnemonic('N');
        btnNext.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            KeyLock.this.goNext(e);
        btnAbout.setMnemonic('A');
        btnAbout.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(KeyLock.this, aboutMsg, "About", JOptionPane.INFORMATION_MESSAGE);
        contentPanel.setLayout(new BorderLayout());
        contentPanel.setPreferredSize(new Dimension(400, 250));
        contentPanel.setMinimumSize(new Dimension(400, 250));
        wizardToolPan.setLayout(new FlowLayout());
        wizardToolPan.add(btnBack);
        wizardToolPan.add(btnNext);
        wizardToolPan.add(btnAbout);
        this.getContentPane().add(contentPanel, java.awt.BorderLayout.CENTER);
        this.getContentPane().add(wizardToolPan, java.awt.BorderLayout.SOUTH);
        this.setSize(400, 300);
        this.createContentPanels();
        this.showCurrent();
      private Vector<JPanel> slides = new Vector<JPanel>();
      private int current = 0;
      private void createContentPanels() {
        for (int j = 0; j < 20; ++j) {
          JPanel p = new JPanel(new FlowLayout());
          p.add(new JLabel("Page: " + j));
          p.add(new JTextField("Page: " + j + ", input something here", 20));
          p.add(new JTextField("Page: " + j + ", input something here", 20));
          p.add(new JTextField("Page: " + j + ", input something here", 20));
          p.add(new JLabel("Input something in password box:"));
          p.add(new JPasswordField(20));
          p.add(new JCheckBox("Try click here, focus will be here."));
          p.add(new JRadioButton("Try click here, focus will be here."));
          slides.add(p);
      public void showCurrent() {
        if (current < 0 || current >= slides.size())
          return;
        JPanel p = slides.get(current);
        this.contentPanel.add(p, java.awt.BorderLayout.CENTER);
        this.pack();
        Component[] comps = p.getComponents();
        if (comps.length > 0) {
          comps[0].requestFocus(); // try delete this line
        this.repaint();
      public void goNext(ActionEvent e) {
        if (current + 1 >= slides.size())
          return;
        this.contentPanel.remove(slides.get(current));
        current++;
        sleep(100);
        this.showCurrent();
      public void goBack(ActionEvent e) {
        if (current <= 0)
          return;
        this.contentPanel.remove(slides.get(current));
        current--;
        sleep(100);
        this.showCurrent();
      public static void sleep(int millis) {
        try {
          Thread.sleep(millis);
        } catch (Exception e) {
          e.printStackTrace();
      public static void main(String[] args) {
        KeyLock wizard = new KeyLock();
        wizard.setVisible(true);
    }The first program will lead to keyboard-lock in RHEL 4 and red flag 5, both J2SE 5 and 6.
    //---second -----------------------------------------
    package test;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class KeyFocusLost extends JFrame {
      private JButton btnPopup = new JButton();
      private JTextField jTextField1 = new JTextField();
      private JPasswordField jPasswordField1 = new JPasswordField();
      private JPanel jPanel1 = new JPanel();
      private JScrollPane jScrollPane3 = new JScrollPane();
      private JTree jTree1 = new JTree();
      private JButton btnAbout = new JButton("About");
      public static final String aboutMsg =
              "<html>  This program is used to find keyboard focus lost problem.<br>" +
              "Click 'popup' button in main window, or select any node in the tree and press F6,<br>" +
              "a dialog popup, and click ok button in the dialog,<br>" +
              "keyboard focus will lost in main window." +
              "</html>";
      public KeyFocusLost() {
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setTitle("Keyboard focus test");
        getContentPane().setLayout(null);
        btnPopup.setBounds(new Rectangle(33, 482, 200, 35));
        btnPopup.setMnemonic('P');
        btnPopup.setText("Popup and lost focus");
        btnPopup.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            PopupDialog dlg = new PopupDialog(KeyFocusLost.this);
            dlg.setVisible(true);
        btnAbout.setBounds(new Rectangle(250, 482, 100, 35));
        btnAbout.setMnemonic('A');
        btnAbout.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(KeyFocusLost.this, aboutMsg, "About", JOptionPane.INFORMATION_MESSAGE);
        jTextField1.setText("Try input here, and try input in password box below");
        jTextField1.setBounds(new Rectangle(14, 44, 319, 29));
        jPasswordField1.setBounds(new Rectangle(14, 96, 319, 29));
        jPanel1.setBounds(new Rectangle(14, 158, 287, 291));
        jPanel1.setLayout(new BorderLayout());
        jPanel1.add(new JLabel("Select any node in the tree and press F6."), java.awt.BorderLayout.NORTH);
        jPanel1.add(jScrollPane3, java.awt.BorderLayout.CENTER);
        jScrollPane3.getViewport().add(jTree1);
        Object actionKey = "popup";
        jTree1.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0), actionKey);
        jTree1.getActionMap().put(actionKey, new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
            PopupDialog dlg = new PopupDialog(KeyFocusLost.this);
            dlg.setVisible(true);
        this.getContentPane().add(jTextField1);
        this.getContentPane().add(jPasswordField1);
        this.getContentPane().add(jPanel1);
        this.getContentPane().add(btnPopup);
        this.getContentPane().add(btnAbout);
      public static void main(String[] args) {
        KeyFocusLost keytest = new KeyFocusLost();
        keytest.setSize(400, 600);
        keytest.setVisible(true);
      static class PopupDialog extends JDialog {
        private JButton btnOk = new JButton();
        public PopupDialog(Frame owner) {
          super(owner, "popup dialog", true);
          setDefaultCloseOperation(DISPOSE_ON_CLOSE);
          this.getContentPane().setLayout(null);
          btnOk.setBounds(new Rectangle(100, 100, 200, 25));
          btnOk.setMnemonic('O');
          btnOk.setText("OK, then focus lost");
          btnOk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              PopupDialog.this.getOwner().toFront();
              try {
                Thread.sleep(100); // try delete this line !!!
              } catch (Exception ex) {
                ex.printStackTrace();
              PopupDialog.this.dispose();
          this.getContentPane().add(btnOk);
          this.getRootPane().setDefaultButton(btnOk);
          this.setSize(400, 300);
    }The second program will lead to keyboard-focus-lost in RHEL 3/4 and red flag 4/5, J2SE 5, not in J2SE 6.
    And I also tried java demo program "SwingSet2" in red flag 5, met keyboard-lock too.
    I guess it should be some kind of incompatibleness of J2SE with some Linux platform. Isn't it?
    Please help, thanks.

    Hi.
    I have same problems on Ubuntu with Java 6 (all versions). I would like to use NetBeans or IntelliJ IDEA but it is not possible due to keyboard locks.
    I posted this bug
    https://bugs.launchpad.net/ubuntu/+bug/174281
    before I found some info about it:
    http://forums.java.net/jive/thread.jspa?messageID=189281
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6506617
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6568693
    I don't know from which part this bug comes, but I wonder why it isn't fixed yet. Does anybody else use NetBeans or IntelliJ IDEA on linux with Java 6 ?
    (I cannot insert link :\ )

  • Error while running Swing program on FreeBSD

    Hi,
    I am trying to run simple swing program "helloworld"
    but while executing it gives following error on FreeBSD
    Exception in thread "main" java.lang.UnsatisfiedLinkError:
    /usr/local/linux-sun-jdk1.4.2/jre/lib/i386/libawt.so: libXp.so.6:
    cannot open shared object file: No such file or directory
            at java.lang.ClassLoader$NativeLibrary.load(Native Method)
            at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1560)
            at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1477)
            at java.lang.Runtime.loadLibrary0(Runtime.java:788)
            at java.lang.System.loadLibrary(System.java:834)
            at sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:50)
            at java.security.AccessController.doPrivileged(Native Method)
            at sun.awt.NativeLibLoader.loadLibraries(NativeLibLoader.java:38)
            at sun.awt.DebugHelper.<clinit>(DebugHelper.java:29)
            at java.awt.EventQueue.<clinit>(EventQueue.java:80)
            at javax.swing.SwingUtilities.invokeLater(SwingUtilities.java:1170)
            at JPanels.main(JPanels.java:29)
    Should i install XFree86-libs package on FreeBsd
    configuration
    FreeBSD 4.10-BETA (GENERIC)
    I am using following packages
    linux-sun-jdk-1.4.2.04 Sun Java Development Kit 1.4 for Linux
    linux_base-8-8.0_4 Base set of packages needed in Linux mode (only for i386)
    linux_devtools-8.0_1 Packages needed for doing development in Linux mode
    libtool-1.3.5_1 Generic shared library support script
    gmake-3.80_1 GNU version of 'make' utility
    automake-1.4.5_9 GNU Standards-compliant Makefile generator (legacy version
    GCC 2.95.4
    gdb 4.18
    ld 2.12.1 supported emulation elf_i386
    regards
    Man479

    This is not really a Swing question. You should install the library which satisfies the lookup of libXp.so.6 .
    I quess the jre for this platform is compiled against this version. Looks to me like some X related library, maybe google can resolve a solution/package to install?
    Greetz

  • Running a Swing program from another program

    I'm having what is most likely newbie problems since I'm relatively new to Swing programming. Basically my situation is this: I've got a program that looks at its command line parameters and either runs through a series of actions or presents a Swing GUI to allow the user to step through the actions one by one.
    My problem is that I bascially don't know how to call (instantiate, declare, etc.) the GUI from my Java code. I tried implementing the GUI class with a runnable interface, but evertime I try to invoke the start on the interface I'm getting an error. I have a feeling I'm just missing something. The Swing GUI works fine if I call it on its own so it's the code the invokes it from the small command line processor that I'm goofing up somehow.
    So to recap, I have a small Java app that I'm trying to call a GUI that I've built and can't seem to get the code right.
    Any pointers to examples or explanation on how to accomplish the above are welcome.
    Thanks,
    Ed

    That the "2" is printed out immediately is as expected, but I don't understand why the JVM exits. The following is, AFAIK, a trimmed down version of what you are doing, and if you run it you'll see that the frame remains until you close it manually:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    public class ShowFrame {
        public static void main(String[] args) {
            AppFrame gui = new AppFrame();
            gui.run();
        private static class AppFrame extends JFrame implements Runnable {
            public AppFrame() {
                setDefaultCloseOperation(EXIT_ON_CLOSE);
                JButton btn = new JButton("Close");
                btn.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        AppFrame.this.dispose();
                getContentPane().add(btn);
                pack();
                setLocationRelativeTo(null);
            public void run() {
                System.out.println("1");
                this.setVisible(true);
                System.out.println("2");
    }Maybe someone else can shed some light over your problem...

  • Placing a telnet session within a java swing program

    I was wondering if there was a way to maybe anchor a telnet session into a JPanel within a Java Swing program. Most of my users end up running a telnet session while using my Swing Program and I was hoping to find a way to bring the two together. If this is possible could someone point me in the right direction (like an online resource) that might show me how to do this.

    You could use sockets and a TextArea and build your own simple telnet application.
    Socket tutorial: http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

  • Swing program - how to increase the size

    Hi Friends,
    I have made a simple swing program and it works fine.But I am not able to make the size(width,height) of the panel.Can someone please tell me how can i do that.Here's some part of my code...
    public class Test extends JPanel
                                 implements ActionListener {
        //instance variable declared here
        public Test() {
            super(new BorderLayout());
            //code for buttons,labels etc
            JPanel buttonPanel = new JPanel(); //use FlowLayout
            add(buttonPanel, BorderLayout.PAGE_START);
        public void actionPerformed(ActionEvent e) {
            //lots of code
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("Test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new Test();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }Thanks for your help.

    OK sorry for that,in future i will post it in the right place.I tried doing this but didn't worked:
           JPanel buttonPanel = new JPanel(); //use FlowLayout
           // buttonPanel.setSize(300, 300);I was followin the FileChooserDemo example from this link:
    http://java.sun.com/docs/books/tutorial/uiswing/components/examples/index.html#FileChooserDemo
    And they used the pack there....now can you help please.

  • Which is the best user-friendly IDE for swing program development

    Which is the best user-friendly IDE for swing program development

    I have seen Sun's Forte and IBM's Visual Age for Java.
    But Borland's JBulider 7 Personal Edition is far more superior than any of these.Borland's JBuilder is the Best.
    Ranga.

  • Error on compling the Swing program

    Hi all,
    I am trying to run a Login Swing program. I am want to go to the next page on click of the LOGIN button.Here is my code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class login extends JFrame implements ActionListener {
         public login(){
              setTitle("Login Page");
              //setSize(500,500);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
              Container pane = getContentPane();
              FlowLayout layout = new FlowLayout();
              pane.setLayout(layout);
              JLabel loginId = new JLabel("LoginId : ", JLabel.CENTER);
              JTextField Id = new JTextField(20);
              if(Id.equals("shri"))
                   System.out.println("login successful");
              JLabel password = new JLabel("Password : ", JLabel.CENTER);
              TextField pwd = new TextField(20);
              pwd.setEchoChar('*');
              JButton Enter = new JButton("Log in");
              private void actionPerformed(ActionEvent e)) {
                   String read = Id.getText();
                   String in = new String(pwd.getText());
                   //validate login and password here. validity will be done by sending login/password to the server
                   if (read.equals("Shri") && in.equals("Shri")) {
                   System.out.println("login successfull");
                   } else {
                   JOptionPane.showMessageDialog(this,"Incorrect login or password","Error",JOptionPane.ERROR_MESSAGE);
                   Id.setText("");
                   pwd.setText("");
                   Id.requestFocusInWindow();
              pane.add(loginId);
              pane.add(Id);
              pane.add(password);
              pane.add(pwd);
              pane.add(Enter,BorderLayout.CENTER);
              setContentPane(pane);
              pack();
         public static void main(String[] args) {
              login enter = new login();
    I'm getting the error->The type login must implement the inherited abstract method ActionListener.actionPerformed(ActionEvent)
         void is an invalid type for the variable actionPerformed
         Syntax error on token "(", ; expected
         Syntax error, insert ";" to complete LocalVariableDeclarationStatement
    Please help me resolve this error and also to improvise the code.

    You code had basic problem like declaration errors. Have modified your code.
    Try this.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Login extends JFrame implements ActionListener {
        JLabel loginId;
        JTextField Id;
        TextField pwd;
        public Login(){
            setTitle("Login Page");
            //setSize(500,500);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
            Container pane = getContentPane();
            FlowLayout layout = new FlowLayout();
            pane.setLayout(layout);
            loginId = new JLabel("LoginId : ", JLabel.CENTER);
            Id = new JTextField(20);
            if(Id.equals("shri")) {
                System.out.println("login successful");
            JLabel password = new JLabel("Password : ", JLabel.CENTER);
            pwd = new TextField(20);
            pwd.setEchoChar('*');
            JButton Enter = new JButton("Log in");
            pane.add(loginId);
            pane.add(Id);
            pane.add(password);
            pane.add(pwd);
            pane.add(Enter,BorderLayout.CENTER);
            setContentPane(pane);
            pack();
        public void actionPerformed(ActionEvent e) {
            String read = Id.getText();
            String in = new String(pwd.getText());
            //validate login and password here. validity will be done by sending login/password to the server
            if (read.equals("Shri") && in.equals("Shri")) {
                System.out.println("login successfull");
            } else {
                JOptionPane.showMessageDialog(this,"Incorrect login or password","Error",JOptionPane.ERROR_MESSAGE);
                Id.setText("");
                pwd.setText("");
                Id.requestFocusInWindow();
        public static void main(String[] args) {
            Login enter = new Login();
    }

  • Best Book for Swing Programming

    Can anyone tell me the name of a swing related book which covers all the major topic of swing programming.
    Thanks in advance

    I like Java Swing from OReilly. Big thick book, and contains nothing but Swing.

  • Font problem when executing a swing program

    Hi! I'm learning to write a simple swing program. The program compiled successfully. When I excuted it, everything worked fine except that I got the following error message:
    Font specified in font.properties not found [--symbol-medium-r-normal--*-%d-*-*-p-*-adobe-fontspecific]
    It's somewhat annoying. Do you have any solution?
    Thank you,
    Liheng

    Thank you. I tried to run Font2DTest. But it didn't work, "Exception in thread "main" java.util.zip.ZipException: No such file or directory"
    I'll keep trying.......
    In JDK under the directory demo/jfc/Font2DTest, there
    is a demo program that shows all available fonts on
    your system. You can find the available font names.
    Then in the font.properties file in jre/lib, search
    for the font name in your error message and replace it
    with an available name from Font2DTest.
    Are you using Unix? What OS, Solaris, Linux?

  • How to start Swing programs without console

    Hi, I'm working on Swing program, which can be started in the MS-DOS console by typing:
    java myProgram
    This works great, but for the end-users, I don't want them to see the ugly console that shows up and occasionally display exception code. How do I get the Swing program to start up without having the accompanying console?
    Any help is appreciated. Thanks! :-)

    you can also package it in a jar and make it executable. There's a good discussion in the Jar Forum about how to do that.

  • Produce EXE files for Swing programs using Visual J++?

    There's a way to make VJ++ to compile Swing programs:
    http://www.stanford.edu/class/cs108/usingvj.html
    But the exe file VJ++ produces won't run though... Does anyone know how to make it work? Thanx in advance

    TestStand 4.0.1 was released well before Visual Studio 2012 existed so the automatic step into behavior from TestStand that launches visual studio and attaches it as a debugger likely does not work.
    But you can just attach to the seqedit.exe process from Visual Studio and set breakpoints in your code and debug teststand just like you would any other process from Visual Studio. Make sure that when you attach with Visual Studio that you make sure you have it set to debug native code.
    Hope this helps,
    -Doug

  • NullPointerException at javax.swing.BufferStrategyPaintManager.flushAccu...

    I've developed an application that, basically, has a JDesktop, and it opens JInternalFrames in it to allow the user to do specific operations. The main external frame is created by a custom widget (developed by other people in my lab) which provides an org.apache.commons.logging.Log console. The console logs user's operations, and shows its contents in a textfield inside the main frame.
    About 5% of the time I get this exception on console when booting my application:
    java.lang.NullPointerException
    at
    javax.swing.BufferStrategyPaintManager.flushAccumulatedRegion(Unknown
    Source)
    at javax.swing.BufferStrategyPaintManager.endPaint(Unknown Source)
    at javax.swing.RepaintManager.endPaint(Unknown Source)
    Even after this error, the application works fine.
    I think it might be a bug on how the custom widget's components are layed out; however, just to be sure, I'd like to ask you if this does remind you of any Swing bug or misbehaviour (e.g. in the internal frames management).
    Thanks in advance, any tip appreciated.

    Here is the stacktrace:
    java.lang.NullPointerException
    at javax.swing.BufferStrategyPaintManager.flushAccumulatedRegion(Unknown Source)
    at javax.swing.BufferStrategyPaintManager.endPaint(Unknown Source)
    at javax.swing.RepaintManager.endPaint(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.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.RepaintManager.seqPaintDirtyRegions(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.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

  • Custom Timer in Swing Program

    Can anyone please provide code for me to insert a custom timer into a
    swing program? I need a clock that will run concurrently with the program. Any tips???

    I have a similar problem...
    Class:
    import java.awt.*;
    import hsa.Console;
    import java.sql.Time;
    import javax.swing.JTextField;
    public class CustomTimer extends Thread implements Runnable
    int secs = 0, mins = 0, hours = 0, day = 1, month = 1, year = 2006;
    Time timer;
    Thread main;
    public CustomTimer ()
    super ();
    public void start ()
    main = new Thread ();
    main.start ();
    public void run (JTextField pasteInHere)
    while (year != 2008)
    timer = new Time (hours, mins, secs);
    secs++;
    if (secs == 60)
    secs = 0;
    mins++;
    if (mins == 60)
    mins = 0;
    hours++;
    if (hours == 24)
    hours = 0;
    day++;
    if (day == 28 & month == 2)
    day = 0;
    month++;
    else if (day == 30 & (month == 2 | month == 4 | month == 6 | month == 9 | month == 11))
    day = 0;
    month++;
    else if (day == 31)
    day = 0;
    month++;
    if (month == 12)
    month = 0;
    year++;
    try
    main.sleep (100);
    pasteInHere.setText ("" + day + "/" + month + "/" + year + " " + timer);
    catch (InterruptedException ie)
    Program:
    import javax.swing.*;
    import java.awt.*;
    public class ClockTest extends JFrame
    public ClockTest ()
    Container contents = getContentPane ();
    setSize (500, 500);
    JPanel hi = new JPanel ();
    JTextField hello = new JTextField ();
    CustomTimer ct = new CustomTimer ();
    ct.run (hello);
    hi.add (hello);
    contents.add (hi);
    public static void main (String[] args)
    new ClockTest ().show ();
    Can anyone tell me why the clock does not run concurrently with the program?

  • Beginning Swing programming problem

    My classmates and I are trying to write a simple Swing program with a single button and a text field that contains the number of times the button has been pressed since the program started. The problem is that in the ActionPerformed method, any changes to the text field ends up with multiple event errors. It will print the count fine to the command prompt, but not the GUI. Any insight would be greatly appreciated.
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class CounterGUI extends JFrame implements ActionListener
         public int count = 0;
         Container contents = getContentPane();
         JTextField counter;
         final String temp = "Total times pressed: ";
         public CounterGUI()
              final int width = 300;
              final int height = 300;
              setSize(width, height);
              JTextField counter = new JTextField(temp + count);
              counter.setEditable(false);
              JButton clicker = new JButton("Click me!");
              clicker.addActionListener(this);
              clicker.setActionCommand("Click");
              contents.add(counter, "Center");
              contents.add(clicker, "South");
         public void actionPerformed(ActionEvent e)
              String command = e.getActionCommand();
              if(command == "Click")
                   count++;
                   counter.setText(temp + count);     
                   System.out.println(count);
         public static void main(String[] args)
         JFrame f = new CounterGUI();
         f.addWindowListener(new WindowCloser());
              f.setVisible(true);

    Hi Guys,
    The line JTextField counter = new JTextField(temp + count); is declared in the constructor, this means that the field counter is not visible to other methods and you'll get a null pointer exception (NPE) when you try to access the class field counter
    Change to counter = new JTextField(temp + count); Now if you were catching and displaying exceptions you'd notice that this was happening.
    Dave

Maybe you are looking for

  • J2EE no longer loads

    I had J2EE running for about an hour and I can no longer bring it up. J2ee loaded fine. I could see localhost:8000 in my browser. I tried to deploy the ConverterApp demo so I could test out J2EE. When I clicked on "Generate SQL," the deploytool froze

  • Brand New Mac Book Pro with defective screen

    Hi Guys, Does anyone here, purchased a brand new Mac Book Pro 13-inch: 2.9GHz with a defective screen? I bought mine, Last June 14. I just noticed the defect last June 29 and returned it to where I purchase it at june 30. There are somewhat 'black sm

  • Console keeps quiting unexpectedly

    On my macbook pro 10.5.8 intel bought in 2008. When ever I start the console. I get the message (The application Console quit unexpectedly)  After relaunching numerous times it will stay on. But when I colse it I get the same message again. I haveran

  • Web/Email experience on your HTPC Mini

    I can understand why people have enjoyed the Mac Mini as a pure HTPC, once it is setup in the entertainment room. Here's a question for those of you who currently have your Mac Mini connected to your HDTV and use it dual purpose: HTPC and basic compu

  • Recently firefox started opening new tabs when I click on search results how do I get this to stop

    When I use Google and I click on a search result it opens a new tab where it used to just take me to a new page in the tab I was using I was looking in the tabs tab in options and saw I could choose it to open in a new window but I don't see an optio