Solved

JOptionPane question

Posted on 2004-08-05
44
1,486 Views
Last Modified: 2013-12-03
import javax.swing.*;
import java.awt.*;


Is there any way that I can change the Font and the Text color in  a JOptionPane instance?

I tried the following simple example. Does not work. Can anyone throw some light?

public class TestJOpFont
{
 public static void main (String [] args)
 {
  JOptionPane jp = new JOptionPane();
     jp.setFont(new Font("SanSerif", Font.PLAIN, 10));
     jp.setForeground(Color.red);
     jp.setBackground(Color.blue);
   
     jp.showMessageDialog(null, "Hello From Venus",
                                  "A Message From Venus",
                                  JOptionPane.PLAIN_MESSAGE);
  }
}
0
Comment
Question by:prain
  • 16
  • 12
  • 4
  • +6
44 Comments
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11730100
listening
0
 

Author Comment

by:prain
ID: 11730138
Can you be specific on your answer?.
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11730169
yep, I tried to test that code but failed to set the fonts and colors. I just wanted to participate in the question, so that i will get an idea from some other experts. Even me too is in learning process

Best Regards
Sudhakar
0
 

Expert Comment

by:pawbroon
ID: 11730181
i read you may have to change the UIManager default properties and make changes accordingly to suit your needs e.g something like UIManager.put ("OptionPane.errorDialog.border.foreground", yourColor)

but there might be a better solution

0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11730193
>>UIManager.put ("OptionPane.errorDialog.border.foreground", yourColor)

This will not work. I have already tested that
0
 
LVL 2

Expert Comment

by:billyea
ID: 11731086
JOptionPane is relatively limited to an icon, title, and text and a few others.
You may need to set a theme, default is Java Look and Feel, if you want a 'Venus' look and feel then I'm outta heck on how to do it.

If someone does advance on my comment, plz give me credit.

Hope this helps.
0
 
LVL 92

Expert Comment

by:objects
ID: 11731519
try:

UIManager.put ("OptionPane.font", yourFont);
UIManager.put ("OptionPane.foreground", yourColor);
 
0
 
LVL 2

Expert Comment

by:billyea
ID: 11732397
Sorry objects, it didn't work, i tried it.
You can use UI Manager for a different purpose, to specify the theme. A theme with a red foreground and blue background. hehe. thats EXCACTLY what you want.

Implement this, SETS THE JAVA LOOK AND FEEL:

public static void main(String[] args) {
    try {
        UIManager.setLookAndFeel(
            UIManager.getCrossPlatformLookAndFeelClassName());
    } catch (Exception e) { }

    new SwingApplication(); //Create and show the GUI.
}

specifiy your own look and feel, they are usually packaged in one or more JAR files.
YOu can execute your own look and field by replacing stuff inside setLookAndFeel()

Example (runs the GTK+ look and feel):

UIManager.setLookAndFeel(
          "com.sun.java.swing.plaf.gtk.GTKLookAndFeel");

Just specify the class name inside the quotes.

You can also set the look and feel inside the command line in runtime:

java -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel MyApp

java -Dswing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel MyApp

Hope I helped!
-Billy
Note: Credits go to Sun for providing this documentation and API specs.


0
 
LVL 92

Expert Comment

by:objects
ID: 11732439
> Sorry objects, it didn't work, i tried it.

Can you post the code you tried it with?

>  A theme with a red foreground and blue background.

And themes are only available in metal, and will be used for all components not just JOptionPane

> thats EXCACTLY what you want

the font also needs to be changed.
0
 
LVL 92

Accepted Solution

by:
objects earned 30 total points
ID: 11732481
the UI resources you actually need to set are:

UIManager.put ("OptionPane.messageFont", yourFont);
UIManager.put ("OptionPane.messageForeground", yourColor);
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 11733167
sudhakar_koundinya, you can       Subscribe       if you want to follow a discussion,
or post a message like           "I am also interested".

No wonder someone gets confused from only the word "listening".
;JOOP!
0
 
LVL 2

Expert Comment

by:billyea
ID: 11733342
>> And themes are only available in metal
Actually those themes are NOT availiable in Metal, they must be handcrafted into Jars and then implemented in runtime.

>> and will be used for all components not just JOptionPane
Yes, a theme APPLIES itself to all components universally.

