Draw string in center

Hi,
I would like to draw a string into center of my own Lable component. How can I know what position of x , y ?
I'm using g.drawString(mytext, x , y ); in paintComponent() method.

I guess you could use one of these:
- Font.getStringBounds()
- TextLayout.getBounds()
- FontMetrics.getStringBounds()

Similar Messages

  • How to draw string vertically?

    Hi,
    The java drawString() method draws string horizontally by default, but I want to draw the string vertically, see an example below: I want to draw the string "abcdef" as below format:
    a
    b
    c
    d
    e
    f
    so, I thought of the AffineTransform, but I can not work it out.
    Who can help me? If you have other ways, they are welcome too.
    Thanks. Robin

    import java.awt.*;
    import java.awt.font.*;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class VText {
        public static void main(String[] args) {
            int w = 200, h = 300;
            BufferedImage image = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g2.setBackground(UIManager.getColor("OptionPane.background"));
            g2.clearRect(0,0,w,h);
            g2.setPaint(Color.black);
            Font font = g2.getFont().deriveFont(18f);
            g2.setFont(font);
            FontRenderContext frc = g2.getFontRenderContext();
            String text = "Hello World";
            g2.drawString(text, 50, h - 25);
            String[] s = text.split("(?<=[\\w\\s])");
            float y = 25f;
            for(int j = 0; j < s.length; j++) {
                float width = (float)font.getStringBounds(s[j], frc).getWidth();
                LineMetrics lm = font.getLineMetrics(s[j], frc);
                float x = (w - width)/2;
                AffineTransform at = AffineTransform.getTranslateInstance(x, y);
                g2.setFont(font.deriveFont(at));
                g2.drawString(s[j], 0, 0);
                y += lm.getAscent();// - lm.getDescent();
            g2.dispose();
            JOptionPane.showMessageDialog(null, new ImageIcon(image), "",
                                          JOptionPane.PLAIN_MESSAGE);
    }

  • Help with drawing strings on JFrame?!?!

    Hey guys, I'm really new to Java (just started AP Comp Sci last month), and we had a project to build a Mastermind application using numbers, which I did. However, I'm trying to learn more on my own, and was hoping to use the example code my teacher gave me to output what I want to say to a JFrame instead of just the command prompt.
    Here is the code for my Mastermind class:
    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Mastermind extends JFrame
         public static void main(String args[])
              int master[] = new int[4];
              int win = 0;
              for(int x = 0; x<4; x++)
                   master[x] = (int)(Math.random()*10);
              System.out.println();
              do {
                   int guess[] = new int[4];
                   int countMaster[] = new int[4];
              String numguess = JOptionPane.showInputDialog("Enter your guess (4 digits, please)");
              for (int x = 0;x<4;x++)
                   guess[x] = (numguess.charAt(x)-48);
              int correctlyPlaced = 0;
              int correct = 0;
              for (int x = 0;x<4;x++)
                   if(master[x] == guess[x])
                        correctlyPlaced += 1;
              for (int x = 0; x<4;x++)
                             for (int y = 0; y<4;y++)
                                  if((guess[x]==master[y]) && (countMaster[y]==0)) {
                                       correct++;
                                       countMaster[y]=1;
                                       y=5;
              System.out.print("Guess:\t\t\t");
              for (int x = 0;x<4;x++) {
                   System.out.print(guess[x]);
              System.out.println();
              System.out.println("Correct:\t\t"+correct);
              System.out.println("Correctly Placed:\t"+correctlyPlaced);
              if (correctlyPlaced==4) {
                   win=1;
         } while(win<1);
         System.out.println("You win!");
              System.exit(0);
    And here is the example code that my teacher gave me for how to draw a string on a JFrame:
    Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Fonts extends JFrame {
         public Fonts()
              super("Using Fonts");
              setSize(420,125);
              show();
         public void paint(Graphics g)
              super.paint(g);
              g.setFont(new Font("Serif", Font.BOLD, 12));
              g.drawString("Serif 12 point bold.",20,50);
         public static void main(String args[])
              Fonts application = new Fonts();
              application.setDefaultCloseOperation (
                   JFrame.EXIT_ON_CLOSE);
    I would like to be able to put "Guess," "Correct," and "Correctly Placed," on a JFrame, with their respective variables. Any ideas? Thank you!!!

    800045 wrote:
    And DrClap, I get that, but I'm not sure how to put my existing code into the class file that uses the JFrame.You wouldn't put your existing code in there. Your existing code is designed to run as a console app and most of it is concerned with the machinery of getting input from the user. If you want to write it as a Swing app, then you wouldn't need any code which writes to a JFrame in the first place.
    So if your goal for learning on your own is to write GUI applications instead of console applications, then go off and read the Swing tutorials. Right now you're going down the wrong road. However if you're trying to learn something else on your own (I can't tell what that might be) then explain what it is you're trying to learn.

  • Polygon and Star Tool Draw Only from Center?

    Adobe Illustrator 15.1.0 (CS 5.5) on Windows 7.
    I was attempting to draw a polygon shape with an upper left origin point, when I noticed that the polygon and star tools only draw out from the center. Modifier keys have no effect. Rectangle and Ellipse tools work normally.
    I don't remember this behaivor from previous versions.
    Is this a bug?

    I think the reason for the "off-beat" function of the star and polygon tools must be that the dimensions of regular stars or polygons  do not coincide with the dimensions of a square bounding box. This works for circles and squares but not for stars or polygons. So for example drawing a polygon in the "normal" way from the corner of its bounding box and with Shift held down would not result in a regular polygon. Drawing from the centre means that the stars and polygons are always kept regular, so you have to make special efforts if you want to distort them.

  • Drawing String In Different Colors

    Hi!
    I need to do the following. Using DrawString method, I need to make a special character, each time it appears in string, invisible(but not to remove it from string). So I decided to draw it in a background color(If you know some other way to hide it, please share it with me). But other letters should be in foreground colors. How can I define only that letter in different(background) color?
    If you understood my problem, please help me to solve it.

    This program will do it :
    import java.awt.event.*;  
    import java.awt.*;
    public class DrawS extends Frame
    public DrawS()
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);
         setBounds(50,50,450,400);
         setBackground(Color.lightGray);
         setForeground(Color.red);
        setVisible(true);
    public void paint(Graphics g)
         super.paint(g);
         String s = "this is a string";
         char   c = 'i';
         g.drawString(s,50,50);
         FontMetrics fm = getFontMetrics(g.getFont());
         int x = 50;
         for (int j=0; j < s.length(); j++)
              if (s.charAt(j) == c) g.setColor(getBackground());
                   else              g.setColor(getForeground());
              g.drawString(s.substring(j,j+1),x,100);
              x = x + fm.charWidth(s.charAt(j));
    public static void main(String[] args )
         new DrawS();
    Noah

  • Java Graphics -- Drawing Strings on JFrame

    Hello and thank you. I'm relatively young and I apologize for asking noob questions. The problem I am having is that I realized after 3 hours of research and then writing this code that when multiple JPanels are added to a JFrame, they overlap (I think) over each other. As a result, the output of this program below is at the bottom right of the frame, the number 841 appears (the last number in my array) and everything else is blank.
    And I could not at all understand how to create graphics objects. It kept giving me an error of not being able to be instantiated. And to be honest, I don't even really understand whats going on when I add the text to my JPanel. I never call paintComponents. And definately I could never even make a graphics object to provide it the parameter required. Anyway, I resolved to use Jpanels because they can be removed using the remove function of the JFrame. And It is vitally important that I can delete the strings off my frame. Here is my code:
    package main;
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    public class VisualFrame extends JFrame{
        ArrayList<JPanel> numbers = new ArrayList<JPanel>();
        public VisualFrame(){
            setSize(1000, 500);
            setTitle("Binary Search");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
        public void createPanels(int[] array){
            int x = 10;
            int y = 20;
            int xOffset = 50;
            int yOffset = 50;
            for(int i=0; i<array.length; i++){
                String num = Integer.toString(array);
    numPanel panel = new numPanel(num, x, y);
    numbers.add(panel);
    add(panel);
    x = x+xOffset;
    if(x>this.getWidth()){
    x = 10;
    y = y+yOffset;
    class numPanel extends JPanel{
    String num;
    int x;
    int y;
    public numPanel(String str, int x, int y){
    num = str;
    this.x = x;
    this.y = y;
    public void paintComponent(Graphics g){
    g.setColor(Color.black);
    g.setFont(new Font("Times", Font.BOLD, 12));
    g.drawString(num, x, y);
    My main method is inside of a different class:
        public static void main(String[] args){
            VisualFrame frame = new VisualFrame();
            frame.createPanels(array);
        }Firstly, do I even have the problem I'm having right? If so,
    Is there a way to restrict the size of the panels to the length and width of what it contains?
    Or can someone give me a good, very detailed link to how to use Graphics? Or perhaps someone could prove to me a good method.
    Edited by: 989946 on Mar 8, 2013 6:45 PM

    Why don't you start by learning from the experts?
    The Java Tutorial has sections that show how to use Java functionality.
    http://docs.oracle.com/javase/tutorial/
    The Graphiics section covers GUI and Swing
    http://docs.oracle.com/javase/tutorial/uiswing/index.html
    >
    Creating Graphical User Interfaces
    Creating a GUI with Swing — A comprehensive introduction to GUI creation on the Java platform.
    >
    And that section has links for trails such as how to use ALL of the different swing components including frames and panels
    http://docs.oracle.com/javase/tutorial/uiswing/components/index.html
    >
    Using Swing Components tells you how to use each of the Swing components — buttons, tables, text components, and all the rest. It also tells you how to use borders and icons.

  • Center aligned Text in image

    Hai,
    I urgently need help. I want to create a jpg image which is totally white in this white image i draw some multiple line text which i want to write in the center of image. I send the Text as string to my class through servlet file. The string has some newline charatcer also. So can anybody tell me how can i draw image with center aligend text.
    I use Graphics2D class for drawing and with fontMetrics to get the length of my message string. But it is not fitted in image and crossing the limit of my image.
    My white image size is not fix i m using different kind of size white image.
    Thanx in advance

    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class TextPanel extends JPanel
         public TextPanel(String text)
              setBackground( Color.WHITE );
              setBorder( new EmptyBorder(5, 5, 5, 5) );
              setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
              add( Box.createVerticalGlue() );
              StringTokenizer st = new StringTokenizer(text, "\r\n");
              while (st.hasMoreTokens())
                   JLabel line = new JLabel( st.nextToken() );
                   line.setFont( UIManager.getFont( "TextField.font" ) );
                   line.setAlignmentX(0.5f);
                   add( line );
              add( Box.createVerticalGlue() );
         public static void main(String[] args)
              String text =
                   "first line\n" +
                   "second line\n" +
                   "a line with more text\n" +
                   "another line";
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.getContentPane().add( new TextPanel( text ) );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • Creating hiding drawer component (suggestions)

    I am attempting to create a hiding drawer component. This is basically a tabbed frame on the side of the container that will allow you to show and hide it. I am able to get the component to show up but the catch is I need to know how to add components such as JList etc.. to it and have them function properly. When I attempt to add a component to it the painting is not working properly. I'm currently extending JPanel should I be using something else? Thanks for the help guys.
    Code is below:
    package com.nashilnux.swing;
    import java.awt.AlphaComposite;
    import java.awt.BasicStroke;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Composite;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import java.awt.Rectangle;
    import java.awt.RenderingHints;
    import java.awt.Stroke;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.font.FontRenderContext;
    import java.awt.font.TextLayout;
    import java.awt.geom.AffineTransform;
    import java.awt.geom.PathIterator;
    import java.awt.geom.Point2D;
    import java.awt.geom.Rectangle2D;
    import java.awt.geom.RoundRectangle2D;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.RepaintManager;
    import javax.swing.text.AbstractDocument.Content;
    * @author me
    public class HidingDrawer extends JPanel
         Rectangle2D button = null;
         private boolean showing = false;
         private JList contentList = null;
         private String title = "";
         private boolean mouseOver = false;
         private JScrollPane listSP = null;
         private Color strokeColor = new Color(226, 242, 255);
         private Color backgroundColor = Color.white;
         private Color tabColor = new Color(226, 242, 255);
         private boolean transparent = false;
         private float transparencyLevel = 0.0f;
         private Dimension expandedDimension = new Dimension(300,200);
         public HidingDrawer()
              setOpaque(false);
              setPreferredSize(new Dimension(300, 200));
              addMouseListener(new MouseAdapter()
                   @Override
                   public void mousePressed(MouseEvent e)
                        hideDrawer(e);
         public HidingDrawer(boolean showDrawer)
              setOpaque(false);
              setPreferredSize(new Dimension(300, 200));
              setLayout(new FlowLayout());
              if (showDrawer)
                   showing = false;
              else
                   showing = true;
              addMouseListener(new MouseAdapter()
                   @Override
                   public void mousePressed(MouseEvent e)
                        hideDrawer(e);
                   @Override
                   public void mouseEntered(MouseEvent e)
                        if (button != null)
                             if (button.contains(new Point2D.Double(e.getX(), e.getY())))
                                  System.out.println("Mouse Over");
                                  mouseOver = true;
                                  repaint();
                   @Override
                   public void mouseExited(MouseEvent e)
                        System.out.println("Mouse exited");
                        mouseOver = false;
                        repaint();
              initalize();
          * @param args
         public static void main(String[] args)
              JFrame frame = new JFrame();
              frame.getContentPane().setBackground(Color.LIGHT_GRAY);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setTitle("UI Drawer Demo");
              // North Panel
              JPanel northPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
              northPanel.setBackground(Color.white);
              JLabel titleLbl = new JLabel("UI Drawer Demo");
              titleLbl.setFont(new Font("Helvectia", Font.BOLD, 18));
              northPanel.add(titleLbl);
              // End NorthPanel
              // West panel component
              HidingDrawer hd = new HidingDrawer(true);
              hd.setTitle("Testing");
              hd.setBackgroundColor(new Color(226, 242, 255));
              hd.setStrokeColor(Color.black);
              hd.setTransparent(true);
              hd.setTransparencyLevel(0.5f);
              frame.getContentPane().setBackground(hd.getBackgroundColor());
              // Add list to the drawer
    //          String[] values = new String[]{"Testing", "Testing 2", "Testing 3"};
    //          JList list = new JList(values);
    //          hd.add(list, BorderLayout.CENTER);
              frame.getContentPane().add(hd, BorderLayout.WEST);
              // Center Panel
              JPanel encapPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
              encapPanel.setBackground(hd.getBackgroundColor());
              JPanel centerPanel = new JPanel();
              centerPanel.setBackground(hd.getBackgroundColor());
              GridBagLayout gLayout = new GridBagLayout();
              int row = 0;
              centerPanel.setLayout(gLayout);
              GridBagConstraints c = new GridBagConstraints(0, 0,1,1,0, 0,GridBagConstraints.WEST,0, new Insets(5,5,5,5),0,0);
              JLabel freqLbl = new JLabel("Frequency");
              centerPanel.add(freqLbl, c);
              c.gridx = 1;
              JTextField freqTxt = new  JTextField(20);
              centerPanel.add(freqTxt, c);
              encapPanel.add(centerPanel);
              frame.getContentPane().add(northPanel, BorderLayout.NORTH);
              frame.getContentPane().add(encapPanel, BorderLayout.CENTER);
              frame.setSize(new Dimension(800, 600));
              frame.setVisible(true);
         public void initalize()
    //          String[] tmpListItems = { "Testing list item 1", "Testing 2", "Testing 3" };
    //          contentList = new JList(tmpListItems);
    //          contentList.setOpaque(true);
    //          contentList.setBackground(getBackgroundColor());
    //          Dimension dim = getPreferredSize();
    //          dim.setSize(dim.getWidth() - 70, dim.getHeight());
    //          listSP = new JScrollPane(contentList);
    //          listSP.setPreferredSize(dim);
    //          listSP.setOpaque(true);
    //          listSP.setBackground(getBackgroundColor());
    //          add(listSP);
              setBackground(getBackgroundColor());
              setBorder(BorderFactory.createLineBorder(Color.black));
          * (non-Javadoc)
          * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
         @Override
         protected void paintComponent(Graphics g)
              Dimension dim = getSize();
              Graphics2D g2d = (Graphics2D) g;
              if (!isShowing())
                   System.out.println("Showing: " + showing);
                   g2d.setPaint(getBackgroundColor());
                   RoundRectangle2D roundRectangle = new RoundRectangle2D.Double(getX() - 10, getY() + 5, dim.width - 20, dim.height - 10, 5, 15);
                   g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                   if(isTransparent())
                        Composite alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getTransparencyLevel());
                        g2d.setComposite(alphaComp);
                   g2d.fill(roundRectangle);
                   BasicStroke stroke = new BasicStroke(3);
                   g2d.setStroke(stroke);
                   g2d.setPaint(getStrokeColor());
                   g2d.draw(roundRectangle);
                   // Draw a fake button
                   // Get the dimension of the current graphic
                   Graphics2D buttonArea = (Graphics2D) g2d.create(getX(), getY(), dim.width, dim.height);
                   buttonArea.setColor(getTabColor());
                   buttonArea.setFont(new Font("Helvetica", Font.BOLD, 16));
                   button = null;
                   button = new Rectangle2D.Double(roundRectangle.getBounds().getMaxX(), (roundRectangle.getMaxY() / 2) - 30, 25, 60);
                   buttonArea.fill(button);
                   buttonArea.draw(button);
                   // Draw the text
                   buttonArea.setStroke(new BasicStroke(3));
                   buttonArea.setPaint(getStrokeColor());
                   buttonArea.draw(button);
                   buttonArea.setClip(button);
                   buttonArea.setPaint(Color.black);
                   AffineTransform transformer = buttonArea.getTransform();
                   transformer.rotate(Math.toRadians(90));
                   buttonArea.transform(transformer);
                   Rectangle2D buttonBounds = button.getBounds2D();
                   Font buttonFont = new Font("Helvectica", Font.BOLD, 18);
                   FontRenderContext frc = buttonArea.getFontRenderContext();
                   TextLayout layout = new TextLayout("Hide", buttonFont, frc);
                   layout.draw(buttonArea, (float)buttonBounds.getY() + 10,(float)((buttonBounds.getX() - (buttonBounds.getX() *2)) -5));
              else
                   System.out.println("Showing: " + showing);
                   Graphics2D buttonArea = (Graphics2D) g2d.create(getX(), getY(), dim.width, dim.height);
                   buttonArea.setPaint(getTabColor());
                   button = null;
                   button = new Rectangle2D.Double(0, (dim.getHeight() / 2) - 30, 25, 60);
                   if (isTransparent())
                        // Set the Composite
                        Composite alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getTransparencyLevel());
                        buttonArea.setComposite(alphaComp);
                   buttonArea.fill(button);
                   buttonArea.setStroke(new BasicStroke(3));
                   buttonArea.setPaint(getStrokeColor());
                   buttonArea.draw(button);
              super.paintComponents(g);
         public void hideDrawer(MouseEvent event)
              if (button != null)
                   if (button.contains(new Point2D.Double(event.getX(), event.getY())))
                        System.out.println("Button Pressed");
                        if (showing)
                             showing = false;
                             setPreferredSize(new Dimension(300, getSize().height));
                             setSize(new Dimension(300, getSize().height));
                             setVisible(true);
                             // Hide the list
    //                         contentList.setVisible(true);
    //                         listSP.setVisible(true);
                        else
                             showing = true;
                             setSize(28, getSize().height);
    //                         contentList.setVisible(false);
    //                         listSP.setVisible(false);
              Object parent = getParent();
              boolean foundParent = false;
              while (!foundParent)
                   Component parentsChild = (Component) parent;
                   Component fParent = ((Component) parent).getParent();
                   if (fParent == null)
                        foundParent = true;
                        parent = parentsChild;
                   else
                        parent = fParent;
              Component pComponent = (Component) parent;
              pComponent.repaint();
          * @param showing
          *            the showing to set
         public void showDrawer(boolean showing)
              this.showing = showing;
          * @return the showing
         public boolean isShowing()
              return showing;
          * @param title
          *            the title to set
         public void setTitle(String title)
              this.title = title;
          * @return the title
         public String getTitle()
              return title;
          * @param strokeColor
          *            the strokeColor to set
         public void setStrokeColor(Color strokeColor)
              this.strokeColor = strokeColor;
          * @return the strokeColor
         public Color getStrokeColor()
              return strokeColor;
          * @param backgroundColor
          *            the backgroundColor to set
         public void setBackgroundColor(Color backgroundColor)
              this.backgroundColor = backgroundColor;
          * @return the backgroundColor
         public Color getBackgroundColor()
              return backgroundColor;
          * @param tabColor
          *            the tabColor to set
         public void setTabColor(Color tabColor)
              this.tabColor = tabColor;
          * @return the tabColor
         public Color getTabColor()
              return tabColor;
          * @param transparent the transparent to set
         public void setTransparent(boolean transparent)
              this.transparent = transparent;
          * @return the transparent
         public boolean isTransparent()
              return transparent;
          * @param transparencyLevel the transparencyLevel to set
         public void setTransparencyLevel(float transparencyLevel)
              this.transparencyLevel = transparencyLevel;
          * @return the transparencyLevel
         public float getTransparencyLevel()
              return transparencyLevel;
    }

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class HD {
        TopCard    topCard;
        HostCard   hostCard;
        CardLayout cards;
        JPanel     cardPanel;
        private JPanel getContent() {
            Color stroke = UIManager.getColor("TabbedPane.foreground");
            Color bg     = UIManager.getColor("TabbedPane.background");
            Color tab    = UIManager.getColor("TabbedPane.contentAreaColor");
            Font font = //new Font("Helvetica", Font.BOLD, 18);
                        new Font("Dialog", Font.BOLD, 18);  // faster
            Dimension d = new Dimension(300,200);
            topCard = new TopCard(stroke, bg, tab, font, d);
            topCard.addMouseListener(mouser);
            hostCard = new HostCard(stroke, bg, tab, font, d);
            hostCard.addMouseListener(mouser);
            addComponents(hostCard);
            cards = new CardLayout();
            cardPanel = new JPanel(cards);
            cardPanel.add("top", topCard);
            cardPanel.add("host", hostCard);
            return cardPanel;
        private void addComponents(JComponent c) {
            String[] tmpListItems = { "Testing list item 1", "Testing 2", "Testing 3" };
            JList list = new JList(tmpListItems);
            int vm = hostCard.MARGIN;
            int right = 35;
            Dimension dim = c.getPreferredSize();
            dim.setSize(dim.width - 70, dim.height - 2*vm - 2*20);
            JScrollPane scrollPane = new JScrollPane(list);
            scrollPane.setPreferredSize(dim);
            c.setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(vm,0,vm,right);
            c.add(scrollPane, gbc);
        public static void main(String[] args) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new HD().getContent());
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        private MouseListener mouser = new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                Object source = e.getSource();
                Point p = e.getPoint();
                if(source == topCard)
                    if(topCard.isControlTrigger(p))
                        cards.next(cardPanel);
                if(source == hostCard)
                    if(hostCard.isControlTrigger(p))
                        cards.next(cardPanel);
    class TopCard extends JPanel {
        Rectangle2D.Double rect;
        Color strokeColor;
        Color backgroundColor;
        Color tabColor;
        Font font;
        public TopCard(Color stroke, Color bg, Color tab, Font f, Dimension d) {
            strokeColor = stroke;
            backgroundColor = bg;
            tabColor = tab;
            font = f;
            setPreferredSize(d);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            Dimension dim = getSize();
            g2.setPaint(Color.lightGray);
            g2.fillRect(0, 0, dim.width, dim.height);
            g2.setPaint(tabColor);
            rect = new Rectangle2D.Double(0, (dim.getHeight() / 2) - 30, 25, 60);
            g2.fill(rect);
            g2.setStroke(new BasicStroke(3));
            g2.setPaint(strokeColor);
            g2.draw(rect);
            // Draw label text.
            String s = "Show";
            g2.setFont(font);
            FontRenderContext frc = g2.getFontRenderContext();
            float width = (float)font.getStringBounds(s, frc).getWidth();
            LineMetrics lm = font.getLineMetrics(s, frc);
            float height = lm.getAscent() + lm.getDescent();
            double x = rect.getCenterX() - height/2 + lm.getDescent();
            double y = rect.getCenterY() - width/2;
            AffineTransform at = AffineTransform.getTranslateInstance(x, y);
            at.rotate(Math.PI/2, 0, 0);
            g2.setFont(font.deriveFont(at));
            g2.drawString(s, 0, 0);
        public boolean isControlTrigger(Point p) {
            return rect.contains(p);
    class HostCard extends JPanel {
        Rectangle2D.Double rect;
        Color strokeColor;
        Color backgroundColor;
        Color tabColor;
        Font font;
        int MARGIN = 5;
        public HostCard(Color stroke, Color bg, Color tab, Font f, Dimension d) {
            strokeColor = stroke;
            backgroundColor = bg;
            tabColor = tab;
            font = f;
            setPreferredSize(d);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            Dimension dim = getSize();
            g2.setPaint(Color.lightGray);
            g2.fillRect(0, 0, dim.width, dim.height);
            BasicStroke stroke = new BasicStroke(3);
            float lineWidth = stroke.getLineWidth();
            double x = getX() - MARGIN - lineWidth;
            double y = getY() + MARGIN;
            double w = dim.width - 20;
            double h = dim.height - 2*MARGIN - lineWidth/2;
            RoundRectangle2D roundRectangle =
                                 new RoundRectangle2D.Double(x, y, w, h, 5, 15);
            g2.setPaint(backgroundColor);
            g2.fill(roundRectangle);
            g2.setStroke(stroke);
            g2.setPaint(strokeColor);
            g2.draw(roundRectangle);
            rect = new Rectangle2D.Double(roundRectangle.getBounds().getMaxX(),
                                         (roundRectangle.getMaxY() / 2) - 30, 25, 60);
            g2.setPaint(tabColor);
            g2.fill(rect);
            g2.setPaint(strokeColor);
            g2.draw(rect);
            g2.setPaint(Color.black);
            // Draw label text.
            String s = "Hide";
            g2.setFont(font);
            FontRenderContext frc = g2.getFontRenderContext();
            float width = (float)font.getStringBounds(s, frc).getWidth();
            LineMetrics lm = font.getLineMetrics(s, frc);
            float height = lm.getAscent() + lm.getDescent();
            x = rect.getCenterX() - height/2 + lm.getDescent();
            y = rect.getCenterY() - width/2;
            AffineTransform at = AffineTransform.getTranslateInstance(x, y);
            at.rotate(Math.PI/2, 0, 0);
            g2.setFont(font.deriveFont(at));
            g2.drawString(s, 0, 0);
        public boolean isControlTrigger(Point p) {
            return rect.contains(p);
    }

  • Drawing a rectangle using a mouse

    Need a simple application that demostrates the use of the mouse on an application window. All that I require is that a user can draw a rectangle by dragging the mouse on the application window. The upper left coordinate should be the location where the user presses the mouse button and the lower right should be where the user releases the mouse button. Should also display the area of the rectangle in a JLabel in the SOUTH region of a BorderLayout.
    Thanks

    How is this:
    import java.awt.event.*;  
    import java.awt.*;
    import javax.swing.*;
    public class DrawR extends JFrame
         JLabel label = new JLabel();
    public DrawR()
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);
         setBounds(50,50,450,400);
         getContentPane().setLayout(new BorderLayout());
         Draw draw = new Draw();     
         getContentPane().add("Center",draw);
         getContentPane().add("South",label);
        setVisible(true);     
    public class Draw extends JPanel
         Rectangle r = null;
    public Draw()
         addMouseListener(new MouseAdapter()     
         {     public void mousePressed(MouseEvent m)
                    r = new Rectangle(m.getX(),m.getY(),1,1);
              public void mouseReleased(MouseEvent m)
         addMouseMotionListener(new MouseMotionAdapter()          
         {     public void mouseDragged(MouseEvent m)
                   r.width  = m.getX() - r.x;
                   r.height = m.getY() - r.y;
                   repaint();
                   label.setText("   "+r);
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         if (r != null) ((Graphics2D)g).draw(r);
    public static void main(String[] args )
         new DrawR();
    Noah
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class DrawR extends JFrame
         JLabel label = new JLabel();
    public DrawR()
         addWindowListener(new WindowAdapter()
    {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);
         setBounds(50,50,450,400);
         getContentPane().setLayout(new BorderLayout());
         Draw draw = new Draw();     
         getContentPane().add("Center",draw);
         getContentPane().add("South",label);
    setVisible(true);     
    public class Draw extends JPanel
         Rectangle r = null;
    public Draw()
         addMouseListener(new MouseAdapter()     
         {     public void mousePressed(MouseEvent m)
                   r = new Rectangle(m.getX(),m.getY(),1,1);
              public void mouseReleased(MouseEvent m)
         addMouseMotionListener(new MouseMotionAdapter()          
         {     public void mouseDragged(MouseEvent m)
                   r.width = m.getX() - r.x;
                   r.height = m.getY() - r.y;
                   repaint();
                   label.setText(" "+r);
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         if (r != null) ((Graphics2D)g).draw(r);
    public static void main(String[] args )
         new DrawR();
    }

  • Length of a string (text) in pixels.

    I'm trying to locate a String's center on an exact position, drawing it to a JPanel. But since i don't know the exact length of the string, it's not that easy. Can anybody help me out there?

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class CenteringStrings
        public static void main(String[] args)
            StringDemoPanel demo = new StringDemoPanel();
            DemoActionPanel action = new DemoActionPanel(demo);
            JFrame f = new JFrame("Centering Strings");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(action, "East");
            f.getContentPane().add(demo);
            f.setSize(500,300);
            f.setLocation(200,200);
            f.setVisible(true);
    class StringDemoPanel extends JPanel
        String text;
        Font font;
        final int
            ASCENT   = 0,
            DESCENT  = 1,
            LEADING  = 2,
            BASELINE = 3;
        int index = -1;
        boolean sizeFlag, boundsFlag;
        public StringDemoPanel()
            text = "Centered text";
            font = new Font("lucida sans oblique", Font.PLAIN, 36);
            sizeFlag = false;
            boundsFlag = false;
            setBackground(Color.white);
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setFont(font);
            FontRenderContext frc = g2.getFontRenderContext();
            LineMetrics lm = font.getLineMetrics(text, frc);
            TextLayout tl = new TextLayout(text, font, frc);
            int w = getWidth();
            int h = getHeight();
            float textWidth = (float)font.getStringBounds(text, frc).getWidth();
            float ascent  = lm.getAscent();
            float descent = lm.getDescent();
            float leading = lm.getLeading();
            float height  = lm.getHeight();
            float x = (w - textWidth)/2;
            float y = (h + height)/2 - descent;
            g2.drawString(text, x, y);
            // marker for string origin (x,y) on baseline
            //g2.setPaint(Color.blue);
            //g2.fill(new Ellipse2D.Double(x - 1, y - 1, 2, 2));
            // physical space of text
            Rectangle2D textSize = tl.getBounds();
            textSize.setFrame(x, y - textSize.getHeight(),
                              textSize.getWidth(), textSize.getHeight());
            // string bounds
            Rectangle2D bounds = font.getStringBounds(text, frc);
            bounds.setFrame(x, y - ascent - leading, bounds.getWidth(), bounds.getHeight());
            switch(index)
                case ASCENT:
                    Rectangle2D r1 = new Rectangle2D.Double(x, y - ascent, textWidth, ascent);
                    g2.setPaint(Color.magenta);
                    g2.draw(r1);
                    break;
                case DESCENT:
                    Rectangle2D r2 = new Rectangle2D.Double(x , y, textWidth, descent);
                    g2.setPaint(Color.orange);
                    g2.draw(r2);
                    break;
                case LEADING:
                    Rectangle2D r3 = new Rectangle2D.Double(x, y - ascent - leading,
                                                            textWidth, leading);
                    g2.setPaint(Color.yellow);
                    g2.draw(r3);
                    break;
                case BASELINE:
                    Line2D line = new Line2D.Double(x, y, x + textWidth, y);
                    g2.setPaint(Color.blue);
                    g2.draw(line);
            if(sizeFlag)
                g2.setPaint(Color.green);
                g2.draw(textSize);
                System.out.println("above size = " + (int)textSize.getY() + "\n" +
                                   "below size = " +
                                   (int)(h - (textSize.getY() + textSize.getHeight())));
            if(boundsFlag)
                g2.setPaint(Color.red);
                g2.draw(bounds);
                System.out.println("above bounds = " + (int)bounds.getY() + "\n" +
                                   "below bounds = " +
                                   (int)(h - (bounds.getY() + bounds.getHeight())));
        public void setIndex(int i)
            index = i;
            repaint();
        public void setSizeFlag(boolean flag)
            sizeFlag = flag;
            repaint();
        public void setBoundsFlag(boolean flag)
            boundsFlag = flag;
            repaint();
    class DemoActionPanel extends JPanel
        StringDemoPanel sdp;
        JRadioButton
            ascentButton, descentButton, leadingButton, baselineButton, clearButton;
        JRadioButton[] buttons;
        JCheckBox
            sizeCheck, boundsCheck;
        JCheckBox[] checks;
        public DemoActionPanel(StringDemoPanel p)
            sdp = p;
            createComponents();
        private void createComponents()
            ascentButton   = new JRadioButton("ascent");
            descentButton  = new JRadioButton("descent");
            leadingButton  = new JRadioButton("leading");
            baselineButton = new JRadioButton("baseline");
            clearButton    = new JRadioButton("clear");
            buttons = new JRadioButton[] {
                ascentButton, descentButton, leadingButton, baselineButton, clearButton
            ButtonGroup group = new ButtonGroup();
            RadioButtonListener buttonListener = new RadioButtonListener();
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weighty = 1.0;
            gbc.insets = new Insets(2,2,2,2);
            gbc.gridwidth = gbc.REMAINDER;
            gbc.anchor = gbc.WEST;
            for(int i = 0; i < buttons.length; i++)
                add(buttons, gbc);
    group.add(buttons[i]);
    buttons[i].addActionListener(buttonListener);
    sizeCheck = new JCheckBox("text size");
    boundsCheck = new JCheckBox("bounds");
    checks = new JCheckBox[] { sizeCheck, boundsCheck };
    CheckBoxListener checkBoxListener = new CheckBoxListener();
    for(int i = 0; i < checks.length; i++)
    add(checks[i], gbc);
    checks[i].addActionListener(checkBoxListener);
    private class RadioButtonListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    JRadioButton button = (JRadioButton)e.getSource();
    if(button == clearButton)
    sdp.setIndex(-1);
    return;
    for(int i = 0; i < buttons.length; i++)
    if(button == buttons[i])
    sdp.setIndex(i);
    break;
    private class CheckBoxListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    JCheckBox checkBox = (JCheckBox)e.getSource();
    if(checkBox == sizeCheck)
    sdp.setSizeFlag(sizeCheck.isSelected());
    if(checkBox == boundsCheck)
    sdp.setBoundsFlag(boundsCheck.isSelected());

  • Drawing rotated text revisited.....

    Hello again,
    I've recently started fiddling with an app that had a method to draw Strings at given Points on a custom JComponent, now I'm trying to extend it to draw the same strings, but throw in an angle should the user choose to do so. But... now here's the part thats foxing me, I want the Point specified to be the center of the String....., i've had a couple of goes, but as soon as the rotation comes in, it goes pair shaped (not literally ;-) , metaphorically).
    Here's some of the code I'm working on, feel free to point bad coding and glaringly obvious problems! I'm aware it doesn't quite do "exactly what it says on the tin", but its definitely a step in the right direction. It should work, but it doesn't. Thoughts anyone?
    /** Method to draw a text label to a specified graphics context.
         @param g2 The graphics context to draw to.
         @param text The label text to draw.
         @param font The font in which to draw the label.
         @param color The color of the label.
         @param angle The angle at which to draw , 0 = horizontal, 90 = vertical.
         @param position The Point at which to draw the label.*/
    public static void drawLabel(Graphics2D g2, String text, Font font, Color color, int angle, Point position)
    //get x,y coordinates from Point
    int x = new Double(position.getX()).intValue();
    int y = new Double(position.getY()).intValue();
    //rotate the point by the required angle
    x = (new Double((x*Math.cos(Math.toRadians(angle)))-(y*Math.sin(Math.toRadians(angle)))).intValue());
    y = (new Double((-x*Math.sin(Math.toRadians(angle)))+(y*Math.cos(Math.toRadians(angle)))).intValue());
    // get the current transform
    AffineTransform startMatrix = g2.getTransform();
    // make a new one...
    AffineTransform rotationMatrix = new AffineTransform();
    // set the text layout
    TextLayout tl = new TextLayout(text,font,g2.getFontRenderContext());
    // rotate the shiny new transform
    rotationMatrix.rotate(Math.toRadians(angle));
    // appy it to g2
    g2.transform(rotationMatrix);
    //set the color of the label
    g2.setPaint(color);
    //draw the label
    tl.draw(g2,x,y);
    //restore the transform for g2
    g2.setTransform(startMatrix);
    }Also I haven't sorted the drawing relative to the center of the string bit yet, so any advice on how to do this would be great.
    Cheers,
    Tom

    This is straightforward, once you understand transforms. I'm surprised no one's answered this yet. Here's an example:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    public class TestRotate extends Frame {
        public static void main(String[] args) {
            new TestRotate().setVisible(true);
        private TestRotate() {
            super("Rotated Text");
            addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        System.exit(0);
            setFont(new Font("default", Font.PLAIN, 24));
            setSize(300, 300);
        public void paint(Graphics g) {
            Graphics2D g2d = (Graphics2D)g;
            TextLayout layout = new TextLayout(
                "This is a string to rotate",
                g2d.getFont(),
                g2d.getFontRenderContext());
            Insets ins = getInsets();
            Dimension dim = getSize();
            Point center = new Point(
                ins.left + (dim.width - ins.left - ins.right) / 2,
                ins.top + (dim.height - ins.top - ins.bottom) / 2);
            g2d.translate(center.x, center.y);
            g2d.rotate(Math.PI / 4);
            layout.draw(g2d, -layout.getAdvance() / 2, 0);

  • How to open a Cash Drawer in AS3? NEED ANSWER ASAP!!!

    Is it in anyway possible to open a cash drawer in actionscript 3 (Flash CS5) that is connected to a receipt printer. NEED ANSWERS ASAP!

    You're right ! But my printer is connected via the ethernet port and i need to use the print API to communicate with it. In ActionScript nothing works I tried to send the escape sequence that should open the drawer : String.fromCharCode(27)+String.fromCharCode(112)+String.fromCharCode(48)+String.fromCharC ode(53)+String.fromCharCode(53) ... it didn't work.
    So i decided to call a little Java program (JAR) through the Air NativeProcess API. This program send the escape sequence to the printer using Java print API.
    Thx for the answer

  • Center text in JTextPane

    I need to center certain text in the JTextPanel
    public InfoDialog{
        private JTextPane textpane;
        private void append(AttributeSet attr, String text){
         try {
              DefaultStyledDocument doc = (DefaultStyledDocument) textpane.getStyledDocument();
                 // Create a style object and then set the style attributes
                    string styleName = (style == PARAGRAPH_HEADER)? "PARAGRAPH_HEADER": "PLAIN_TEXT";
                 doc.addStyle(styleName, null);
                 int b4InsertLength = doc.getLength();
                 doc.insertString(doc.getLength(), text, style);
                 doc.setParagraphAttributes(b4InsertLength, text.length(), style, true);  // tried with false param..but still doesn't work
                 //doc.insertString(b4InsertLength, text, style);
              catch (BadLocationException e) {}               
        pubilc void appendHeader(String text){
         append(PARAGRAPH_HEADER, text);
        public void appendText(AttributeSet set, String text){
            append(set, text);
        public void appendText(String text){
            append(PLAIN_TEXT, text);
        public void initAttributeSet(){
         PARAGRAPH_HEADER = new SimpleAttributeSet();
         PARAGRAPH_HEADER.addAttribute("AttrType", "PARAGRAPH_HEADER");
            StyleConstants.setItalic(PARAGRAPH_HEADER, false);
            StyleConstants.setBold(PARAGRAPH_HEADER, true);
            StyleConstants.setUnderline(PARAGRAPH_HEADER, true);
            StyleConstants.setFontFamily(PARAGRAPH_HEADER, "SansSerif");
            StyleConstants.setFontSize(PARAGRAPH_HEADER, 14);
            StyleConstants.setBackground(PARAGRAPH_HEADER, Color.white);
            StyleConstants.setForeground(PARAGRAPH_HEADER, Color.blue);
            StyleConstants.setAlignment(PARAGRAPH_HEADER, StyleConstants.ALIGN_CENTER);
         // other attribute set get set here too
    }I've seen example, but they center the text for all text in the document. i just wanted to center certain text.

    my fault. i should have figure it out.
    It is centering the specified text.
    I thought it didn't because i didn't see the text in the center
    infoDialog.appendHeader("Title");   // use the fontmetric of the "Title" string and center the "title" string on that length (duh!)
    should have been
    infoDialog.appendHeader("\nTitle\n");  // this will use the font metric of the width of the textpane and center the text

  • Width of String

    Hi All,
    I need to use graphics to draw String. How can I know the physical width of a string(not the length of a string)?
    It is highly appreciated that anyone can answer me. Thanks!

    String s = "What is the width of this string";
    FontMetrics fm = getFontMetrics(g.getFont());
    int w = fm.stringWidth(s);
    Noah

  • Remove leading zeros from string

    I am working on a report and I am having a little issue with the output.
    I have several dollar amount fields that I need to format with only the decimal place. The amount fields are coming in as strings between 10-16 characters.
    I could not find a way to use the currency formatter so I used substrings to break it apart and put it back together in the format I need. However I am now running into an issue with leading zeros. I can't used ReplaceAll as there is a possibility of having a 0 in the amount field.
    Here is what I have done for the substrings:
    int intLength = strField.length();
    intDollar = intLength - 2;          
    strDollar = strField.substring(1, intDollar);
    strCent = strField.substring(intDollar, intLength);
    System.out.println(strDollar + "." + strCent);The original string: 0000000037049469
    My output now: 00000000370494.69
    Desired output: 37049469
    Any suggestions on how to remove the leading zeros?
    Edited by: xxwhocaresxx on Jun 10, 2009 12:11 PM

    804350 wrote:
    Just wanted to comment that I solved the issue differently by casting the string value to an integer and back. Don't know if it's bad solution performancewiseNever, ever, ever, ever, ever, ever, ever worry about performance. At least not until you're much further along the road; and even then not until you've proved that it's inadequate.
    but it's quite compact and readable and did the job of eliminating leading zeros.I suspect you'll also find that it has the great advantage of providing you with a dollar (or cent) value that you can use elsewhere in your program the way it was intended.
    example:
    String noZeros = String.valueOf(Integer.parseInt(stringWithZeros));Or possibly even more usefully:
    int cents = Integer.parseInt(stringWithZeros);
    String noZeros = String.valueOf(cents);I'd also suggest looking up the NumberFormat and DecimalFormat classes, and PrintStream.printf(); all very useful for what you're trying to do.
    Winston

Maybe you are looking for

  • I need a replacement HD audio driver other than the IDT/Beats hunka junk.

    Anyone out there know if its alright to install a HD audio driver (brandwise) other than the one that came pre loaded on my HP Dv6 A8 windows7 x64? Hp apparently has IDT by the short hairs, not letting anything get out without being overprocessed, co

  • List of security scans in EarlyWatch

    Is it possible to see tech details for all security checks performed by Solution Manager?   For example, EWA may list a problem with Spool security, indicating that a large# of people can view another's spool requests.  Are these checks contained in

  • MARS drop rules problem

    Hi All, we were receiving lots of false positive, so I've created drop rules in MARS. still it is generating incident, but I am sure drop rule should cover based on source/dest and port number. I've activated, rebooted, but still the same issue. any

  • C7, can't get rid of "call forwarding enabled" mes...

    It appears always and is terribly annoying, because it prevents from stopping a call if for example a wrong number has been dialed. It tells me some like "Attention. Call forwarding enabled.". It is probably because of operators voice mail service re

  • VXML Problem

    Hi All, I have a problem with my vxml inside my TCL script. By the way i'm using the TCL2.0 script. The problem is vxml process change my output to another value. Example : .Jan 17 13:15:25.185: <var>: namep=aniNo1 expr=0122222222 .Jan 17 13:15:25.18