Problem in showMessageDialog method of JOptionPane

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwingComp extends JFrame implements ActionListener{
public SwingComp()
JPanel p = new JPanel();
JButton b = new JButton("OK");
          b.addActionListener(this);
p.add(b);
                add(p);  
                pack();
                setVisible(true);
public static void main(String args[])
          new SwingComp();
public void actionPerformed(ActionEvent e)
          JOptionPane.showMessageDialog( null, "Message", "Title", JOptionPane.ERROR_MESSAGE );
//JDialog d = new JDialog();
//JButton b1 = new JButton("some");
//d.add(b1);
//d.pack();
//d.setVisible(true);
}After running the above code is there any way in which I can add action listener to the ok button that is displayed by JOptionPane.showMessageDialog( null, "Message", "Title", JOptionPane.ERROR_MESSAGE ); dialog.

You'll need to customize the option pane in order to
achieve what you want. The following link
demonstrates customizing a JOptionPane dialog.
You'll need to adapt the code for your purposes but
it clearly demonstrates the technique.
http://forum.java.sun.com/thread.jspa?forumID=513&thre
adID=248471Thanks for the information. Is there any other way by which the problem can be solved, I mean without customising...

Similar Messages

  • Problem with WindowClosing() method

    Hello everyone,
    I have some problem with WindowClosing() method, in which I gave options
    to quit or not. Quit is working fine but in case of Cancel, its not returning to
    the frame. Can anyone help me ....Here is my code
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    public class TestFrame extends JPanel
         public static void main(String[] args)
              JFrame frame = new JFrame("Frame3");
              WindowListener l = new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        int button = JOptionPane.showConfirmDialog(null,"OK to Quit","",JOptionPane.YES_NO_OPTION, -1);
                        if(button == 0)     {
                             System.exit(0);
                                   else
                                              return;
              frame.addWindowListener(l);
              frame.setSize(1200,950);     
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
    }

    Maybe try
    int button = JOptionPane.showConfirmDialog(yourframe,"OK to
    Quit","",JOptionPane.YES_NO_OPTION, -1);

  • I have problem with pay method

    I have problem with pay method. My card declined. I change card and I have the same problem. What can i do? Why declined my card again?

    Contact iTunes store support: https://ssl.apple.com/emea/support/itunes/contact.html.

  • Problem with traverse method

    Hi, I am having this problem:
    I made a CustomItem, a TextField, now I overloaded the traverse method, so if the keycode is Canvas.UP or Canvas.DOWN then return false else return true.
    The problem is that when I press the left or rigth button it also returns false and not true.
    and there is another problem with traverse, before returning false or true I set a boolean and call to repaint to draw it on some way if its selected or not, the paint method is being called but it just dont draw as desired.
    protected void paint(Graphics g, int ancho, int alto) {
              System.out.println ("Dentro del paint, seleccionado="+seleccionado);
              try {
                   g.drawString(label, 0, 0, Graphics.TOP|Graphics.LEFT);
                   if (!seleccionado) {
                        g.setColor(120, 120, 120);
                   g.drawRect(0, 4, tama�oTexto+8, 25);
                   if (seleccionado) {
                        g.setColor(255, 255, 255);
                        g.fillRect(1, 5, (tama�oTexto+8-1), 23);
                   g.setColor(0, 0, 0);
                   if (!seleccionado) {
                        g.setColor(80, 80, 80);
                   g.drawString(texto, 4, 7, Graphics.TOP|Graphics.LEFT);
                   if (seleccionado) {
                        int cursorX=Font.getDefaultFont().charsWidth((texto.substring(0, idLetraActual)).toCharArray(), 0, texto.substring(0, idLetraActual).length())+4;
                        g.drawChar('|', cursorX, 7, Graphics.TOP|Graphics.LEFT);
              } catch (Exception E){
                   E.printStackTrace();
         }the traverse method set the seleccionado variable and calls to repaint but instead of being false the paint method is drawing it as true (most of times).

    I have a problem with findByxxx() method.. in
    Container managed bean.
    i have
    Collection collection =
    home.findByOwnerName("fieldValue");
    specified in my Client Program, where ownerName is the
    cmp fieldname..
    and
    public Collection findByOwnerName(String ownerName)
    throws RemoteException, FinderException
    defined in my home interface.
    i have not mentioned the findBy() method anywhere else
    (Bean class). You have to describe the query in the deployment descriptor.
    >
    Even if i have a same "fieldValue" in the database
    (Oracle), which i specified in findBy() method, iam a
    result of owner Not found, which is not the case as i
    have that owner name.
    for the same application if i use findByPrimaryKey(),
    it is working..
    Can any one please post me the solution.

  • Problem with Vector method addElement

    I am new to Java. I am using JDK 1.3. I am writing a program that will convert a text file to a binary file that stores a Vector object. I have narrowed my problem to the method that reads the text file and creates my vector. Each element in my vector stores an integer and a string variable. The reading of the text file works find and the creation of my record works find. It seems that the storing of the record in the vector is not working. When I print the first 10 elements of the vector, it have the same record(the last record of my text file). What is wrong with the method below? I am also appending the result of running my program.
    private static void readTextFile(File f) {
    try {
    FileReader fileIn = new FileReader(f);
    BufferedReader in = new BufferedReader(fileIn);
    String line;
    int i;
    SsnLocationRecord recordIn = new SsnLocationRecord();
    int ctr = 0;
    while (true) {
    line = in.readLine();
    if (line == null)
    break;
    ctr += 1;
    i = line.indexOf(" ");
    recordIn.putAreaNumber(Integer.parseInt(line.substring(0,i).trim()));
    recordIn.putLocation(line.substring(i+1).trim());
    records.addElement(recordIn);
    if (ctr < 11)
    System.out.println(recordIn);
    in.close();
    } catch (IOException e) {
    System.out.println ("Error reading file");
    System.exit(0);
    for (int i = 0; i < 11; i++)
    System.out.println((SsnLocationRecord) records.elementAt(i));
    RESULTS:
    C:\Training\Java>java ConvertTextFileToObjectFile data\ssn.dat
    0 null
    3 New Hampshire
    7 Maine
    9 Vermont
    34 Massachusetts
    39 Rhode Island
    49 Connecticut
    134 New York
    158 New Jersey
    211 Pennsylvania
    680 Nevada
    680 Nevada
    680 Nevada
    680 Nevada
    680 Nevada
    680 Nevada
    680 Nevada
    680 Nevada
    680 Nevada
    680 Nevada
    680 Nevada
    C:\Training\Java>

    First of all it would be better if you did a priming read and then checked line == null in the while statement instead of the way you have it.
    ctr++ will also accomplish what ctr +=1 is doing.
    you need to create a new instance of SsnLocationRecord for each line read. What you are doing is overlaying the objects data each time you execute the .putxxxx methods. The reference to the object is placed in the vector. The actual object is still being updated by the .putxxx methods (NOTE : THIS IS THE ANSWER TO YOUR MAIN QUESTION).
    you close should be in a finally statement.
    To process through all the elements of a Vector create an Enumeration and then use the nextElement() method instead of the elementAt is probably better. (Some will argue with me on this I am sure).
    Also, on a catch do not call System.exit(0). This will end your JVM normally. Instead throw an Exception (Runtime or Error level if you want an abnormal end).

  • Problem with prerender method

    Hi,
    I have a problem with the method prerender. A month ago, I started to develop a web project using Sun Studio Creator and a few page beans that i used extended the Abstract Page Bean, so I overrided the prerender and customized it.
    The problem is that, now i'm using eclipse and the configuration files of the project has changed and the prerender method never execute.
    I want to know why it is happening. Maybe the project is "bad-configurated"?
    Thanks

    The code of java bean doesn't change, the only thing that has changed is the configuration files (faces-config.xml, web.xml, etc).
    I put a breakpoint in the prerender method but the lifecycle doesn�t execute this method.
    After serveral changes, I wrote this code in the method prerender :
    int i=0;
    i = 1;
    And the prerender method doesn't execute.
    I'm a bit lost,
    thanks

  • Problem with affinetransformOp method...

    I have a serious problem with filter method
    I Want to make a image flipping or some other filtering by using
    AffineTransformOp
    but it printouts an erro like this
    cannot resolve symbol
    op.filter (img, flipped)
    (the error pointer shows ".after the op")
    a code from my one of the filters
    BufferedImage flipped = new BufferedImage(img.getHeight(), img.getWidth(),BufferedImage.TYPE_INT_RGB);
    AffineTransform trans = new AffineTransform(0, 1, 1, 0, 0, 0);
    AffineTransformOp op = new AffineTransformOp(trans, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    op.filter(img, flipped); //img is my buffered image source
    I used some other ways like (img, null) but always give out error.
    thanks..

    Did you declare "img" as BufferedImage or something else?
    What is the full error message?

  • Problems using GET method in JSP

    Hi,
    I had some problems using GET method in JSP.
    I'm using Apache web server 1.3 and Tomcat 3.3.1 in windows 2000.
    And I'm using language English and Korean.
    When I send messages using POST method, all is good
    But when I send message using GET method, English is good, but Korean is not good.
    I tried to encode using
    URLEncode.encode(str, "UTF-8")
    and decoding it using
    URLDecode.decode(request.getParameter(tag), "UTF-8")
    but it didn't work.
    How can I receive request including Korean using GET method in JSP?
    If anyone have solutions, please let me know.
    thanks.

    Hi,
    I had some problems using GET method in JSP.
    I'm using Apache web server 1.3 and Tomcat 3.3.1 in
    windows 2000.
    And I'm using language English and Korean.
    When I send messages using POST method, all is good
    But when I send message using GET method, English is
    good, but Korean is not good.
    I tried to encode using
    URLEncode.encode(str, "UTF-8")
    and decoding it using
    URLDecode.decode(request.getParameter(tag), "UTF-8")
    but it didn't work.
    How can I receive request including Korean using GET
    method in JSP?
    If anyone have solutions, please let me know.
    thanks.This problem appears, when one use UTF-16 encoding in JSP - am I right?
    If so there are two solutions:
    1) Temporary: Use "UTF-8" - or any other 8 bit encoding scheme and
    encode Korean symbols with "&1234;" kind of escapes - though it
    may not work
    2) Absolute: get my piece of code, which I have managed to write
    just a month ago resolving absolutely similar problem with UTF-16
    in code using Chinese/Russian/English encodings
    But I wouldn't say that it's costs 10 DDs :) - it's much more
    expensive... So try 1st variant if it wouldn't help - let me know.
    I'll figure :)
    Paul

  • Screen Resolution Problem in Session Method

    Hi
    I want to use session method in BDC. How to resolve screen resolution problem in Session Method?
    Please give me the code or steps regarding this.
    Thanks & Regards
    venkateswararao

    Hi
    U can only run the session with the option Dynpro Standard Size setted.
    In this way the system should be use the same resolution for every situation.
    Max

  • Problems w my method paymet

    Problems w my method payment

    Go to settings/itunes & app store tap on ID then view ID then tap payment information and see whether paypal is a payment option for you.  If it is not then you will need to check from one of the available payment options

  • I have problem verifying payment method by my pre-paid visa credit card

    I have a problem verifying payment method by my pre-paid visa credit card ???

    Apple does not accept pre paid cards >  iTunes Store: Accepted forms of payment
    Purchase an iTunes gift card that you can redeem and use to purchase iTunes and App Store content.
    http://www.apple.com/itunes/gifts/?cid=wwa-us-kwg-music-itu

  • I am trying to install free apps but I always get billing problem? Payment Method!!?

    I am trying to install free apps but I always get billing problem? Payment Method!!?

    Likely because you are trying to create a Mac App Store account with an existing Apple ID. The None option often is not available in that case. If you create a new Apple ID and iTunes/Mac App Store account following these instructions carefully, you will be successful in getting free apps without a payment method.
    Creating an iTunes Store, App Store, iBookstore, and Mac App Store account without a credit card -
    http://support.apple.com/kb/HT2534

  • JOptionPane showMessageDialog method

    I need to pop up an information dialog with an O.K button to close it.
    When I used JOptionPane showMessageDialog I realized that until I press the O.K button the exacution is halted.
    Can anyone tell me how to avoid this halt ? maybe by using other method/class.

    Try doing it in a seprate thread. Havent tried this my self, but I suppose it should work.
    Hope this helps
    Regards
    Omer

  • Problem with flush method

    Hello, I'm new in java development, and I'm french with a student English, sorry if that I say is strange is the expressions.
    I have a problem with network streams and serialization.
    I want to establish a connection between 2 apps, on 2 different computers. For the development, the tests are local (IP : 127.0.0.1)
    The problem : I send 4 bytes and I flush after, and I receive 6 bytes. To know what is transmitting on the connection, I override the OutputStream class.
    I think that the flush() method produces 2 bytes but i don't think how.
    I put you the codes follow :
    Thanks for any help.
    The sender function :
    // This function is called when the user want to send data to another user.
    // This piece of function establishing the connection between 2 users.
    public int startListeningForNFT(String senderUserName, int indexOfSender) {
          System.out.println(senderUserName + " demande à " + this.userName + " de démarrer la procédure de réception.");
          /* Cette fonction est l'interface ente le serveur et le client2,
           * elle retourne le port  et l'IP que le client2 le lui a renvoyé. */
          /* This function send an Integer which will trig a reception function in the receiver
             This function is called in a Thread. */
          try {
             this.oos.writeObject(44);
             this.oos.flush();
             System.out.println("On a bien envoyé OBJ2AskerInfos sur le port " + portToListen);
             byte b = this.ois.readByte();
             System.out.println("Byte = " + b);
             b = this.ois.readByte();
             System.out.println("Byte = " + b);
             b = this.ois.readByte();
             System.out.println("Byte = " + b);
             b = this.ois.readByte();
             System.out.println("Byte = " + b);
             b = this.ois.readByte();
             System.out.println("Byte = " + b);
          catch (IOException e) { e.printStackTrace(); }
          return Constantes.PORT_DATA;
       }The receiver function :
    public class ClientClient implements WindowClient {
       // This 3 attributes are initalized correctly.
       private Socket comSocket;
       private String comPort;
       private String userName;
       public ClientClient() {
          try {
          comSocket = new Socket(ipToJoin, Integer.parseInt(comPort));
          oos = new ObjectOutputStream(new DebugOutputStream(comSocket.getOutputStream()));
          ois = new ObjectInputStream(comSocket.getInputStream());
          oos.writeObject(userName);
          oos.flush();
          ThreadInputListener til = new ThreadInputListener();
          til.start();
          catch (UnknownHostException e) { e.printStackTrace(); }
          catch (ClassNotFoundException e) { e.printStackTrace(); }
          catch (IOException e) {
             e.printStackTrace();
             JOptionPane.showMessageDialog(null, ("Auncun serveur n'a été trouvé sur l'adresse indiquée :\n" + ipToJoin), "Erreur", JOptionPane.ERROR_MESSAGE);
       public class ThreadInputListener extends Thread {
          @SuppressWarnings("unchecked")
          public void run() {
             try {
                while(true) {
                   Object receivedObject = ois.readObject();
                   // Si l'objet reçu est un OBJ2InfosOnAsker => Renvoyer le port.
                   // If received Object is an integer
                   if(receivedObject instanceof Integer) {
                      System.out.println(userName +" a bien reçu l'objet OBJ2InfosOnAsker...");
                      System.out.println(userName +" a bien reçu int." + receivedObject);
                      System.out.println("On lance les 4 int :");
                      // Send 4 bytes to the sender (control bytes, just for solve the problem)
                      oos.writeByte(7);
                      oos.writeByte(8);
                      oos.writeByte(9);
                      oos.writeByte(10);
                      oos.flush();
                      System.out.println("...et a bien envoyé le port");
             catch (IOException e) {
                // ArrayList<HostClient> temp = new ArrayList<HostClient>();
                // temp.add(new HostFictiveClient(userName));
                // fenetreprincipale.updateClientList(temp);
                fenetreprincipale.addDiscution("Vous avez été déconnecté du serveur.");
             catch (ClassNotFoundException e) { e.printStackTrace(); }
       }The override function of OutputStream :
       public class DebugOutputStream extends OutputStream {
          private OutputStream os;
          public DebugOutputStream(OutputStream os) {
             super();
             this.os = os;
          @Override
          public void write(int b) throws IOException {
             System.out.println("ClientClient envoie " + b + " soit " + ((char)b));
             os.write(b);
    }The sender function says :
    Host demande à User1 de démarrer la procédure de réception.
    On a bien envoyé OBJ2AskerInfos sur le port 3001
    Byte = 4
    Byte = 0
    Byte = 7
    Byte = 8
    Byte = 9And the receiver function says :
    User1 a bien reçu l'objet OBJ2InfosOnAsker...
    User1 a bien reçu int.44
    On lance les 7 int :
    ClientCLient envoie 119 soit w       //
    ClientCLient envoie 4 soit          // Both of this lines are stranges
    ClientCLient envoie 7 soit
    ClientCLient envoie 8 soit
    ClientCLient envoie 9 soit      
    ClientCLient envoie 10 soit
    ...et a bien envoyé le port

    Minimus wrote:
    Ok, but this layer has maid just to print in the eclipse console the bytes written on the stream, With or without this function, the flush() operation generate 2 bytes, I don't know why.
    When I want to send manually the byte '7', the result of both lines :
       oos.writeByte(7);
    oos.flush();is that my writeByte and my flush send 3 bytes :
    Byte val = 119 charcode = w
    Byte val = 1 charcode =
    Byte val = 7 charcode =
    Only the 'Byte val = 7 charcode = ' line is good.
    Why the flush generate 2 unknown bytes at this code position ?Actually, it's (might be) writing more than two bytes. Run this:
    public class OOSTest {
       public static void main(String[] args) throws Throwable {
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          ObjectOutputStream oos = new ObjectOutputStream(baos);
          oos.writeByte(7);
          oos.close();
          byte[] bytes = baos.toByteArray();
          System.out.println(Arrays.toString(bytes));
          //prints "[-84, -19, 0, 5, 119, 1, 7]"
    }The explanation is in the Javadoc for ObjectOutputStream:
    Primitive data, excluding serializable fields and externalizable data, is written to the ObjectOutputStream in block-data records. A block data record is composed of a header and data. The block data header consists of a marker and the number of bytes to follow the header. OOSs should only be used when the OIS is being used properly on the other end. If you don't want this header, use a DataOutputStream. Is there an actual problem or are you just confused about the extra bytes? If there is a problem in reading, my guess is that you're somehow not reading from your OIS symmetrically with your OOS. Can you post a complete, compilable example that demonstrates the behaviour? There's obviously an issue somewhere, I just haven't spotted it yet.
    If there wasn't an actual problem in reading, well: there's your explanation.
    Edited by: endasil on 26-Oct-2009 10:55 AM

  • Color filling problem in fillarc() method of Graphics class

    I draw a circle in a panel. The circle space is divided to more than one sectors.The sectors are filled to particular color using fillarc(int x, int y, int start_angle, int end_angle) method of java.awt.Graphics class.
    When i fill the color, i faced a problem. That is i have seen the panel background Color in some pixels of thet arc spaces.
    How will i fill the particular color in full arc spaces? How will i solve this problem?
    Thanks for your advance reply.
    Regards
    Murali.R

    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class ArcFill extends JPanel {
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth();
            int h = getHeight();
            double radius = Math.min(w,h)*7/16.0;
            double x = (w - 2*radius)/2;
            double y = (h - 2*radius)/2;
            Ellipse2D.Double circle = new Ellipse2D.Double(x,y,2*radius,2*radius);
            // Fill east sector with Arc2D.
            Rectangle r = circle.getBounds();
            double start = -45.0;
            double extent = 90.0;
            int type = Arc2D.PIE;
            Arc2D.Double arc = new Arc2D.Double(r, start, extent, type);
            g2.setPaint(Color.red);
            g2.fill(arc);
            // Fill south sector.
            arc.setAngleStart(-135.0);
            g2.setPaint(Color.green.darker());
            g2.fill(arc);
            arc.setAngleStart(-225);
            g2.setPaint(Color.blue);
            g2.fill(arc);
            arc.setAngleStart(-315);
            g2.setPaint(Color.orange);
            g2.fill(arc);
            // Draw circle and lines.
            g2.setPaint(Color.black);
            g2.draw(circle);
            double theta = -Math.PI/4;
            double cx = circle.getCenterX();
            double cy = circle.getCenterY();
            for(int j = 0; j < 4; j++) {
                x = cx + radius*Math.cos(theta);
                y = cy + radius*Math.sin(theta);
                g2.draw(new Line2D.Double(cx, cy, x, y));
                theta += Math.PI/2;
        public static void main(String[] args) {
            ArcFill panel = new ArcFill();
            panel.setPreferredSize(new Dimension(400,400));
            JOptionPane.showMessageDialog(null, panel, "", -1);
    }

Maybe you are looking for

  • I got a new MacBook, and iChat will not open at all.

    About a month ago, I got a new MacBook (the regular one, not Air or Pro). Everything is working fine, except for iChat. It has never opened since purchasing my new computer and it continues not to. When you double click the iChat icon, "iChat" appear

  • Can I use creative cloud on both of my computers for the same subscription

    I am looking at upgrading to the creative cloud but I want to know if I can use the one subscription on both my laptop and my desktop 

  • How to change "next" "previous" in ADF table ?

    **hi ,** **I am using oracle jdev 10.1.3.4** **I want to put my own text instead of "next" "previous" in ADF table , also I have the same problem in shuttle box ,** **I want to change the default javascript validation (ex: shuttle box alerts)** **I d

  • CF7 - sending a form using "Enter" key

    As I wrote in the subject, i've goit a question. How can I send a form using the "Enter" key. When I push the Enter nothing happneds. Can someone help me?

  • Displaying UTF chinese characters

    Here's my code           final StringBuilder sb = new StringBuilder();           DropWindow dw = new DropWindow() {                public void runFile(File f, Object[] extras) {                     try {                          String str = IOUtils.