>>the font also needs to be changed
Font comes in a theme, if you have a theme that theme has a font! Get it?

For more info on themes and some you can download to help your Application:
http://www.codeproject.com/java/theme.asp

Good luck prain!
0
 
LVL 92

Expert Comment

by:objects
ID: 11733374
> Actually those themes are NOT availiable in Metal

Thats not what I meant, I meant that themes can only be used if you are using the Metal L&F.
And as they also apply to all components then they are not really suitable for changing look of a specific component.

0
 
LVL 2

Expert Comment

by:billyea
ID: 11733428
A systemwide change is what is required, as far as I know, there is not one surefire way to configure a specific component completely. if you want high configuration, make your own window and button and don't use JOptionPane.

0
 
LVL 1

Expert Comment

by:wolfc
ID: 11735041
In addition to the resources already mentioned by objects:
      UIManager.put ("OptionPane.buttonFont", font);
      UIManager.put ("OptionPane.background", Color.blue);

But why not build your own JDialog?
0
 

Author Comment

by:prain
ID: 11736052
Hello all.

Thanks for all the inputs.

I tried the suggestions made by objects and wolfc. Not all of them working though. Specially the font.
The color of the message body changes. The background color also can be changed - of course not
the whole message area. The message area is still gray but around it you can see the color you set.
Looks like they have a panel or something to put the message body. The internal panel (i think)
is still the default color gray.

Setting fonts does not work at all.

Also once you set these attributes, they are permement through out the life time of your WHOLE system.
Is there any any I can get them back to the original attributes and change when ever I need?

I trued this by using the getUI() of JOptionPane method and playing with it. It did not work.

Thanks anyways for all of your efforts.

prain.
0
 
LVL 1

Expert Comment

by:wolfc
ID: 11737018
Hehe, back to square one.

Look at the source code of JOptionPane, it gives neat insights. Especially if you want to build your own JDialog.
0
 
LVL 2

Expert Comment

by:billyea
ID: 11738523
Did mine work?
If it did then you've succeded. This question was getting rather stale.
If you've found the answer then please put it down here.
0
 
LVL 2

Expert Comment

by:billyea
ID: 11738543
And as wolf and I mentioned, ti's better off creating your own window (aka JDialog) for the highest level of configuration.
Otherewise you're stuck with the stipd JoptionPane options. VERY TACKY!
0
 
LVL 92

Expert Comment

by:objects
ID: 11740332
> Setting fonts does not work at all.

The font changes here when I tried it, can you post your code.
0
 
LVL 2

Assisted Solution

by:billyea
billyea earned 20 total points
ID: 11740483
Wut version of Java do you run, the new J2SE?
0
 
LVL 3

Expert Comment

by:JohnnyAffa
ID: 11752333
i dont think you can actually set a font such as "Tahoma" in text components by using  [component].setFont(new Font("Tahoma",Font.PLAIN,16)), even though the font is installed on a system. you can however, draw a String on any component based on the font attributes you set.

public void paint(Graphics g)
{
   Graphics c = [component].getGraphics();

   c.setFont(new Font("Tahoma",Font.PLAIN,16));
   c.setFont(font);
   c.drawString([string][x],[y]);
}

to get your systems available fonts use

java.awt.GraphicsEnvironment;

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String string_fontFamily[] = ge.getAvailableFontFamilyNames();
Font font_fontFamily[] = ge.getAllFonts();

the first method is recommended because the size of the font  object as opposed to the font name which you could use to get a font from a list.

0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 30

Expert Comment

by:mayankeagle
ID: 11753136
>> [component].setFont(new Font("Tahoma",Font.PLAIN,16)), even though the font is installed on a system

I guess the font should be in jre/lib/fonts?
0
 
LVL 2

Expert Comment

by:billyea
ID: 11756258
that would be quite inefficient for development, as the fonts would have to be move to that folder in order to run.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11759801
True.
0
 
LVL 92

Expert Comment

by:objects
ID: 11759822
did i mess something, when did using tahoma font become a requirement?
0
 
LVL 3

Expert Comment

by:JohnnyAffa
ID: 11761479
> objects since the question asked............
"Is there any way that I can change the Font and the Text color in  a JOptionPane instance?"...........yes 8-)

