Change font in String ?

Is it possible to change font of a String like U cant do it with html coding? If I have :
String text ="this is a text";
can I change the color and the size of the text and so on, instead of the default ones?

You can set these attributes for the component which displays your string. For example, if you want to use a JLabel to display your String you can set the font, font style and colour of the JLabel.
JLabel lab = new JLabel(String);
lab.setFont(new Font("Arial", Font.BOLD, 16);
lab.setForegound(Color.red);You can do the same for JTextAreas and JTextFields. However, all of the text in these components will take the same formatting. JTextPane and JEditorPane are more flexible in that you can display text in various colours and fonts etc.
have a look at the Swing Tutorial. Follow the link to Text Components.

Similar Messages

  • How to change font/ font color etc in a graphic object using JCombobox?

    Hello
    My program im writing recently is a small tiny application which can change fonts, font sizes, font colors and background color of the graphics object containing some strings. Im planning to use Jcomboboxes for all those 4 ideas in implementing those functions. Somehow it doesnt work! Any help would be grateful.
    So currently what ive done so far is that: Im using two classes to implement the whole program. One class is the main class which contains the GUI with its components (Jcomboboxes etc..) and the other class is a class extending JPanel which does all the drawing. Therefore it contains a graphics object in that class which draws the string. However what i want it to do is using jcombobox which should contain alit of all fonts available/ font sizes/ colors etc. When i scroll through the lists and click the one item i want - the graphics object properties (font sizes/ color etc) should change as a result.
    What ive gt so far is implemented the jcomboboxes in place. Problem is i cant get the font to change once selecting an item form it.
    Another problem is that to set the color of font - i need to use it with a graphics object in the paintcomponent method. In this case i dnt want to create several diff paint.. method with different property settings (font/ size/ color)
    Below is my code; perhaps you'll understand more looking at code.
    public class main...
    Color[] Colors = {Color.BLUE, Color.RED, Color.GREEN};
            ColorList = new JComboBox(Colors);
    ColorList.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ev) {
                     JComboBox cb = (JComboBox)ev.getSource();
                    Color colorType = (Color)cb.getSelectedItem();
                    drawingBoard.setBackground(colorType);
              });;1) providing the GUI is correctly implemented with components
    2) Combobox stores the colors in an array
    3) ActionListener should do following job: (but cant get it right - that is where my problem is)
    - once selected the item (color/ font size etc... as i would have similar methods for each) i want, it should pass the item into the drawingboard class (JPanel) and then this class should do the job.
    public class DrawingBoard extends JPanel {
           private String message;
           public DrawingBoard() {
                  setBackground(Color.white);
                  Font font = new Font("Serif", Font.PLAIN, fontSize);
                  setFont(font);
                  message = "";
           public void setMessage(String m) {
                message = m;
                repaint();
           public void paintComponent(Graphics g) {
                  super.paintComponent(g);
                  //setBackground(Color.RED);
                  Graphics2D g2 = (Graphics2D) g;
                  g2.setRenderingHint             
                  g2.drawString(message, 50, 50);
           public void settingFont(String font) {
                //not sure how to implement this?                          //Jcombobox should pass an item to this
                                   //it should match against all known fonts in system then set that font to the graphics
          private void settingFontSize(Graphics g, int f) {
                         //same probelm with above..              
          public void setBackgroundColor(Color c) {
               setBackground(c);
               repaint(); // still not sure if this done corretly.
          public void setFontColor(Color c) {
                    //not sure how to do this part aswell.
                   //i know a method " g.setColor(c)" exist but i need to use a graphics object - and to do that i need to pass it in (then it will cause some confusion in the main class (previous code)
           My problems have been highlighted in the comments of code above.
    Any help will be much appreciated thanks!!!

    It is the completely correct code
    I hope that's what you need
    Just put DrawingBoard into JFrame and run
    Good luck!
    public class DrawingBoard extends JPanel implements ActionListener{
         private String message = "message";
         private Font font = new Font("Serif", Font.PLAIN, 10);
         private Color color = Color.RED;
         private Color bg = Color.WHITE;
         private int size = 10;
         public DrawingBoard(){
              JComboBox cbFont = new JComboBox(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames());
              cbFont.setActionCommand("font");
              JComboBox cbSize = new JComboBox(new Integer[]{new Integer(14), new Integer(13)});
              cbSize.setActionCommand("size");
              JComboBox cbColor = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbColor.setActionCommand("color");
              JComboBox cbBG = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbBG.setActionCommand("bg");
              add(cbFont);
              cbFont.addActionListener(this);
              add(cbSize);
              cbSize.addActionListener(this);
              add(cbColor);
              cbColor.addActionListener(this);
              add(cbBG);
              cbBG.addActionListener(this);
         public void setMessage(String m){
              message = m;
              repaint();
         protected void paintComponent(Graphics g){
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D)g;
              g2.setColor(bg);//set background color
              g2.fillRect(0,0, getWidth(), getHeight());          
              g2.setColor(color);//set text color
              FontRenderContext frc = g2.getFontRenderContext();
              TextLayout tl = new TextLayout(message,font,frc);//set font and message
              AffineTransform at = new AffineTransform();
              at.setToTranslation(getWidth()/2-tl.getBounds().getWidth()/2,
                        getWidth()/2 + tl.getBounds().getHeight()/2);//set text at center of panel
              g2.fill(tl.getOutline(at));
         public void actionPerformed(ActionEvent e){
              JComboBox cb = (JComboBox)e.getSource();
              if (e.getActionCommand().equals("font")){
                   font = new Font(cb.getSelectedItem().toString(), Font.PLAIN, size);
              }else if (e.getActionCommand().equals("size")){
                   size = ((Integer)cb.getSelectedItem()).intValue();
              }else if (e.getActionCommand().equals("color")){
                   color = (Color)cb.getSelectedItem();
              }else if (e.getActionCommand().equals("bg")){
                   bg = (Color)cb.getSelectedItem();
              repaint();
    }

  • How do I change fonts in a Text field ??

    Okay I've tried to implement a JComboBox that allows the user to change fonts in the text field. So far I've tried different methods to do it but to no avail. Could somebodoy here read the programs source code for me and tell me where I went wrong?
    /* * My GUI Client */
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import javax.swing.event.*;
    //for HTML Headers
    import javax.swing.text.StyledEditorKit.*;
    import javax.swing.text.html.HTMLEditorKit.*;
    import javax.swing.text.html.*;
    import javax.swing.event.HyperlinkListener;
    import javax.swing.event.HyperlinkEvent;
    import javax.swing.event.HyperlinkEvent.EventType;
    import javax.swing.text.html.HTMLFrameHyperlinkEvent;
    //for layout managers
    import java.awt.event.*;
    //for action and window events
    import java.io.*;
    import java.net.*;
    import java.awt.GraphicsEnvironment;
    //for font settings
    import java.lang.Integer;
    import java.util.Vector;
    import java.awt.font.*;
    import java.awt.geom.*;
    public class guiClient extends JFrame implements ActionListener {
    protected static final String textFieldString = "JTextField";
    protected static final String loadgraphicString = "LoadGraphic";
    protected static final String connectString = "Connect";
    static JEditorPane editorPane;
    static JPanel layoutPanel = new JPanel(new BorderLayout());
    static JPanel controlPanel = new JPanel(new BorderLayout());
    static JPanel buttonPanel = new JPanel(new BorderLayout());
    static JPanel fontPanel = new JPanel(new BorderLayout());
    static PrintStream out;
    static DrawPanel dPanel;
    static DrawPanel dPButton;
    static DrawPanel dFonts;
    static DrawControls dControls;
    static DrawButtons dButtons;
    static String userString;
    static String currentFont;
    String fontchoice;
    String fontlist;
    static JTextField userName = new JTextField();
    public static JMenuBar menuBar;
    private static JButton connectbutton = new JButton("Connect");
    static boolean CONNECTFLAG = false;
    //create the gui interface
    public guiClient() {
         super("My Client");
    // Create a ComboBox
    GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String envfonts[] = gEnv.getAvailableFontFamilyNames();
    Vector vector = new Vector();
    for ( int i = 1; i < envfonts.length; i++ ) {
    vector.addElement(envfonts);
    JComboBox fontlist = new JComboBox (envfonts);
         fontlist.setSelectedIndex(0);
         fontlist.setEditable(true);
         fontlist.addActionListener(this);
         fontchoice = envfonts[0];     
    //Create a regular text field.
         JTextField textField = new JTextField(10);
         textField.setActionCommand(textFieldString);
         textField.addActionListener(this);          
    //Create an editor pane.
    editorPane = new JEditorPane();
         editorPane.setContentType("text");
         editorPane.setEditable(false);
    //set up HTML editor kit
         HTMLDocument m_doc = new HTMLDocument();
         editorPane.setDocument(m_doc);
         HTMLEditorKit hkit = new HTMLEditorKit();
         editorPane.setEditorKit( hkit );
         editorPane.addHyperlinkListener( new HyperListener());
    //Create whiteboard
    dPanel = new DrawPanel();
    dPButton = new DrawPanel();
    dFonts = new DrawPanel();
    dControls = new DrawControls(dPanel);
    dButtons = new DrawButtons(dPButton);
         //JLable fontLab = new JLabel(fontLable);
    //fontLab.setText("Fonts");
    //Font newFont = getFont().deriveFont(1);
    //fontLab.setFont(newFont);
    //fontLab.setHorizontalAlignment(JLabel.CENTER);
    JPanel whiteboard = new JPanel();
    whiteboard.setLayout(new BorderLayout());
    whiteboard.setPreferredSize(new Dimension(300,300));
    whiteboard.add("Center",dPanel);
    whiteboard.add("South",dControls);
    whiteboard.add("North",dButtons);
         JScrollPane editorScrollPane = new JScrollPane(editorPane);
         editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
         editorScrollPane.setPreferredSize(new Dimension(250, 145));
         editorScrollPane.setMinimumSize(new Dimension(50, 50));
    //put everything in a panel
         JPanel contentPane = new JPanel();
         JPanel fontPane = new JPanel();
         contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
    //add whiteboard
         contentPane.add(whiteboard);
    //add editor box
         contentPane.add(editorScrollPane);
    //add spacer
         contentPane.add(Box.createRigidArea(new Dimension(0,5)));
    //add textfield
         contentPane.add(textField);
    //set up layout pane
         //layoutPanel.add(GridLayout(2,1),fontLab);
         layoutPanel.add( BorderLayout.NORTH, fontlist);     
         layoutPanel.add(BorderLayout.WEST,new Label("Name: ")); //add a label
         layoutPanel.add(BorderLayout.CENTER, userName ); //add textfield for user names
         layoutPanel.add(BorderLayout.SOUTH, connectbutton);//add dropdown box for fonts
         //fontPane.add(BorderLayout.NORTH,fontlist);
         contentPane.add(layoutPanel);
         contentPane.add(controlPanel);
         contentPane.add(buttonPanel);
    //Create the menu bar.
    menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    //Build the first menu.
         JMenu menu = new JMenu("File");
         menu.setMnemonic(KeyEvent.VK_F);
         menuBar.add(menu);
    //a group of JMenuItems
         JMenuItem menuItem = new JMenuItem("Load Graphic", KeyEvent.VK_L);
         menu.add(menuItem);
    menuItem.setActionCommand(loadgraphicString);
         menuItem.addActionListener(this);
    connectbutton.setActionCommand(connectString);
    connectbutton.addActionListener(this);
         setContentPane(contentPane);
    static private void insertTheHTML(JEditorPane editor, String html, int location) throws IOException {
         HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit();
         Document doc = editor.getDocument();
         StringReader reader = new StringReader(html);
         try {
              kit.read(reader, doc, location);
         } catch (BadLocationException e) {}
    //listen for actions being performed and process them
    public void actionPerformed(ActionEvent e) {
    //if the action is from the textfield (e.g. user hits enter)
         if (e.getActionCommand().equals(textFieldString)) {
              JTextField fromUser = (JTextField)e.getSource();
         if (fromUser != null){
    //place user text in editor pane
    //send message to server
                   if (userName.getText() != null) {
                        userString = userName.getText().trim();
                   out.println(userString + ": " + fromUser.getText());
              fromUser.setText("");
         } else if(e.getActionCommand().equals(connectString)) {
              CONNECTFLAG = true;
    } else if (e.getActionCommand().equals(loadgraphicString) ) {
              final JFileChooser fc = new JFileChooser();
              int returnVal = fc.showOpenDialog(this);
              if (returnVal == JFileChooser.APPROVE_OPTION) {
                   File file = fc.getSelectedFile();
                   dPanel.loadImage(file.getAbsolutePath());
                   sendImage(file);
         else if (e.getActionCommand().equals(fontlist)){
         JComboBox cb = (JComboBox)e.getSource();
    String newSelection = (String)cb.getSelectedItem();
    currentFont = newSelection;
         userString = currentFont;
    return;
    /*public void itemStateChanged (ItemEvent e) {
    if ( e.getStateChange() != ItemEvent.SELECTED ) {
    return;
    if ( list == fontlist ) {
    fontchoice = (String)fontlist.getSelectedItem();
         userString.changeFont(fontchoice);
    //append text to the editor pane and put it at the bottom
    public static void appendText(String text) {
         if (text.startsWith("ID ") ) {
              userString = text.substring(3);
         } else if (text.startsWith("DRAW ") ) {
              if (text.regionMatches(5,"LINE",0,4)) {
    dPanel.processLine(text);
         }else if (text.regionMatches(5,"POINTS",0,5)) {
         dPanel.processPoint(text);
         } else if (text.startsWith("IMAGE ") ) {
    int len = (new Integer( text.substring(6, text.indexOf(",")))).intValue();
    //get x and y coordinates
         byte[] data = new byte[ (int)len ];
         int read = 0;
    try {
         while (read < len) {
         data = text.getBytes( text.substring(0, len) );
    } catch (Exception e) {}
         Image theImage = null;
         theImage = dPanel.getToolkit().createImage(data);
         dPanel.getToolkit().prepareImage(theImage, -1, -1, dPanel);
         while ((dPanel.getToolkit().checkImage(theImage, -1, -1, dPanel) & dPanel.ALLBITS) == 0) {}
              dPanel.drawPicture(0, 0, theImage);
    } else {
    //set current position in editorPane to the end
              editorPane.setCaretPosition(editorPane.getDocument().getLength());
    //put text into the editorPane
              try {
                   insertTheHTML(editorPane, text, editorPane.getDocument().getLength());
              } catch (IOException e) {}
    } //end of appendText(String)
    public void sendImage(File file) {
    //find length of file
         long len = file.length();
    //read file into byte array
         byte[] byteArray = new byte[(int)len];
         try {
              FileInputStream fstream = new FileInputStream(file);
              if (fstream.read(byteArray) < len) {
    //error could not load file
              } else {
              out.println("IMAGE " + len + ",");
                   out.write(byteArray, 0, (int)len); //write file to stream
         } catch(Exception e){}
    //run the client
    public static void main(String[] args) {
         String ipAddr=null, portNr=null;
              if (args.length != 2) {
                   System.out.println("USAGE: java guiClient IP_Address port_number");
                   System.exit(0);
              } else {
         ipAddr = args[0];
              portNr = args[1];
              JFrame frame = new guiClient();
              frame.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) { System.exit(0); }
              frame.pack();
              frame.setVisible(true);
              while(CONNECTFLAG == false){}
    //sames as previous client,
    //set up connection and then listen for messages from the Server
              String socketIP = ipAddr;
              int port = Integer.parseInt(portNr);
    //the IP address of the machine where the server is running
              Socket theSocket = null;
    //communication line to the server
              out = null;
    //for message sending
              BufferedReader in = null;
    //for message receiving
              try {
              theSocket = new Socket(socketIP, port );
    //try to connect
              out = new PrintStream(theSocket.getOutputStream());
                   dPanel.out = out;
    //for client to send messages
              in = new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
                   BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
                   String fromServer;
                   while ((fromServer = in.readLine()) != null) {
                   appendText(fromServer);
                   if (fromServer.equals("BYE")) {
                        appendText("Connection Closed");
                        break;
              out.close();
    //close all streams
              in.close();
              theSocket.close();
    //close the socket
         } catch (UnknownHostException e) {
    //if the socket cannot be openned
              System.err.println("Cannot find " + socketIP);
              System.exit(1);
              } catch (IOException e) { //if the socket cannot be read or written
              System.err.println("Could not make I/O connection with " + socketIP);
              System.exit(1);
    class HyperListener implements HyperlinkListener {
    public JEditorPane sourcePane;
    public void hyperlinkUpdate(HyperlinkEvent e) {
    if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
    sourcePane = (JEditorPane) e.getSource();
                   if (e instanceof HTMLFrameHyperlinkEvent) {
    HTMLFrameHyperlinkEvent event = (HTMLFrameHyperlinkEvent) e;
                        System.out.println(event.getTarget());
                        HTMLDocument doc = (HTMLDocument) sourcePane.getDocument();
                        doc.processHTMLFrameHyperlinkEvent(event);
    else {
    try {}
    catch (Exception ev){
         ev.printStackTrace();
    Well sorry the source code takes up the whole forum but I need a good feedback from this.

    All right...
    public class guiClient extends JFrame implements ActionListener {
    static String userString;
    static String currentFont;
    String fontchoice;
    String fontlist;
    static JTextField userName = new JTextField();
    public guiClient() {
         super("My Client");
    public guiClient() {
         super("My Client");
    // Create a ComboBox
    GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String envfonts[] = gEnv.getAvailableFontFamilyNames();
    Vector vector = new Vector();
    for ( int i = 1; i < envfonts.length; i++ ) {
    vector.addElement(envfonts);
    JComboBox fontlist = new JComboBox (envfonts);
         fontlist.setSelectedIndex(0);
         fontlist.setEditable(true);
         fontlist.addActionListener(this);
         fontchoice = envfonts[0];     
    //Create a regular text field.
         JTextField textField = new JTextField(10);
         textField.setActionCommand(textFieldString);
         textField.addActionListener(this);
    public void actionPerformed(ActionEvent e) {
    //if the action is from the textfield (e.g. user hits enter)
         if (e.getActionCommand().equals(textFieldString)) {
              JTextField fromUser = (JTextField)e.getSource();
         if (fromUser != null){
    //place user text in editor pane
    //send message to server
                   if (userName.getText() != null) {
                        userString = userName.getText().trim();
                   out.println(userString + ": " + fromUser.getText());
              fromUser.setText("");
         else if (e.getActionCommand().equals(fontlist)){
         JComboBox cb = (JComboBox)e.getSource();
    String newSelection = (String)cb.getSelectedItem();
    currentFont = newSelection;
         userString = currentFont;
    return;

  • How to change font size for tracks in Songs view, iTunes 11?

    I'm wondering which field in TextStyles.plist for the new iTunes 11 (I've gotten rid of Helvetica for Lucida Grande thanks to another forum on here!) - controls the font size for track title, time, artist, album, etc. as seen here - I would like to have it smaller, and have been playing around on several forums and not found the magical field to get that exact thing smaller. Many thanks in advance.

    You're going to love me forever:
    <key>9002</key>
    <dict>
    <key>- loc hint -</key>
    <string>List Contents (Small)</string>
    <key>font</key>
    <string>HelveticaNeue</string>
    <key>size</key>
    <integer>12</integer>
    </dict>
    It's that interger "12" that's determines the size. Adjust it until you're happy—provided that it's an interger.
    I actually go with "HelveticaNeue" with a size of 11. I like to see lots of tabular information at once, horizontally, without changing my resolution… within reason, e.g. Fiona Apple album titles still have ellipses.
    An unfortunate aspect to this is that the row height isn't altered unless the font size specified is greater than 12—the font takes the row height along for the ride when it's bigger, but the row doesn't come along for the ride when the font gets smaller. It's likely you could change the minimum row height to be lower, in some other plist—search for something like "list contents (small)" or "list (small)" or whatever—but I don't know where that would be found, or if it could be found at all.
    Nonetheless, this should address your query.

  • Why I cannot change font  and Color in JFrame title??

    Dear sir:
    I try to change font and Color in JFrame title in code below,
    It display all html code, not expected formatted ones.
    but fail. Looks like no way to do it??
    Can somebody help??
    Thanks
    import java.awt.BorderLayout;
    import java.awt.Toolkit;
    import javax.swing.*;
    public class JFrameTester {
      public static void main(String[] args) {
         String iconPath ="file:C:/eclipse/workspace/Test/images/long.PNG";
         String title = "<html><body bgcolor=\"yellow\">" + "<img src=\""+iconPath+"\">" +
              " <font size=\"6\" face=\"Verdana\" color=\"red\"><b>"+ "New Tester" + "</b></font></html>";
        JFrame f = new JFrame(title);
        f.setIconImage(Toolkit.getDefaultToolkit().getImage("images/123.gif"));
        f.setSize(250, 250);
        f.setLocation(300,200);
        f.getContentPane().add(new BorderLayout().CENTER, new JTextArea(10, 40));
        f.setVisible(true);
    }

    Looks like no way to do it??depends on the L&F you want.
    here's one way
    import java.awt.*;
    import javax.swing.*;
    class JFrameTester {
      public static void main(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        UIManager.put("activeCaption", new javax.swing.plaf.ColorUIResource(Color.RED));
        UIManager.put("activeCaptionText", new javax.swing.plaf.ColorUIResource(Color.YELLOW));
        String title = "Hello World";
        JFrame f = new JFrame(title);
        f.getLayeredPane().getComponent(1).setFont(new Font("Tall Paul",Font.ITALIC,24));
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(250, 250);
        f.setLocation(300,200);
        f.getContentPane().add(new BorderLayout().CENTER, new JTextArea(10, 40));
        f.setVisible(true);
    }

  • Changing Font for JLabels

    Hello, I have created a small test program using a JComboBox. The purpose of this program is to change a JLabel to a certain font, based on the font that the user chooses from the JComboBox. My main concern is actually changing to font and I have no clue how to do this.
    The following is the code for this test program:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class FontTest implements ActionListener{
         JFrame frame;
         JPanel contentPane;
         JComboBox font;
         JLabel fontPrompt, word;
         public FontTest(){
              frame = new JFrame("Font Styles");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              contentPane = new JPanel();
              contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
              contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
              fontPrompt = new JLabel("Select a font: ");
              fontPrompt.setAlignmentX(JLabel.LEFT_ALIGNMENT);
              contentPane.add(fontPrompt);
              String[] names = {"Times New Roman", "Ariel"}; //any font names that are available
              font = new JComboBox(names);
              font.setAlignmentX(JComboBox.LEFT_ALIGNMENT);
              font.setSelectedIndex(0);
              font.addActionListener(this);
              contentPane.add(font);
              word = new JLabel("font styles");
              word.setBorder(BorderFactory.createEmptyBorder(20, 0, 0, 0));
              contentPane.add(word);
              frame.setContentPane(contentPane);
              frame.pack();
              frame.setVisible(true);
         public void actionPerformed(ActionEvent event){
              JComboBox comboBox = (JComboBox)event.getSource();
              String fontWord = (String)comboBox.getSelectedItem();
              if(fontWord == "Times New Roman"){//if any of these choices in the JComboBox are clicked,
                                                      //I would like the JLabel "font styles" to change font.                              
              else if(fontWord == "Ariel"){
         private static void runGUI(){
              JFrame.setDefaultLookAndFeelDecorated(true);
              FontTest display = new FontTest();
         public static void main(String[] args){
              javax.swing.SwingUtilities.invokeLater(new Runnable(){
                   public void run(){
                        runGUI();
    }It would be great if you guys could help me. Any font style is alright.
    Thanks in advance.

    Hi,
    Build a Font object and call setFont on the JLabel.
    Hope that help,
    Jack

  • Chat server change font tb

    I have created a chat server and have included a change font button where you can go in and select from the list of fonts colours and sizes and set them for the font to change.
    My question is can i get a list of fonts and colours to choose from or do I need to write them in an array string and somehow assign each one to the correct font/colour/size?
    Thanks

    I made you a small example:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame {
        private JComboBox faceBox;
        private JComboBox colourBox;
        private JComboBox sizeBox;
        private JLabel exampleLabel;
        public Test () {
            ActionListener actionListener = new ActionListener () {
                public void actionPerformed (ActionEvent event) {
                    updateExampleLabel ();
            faceBox = new JComboBox (getFaces ());
            faceBox.addActionListener (actionListener);
            colourBox = new JComboBox (getColours ());
            colourBox.addActionListener (actionListener);
            sizeBox = new JComboBox (getSizes ());
            sizeBox.addActionListener (actionListener);
            exampleLabel = new JLabel ();
            exampleLabel.setHorizontalAlignment (SwingConstants.CENTER);
            exampleLabel.setPreferredSize (new Dimension (400, 200));
            JPanel boxesPanel = new JPanel (new GridLayout (1, 3));
            boxesPanel.add (new TitledPanel (faceBox, "Font"));
            boxesPanel.add (new TitledPanel (colourBox, "Colour"));
            boxesPanel.add (new TitledPanel (sizeBox, "Size"));
            getContentPane ().setLayout (new BorderLayout ());
            getContentPane ().add (exampleLabel);
            getContentPane ().add (boxesPanel, BorderLayout.SOUTH);
            setDefaultCloseOperation (EXIT_ON_CLOSE);
            setTitle ("Font test");
            updateExampleLabel ();
            pack ();
            setLocationRelativeTo (null);
            show ();
        private Face[] getFaces () {
            Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment ().getAllFonts ();
            Face[] faces = new Face[fonts.length];
            for (int i = 0; i < faces.length; i ++) {
                faces[i] = new Face (fonts);
    return faces;
    private Colour[] getColours () {
    return new Colour[] {
    new Colour (Color.BLACK, "Black"),
    new Colour (Color.BLUE, "Blue"),
    new Colour (Color.GREEN, "Green"),
    new Colour (Color.ORANGE, "Orange"),
    new Colour (Color.RED, "Red"),
    new Colour (Color.WHITE, "White"),
    new Colour (Color.YELLOW, "Yellow")
    private Size[] getSizes () {
    int lower = 10;
    int upper = 36;
    Size[] sizes = new Size[(upper - lower) / 2 + 1];
    for (int i = 0; i < sizes.length; i ++) {
    sizes[i] = new Size (lower + i * 2);
    return sizes;
    private void updateExampleLabel () {
    Face face = (Face) faceBox.getSelectedItem ();
    Colour colour = (Colour) colourBox.getSelectedItem ();
    Size size = (Size) sizeBox.getSelectedItem ();
    exampleLabel.setText ("Font: " + face + ", colour: " + colour + ", size: " + size);
    exampleLabel.setFont (face.getFont ().deriveFont (size.getSize ()));
    exampleLabel.setForeground (colour.getColour ());
    private class Face {
    private Font font;
    public Face (Font font) {
    this.font = font;
    public Font getFont () {
    return font;
    public String toString () {
    return font.getName ();
    private class Colour {
    private Color colour;
    private String name;
    public Colour (Color colour, String name) {
    this.colour = colour;
    this.name = name;
    public Color getColour () {
    return colour;
    public String toString () {
    return name;
    private class Size {
    private float size;
    public Size (float size) {
    this.size = size;
    public float getSize () {
    return size;
    public String toString () {
    return String.valueOf ((int) size);
    private class TitledPanel extends JPanel {
    public TitledPanel (JComponent component, String title) {
    setBorder (BorderFactory.createTitledBorder (title));
    setLayout (new BorderLayout ());
    add (component);
    public static void main (String[] parameters) {
    new Test ();
    }Swing experts will slag me off because I'd rather create a class than set a renderer, but that's their problem, I suppose.
    Kind regards,
      Levi

  • Dynamically changing font - Ugly chars on Win 2000

    Hi,
    I wrote simple class called FontChooser (extends JDialog). It can be "plugged" into any JFrame to change font at runtime. Looks like ordinary font dialog, nothing special.
    The FontChooser itself works (IMHO) just fine but I'm facing a problem: Almost all PLAIN fonts on Windows 2000 (sp4) have several ugly characters. For example Tahoma PLAIN 11 has ugly char '8'.
    Strange is that BOLD fonts are always displayed OK - the ugly things are "covered".
    The only font that's OK is Arial. (Any size, any style.) Brobably because it's the Swing default font.
    Changing the font is done by this method:
    * The method simply iterates through the table of  GUI keys and updates every key whose name ends with "font".
    Thus, FontChooser is not able to deal with different fonts at the same time.
    public void updateFontKeys(FontUIResource font) {
      UIDefaults def = UIManager.getDefaults();
      Enumeration en = def.keys();
      while(en.hasMoreElements()) {
        String key = en.nextElement().toString();
        if(key.toLowerCase().endsWith("font"))
          UIManager.put(key,font);
    // Note: FontUIResource is just a new (Swing)
    // "version" of java.awt.Font.I also tried to change Swing component's font using html
    - instead of changing gui keys - but the result was the
    same :o(
    Any hint will be very appreciated :o) Thanks.

    You can download FontChooser (with a simple demo app) from http://www.volny.cz/dojcland/gui/FontChoosing.zip
    The archive includes binaries, source and javadoc.

  • Can we change data in string object.

    Can we change data in string object.

    Saw this hack to access the char[]'s in a String in another thread. Beware that the effects of doing this is possible errors, like incorrect hashCode etc.
    import java.lang.reflect.*;
    public class SharedString {
            public static Constructor stringWrap = null;
            public static String wrap(char[] value, int offset, int length) {
                    try {
                            if (stringWrap == null) {
                                    stringWrap = String.class.getDeclaredConstructor(new Class[] { Integer.TYPE, Integer.TYPE, char[].class });
                                    stringWrap.setAccessible(true);
                            return (String)stringWrap.newInstance(new Object[] { new Integer(offset), new Integer(length), value });
                    catch (java.lang.NoSuchMethodException e) {
                            System.err.println ("NoMethod exception caught: " + e);
                    catch (java.lang.IllegalAccessException e) {
                            System.err.println ("Access exception caught: " + e);
                    catch (java.lang.InstantiationException e) {
                            System.err.println ("Instantiation exception caught: " + e);
                    catch (java.lang.reflect.InvocationTargetException e) {
                            System.err.println ("Invocation exception caught: " + e);
                    return null;
            public static void main(String[] args) {
                    char[] chars = new char[] { 'l', 'e', 'v', 'i', '_', 'h' };
                    String test = SharedString.wrap(chars, 0, chars.length);
                    System.out.println("String test = " + test);
                    chars[0] = 'k';
                    chars[1] = 'a';
                    chars[2] = 'l';
                    chars[3] = 'l';
                    chars[4] = 'a';
                    chars[5] = 'n';
                    System.out.println("String test = " + test);
    } Gil

  • How do I change font and colors back to default?

    I have changed the font and color of the text through the tools button and the options button and the content tab. I find nothing telling me how to change the font and colors back to default font and colors. Can you advise me? I'm using Windows 7 Home Premium OS. Thanks.

    Hi Brenda19605,
    You can use this article to set the fonts and colors: https://support.mozilla.org/en-US/kb/change-fonts-and-colors-websites-use?esab=a&s=font&r=0&as=s
    The default settings for the font are in this article:
    https://support.mozilla.org/en-US/kb/Some%20text%20shows%20up%20bold%20after%20upgrade
    Unfortunately for the default colors has no good reference. But for text it is black (most lower left) color, background is white (most upper left color). Unvisited links is blue (column 8, row 5) and visited link is purple (column 9, row 5).
    Let me know if you need anymore help!
    Lordfreak

  • Email will not let me change fonts all of a sudden.

    Email will not let me change fonts all of a sudden.  It says I don't have the neccesay permissions in ~/library/preferences.  this has just happened recently.

    Who is your email provider?
    You can try resetting your iPad by simultaneously pressing and holding the Home and Sleep/Wake buttons until you see the Apple Logo. This can take up to 15 seconds so be patient and don't release the buttons until the logo appears. Try again to see if the problem persists.
    If yes, try deleting the mail account and adding it again.

  • How to change fonts in iCal?

    How to change fonts in iCal?  I can't harly read my calendar-tiny print size.  How could I change the font size?

    Your question really got me thinking.   Actually, I don't think you should feel like an idiot at all.  I think it is Apples failure that they made this difficult.  Seriously, who would ever think to press Command and arrow to switch months?  The little arrows next to the word Today are so small and inconspicuous that I remember having this very same question when I started using iCal too. 
    So, here is what I did to make it easier for my wife that uses iCal too. 
    Open System Preferences, Keyboard, Keyboard Shortcuts Tab, and finally Application Shortcuts.
    Click on the Plus symbol under the right hand pane.
    Select iCal from the Application list
    Add two shortcuts:  One named Next and the other named Previous and press your desired Keyboard Shortcut.
    I assigned the left arrow and right arrow for these tasks.
    Now it makes more sence for someone that is not used to Apples idotic way of doing things. ;-)
    I use keyboard shortcuts all over the place.  Actually, sometimes it gets me into trouble when I use someone elses computer and my shortcuts don't work.  I blame their computer for it and forget it was my "tuning".

  • How to change font size on screen

    how to change font size on screen

    I'm not certain what font sizes you wish to change, when on a page you can use command and the += button to zoom in and make the fonts larger. On the finder desktop you can make what ever is on the desktop larger or smaller from the finder menu click view, custom view options, and adjust the icon size with the slider on the top, and the text using the text size box to select the size that your comfortable with.
    Forgot to add these.
    http://support.apple.com/kb/PH10876
    http://support.apple.com/kb/PH10877
    Hope this helps.

  • How can I change font size in iCal 3.0.8?

    How can I change font size in iCal 3.0.8?

    Julian,
    There is no user option to change the font size in iCal.
    For other posts regarding this topic, read some of the links in "More Like This." box just to the right of your first post in this thread.

  • How to change font size on web page when have no icon in View tool to do so

    menu bar at top of screen does not have icon to change font size of a web page as described in your support information--you show it as between stop and reload in View icon and I do not have it at all in my toolbar.

    See this: <br />
    https://support.mozilla.com/en-US/kb/Page+Zoom

Maybe you are looking for

  • Change of Material Valuation Class - What Approach to Consider?

    Dear SAP Expert ... In OSS notes # 160970, it mentions that starting from release 4.6B we can use Customizing Transaction OMT4 (Change System Message) to change corresponding check from error to warning.  With this function, the system won't check if

  • Query for Day and Month Only

    I have a table with a date field that I need to query by day and month only. Basically, if I search for "04/15", the query would return records whose date includes: 04/15/2006, 04/15/2007, 04/15/2008, etc. How can I do that on SQL Server? Thx!

  • Layers on PS 11 trial

    Hi, can anyone tell me if there are restirctions of tool use on the elements 11 trial. i want to cut,copy,paste, and use layers, and the drop down menus for these are not highlighted. I must admit  i have not used ps11 before but do use other program

  • Image File:///tmp/ftproot/usb_1/.... cannot be displayed because it contains errors

    Hi, Is anyone experienced with the following error when displaying image from DMP 4305G as local or remote url? Imge File:///tmp/ftproot/usb_1/.... cannot be displayed because it contains errors . Imge Jpeg/gif file displaying fine but after warning

  • CallOut load time

    Hi! Following the tutorial on the new component devgirl CallOut, http://devgirl.org/2011/10/17/flex-mobile-development-callout-component-sample-with-source /, I have created a CallOutButton CallOut which contains several states. Each state has a list