2 quick java questions

hi, im working on a large grpahics project with some people, and i had a couple of simple questions.
1) is it possible to detect the colour of a spefic pixel on an image?
Maybe some sort of method that returns the color or something? This woudl be for collision detection, since we're going to have a character walking around a building and this is pretty much the only thing i can think of for collision.
2) Is it possible to load a large image, and then make the screen only show a small portion of it? and then when you move, it kind of resets the focus on the larger image to your new location? This would be used to help the character move around the large map.
Thanks for all the help!

Youre going to want to get VERY acquainted with Image and BufferedImage, lol.
Note the getRGB method.
As for resizing, there are many ways to do this ranging from very simple
to a bit complicated.
int getRGB(int x, int y)
Returns an integer pixel in the default RGB color model (TYPE_INT_ARGB) and default sRGB colorspace.
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/image/BufferedImage.html
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Image.html

Similar Messages

  • Hi all .hope all is well ..A quick trim question

    Hi all
    Hope all is well ......
    I have a quick trim question I want to remove part of a string and I am finding it difficult to achieve what I need
    I set the this.setTitle(); with this
    String TitleName = "Epod Order For:    " + dlg.ShortFileName() +"    " + "Read Only";
        dlg.ShortFileName();
        this.setTitle(TitleName);
        setFieldsEditable(false);
    [/code]
    Now I what to use a jbutton to remove the read only part of the string. This is what I have so far
    [code]
      void EditjButton_actionPerformed(ActionEvent e) {
        String trim = this.getTitle();
          int stn;
          if ((stn = trim.lastIndexOf(' ')) != -2)
            trim = trim.substring(stn);
        this.setTitle(trim);
    [/code]
    Please can some one show me or tell me what I need to do. I am at a lose                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

    there's several solutions:
    // 1 :
    //you do it twice because there's a space between "read" and "only"
    int stn;
    if ((stn = trim.lastIndexOf(' ')) != -1){
        trim = trim.substring(0,stn);
    if ((stn = trim.lastIndexOf(' ')) != -1){
          trim = trim.substring(0,stn);
    //2 :
    //if the string to remove is always "Read Only":
    if ((stn = trim.toUpperCase().lastIndexOf("READ ONLY")) != -1){
       trim = trim.substring(0,stn);
    //3: use StringTokenizer:
    StringTokenizer st=new StringTokenizer(trim," ");
        String result="";
        int count=st.countTokens();
        for(int i=0;i<count-2;i++){
          result+=st.nextToken()+" ";
        trim=result.trim();//remove the last spaceyou may find other solutions too...
    perhaps solution 2 is better, because you can put it in a separate method and remove the string you want to...
    somthing like:
    public String removeEnd(String str, String toRemove){
      int n;
      String result=str;
      if ((n = str.toUpperCase().lastIndexOf(toRemove.toUpperCase())) != -1){
       result= str.substring(0,stn);
      return result;
    }i haven't tried this method , but it may work...

  • How to make Quick java Doc to works for j2ee APIs (CTRL+D)

    Hi
    Thank you for reading my post
    i find that jdeveloper can show a quick java doc for java API , but i do not know why it does not show any document for j2ee stuff.
    can some one tell me the solution ?
    Thanks

    Hi
    Thank you for reply ,
    where i can find source codes for java ee stuff ?
    I want all of APIs to have quick java doc as it is very usefull.
    thanks

  • Java Question... please help

    I am running  Snow Leopard  (mac os x version 10.6.8)
    For the past couple of years I've played gin in yahoo games.  
    Yesterday when I entered the gin lobby ...the font was so tiny
    I wasn't able to read it.   I checked Java on my computer and
    it is enabled, however I just realized when I go into the gin
    lobby... there is no java icon on the dock.   Since the font size
    is fine in all other applications, I am presuming this is a Java
    issue.  
    Help if you are able.. please and thanks

    Huh? Is this a Java question? Where's the Java? I just see a little JavaScript. Do you know how to use servlets and JSPs?
    Jesper

  • What kind of Java questions can I ask?

    Here's a change:
    I want to interview some good java people. I have lots of Java questions in mind which I could ask them, however fellow JavaGuru's
    I would like some potential questions from you which I could ask someone who claims he/she is a good java programmer??
    I am asking because I want to be as fair as possible to the applicant and not ask them questions which I think are tough etc...

    Touchy subject.
    The language is not as important, as understanding programming concepts.
    So fine, when the programmer's horizont involves some abstraction levels.
    If a programmer can write an UML class diagram for a linked list.
    If a programmer knows a design pattern Singleton.
    If a programmer can write his/her own single linked list class with sorted insertion.
    Language concepts:
    - Why:
    import java.util.*;
    Map map = new HashMap();
    - Answer:
    Hiding the choice of implementation (HashMap) by using the more general
    interface Map.
    Don't expect much on an interview though. The situation might not be
    adequate to distinghuish between the good and the bad apples.
    Talking code is a good starting point, code of your making unfortunately.
    A good programmer will hesitate to show really useful code.
    A bad programmer might have stolen his/her code.
    The problem you might have, that you are in search of an expert, not
    having the expertise in-house. In that case you might get a better
    picture, talking about which IDE would be opportune, whether he/she
    has experience with the source version system CVS, what would his/her
    ideas be about coming projects.
    That would establish a common line of communication.

  • Quick script question

    Hi all,
    Could anyone advise me if i can add anything within - header('Location: http://www.mysite.co.uk/thankyou.html'); in the script below so as the page
    re- directs back to the main index page after a few seconds ?
    Thankyou for any help.
    <?php
    $to = '[email protected]';
    $subject = 'Feedback form results';
    // prepare the message body
    $message = '' . $_POST['Name'] . "\n";
    $message .= '' . $_POST['E-mail'] . "\n";
    $message .= '' . $_POST['Phone'] . "\n";
    $message .= '' . $_POST['Message'];
    // send the email
    mail($to, $subject, $message, null, '');
    header('Location: http://www.mysite.co.uk/thankyou.html');
    ?>

    andy7719 wrote:
    Mr powers gave me that script so im rather confused at this point in time
    I don't think I "gave" you that script. I might have corrected a problem with it, but I certainly didn't write the original script.
    What you're using is far from perfect, but to suggest it would lay you open to MySQL injection attacks is ludicrous. For you to be prone to MySQL injection, you would need to be entering the data into a MySQL database, not sending it by email.
    There is a malicious attack known as email header injection, which is a serious problem with many PHP email processing scripts. However, to be prone to email header injection, you would need to use the fourth argument of mail() to insert form data into the email headers. Since your fourth argument is null, that danger doesn't exist.
    One thing that might be worth doing is checking that the email address doesn't contain a lot of illegal characters, because that's a common feature of header injection attacks. This is how I would tidy up your script:
    <?php
    $suspect = '/Content-Type:|Bcc:|Cc:/i';
    // send the message only if the E-mail field looks clean
    if (preg_match($suspect, $_POST['E-mail'])) {
      header('Location: http://www.example.com/sorry.html');
      exit;
    } else {
      $to = '[email protected]';
      $subject = 'Feedback form results';
      // prepare the message body
      $message = 'Name: ' . $_POST['Name'] . "\n";
      $message .= 'E-mail: ' . $_POST['E-mail'] . "\n";
      $message .= 'Phone: ' . $_POST['Phone'] . "\n";
      $message .= 'Message: ' . $_POST['Message'];
      // send the email
      mail($to, $subject, $message);
      header('Location: http://www.example.com/thankyou.html');
      exit;
    ?>
    Create a new page called sorry.html, with a message along the lines of "Sorry, there was an error sending your message". Don't put anything about illegal attacks. Just be neutral.
    By the way, when posting questions here, don't use meaningless subject lines, such as "Quick script question". If you're posting here, it's almost certain to be a question about a script. It doesn't matter whether it's quick. Use the subject line to tell people what it's about.

  • Interesting Java Questions. Need answers Pls

    Hi All,
    I have come accross few java question, could any one please provide best answers please?
    1. Why the wait() method is there in the Object class? Not in the Threads?
    2. Why JDBC has all interfaces & not classes?
    3. Which type of collection do u prefer to make the incoming objects in sort order?
    4. Why the hasCode() method should be implemented if we are overiding the equals(0 method?
    Please provide me best answers ASAP.
    Girish.K

    do u prefer tohttp://www.catb.org/~esr/faqs/smart-questions.html#writewell
    How To Ask Questions The Smart Way
    Eric Steven Raymond
    Rick Moen
    Write in clear, grammatical, correctly-spelled language
    We've found by experience that people who are careless and sloppy writers are usually also careless and sloppy at thinking and coding (often enough to bet on, anyway). Answering questions for careless and sloppy thinkers is not rewarding; we'd rather spend our time elsewhere.
    So expressing your question clearly and well is important. If you can't be bothered to do that, we can't be bothered to pay attention. Spend the extra effort to polish your language. It doesn't have to be stiff or formal - in fact, hacker culture values informal, slangy and humorous language used with precision. But it has to be precise; there has to be some indication that you're thinking and paying attention.
    Spell, punctuate, and capitalize correctly. Don't confuse "its" with "it's", "loose" with "lose", or "discrete" with "discreet". Don't TYPE IN ALL CAPS; this is read as shouting and considered rude. (All-smalls is only slightly less annoying, as it's difficult to read. Alan Cox can get away with it, but you can't.)
    More generally, if you write like a semi-literate b o o b you will very likely be ignored. So don't use instant-messaging shortcuts. Spelling "you" as "u" makes you look like a semi-literate b o o b to save two entire keystrokes.

  • Quick java udf question

    Hi sorry for this completely stupid question but the below piece of code I am trying to dissect and understand.
    I understand the first line I am creating a new global container but the second line I am not so sure what the (integer) would be for. Is this meant to be a variable or a return type? What could that possibly be for I mean a type in parenthesis after the equals sign.
    GlobalContainer gc = container.getContainer();
    Integer counter = (Integer) gc.getParameter("counter");
    Thank you for your help.

    GlobalContainer is a container object stores values and can be retrieved by UDF during runtime. This GlobalContainer stores values and can be accessed by any UDF in the same namespace. This is similar to class variable or static variable of java class.
    In your case, It has a parameter which is set as ("counter", Integer) . Basically it is a key value pair and very similar to Hashtable in java.
    Example
    setParameter(String  str , Object  Integer);
    >What could that possibly be for I mean a type in parenthesis after the equals sign.
    typecast to integer in paranthesis, because we store the value here as Integer object.
    Integer counter = (Integer) gc.getParameter("counter");
    expecting  return type is Integer.
    Also refer this [link |global container;for further refereence

  • Quick Java version question...

    I'm unable to use VNC while connected through a semi-restricted VPN tunnel into work (I have to visit a certain website at work and when I click a button an Aventail application springs into life and I get a VPN tunnel). My work doesn't support Macs, so I spoke to tech support for the VNC vendor and he assured me they support Macs. He said to make sure I'm running version 1.5 or 1.6 of JRE (Java Runtime Environment) and Safari. I don't know how to determine that - anybody out there able to help?

    Thanks for the reply - I'll give this a try when I get home later on. It does seem a bit odd that I was asked to inquire about JRE, but this Java Preferences application talks about JSE. I don't suppose they're the same thing?...

  • Urgent help with quick translation questions

    Hello,
    I am somewhat new to Java. I have a translation to hand in in a few hours (French to English). Argh! I have questions on how I worded some parts of the translation (and also if I understood it right). Could you, great developers, please take a look and see if what I wrote makes sense? I've put *** around the words I wasn't sure about. If it sounds strange or is just plain wrong, please let know. I also separated two terms with a slash, when I was in doubt of which one was the best.
    Many thanks in advance.
    1) Tips- Always ***derive*** the exceptions java.lang.Exception and java.lang.RuntimeException.
    Since these exceptions have an excessively broad meaning, ***the calling layers will not know how to
    distinguish the message sent from the other exceptions that may also be passed to them.***
    2) The use of the finally block does not require a catch block. Therefore, exceptions may be passed back to the
    calling layers, while effectively freeing resources ***attributed*** locally
    3) TIPS- Declare the order for SQL ***statements/elements*** in the constant declaration section (private static final).
    Although this recommendation slightly hinders reading, it can have a significant impact on performance. In fact, since
    the layers of access to data are ***low level access***, their optimization may be readily felt from the user’s
    perspective.
    4) Use “inlining.”
    Inlining is a technique used by the Java compiler. Whenever possible, during compilation, the compiler
    copies the body of a method in place of its call, rather than executing a ***memory jump to the method***.
    In the example below, the "inline" code will run twice as fast as the ***method call***
    5)tips - ***Reset the references to large objects such as arrays to null.***
    Null in Java represents a reference which has not been ***set/established.*** After using a variable with a
    large size, it must be ***reassigned a null value.*** This allows the garbage collector to quickly ***recycle the
    memory allocated*** for the variable
    6) TIPS Limit the indexed access to arrays.
    Access to an array element is costly in terms of performance because it is necessary to invoke a verification
    that ***the index was not exceeded.***
    7) tips- Avoid the use of the “Double-Checked Locking” mechanism.
    This code does not always work in a multi-threaded environment. The run-time behavior ***even depends on
    compilers.*** Thus, use the following ***singleton implementation:***
    8) Presumably, this implementation is less efficient than the previous one, since it seems to perform ***a prior
    initialization (as opposed to an initialization on demand)***. In fact, at runtime, the initialization block of a
    (static) class is called when the keyword MonSingleton appears, whether there is a call to getInstance() or
    not. However, since ***this is a singleton***, any occurrence of the keyword will be immediately followed by a
    call to getInstance(). ***Prior or on demand initializations*** are therefore equivalent.
    If, however, a more complex initialization must take place during the actual call to getInstance, ***a standard
    synchronization mechanism may be implemented, subsequently:***
    9) Use the min and max values defined in the java.lang package classes that encapsulate the
    primitive numeric types.
    To compare an attribute or variable of primitive type integer or real (byte, short, int, long, float or double) to
    ***an extreme value of this type***, use the predefined constants and not the values themselves.
    Vera

    1) Tips- Always ***derive*** the exceptions java.lang.Exception and java.lang.RuntimeException.***inherit from***
    ***the calling layers will not know how to
    distinguish the message sent from the other exceptions that may also be passed to them.***That's OK.
    while effectively freeing resources ***attributed*** locally***allocated*** locally.
    3) TIPS- Declare the order for SQL ***statements/elements*** in the constant declaration section (private static final).***statements***, but go back to the author. There is no such thing as a 'constant declaration section' in Java.
    Although this recommendation slightly hinders reading, it can have a significant impact on performance. In fact, since
    the layers of access to data are ***low level access***, their optimization may be readily felt from the user’s
    perspective.Again refer to the author. This isn't true. It will make hardly any difference to the performance. It is more important from a style perspective.
    4) Use “inlining.”
    Inlining is a technique used by the Java compiler. Whenever possible, during compilation, the compiler
    copies the body of a method in place of its call, rather than executing a ***memory jump to the method***.
    In the example below, the "inline" code will run twice as fast as the ***method call***Refer to the author. This entire paragraph is completely untrue. There is no such thing as 'inlining' in Java, or rather there is no way to obey the instruction given to 'use it'. The compiler will or won't inline of its own accord, nothing you can do about it.
    5)tips - ***Reset the references to large objects such as arrays to null.***Correct, but refer to the author. This is generally considered bad practice, not good.
    Null in Java represents a reference which has not been ***set/established.******Initialized***
    After using a variable with a
    large size, it must be ***reassigned a null value.*** This allows the garbage collector to quickly ***recycle the
    memory allocated*** for the variableAgain refer author. Correct scoping of variables is a much better solution than this.
    ***the index was not exceeded.******the index was not out of range***
    The run-time behavior ***even depends on compilers.***Probably a correct translation but the statement is incorrect. Refer to the author. It does not depend on the compiler. It depends on the version of the JVM specification that is being adhered to by the implementation.
    Thus, use the following ***singleton implementation:***Correct.
    it seems to perform ***a prior initialization (as opposed to an initialization on demand)***.I would change 'prior' to 'automatic pre-'.
    ***this is a singleton***That's OK.
    ***Prior or on demand initializations***Change 'prior' to 'automatic'.
    ***a standard
    synchronization mechanism may be implemented, subsequently:***I think this is nonsense. I would need to see the entire paragraph.
    ***an extreme value of this type******this type's minimum or maximum values***
    I would say your author is more in need of a technical reviewer than a translator at this stage. There are far too serious technical errors in this short sample for comfort. The text isn't publishable as is.

  • Hardcore Java Questions Thread

    Greetings,
    I am otherwise known as Robert Simmons jr. O'Reilly has recently published my first book entitled hardcore java. Since the motivation for some of the content came from questions asked on this forum, I decided to make a question an answer thread on this forum to deal with your questions on the book, its content and topics.
    You can find the book at O'Reilly:
    http://www.oreilly.com/catalog/hardcorejv/
    Or Amazon.com
    http://www.amazon.com/exec/obidos/tg/detail/-/0596005687/qid=1080130526/sr=8-1/ref=sr_8_xs_ap_i1_xgl14/103-4213374-6043826?v=glance&s=books&n=507846
    It is also on sale in quite a few other places but I just mentioed two of the most popular.
    Feel free to ask your questions and I will knock them down as quick as I can.
    -- Robert Simmons Jr.

    I read the sample chapter about using final and,
    whilst I agree with you about using final beinggood
    coding practise, there are a few points I wouldmake:
    Example 2-2. Simple constants using final:
    public static class CircleToolsBetter {
    /** A value for PI. **/
    public final static double PI = 3.141;I think you should limit the scope of that variableby
    making it private.Why? What would be your motivation in hiding this
    value? At any rate, the example you are mentioning
    wasnt designed to demonstrate guarding access to
    constants. I talk about that a bit later in the
    chapter. There may be reasons for havign this private,
    I concede that. Just in this example I cant think of
    one. At any rate derived classes will probably need PI
    so protected would be a better option if you want to
    seal it off for some reason. I just think that you should always try to limit the scope of a variable as much as possible. I know that wasn't the point of that particular example, but I think it's good practise "in general".
    At any rate derived classes will probably need PI so
    protected would be a better option if you want to seal
    it off for some reason.Ah, but what about classes (it's public in the example), they could reference that variable and then if it changes ...
    In the section "Public Primitives and
    Substitution" you don't mention anywhere thatyou
    can get around the problem of having to recompile
    dependant classes by using static initializion and
    also by interning Strings. I think that would makea
    good addition to that section.Good feedback, Ill think about that for revision 2.
    There is some other material that didnt make that
    chapter as well. =) However, I do talk abotu
    initialization in detail in chapter one. You should
    check it out. =) Do I have to buy the book : )
    You say[i] "Most singleton classes shouldn't be
    declared as final. You never know what otherfeatures
    your class's user will dream up. However, since
    singleton classes need to be protected fromexternal
    instantiation, you can't make the constructorpublic.
    The solution to the problem is a protected
    constructor". I think you should add that thismeans you must put your singleton in a relevant
    package (i.e. Not in a package with classes that
    shouldn't be able to instantiate the singleton!)Of course you should always employ good package
    management. In fact package management might be in
    second edition as I do have quite a few notes on it.
    However, a singleton can only instantiate itself and
    that only once, so I dotn see why you think this is a
    concern. The goal of protected constructors is to
    prevent external instantiation of the class. Perhaps
    you were thinking of constructors with "package
    private" access (ie no public, private or protected
    keyword used) ?? Protected constructors can only be
    accessed bby the class and subclasses, whereas a
    "package private" constructor can be accessed by any
    class in the package.
    A protected constructor is accessible to the class itself, its subclasses, and classes in the same package.

  • Quick naming question

    Wasnt sure if its a naming issue or not but Ive never ran into the problem and Im not sure how to describe it....so here goes.
    Question: Is there a way to insert a string into the name of a component name and have java see it as the actual component name. (see that question still sounds incorrect)
    What I mean is......
    you have 10 buttons named oneB, twoB, threeB,......tenB
    I need to either change a whole lot of code and make what I want to be simple, very large and complex or, find a way to....
    "one"B.setLocation(whereverNotImportant);
    or
    (someObject.getString( ) ) + B.setLocation(whereverNotImportant);
    It looks really odd to me. If theres a way to do it, it just saved me a lot of annoyance.....if not well, Im gonna need more energy drinks.

    Paul5000 wrote:
    Fair enough. I kept adding features onto the code and it grew into needing something different. Was just hoping there was a quick workaround so I didnt have to go back and recode half of it.When you've got Franken-code, the answer is to recode it.

  • Simple basic java question

    public static void main(String[] args)
    ..anyone know the statement as above could be start at begining , so what is the (String[ ] args) mean in java ?
    in my ideas of this statement is
    publc : indicates the statemean can be used as all class , this is open for public use
    static mean the main method can used as class method
    void indicate that the statement return nothing
    main indicate any class should be run this first.
    so my question what is the function of (String [ ] args) ? // one string array call args ?

    String[] args is indeed an array of Strings called args. The reason it's there is to collect any arguments passed to your code when you start it.
    eg. if you have a class called TestClass and you called it from the command line like this:
    java TestClass exam tomorrow oh shite
    .......then the args array would hold the four Strings:
    exam
    tomorrow
    oh
    shite

  • Forte for Java question

    By using the JDBC form wizard, I generated a swing program. Along with the java code, there is a form file which looks like an xml file. My question is how to complie and run the java source code without a forte4j IDE?
    Thanks

    One thing is you need the jdbc in your classpath or specify at runtime. Search compiler in the forte help menu - to see options.
    execution : <specify at runtime>
    java -classpath:.;postgresql.org Program
    -- above for postgresql driver residing in same directory as Program.class
    compile : javac Progam.java or javac -classpath .;postgresql.org Progam.java
    Ray

  • TextSamplerDemo.java question

    I took the TextSamplerDemo from http://java.sun.com/docs/books/tutorial/uiswing/components/text.html and stripped it down to the one thing I have a question about. Given the code below, how do I implement the toolbar button to make selected text turn bold? I've been beating my head againt this one for a couple of days now and getting nowhere.
    Any help would be deeply appeciated.
    --gary
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*; //for layout managers and more
    import java.awt.event.*; //for action events
    public class TextSamplerDemo extends JPanel
    implements ActionListener {
    private String newline = "\n";
    protected static final String textFieldString = "JTextField";
    public TextSamplerDemo() {
    setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    JToolBar toolBar = buildToolbar();
    add(toolBar);
    //Create a text pane.
    JTextPane textPane = createTextPane();
    JScrollPane paneScrollPane = new JScrollPane(textPane);
    paneScrollPane.setVerticalScrollBarPolicy(
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    paneScrollPane.setPreferredSize(new Dimension(250, 155));
    paneScrollPane.setMinimumSize(new Dimension(10, 10));
    add(textPane);
    public void actionPerformed(ActionEvent e) {
    private JTextPane createTextPane() {
    String[] initString =
    { "This is an editable JTextPane, ",            //regular
    "another ", //italic
    "styled ", //bold
    "text ", //small
    "component, " + newline, //large
    "which supports embedded components..." + newline,//regular
    newline + "JTextPane is a subclass of JEditorPane that " + newline +
    "uses a StyledEditorKit and StyledDocument, and provides " + newline +
    "cover methods for interacting with those objects."
    String[] initStyles =
    { "regular", "italic", "bold", "small", "large",
    "regular", "regular"
    JTextPane textPane = new JTextPane();
    StyledDocument doc = textPane.getStyledDocument();
    addStylesToDocument(doc);
    try {
    for (int i=0; i < initString.length; i++) {
    doc.insertString(doc.getLength(), initString,
    doc.getStyle(initStyles[i]));
    } catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text into text pane.");
    return textPane;
    protected void addStylesToDocument(StyledDocument doc) {
    //Initialize some styles.
    Style def = StyleContext.getDefaultStyleContext().
    getStyle(StyleContext.DEFAULT_STYLE);
    Style regular = doc.addStyle("regular", def);
    StyleConstants.setFontFamily(def, "SansSerif");
    Style s = doc.addStyle("italic", regular);
    StyleConstants.setItalic(s, true);
    s = doc.addStyle("bold", regular);
    StyleConstants.setBold(s, true);
    s = doc.addStyle("small", regular);
    StyleConstants.setFontSize(s, 10);
    s = doc.addStyle("large", regular);
    StyleConstants.setFontSize(s, 16);
    private JToolBar buildToolbar() {
    JToolBar toolBar = new JToolBar();
    toolBar.setRollover( true );
    toolBar.setFloatable( false );
    JButton boldButton = new JButton("Bold");
    boldButton.setToolTipText( "Set selected text to bold" );
    boldButton.addActionListener( new ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    // code here to make selected text bold
    toolBar.add( boldButton );
    return toolBar;
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("TextSamplerDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new TextSamplerDemo();
    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();

    try this, but im'not sure.
    StyleContext styleContext = StyleContext.getDefaultStyleContext();
    Style def = styleContext.getStyle(StyleContext.DEFAULT_STYLE);
    Style bold = styledDocument.addStyle("bold", def);
    StyleConstants.setBold(bold, true);into the listener of your component insert this:
    int start = getSelectionStart();
    int len = getSelectionEnd() - start;
    styledDocument.setCharacterAttributes(start, len, bold, true);by gino

Maybe you are looking for