my "tahoma" comment was an example of font assingment

> billyea, not really, you could set classpath to "....../jre/lib/fonts"

> mayankeagle, doesnt make a difference. try copying windows fonts to the /jre/lib/fonts and watch what "doesnt" happen :(

the file jre/lib/font.properties i think must be edited to include additional "displayable" fonts. simply copying the installed fonts to the /jre/lib/fonts folders doesnt seem to do the trick. if you read the file, youll see that only standard fonts are made available ie

contents of font.properties
.......
dialog.0=Arial,ANSI_CHARSET
dialog.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
dialog.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

dialog.bold.0=Arial Bold,ANSI_CHARSET
dialog.bold.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
dialog.bold.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

dialog.italic.0=Arial Italic,ANSI_CHARSET
dialog.italic.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
dialog.italic.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

dialog.bolditalic.0=Arial Bold Italic,ANSI_CHARSET
dialog.bolditalic.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
dialog.bolditalic.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

dialoginput.0=Courier New,ANSI_CHARSET
dialoginput.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
dialoginput.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

dialoginput.bold.0=Courier New Bold,ANSI_CHARSET
dialoginput.bold.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
dialoginput.bold.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

dialoginput.italic.0=Courier New Italic,ANSI_CHARSET
dialoginput.italic.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
dialoginput.italic.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

dialoginput.bolditalic.0=Courier New Bold Italic,ANSI_CHARSET
dialoginput.bolditalic.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
dialoginput.bolditalic.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

serif.0=Times New Roman,ANSI_CHARSET
serif.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
serif.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

serif.bold.0=Times New Roman Bold,ANSI_CHARSET
serif.bold.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
serif.bold.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

serif.italic.0=Times New Roman Italic,ANSI_CHARSET
serif.italic.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
serif.italic.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

serif.bolditalic.0=Times New Roman Bold Italic,ANSI_CHARSET
serif.bolditalic.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
serif.bolditalic.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

sansserif.0=Arial,ANSI_CHARSET
sansserif.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
sansserif.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

sansserif.bold.0=Arial Bold,ANSI_CHARSET
sansserif.bold.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
sansserif.bold.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

sansserif.italic.0=Arial Italic,ANSI_CHARSET
sansserif.italic.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
sansserif.italic.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

sansserif.bolditalic.0=Arial Bold Italic,ANSI_CHARSET
sansserif.bolditalic.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
sansserif.bolditalic.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

monospaced.0=Courier New,ANSI_CHARSET
monospaced.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
monospaced.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

monospaced.bold.0=Courier New Bold,ANSI_CHARSET
monospaced.bold.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
monospaced.bold.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

monospaced.italic.0=Courier New Italic,ANSI_CHARSET
monospaced.italic.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
monospaced.italic.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED

monospaced.bolditalic.0=Courier New Bold Italic,ANSI_CHARSET
monospaced.bolditalic.1=WingDings,SYMBOL_CHARSET,NEED_CONVERTED
monospaced.bolditalic.2=Symbol,SYMBOL_CHARSET,NEED_CONVERTED
..................

so basically, you can only use the font list in the font.properties file unless you edit the file manually i guess.
0
 
LVL 2

Expert Comment

by:billyea
ID: 11768451
that's alot of code (not to be in-technical or anything) :)
But this puts us back to square two. We still dont have any 'working' model.

And I still reccoment making your own dialog with JDialog instead of using JOptionPane. Using JDialog, you can then use JFrameBuilder (a shareware program with so little restrictions that you can call it freeware) to customize it and then implement it.
This way is ALOT easier than actual coding, it's alot more versatile for beginners (not that you're a beginner, it's good universally too!).
0
 
LVL 92

Expert Comment

by:objects
ID: 11768470
> We still dont have any 'working' model.

Actually I posted code above for setting message colour and font :)

0
 
LVL 2

Expert Comment

by:billyea
ID: 11768483
>>Actually I posted code above for setting message colour and font :)
Well it's not 'working' :)
0
 
LVL 2

Expert Comment

by:billyea
ID: 11768498
All who think that this lovable JOptionPane should be abandoned in place of a more highly configurable JDialog (which can be further configured using third party software). Say 'B'.
0
 
