Help regarding Java Swing

Hi All,
I am a bit confused witht the shortcut syntax for adding action listeners for event handling.
In the Java tutorial it is mentioned that for implementing an event handler following are the three steps:
1. Create a class that implements ActionListener interface.
For example:
public class MyClass implements ActionListener {
2. Registers an instance of the event handler class as a listener on one or more components.
For example:
someComponent.addActionListener(instanceOfMyClass);
3. In the event handler class, a few lines of code implement the methods in the listener interface.
For example:
public void actionPerformed(ActionEvent e) {
...//code that reacts to the action...
In the tutorial a shortcut syntax is also given:
For Example:
Class TestApp {
JButton btn = new JButton("Test");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
...//code that reacts to the action...
My doubt is:
1. How are we allowed to create an instance of ActionListener which is an "interface". (doesnt addActionListener expect instance of a class that implements the ActionListener interface? )
2. How are we able to access local variables of class "TestApp" the inside the actionPerformed() function.
Could anyone explain more about this shortcut syntax of adding action listeners?
Thanks in regards
Arun

The example uses so-called "anonymous inner classes". ActionListener is an interface, of course. But if you use the construct
new ActionListener() {
   public void actionPerformed(ActionEvent e) {
   ...//code that reacts to the action...
}this is about equivalent to defining an inner class
private class MyActionListener implements ActionListener {
   public void actionPerformed(ActionEvent e) {
   ...//code that reacts to the action...
}and using that class. The difference is mainly, that the in nthe shortcut notation the class has no explicit name, it is anonymous.
There are advantages and disadvantages to that. The main disadvantage is, that you create a large amount of classes in this way. I've read somewhere, that SUN is planning to rewrite the examples without the use of anonymous inner classes.

Similar Messages

  • Need help regarding Java decoding of IMAP attachment (IOStream related ques

    Hi ,
    I need some help regarding the processing of an IMAP attachment , It is a basic IOStream related question I guess.
    I have some attachment to a mail , I try to fetch it using javamail and read the content and write it to a file , I was able to do it successfully when I was using stream.read( tempBuffer) function but when I started using stream.read( tempBuffer, 0, m_maxDataSize ); it is giving me following exception
    java.io.IOException: Error in encoded stream: needed at least 2 valid base64 characters, but only got 1 before padding character (=), the 10 most recent characters were: "/59PT/eXQ="
         at com.sun.mail.util.BASE64DecoderStream.decode(BASE64DecoderStream.java:259)
         at com.sun.mail.util.BASE64DecoderStream.read(BASE64DecoderStream.java:148)
    ***Here is the snippet of code that is running this:***
    m_contentObj = m_message.getContent();
    if(m_contentObj instanceof InputStream)
         System.out.println(" Content is type of InputStream");
         InputStream stream = (InputStream) m_contentObj;
         byte[] tempBuffer = new byte[m_maxDataSize];
         stream.skip( m_currPos );
         int bytesRead=stream.read( tempBuffer, 0, m_maxDataSize );
         System.out.println(" Read the following no of bytes from the Object::"+bytesRead);
         m_currPos+=     bytesRead;
    Please suggest what to do.
    Thanks & Regards
    Saurabh

    BUMP, just incase its been missed by a new board member

  • Help with java swing

    Hi people!i need some help
    Im a new user for java programming language.Well im programming an application using java swing libraries. I have some problems trying to accesing variables from those swing Jpanels. Ill make it clear....
    Im using Netbeans...
    I have a class for the window (a JFrame) including 2 Jtextfields and 2 Jlabels
    import .......
    public class myclass extends javax.swing.JFrame{
    public double gp;
    public double gv;
    public G() {
    initComponents();
    gpnom=this.gpnom;
    gvnom=this.gvnom;
    private void TXFgpnom(java.awt.event.ActionEvent evt) {        //TXField                                
    gpnom= Double.parseDouble(TXFgpnom.getText());
    gvnom= Double.parseDouble(TXFgvnom.getText());
    .......//theres a lot of more code .for listeners..next...
    Now ive created a new file (a new class)in the same package ,but i cant access public variables from swing class
    //the next class was created in a new file
    public class hi () {
    JPanel prin =(JPanel) new myclass().getContentPane(); //ok
    double number=gpnom // error variable not found
    When i try to get the value of "number" ...i always get "ERROR" And the class for that textfield was public..i think...
    HOw can i use variables from that Jpanel?
    Id appreciate an answer...
    thanx for your help!
    Paco

    In future Swing related questions should be posted in the Swing forum and camickr will be more likely to answer if you have used code tags to properly format your code.
    Luckily this problem does not seem to be Swing related in the least because the public variables you have in your other class are named gp and gv and further when you access public variables (or properties) of a class you must access them by an instance of that class. Which you don't appear to be doing either.

  • Need Help Regarding JAVA BEAN

    Is any one tell me that JAVA BEAN only used in WEB or also you in Desktop applications???? and aslo tell how i implement Java class and use JAVA BEAN. I need help regarding above matter
    thanks in advance
    Rehan MIrza

    Here is a good link that indicate that JavaBean is not only for applets
    http://java.sun.com/docs/books/tutorial/javabeans/whatis/beanDefinition.html
    quote:
    The JavaBeans API makes it possible to write component software in the Java programming language. Components are self-contained, reusable software units that can be visually composed into composite components, applets, applications, and servlets using visual application builder tools. JavaBean components are known as Beans.
    Francois

  • New help on java swing GUI.....

    k, im new to java. Just started learning a month ago. Anyway, I was wondering how one can link gui together using buttons. For example, when i press enter on a registration gui, it'll take me to the confirmation gui. What's the best way to do this? anyone has any idea or can point me to a website with info. Thanks A lots folks.

    Well, bascially you would add a Button (e.g. "Next" or "Submit") to your Window/Panel (whatever you prefer). This add has an ActionListener assigned which will open up the next Window/Panel.
    Then you define this button to be your default button on that window (check JRootPane.setDefaultButton() for this) so that Enter will fire the button.
    Check the Swing online tutorial for an introduction to Swing and how Buttons (and their associated ActionListener) work.
    Thomas

  • Help regarding java.lang.UnsatisfiedLinkError

    Hi everyone ,
    I have a doubt regarding native property. I am using eclipse I wrote a program (inputoutput.java) to clear the screen after printing a line. This program creates an object (�console�) of �test� class and calls �clear� method. The test class loads the �ClearFunc.dll� file. I placed the ClearFunc.dll file along with the other class files. When I execute it is giving the following error.
    Exception in thread "main" java.lang.UnsatisfiedLinkError: no ClearFunc.dll in java.library.path
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.loadLibrary0(Unknown Source)
    at java.lang.System.loadLibrary(Unknown Source)
    at inputoutput.test.<clinit>(test.java:15)
    at inputoutput.Printing.printing(inputoutput.java:22)
    at inputoutput.inputoutput.main(inputoutput.java:51)
    �test.java code�
    package inputoutput;
    public class test {
    //static final String path ="D:/java_workspace/input_output/bin/inputoutput/ClearFunc";
    public native void clear();
    /*public static void main(String[] args) {
    new test().clear();
    static {
    try{
    System.out.println("hi");
    System.loadLibrary("ClearFunc.dll");
    System.out.println("hello");
    catch(Exception e)
    System.out.println(e.toString()+"santhu");
    e.printStackTrace();
    "inputoutput.java code"/**
    package inputoutput;
    import java.io.*;
    * @author Santhosh_Thadvai
    class Printing implements Runnable{
         Thread t;
         public void run(){
         public void printing()throws IOException,FileNotFoundException {
              try{
                   test console = new test();
                   t=new Thread();
              t.start();
              FileInputStream fileinputstream = new FileInputStream("out.txt");
              int value = fileinputstream.read();
              while(value!=-1){
                   System.out.print((char)value);
                   Thread.sleep(50);
                   value=fileinputstream.read();
                   if((char)value=='\n')
                        console.clear();
              fileinputstream.close();
              catch(InterruptedException e){
                   System.out.println(e);
    public class inputoutput {
         * @param args
         public static void main(String[] args) throws IOException {
              Printing b=new Printing();
              b.printing();
    }

    plz, surround your code with : [code ] [ /code ]

  • Urgent help regarding Java regular expressions.

    hello everyone,
    I am trying to parse a html file which contains
    dyn.Img("http://www.boston.com/news/nation/articles/2007/06/21/bill_clinton_takes_bigger_campaign_role&h=306&w=410&sz=13&hl=en&start=43","","QFo9lqKeMR7uzM:","http://cache.boston.com/resize/bonzai-fba/AP_Photo/2007/06/21/1182410228_1931/410w.jpg","125","93","\x3cb\x3eBill Clinton\x3c/b\x3e takes bigger campaign \x3cb\x3e...\x3c/b\x3e","","","410 x 306 - 13k","jpg","www.boston.com","","","http://tbn0.google.com/images","1")
    the given above function many times. I have to fetch the whole functions into an array. So i have to write a regular expression which recognises the whole above string.
    Can anyone please help me.
    Thank you,
    chaitanya

    well if this is all you want
    http://cache.boston.com/resize/bonzai-fba/AP_Photo/2007/06/21/1182410228_1931/410w.jpg
    You can always substring it like chuck said
    ***BUT all the images would have to be .jpg for this to work***
    back = we.indexOf(".jpg");
    int x = 0;
    while (back < web.lastIndexOf(".jpg"))
                    back = web.indexOf("http",back+1);
                    picture[x] = web.substring(front, back);
                    x++;
                    front = back;
                  }       Might not be the best code but it worked with a website i had to parse
    Message was edited by:
    mark07

  • Help regarding Java

    Can java work on Dos Operating System ???.

    Sun Java (and all derived versions) will not work on MSDOS (or any of its derived versions.) There was supposedly something that ran and was named Java(?), but no more. If you mean a DOS (Disk Operating System) other than MSDOS, I have no idea.

  • Regarding java swing JFrame

    Sir!
    Whenever I Create a JFrame or Frame, the components of the frame are not
    visible until I maxmize the frame window.Once maximized, the components
    remain visible even after restoring to the initial size of the frame set
    by setSize() method.Why?

    Did you call the validate method after adding all the components to your Frame?
    abraham

  • Need help for connecting Ms Acces with java Swing in Mac OS

    Hi all,
    i need to connect to Ms Access in MAc os through my java swing program.
    Is it possible for accessing Ms access through dsn in Mac OS.
    If Possible which driver shall i use for Establishing Connection with MS Access in Mac OS.
    Suggestion is needed urgently.
    Can anybody help me out regarding this..
    Thanks in advance.
    Regards,
    sreand

    if I don't find a better solution I'll try your 2nd option but what do you mean by "combo" update?
    My understanding is to simply insert the OS 10.5 installation CD, reinstall the OS and the just keep updating it via the OS SSoftware update panel and stop untill I see the scary Java 8 update. Is that what you meant?
    While you can do it that way, the combo update picks up operating system updates through a collection of releases. When dealing with operating system upgrades, I've found using the combo updates to be more reliable than Software Update, as sometimes Software Update doesn't apply updates correctly, and weird things can happen. Doesn't happen often though, thankfully.
    So the OS X 10.5.5 Combo update contains all updates between 10.5.0 and 10.5. The 10.5.8 combo update contains the updates from 10.5 thru 10.8. Here are the updates:
    10.5 combo update: http://support.apple.com/kb/DL692
    10.8 combo update: http://support.apple.com/kb/DL866
    If you go down the combo path, repair permissions before and after doing each update. Then do Software Update for any other non-OS X updates, and don't apply the Java Update 8.

  • Chess: java swing help need

    Hi, I have just learn java swing and now creating a chess game. I have sucessfully create a board and able to display chess pieces on the board. By using JLayeredPane, I am able to use drag and drop for the piece. However, there is a problem which is that I can drop the chess piece off the board and the piece would disappear. I have try to solve this problem by trying to find the location that the chess piece is on, store it somewhere and check if the chess piece have been drop off bound. However, I could not manage to solve it. Also, I am very confuse with all these layer thing.
    Any suggestion would be very helpful. Thanks in advance
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class ChessBoard extends JFrame implements MouseListener, MouseMotionListener
    Object currentPosition;
    Color currentColor;
    Dimension boardSize = new Dimension(600, 600);
    JLayeredPane layeredPane;
    JPanel board;
    JPanel box;
    JLabel chessPiece;
    int xAdjustment;
    int yAdjustment;
    public ChessBoard()
    // Use a Layered Pane for this this application
    layeredPane = new JLayeredPane();
    getContentPane().add(layeredPane);
    layeredPane.setPreferredSize( boardSize );
         layeredPane.addMouseListener( this );
    layeredPane.addMouseMotionListener( this );
    // Add a chess board to the Layered Pane
    board = new JPanel();
         // set "board" to the lowest layer (default_layer)
    layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);
    board.setLayout( new GridLayout(8, 8) );
    board.setPreferredSize( boardSize );
    board.setBounds(0, 0, boardSize.width, boardSize.height);
         addShade();
         addPiece();
    public void addShade()
         for (int i = 0; i < 64; i++)
    box = new JPanel( new BorderLayout() );
    board.add( box, BorderLayout.CENTER );
         if( ((i / 8) % 2) == 0)
                   if( (i % 2) ==0)
                        box.setBackground(Color.lightGray);
                   } else {
                        box.setBackground( Color.white);
              } else {
                   if( (i % 2) ==0)
                        box.setBackground(Color.white);
                   } else {
                        box.setBackground(Color.lightGray);
    //Method for adding chess pieces to the board
    public void addPiece()
    // Add a few pieces to the board
         //black pieces
         for (int i = 0; i < 64; i++)
              //adding black pieces
              if (i < 8)
                   String fileName = i + ".gif";
                   JLabel blackPieces = new JLabel( new ImageIcon( fileName ) );
                   JPanel panel = (JPanel)board.getComponent( i );
                   panel.add( blackPieces );
              //adding black pones
              if ((i > 7) && (i < 16))
                   String fileName = "8.gif";
                   JLabel blackPones = new JLabel( new ImageIcon( fileName ) );
                   JPanel panel = (JPanel)board.getComponent( i );
                   panel.add( blackPones );
              //jump to white position (Component 48)
              if (i == 16) i = 48;
              //adding white pones
              if(( i > 47 ) && (i < 56))
                   JLabel whitePones = new JLabel( new ImageIcon("48.gif") );
                   JPanel panel = (JPanel)board.getComponent( i );
                   panel.add( whitePones );
              //adding white pieces
              if (i > 55)
                   String fileName = i + ".gif";
                   JLabel whitePieces = new JLabel( new ImageIcon( fileName ) );
                   JPanel panel = (JPanel)board.getComponent( i);
                   panel.add( whitePieces );
    ** Add the selected chess piece to the dragging layer so it can be moved
    public void mousePressed(MouseEvent e)
    chessPiece = null;
    Component c = board.findComponentAt(e.getX(), e.getY());
         c.setBackground(Color.red);
    if (c instanceof JPanel) return;
    Point parentLocation = c.getParent().getLocation();
    xAdjustment = parentLocation.x - e.getX();
    yAdjustment = parentLocation.y - e.getY();
    chessPiece = (JLabel)c;
    chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);
    chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight());
    layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);
    ** Move the chess piece around
    public void mouseDragged(MouseEvent me)
    if (chessPiece == null) return;
    chessPiece.setLocation(me.getX() + xAdjustment, me.getY() + yAdjustment);
    ** Drop the chess piece back onto the chess board
    public void mouseReleased(MouseEvent e)
         Component c = board.findComponentAt(e.getX(), e.getY());
         int x = (int)c.getBounds().getX();
         int y = (int)c.getBounds().getY();
         System.out.println(c.getLocation());
         System.out.println(x + " "+ y);
         c.setBackground(currentColor);
    if (chessPiece == null) return;
    chessPiece.setVisible(false);
    if (c instanceof JLabel)
    Container parent = c.getParent();
         //remove the piece that is capture
    parent.remove(0);
    parent.add( chessPiece );
    else
    Container parent = (Container)c;
    parent.add( chessPiece );
    chessPiece.setVisible(true);
    public void mouseClicked(MouseEvent e) {}
    public void mouseMoved(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    private static void createAndShowGUI()
         //Make sure we have nice window decorations
         JFrame.setDefaultLookAndFeelDecorated(true);
         JFrame frame = new ChessBoard();
         frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
         //Display the window
         frame.pack();
         frame.setResizable( false );
         frame.setLocationRelativeTo( null );
         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();
    }

    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class ChessBoardRx extends JFrame implements MouseListener, MouseMotionListener
        Object currentPosition;
        Color currentColor;
        Dimension boardSize = new Dimension(600, 600);
        JLayeredPane layeredPane;
        JPanel board;
        JPanel box;
        JLabel chessPiece;
        int xAdjustment;
        int yAdjustment;
        Container lastParent;
        public ChessBoardRx()
            // Use a Layered Pane for this this application
            layeredPane = new JLayeredPane();
            getContentPane().add(layeredPane);
            layeredPane.setPreferredSize( boardSize );
            layeredPane.addMouseListener( this );
            layeredPane.addMouseMotionListener( this );
            // Add a chess board to the Layered Pane
            board = new JPanel();
            // set "board" to the lowest layer (default_layer)
            layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);
            board.setLayout( new GridLayout(8, 8) );
            board.setPreferredSize( boardSize );
            board.setBounds(0, 0, boardSize.width, boardSize.height);
            addShade();
            addPiece();
    //        populateBoard();
        public void addShade()
            for (int i = 0; i < 64; i++)
                box = new JPanel( new BorderLayout() );
                board.add( box, BorderLayout.CENTER );
                if( ((i / 8) % 2) == 0)
                    if( (i % 2) ==0)
                        box.setBackground(Color.lightGray);
                    } else {
                        box.setBackground( Color.white);
                } else {
                    if( (i % 2) ==0)
                        box.setBackground(Color.white);
                    } else {
                        box.setBackground(Color.lightGray);
        //Method for adding chess pieces to the board
        public void addPiece()
            // Add a few pieces to the board
            //black pieces
            for (int i = 0; i < 64; i++)
                //adding black pieces
                if (i < 8)
                    String fileName = i + ".gif";
                    JLabel blackPieces = new JLabel( new ImageIcon( fileName ) );
                    JPanel panel = (JPanel)board.getComponent( i );
                    panel.add( blackPieces );
                //adding black pones
                if ((i > 7) && (i < 16))
                    String fileName = "8.gif";
                    JLabel blackPones = new JLabel( new ImageIcon( fileName ) );
                    JPanel panel = (JPanel)board.getComponent( i );
                    panel.add( blackPones );
                //jump to white position (Component 48)
                if (i == 16) i = 48;
                //adding white pones
                if(( i > 47 ) && (i < 56))
                    JLabel whitePones = new JLabel( new ImageIcon("48.gif") );
                    JPanel panel = (JPanel)board.getComponent( i );
                    panel.add( whitePones );
                //adding white pieces
                if (i > 55)
                    String fileName = i + ".gif";
                    JLabel whitePieces = new JLabel( new ImageIcon( fileName ) );
                    JPanel panel = (JPanel)board.getComponent( i);
                    panel.add( whitePieces );
        private void populateBoard() {
            int[][] pos = {
                { 9, 7, 5, 1, 3, 5, 7, 9 },
                { 8, 6, 4, 0, 2, 4, 6, 8 }
            for(int j = 0; j < 8; j++) {
                String fileName = "chessImages/" + pos[0][j] + ".jpg";
                JLabel label = new JLabel( new ImageIcon( fileName ) );
                JPanel panel = (JPanel)board.getComponent( j );
                panel.add( label );
            for(int j = 8; j < 16; j++) {
                String fileName = "chessImages/" + 11 + ".jpg";
                JLabel label = new JLabel( new ImageIcon( fileName ) );
                JPanel panel = (JPanel)board.getComponent( j );
                panel.add( label );
            for(int j = 56, k = 0; j < 64; j++, k++) {
                String fileName = "chessImages/" + pos[1][k] + ".jpg";
                JLabel label = new JLabel( new ImageIcon( fileName ) );
                JPanel panel = (JPanel)board.getComponent( j );
                panel.add( label );
            for(int j = 48; j < 56; j++) {
                String fileName = "chessImages/" + 10 + ".jpg";
                JLabel label = new JLabel( new ImageIcon( fileName ) );
                JPanel panel = (JPanel)board.getComponent( j );
                panel.add( label );
         ** Add the selected chess piece to the dragging layer so it can be moved
        public void mousePressed(MouseEvent e)
            chessPiece = null;
            Component c = board.findComponentAt(e.getX(), e.getY());
            c.setBackground(Color.red);
            if (c instanceof JPanel) return;
            lastParent = c.getParent();
            Point parentLocation = c.getParent().getLocation();
            xAdjustment = parentLocation.x - e.getX();
            yAdjustment = parentLocation.y - e.getY();
            chessPiece = (JLabel)c;
            chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);
            chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight());
            layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);
         ** Move the chess piece around
        public void mouseDragged(MouseEvent me)
            if (chessPiece == null) return;
            chessPiece.setLocation(me.getX() + xAdjustment, me.getY() + yAdjustment);
         ** Drop the chess piece back onto the chess board
        public void mouseReleased(MouseEvent e)
            Component c = board.findComponentAt(e.getX(), e.getY());
            if(c == null) {
                layeredPane.remove(chessPiece);
                lastParent.add(chessPiece);
                Rectangle r = lastParent.getBounds();
                chessPiece.setLocation(r.x+xAdjustment, r.y+yAdjustment);
                lastParent.validate();
                lastParent.repaint();
                return;
            int x = (int)c.getBounds().getX();
            int y = (int)c.getBounds().getY();
            System.out.println(c.getLocation());
            System.out.println(x + " "+ y);
            c.setBackground(currentColor);
            if (chessPiece == null) return;
            chessPiece.setVisible(false);
            if (c instanceof JLabel)
                Container parent = c.getParent();
                //remove the piece that is capture
                parent.remove(0);
                parent.add( chessPiece );
            else
                Container parent = (Container)c;
                parent.add( chessPiece );
            chessPiece.setVisible(true);
        public void mouseClicked(MouseEvent e) {}
        public void mouseMoved(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {}
        private static void createAndShowGUI()
            //Make sure we have nice window decorations
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new ChessBoardRx();
            frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
            //Display the window
            frame.pack();
            frame.setResizable( false );
            frame.setLocationRelativeTo( null );
            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();
    }

  • Java Swing Help

    Hi, I am currently using a program called JPadPro for my java source codes. I am just beginning to learn java and I have just started on Java Swing GUI codings. My problem is that the program compiles, but it doesn't run. It always give me an error saying
    "Cannot find main method, Program will exit". there is nothing wrong with my source code because I can run somewhere else. I think I didn't configure my Jpadpro correctly. (but anything without GUI does work)
    Thank You for your help :)

    Even though you are running a swing application, you still need a main method just as in non-GUI applications. The main should create an instance of the JFrame at the base of you swing app. A simple example is as follows:
    public class mySwingApp extends JFrame {
    public mySwingApp(String title) {
    super(title);
    // GUI components, layouts, possible listeners here
    public static void main(String[] args) {
    JFrame mainFrame = new mySwingApp("My first swing app");
    mainFrame.setSize(200, 200);
    mainFrame.setVisible(true);
    }Hope this helps some!
    -JBoeing

  • Chess: Java Swing problem!! Help need

    Hi, I have just learn java swing and now creating a chess game. I have sucessfully create a board and able to display chess pieces on the board. By using JLayeredPane, I am able to use drag and drop for the piece. However, there is a problem which is that I can drop the chess piece off the board and the piece would disappear. I have try to solve this problem by trying to find the location that the chess piece is on, store it somewhere and check if the chess piece have been drop off bound. However, I could not manage to solve it. Also, I am very confuse with all these layer thing.
    Any suggestion would be very helpful. Thanks in advance

    I wonder if you are biting off a little more than you can chew. This seems like a big project for a beginning coder. Anyway, my suggestions can only be general since we only have general information:
    1) Break the big problem down into little pieces. Get the pieces working, then put them together.
    2) Make sure your program logic is separate from your GUI.
    3) If still having problems, post an SSCCE. See this link to tell you how:
    http://homepage1.nifty.com/algafield/sscce.html
    4) And as camikr would say (and flounder just said): next time, post this in the Swing forum.
    Good luck!

  • A tiny font is used in many places across Java Swing applications (help!)

    In many places in Java but mostly in text boxes I'm seeing a very small font that is quite hard to read.
    I am seeing this all over the place in Java programs and it is getting on my nerves.
    I'm not sure what is causing this.
    I also encountered this issue when running Java on Windows XP.
    I really need help on how to solve this,
    Or maybe it is actually a bug with Java itself and Windows?
    An image of the problem in SwingSet2:
    [SwingSet 2 Tiny Font Example|http://img687.imageshack.us/img687/1373/swingset2tinyfont.png]
    System spec:
    Windows 7 Professional 32-bit (Aero is on)
    Java 6 Update 20
    English system locale and language
    No special dpi settings (default)
    Screen Resolution: 1280x1024
    Avast Antivirus 5.0
    An intel graphics card
    Edited by: Temp111 on May 9, 2010 7:38 AM

    camickr wrote:
    That is not a problem. Somewhere in that code the programmer uses setFont(....) to make it a smaller font. The default font of a text component does not behave like that.
    For more help create a [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://sscce.org/], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.No, it's defiantly a problem. Probably in the default fonts that Swing uses in some places.
    I detected one place where I can easily trigger this issue, a JTextArea And the Windows Look and Feel, So here is a SSCCE for you:
    [Picture Of Tiny Font SSCCE With Tiny Font issue|http://img88.imageshack.us/img88/7876/tinyfont.png]
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    public class TinyFont {
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              } catch (ClassNotFoundException e) {
                   e.printStackTrace();
              } catch (InstantiationException e) {
                   e.printStackTrace();
              } catch (IllegalAccessException e) {
                   e.printStackTrace();
              } catch (UnsupportedLookAndFeelException e) {
                   e.printStackTrace();
              JFrame frame = new JFrame("Tiny Font");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JTextArea textArea = new JTextArea("Tiny Font Test");
              frame.add(textArea);
              frame.setSize(150, 100);
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
    }But I also encountered this issue in other places that use Swing.
    Try SwingSet2 Source Code Tab for example: [SwingSet2|http://java.sun.com/products/jfc/jws/SwingSet2.jnlp]

  • Help! how can I update JDK from 1.3 to 1.4 for Java Swing correctly?

    Urgent! currently I meet one trouble for GUI display, which is developed by Java Swing when I update my JDK1.3 to 1.4. I use JRun as web server and all of the GUI Java Swing code developed based on JDK 1.3 and before I update, all of the GUI display is correct and there are no problem, but after I update to JDK 1.4, I always meet this kind of problem "java.lang NoClassDefFoundError" which is displaye on Java Console and "Exception:java.lang.NullPintException" is displayed on GUI. Sometimes, I need to try two times to display GUI(Jave Swing), then it can work. Could you give me a fever and show me how to fix this problems? which kind of change in JDK Java Swing package?
    Thank you much.
    Steven

    I have recompiled app. by JDK1.4 and I also changed classpath but I can not fix the problem. The strange thing is that I can view the The same GUI(Java Swing) which is installed in another computer using the same JRUN too, but in local computer I can not view the GUI. Do you have some other suggestions? Why Can I view the same GUI instaaled in another computer?
    Very Thanks
    Steven

Maybe you are looking for

  • Will Apple tv ONLY work with an HDMI connection on the tv?

    My television has one HDMI port and it is connected to my Bose setup.  If I get an Apple TV, will that also have to be connected to the same HDMI port? Or, can it work connected to the "old fashioned" video and audio ports?

  • Screen went black, now it's making noise.

    My iMac screen went black during use.  When I re-started, it began making a roaring noise.  Any ideas what the problem might be?

  • What is best way dealing with large tiff file in OSX Lion?

    I'm working with large tiff  file (engineering drawing), but preview couldnt handle (unresponsive) this situation. What is best way dealing with large tiff file in OSX Lion? (Viewing only or simple editing) Thx, 54n9471

  • Session management in JAX-RCP with JWSDP 1.0_01

    Hi all, How can I access to the HTTP Session of the TOMCAT which run the Web Services engine? Browsing by the API I've found the method getHttpSession() in the interface javax.xmlrpc.server.ServletEndpointContext. How can get an instance which implem

  • How do you convert a date entry to a numeric value?

    In Excel, I used to use the MAX() function on a range of dates to get the latest date from the range.  This does not work in Numbers. Here is the function I used in Excel: =IF(OR(TODAY()-MAX(J4:J56)>179,'Sheet 1 - Table 1'!I2-MAX(I4:I56)>4999),"NEED