tags:

views:

373

answers:

3

Consider that I have written "File" at the top left corner and then how can I add a button at the top right corner?

public class FileViewer extends JPanel
{
    private static final long serialVersionUID = 1L;

    public void paintComponent(Graphics g)
    {
        Graphics2D graphic = (Graphics2D)g;
        graphic.drawString("HTML File:", 14, 15);
    }
}
+1  A: 

I'm going to go out on a limb here and assume you're talking about positioning with Swing (or SWT for that matter).

To position elements intelligently, you need your container (window, panel, whatever) to have a layout manager. The layout manager is responsible for position the child controls within a container.

For example, the Java tutorials here show how to use the many standard layout managers that ship with Java. There are also some that don't ship with Java. Of particular interest is SWT which has a more platform-native look and feel.

Update:

I see by your added stuff I was totally off-base, since you're just looking for a way to write text to a graphics handle in paintComponent.

You already have part of the answer: you've used Graphics2D.drawString(String,x,y) where the x and y specify the location to draw at.

What you need to do is change x and y to draw in the top-right corner. Actually, it's only x that needs to change.

This is where it gets tricky. You have to calculate y depending on the size of your workspace and the size of your text string.

I don't know the specifics for Java since I've never done graphic output but it's likely that:

  • there's a method you can call on graphic to return the available paint rectangle; this will get you the maximum y value.
  • you'll need to pass the string into another method to get the width required for it (based on font information).

Once you have both of those, simply subtract the second from the first and you should have a starting y value to enable the string to finish in the top right corner.

paxdiablo
@pax: limb broke :-)
Stephen C
Yeah, I'll just dust myself off and move along (trying to look dignified). :-)
paxdiablo
+7  A: 
OscarRyz
A: 

You can add a button in the constructor using the add() method. you might want to set the alignment to right so that the button is drawn to the right

The paint method is generally not used to add UI controls on screen.

Having said this, i would like you to read the comments posted by others on the way you have framed your question to us.

Salvin Francis