LVL 92

Expert Comment

by:objects
ID: 11768530
> Well it's not 'working' :)

why do you say that?
0
 
LVL 2

Expert Comment

by:billyea
ID: 11768541
I tested it.
0
 
LVL 92

Expert Comment

by:objects
ID: 11768566
then post your code and I'll see what you did wrong.
0
 
LVL 2

Expert Comment

by:billyea
ID: 11768639
Okay, here is the framework for the code, this class starts the frame.

public class JOptionPane {
   
    public static void main(String[] args) {
        // Create application frame.
        JOptionPaneFrame frame = new JOptionPaneFrame();
       
        // Show frame
        frame.setVisible(true);
    }
}

This class constructs the frame and menubar, also showing the JOptionPane:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * Sample application using Frame.
 *
 * @author
 * @version 1.00 04/08/10
 */
public class JOptionPaneFrame extends Frame {
   
    /**
     * The constructor.
     */  
     public JOptionPaneFrame() {
           
           JOptionPane.showMessageDialog (null, "Testing","Main", JOptionPane.PLAIN_MESSAGE);
           UIManager.put ("OptionPane.font", null);
            UIManager.put ("OptionPane.foreground", Color.BLUE);
               
        MenuBar menuBar = new MenuBar();
        Menu menuFile = new Menu();
        MenuItem menuFileExit = new MenuItem();
       
        menuFile.setLabel("File");
        menuFileExit.setLabel("Exit");
       
        // Add action listener.for the menu button
        menuFileExit.addActionListener
        (
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JOptionPaneFrame.this.windowClosed();
                }
            }
        );
        menuFile.add(menuFileExit);
        menuBar.add(menuFile);
       
        setTitle("JOptionPane");
        setMenuBar(menuBar);
        setSize(new Dimension(400, 400));
       
        // Add window listener.
        this.addWindowListener
        (
            new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    JOptionPaneFrame.this.windowClosed();
                }
            }
        );  
    }
   
   
    /**
     * Shutdown procedure when run as an application.
     */
    protected void windowClosed() {
          
          // TODO: Check if it is safe to close the application
          
        // Exit application.
        System.exit(0);
    }
}
0
 
LVL 92

Expert Comment

by:objects
ID: 11768659
you set the wrong properties, and in the wrong place.
0
 
LVL 2

Expert Comment

by:billyea
ID: 11768666
ok, the right code?
0
 
LVL 2

Expert Comment

by:billyea
ID: 11768680
and I don't just want what you quoted above, I want a REAL working application that i can execute and see the results.
0
 
LVL 92

Expert Comment

by:objects
ID: 11768707
> I want a REAL working application that i can execute and see the results

I thought we were helping prain?
0
 
LVL 2

Expert Comment

by:billyea
ID: 11768738
Ok, I want the code posted up here so that prain can view it.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11769892
>> public class JOptionPane

I'd prefer giving a class-name which is not that of an existing Java class (though the package would be different - but just to avoid confusion, unless we're using fully-qualified class-names in the code).

>> UIManager.put ("OptionPane.font", null);
>> UIManager.put ("OptionPane.foreground", Color.BLUE);

I guess objects said to set these properties:

>> UIManager.put ("OptionPane.messageFont", yourFont);
>> UIManager.put ("OptionPane.messageForeground", yourColor);

Moreover, shouldn't you be setting these properties before you display the message-dialog? If you set these properties after calling showMessageDialog (), I don't expect the already displayed JOptionPane to get refreshed with those colours/ fonts.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11769896
>>  I want the code posted up
>> prain can view it

:-)
0
 

Author Comment

by:prain
ID: 11771983
Ok guys.

First of all I must thank all of you for all the inputs.
Actually the exchanges of ideas for this question was great.

Objects put out the correct way of doing this. As I said in my previous comment, it was not working fully. That was because of the version of Java I was using. It was 1.3.1. Then I tested this on J2SE 1.4.2. It works great. So some credit is going to Mr. billyea who pointed out about the version. So I decided to split the points between Object and billyea.

Thanks all for your help. Its time to close this as my e-mail box is also gettring filled to much for this question.....

Thanks all.
Have a great day!.
0
 
LVL 92

Expert Comment

by:objects
ID: 11779367
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now