Include Graphics2D in JComponent

Hi,
I have created a class extends JComponent.
how can i set the component graphics?
Help needed. Thanks

Hello,
a small example to illustrate how to drawImage
PS: You dont need the MediTracker for one image,
but if you load many images or you must know exactly when an images is loaded use it.class MainPanel extends JPanel
     private Toolkit tool = Toolkit.getDefaultToolkit();
     private MediaTracker media = new MediaTracker(this);
     private Image background = tool.getImage(imagePathAsString);
     MainPanel()
          super();
          media.addImage(background, 0);
          try
          {     //wait to calcute sizes correctly
               media.waitForID(0);
          }catch (InterruptedException e){}
     public void paintComponent(Graphics g)
          super.paintComponent(g);
          g.drawImage(background, 0, 0, this);
     public Dimension getPreferredSize()
          return new Dimension(background.getWidth(this), background.getHeight(this));
}regards,
Tim

Similar Messages

  • Help Please - Landscape Printing in JDK1.3

    Iam trying to print a line of text of 160 chars wide in landscape
    format. The ImageableWidth and ImageableHeight are 792 and 612
    respectively. The ImageableX and ImageableY are both 72(1 inch).
    Font -> ("Courier", Font.PLAIN, 7),
    noOfChars/line -> 162 for the Imageable area 792 x 612
    But after printing I could see the line starting after 2 inches
    as Right Margin, because of which, I'm not able to print the
    complete 160 char line.
    I set the value posX=0 to start after 1 inch, but still the printing
    starts only after 2 inches but initial few chars are eaten.
    when posX = 72
    <- 2" R Margin ->0123456789 0123456789 .... 154th char
    when posX = 0
    <- 2" R Margin ->56789 0123456789 ....... 160th char
    please help.
    lenin.
    import java.util.*;
    import java.awt.*;
    import java.awt.print.*;
    public class Printer implements Printable {
         public int print(Graphics g, PageFormat format, int pageIndex) {
         String content = "0123456789 0123456789 0123456789 " +
              "0123456789 0123456789 0123456789 " +
              "0123456789 0123456789 0123456789 " +
              "0123456789 0123456789 0123456789 " +
              "0123456789 0123456789 0123456789 012345";
         int totalWidth = (int) format.getImageableWidth();
         int totalHeight = (int) format.getImageableHeight();
         System.out.println("ImageableWidth : " + totalWidth);
         System.out.println("ImageableHeight : " + totalHeight);
         int posX = (int) (format.getImageableX());
         int posY = (int) (format.getImageableY());
         posY += 20;
         System.out.println("PosX : " + posX);
         System.out.println("PosY : " + posY);          
         pageIndex++;
         FontMetrics fontMetrics =
    g.getFontMetrics(new Font("Courier", Font.PLAIN, 7));
         int charWidth = fontMetrics.stringWidth("W");
         int charHeight = fontMetrics.getHeight() + 1;
         int noOfLines = Math.round(totalHeight / charHeight);
         int noOfCharsPerLine = Math.round(totalWidth / charWidth);
         System.out.println("No Of Lines : " + noOfLines);
         System.out.println("No Of Char/Line : " + noOfCharsPerLine);
         if (pageIndex > 0) {
         g.setFont(new Font("Courier", Font.PLAIN, 7));
         g.drawString(content, posX, posY);
         return 0;          
         public static void main(String args[]) {
              Printer myPrinter = new Printer();
              PrinterJob job = PrinterJob.getPrinterJob();
              PageFormat pageFormat = job.defaultPage();
              pageFormat.setOrientation(PageFormat.LANDSCAPE);
              Book book = new Book();          
              book.append(myPrinter,pageFormat);          
              job.setPageable(book);
              if (job.printDialog()) {
                   try {
                        job.print();
                   catch (Exception e) {
                        e.printStackTrace();
              System.exit(0);

    Hi,
    I'm developing a report program with java and I want to print this report.
    These are my page settings:
    paper.setSize(594.936, 841.536);
    paper.setImageableArea(0,0,594.936, 841.536)
    and my print method includes :
    Graphics2D g2d = (Graphics2D) g;
    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    but I can't use the page effectively. I have 28 mm blank from the left and 13 mm blank from the right.
    I can't write anything this blank sections. It looks as if it was deleted.
    What should I do?
    Thank you very much for your help.

  • Anchor point used in drawImage() of  Graphics class

    Hi all,
    This is sourab.I need to know about the concepts of anchor point used in drawImage() of Graphics class.We all know in drawImage() method has four co-ordinates.First one is for Image name,second one is for x coordinate ,third one is for y coordinate and the final one is for anchor point.Actually anchor point will place the image in the corresponding position.Now my doubt is what is the purpose of x,y coordinates.
    Also i want some links to learn about this anchor point concepts.Can anyone provide solution to me ASAP.
    Regards/Thanks,
    Sourab

    We all know in drawImage() method has four co-ordinates. [co&ouml;rdinates?]http://java.sun.com/javase/6/docs/api/java/awt/Graphics.html
    Or 5 or 6 or 7 or 10 or 11. And if you include Graphics2D:
    http://java.sun.com/javase/6/docs/api/java/awt/Graphics2D.html
    There is second one taking 4 arguments, and one taking 3.

  • Clearing the input box

    When I make a program that asks the user to input two integers and then the program computes the sum and displays it, I noticed that every time I re-run the program the previous first integer that was entered is still sitting in the input box. I've made this same program in both Eclipse and JDeveloper and neither one of those do this. It's rather annoying to re-run the program and to be looking at the input box and it still has previous input stuck in it.
    Just wondering if there is any way to clear the input box automatically upon re-running the program.

    This is just a console application. When I say re-run, I mean after you are done looking at the output, you hit the run button again to run the program again and have fun entering in new integer values. That's what I like to do with most of my programs. Here is the code:
    import java.util.*;
    public class GettingInput {
        public static void main(String args[])
            // create Scanner to obtain input from command window
            Scanner input = new Scanner( System.in );           
            int number1; // first number to add  
            int number2; // second number to add 
            int sum; // sum of number1 and number2
            System.out.println( "Enter first integer: " ); // prompt
            number1 = input.nextInt(); // read first number from user
            System.out.println( "Enter second integer: " ); // prompt
            number2 = input.nextInt(); // read second number from user
            sum = number1 + number2; // add numbers
            System.out.print( "The sum is " + sum);
    }Getting back to that JComponent thing, in order to make the setText( ) thing work, would I just include an import JComponent statement at the top of my code or what?

  • How to include Time delay in GUI enviroment

    hi all,
    i want to include time delay while drawing the shapes in the Canvas. I tried with Thread.sleep() and also delaying methods by making them to loop for large number of times.... but it affects the repainting of my Frame window like just previously executed snippet of the code gets repeated again and the delay between the shapes drawn cannot be visually seen..
    Can anyone help me????

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class DrawingExample extends JPanel implements ActionListener {
        private Timer timer = new Timer(200, this);
        private Rectangle[] rects = new Rectangle[10];
        private int currentUB;
        private boolean desc;
        public DrawingExample() {
            for(int i=0; i<rects.length; ++i)
                rects[i] = new Rectangle(i*15, i*15, 40, 40);
            timer.start();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            for(int i=0; i<currentUB; ++i)
                g2.draw(rects);
    public static void main(String[] args) {
    EventQueue.invokeLater(buildApp);
    public void actionPerformed(ActionEvent evt) {
    currentUB += desc ? -1 : +1;
    if (currentUB == -1) {
    desc = false;
    currentUB = 1;
    } else if (currentUB == rects.length+1) {
    desc = true;
    currentUB = rects.length-1;
    repaint();
    static Runnable buildApp = new Runnable() {
    public void run() {
    JComponent comp = new DrawingExample();
    comp.setPreferredSize(new Dimension(300,300));
    JFrame f = new JFrame();
    f.getContentPane().add(comp);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);

  • SetBackground() useless for JComponent?

    if you extend JComponent and then use setBackground(Color.RED), actually there is no change of the background.
    According to the API doc,
    public void setBackground(Color bg)
    Sets the background color of this component. The background color is used only if the component is opaque, and only by subclasses of JComponent or ComponentUI implementations. Direct subclasses of JComponent must override paintComponent to honor this property.
    It is up to the look and feel to honor this property, some may choose to ignore it.
    even if I set the JComponent to be opaque or override paintComponent() method, it doesn't work.
    codes are as follow:
    class MyComponent extends JComponent
    {   public void paintComponent(Graphics g)
        {    setOpaque(true);
             setBackground(Color.RED);  // no use :(
    }so how to interpretate that method detail of api doc? and how to use setBackgound() method to set the background color of a JComponent.
    BTW, if i extend JPanel instead, then in the paintComponent() method, I have to call super.paintComponent(g) --> why so?
    thx in advance

    so if i want to fill the background with RED (it already has some shapes painted on it)I suggest you read about Swing's painting architecture, as described in the tutorial .
    When paintComponent() is invoked (by the Swing painting framework) it is supposed to paint everything (background +++ "other shapes") in the painting rectangle, except:
    - the components underneath (which may appear if your own component is translucent, but that's a bit involved), including the immediate parent Container and its parent container hierarchy, which have automatically paint themselves in that area when their own paintComponent method, before your paintComponent() method was called in turn
    - the components above, which will automatically paint themselves over what your paintComponent() method is just painting, when their own paintComponent method is called in turn.
    If your JComponent subclass paints two things (say, a background fill, and green squares on top of that), it has to paint both each time your paintComponent is called, on the supllied Graphics rectangle.
    class MyComponent extends JComponent
    {   public MyComponent()
        {    setBackground(Color.RED);
        public void paintComponent(Graphics g)
        {    Graphics2D g2=(Graphics2D)g;
             g2.fill(...); // rectangle of background color
             g2.draw(...); // whatever is supposed to appear on top
    if it is g2.fillRect(0,0,getWidth(),getHeight()), then it will cover other drawings on the component.Maybe, but you will redraw those drawings just after filling the rectangle, so they will appear anyway.
    Now if you're concerned with doing an animation, there are a lot of techniques to optimize painting so as to not repaint everything, but do some practice and research before discussing them, as you seem to begin with Swing.
    Good luck.

  • JComponent not showing in JPanel

    I've tried the add() method but nothing is displayed when I try to add Test to GraphicsTest. How should I be adding it? Can someone show me? I've included the code I'm using.
    This is my way and it's not working. Can someone show me or make me aware of what the problem actually is?
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JPanel;
    public class GraphicsTest extends JPanel
        private Graphics2D g2d;
        private String state;
        private int x, y;
        GraphicsTest()
            Test t = new Test();
            t.setVisible(true);
            add(t);
        @Override
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            g2d = (Graphics2D) g;
            g2d.setColor(Color.BLACK);
            g2d.drawString("STATE: " + state, 5, 15);
            g2d.drawString("Mouse Position: " + x + ", " + y, 5, 30);
            g2d.setColor(Color.red);
            Rectangle2D r2d = new Rectangle2D.Double(x, y, 10, 10);
            g2d.draw(r2d);
            g2d.dispose();
        public void setState(String state) { this.state = state; }
        public String getState() { return state; }
        public void setX(int x) { this.x = x; repaint(); }
        public void setY(int y) { this.y = y; repaint(); }
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JComponent;
    public class Test extends JComponent
        @Override
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(Color.red);
            g2d.drawString("Hello", 50, 50);
            g2d.dispose();
    }

    The object in Test ("hello") is not appearing.
    import java.awt.EventQueue;
    //import java.awt.event.MouseEvent;
    //import java.awt.event.MouseListener;
    //import java.awt.event.MouseMotionListener;
    import javax.swing.JFrame;
    public class MainWindow
        public static void main(String[] args)
            new MainWindow();
        JFrame frame;
        GraphicsTest gt = new GraphicsTest();
        MainWindow()
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    frame = new JFrame("Graphics Practice");
                    frame.setSize(680, 420);
                    frame.setVisible(true);
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    //                gt.addMouseListener(new MouseListener() {
    //                    public void mouseClicked(MouseEvent e) {}
    //                    public void mousePressed(MouseEvent e) {}
    //                    public void mouseReleased(MouseEvent e) {}
    //                    public void mouseEntered(MouseEvent e) {
    //                        gt.setState("Mouse has entered");
    //                    public void mouseExited(MouseEvent e) {
    //                        gt.setState("Mouse has not entered");
    //                gt.addMouseMotionListener(new MouseMotionListener() {
    //                    public void mouseDragged(MouseEvent e) {}
    //                    public void mouseMoved(MouseEvent e) {
    //                        gt.setX(e.getX());
    //                        gt.setY(e.getY());
                    frame.add(gt);
    }

  • Trying to scroll a JComponent with JScrollPane but can't do it. :(

    Hi, what im trying to do seems to be simple but I gave up after trying the whole day and I beg you guys help.
    I created a JComponent that is my map ( the map consists only in squared cells ). but the map might be too big for the screen, so I want to be able to scroll it. If the map is smaller than the screen,
    everything works perfect, i just add the map to the frame container and it shows perfect. But if I add the map to the ScrollPane and them add the ScrollPane to the container, it doesnt work.
    below is the code for both classes Map and the MainWindow. Thanks in advance
    package main;
    import java.awt.Color;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowStateListener;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JViewport;
    public class MainWindow implements WindowStateListener {
         private JFrame frame;
         private static MainWindow instance = null;
         private MenuBar menu;
         public Map map = new Map();
         public JScrollPane Scroller =
              new JScrollPane( map,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
         public JViewport viewport = new JViewport();
         private MainWindow(int width, int height) {
              frame = new JFrame("Editor de Cen�rios v1.0");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(width,height);
              frame.setVisible(true);
              menu = MenuBar.createMenuBar();
              JFrame.setDefaultLookAndFeelDecorated(false);
              frame.setJMenuBar(menu.create());
              frame.setBackground(Color.WHITE);
              frame.getContentPane().setBackground(Color.WHITE);
                                    // HERE IS THE PROBLEM, THIS DOESNT WORKS   <---------------------------------------------------------------------------------------
              frame.getContentPane().add(Scroller);
              frame.addWindowStateListener(this);
    public static MainWindow createMainWindow(int width, int height)
         if(instance == null)
              instance = new MainWindow(width,height);
              return instance;               
         else
              return instance;
    public static MainWindow returnMainWindow()
         return instance;
    public static void main(String[] args) {
         MainWindow mWindow = createMainWindow(800,600);
    public JFrame getFrame() {
         return frame;
    public Map getMap(){
         return map;
    @Override
    public void windowStateChanged(WindowEvent arg0) {
         map.repaint();
    package main;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import javax.swing.JComponent;
    import javax.swing.Scrollable;
    public class Map extends JComponent  implements Scrollable{
         private Cell [] mapCells;
         private String mapPixels;
         private String mapAltura;
         private String mapLargura;
         public void createMap(String pixels , String altura, String largura)
              mapPixels = pixels;
              mapAltura = altura;
              mapLargura = largura;
              int cells = Integer.parseInt(altura) * Integer.parseInt(largura);
              mapCells = new Cell[cells];
              //MainWindow.returnMainWindow().getFrame().getContentPane().add(this);
              Graphics2D grafico = (Graphics2D)getGraphics();
              for(int i=0, horiz = 0 , vert = 0; i < mapCells.length; i++)
                   mapCells[i] = new Cell( horiz, vert,Integer.parseInt(mapPixels));
                   MainWindow.returnMainWindow().getFrame().getContentPane().add(mapCells);
                   grafico.draw(mapCells[i].r);
                   horiz = horiz + Integer.parseInt(mapPixels);
                   if(horiz == Integer.parseInt(mapLargura)*Integer.parseInt(mapPixels))
                        horiz = 0;
                        vert = vert + Integer.parseInt(mapPixels);
              repaint();
         @Override
         protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              System.out.println("entrou");
              Graphics2D g2d = (Graphics2D)g;
              if(mapCells !=null)
                   for(int i=0, horiz = 0 , vert = 0; i < mapCells.length; i++)
                        g2d.draw(mapCells[i].r);
                        horiz = horiz + Integer.parseInt(mapPixels);
                        if(horiz == Integer.parseInt(mapLargura)*Integer.parseInt(mapPixels))
                             horiz = 0;
                             vert = vert + Integer.parseInt(mapPixels);
         @Override
         public Dimension getPreferredScrollableViewportSize() {
              return super.getPreferredSize();
         @Override
         public int getScrollableBlockIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              // TODO Auto-generated method stub
              return 5;
         @Override
         public boolean getScrollableTracksViewportHeight() {
              // TODO Auto-generated method stub
              return false;
         @Override
         public boolean getScrollableTracksViewportWidth() {
              // TODO Auto-generated method stub
              return false;
         @Override
         public int getScrollableUnitIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              // TODO Auto-generated method stub
              return 5;

    Im so sorry Darryl here are the other 3 classes
    package main;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.filechooser.FileNameExtensionFilter;
    public class MenuActions {
         public void newMap(){
              final JTextField pixels = new JTextField(10);
              final JTextField hCells = new JTextField(10);
              final JTextField wCells = new JTextField(10);
              JButton btnOk = new JButton("OK");
              final JFrame frame = new JFrame("Escolher dimens�es do mapa");
              frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
              btnOk.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
              String txtPixels = pixels.getText();
              String hTxtCells = hCells.getText();
              String wTxtCells = wCells.getText();
              frame.dispose();
              MainWindow.returnMainWindow().map.createMap(txtPixels,hTxtCells,wTxtCells);         
              frame.getContentPane().add(new JLabel("N�mero de pixels em cada c�lula:"));
              frame.getContentPane().add(pixels);
              frame.getContentPane().add(new JLabel("Altura do mapa (em c�lulas):"));
              frame.getContentPane().add(hCells);
              frame.getContentPane().add(new JLabel("Largura do mapa (em c�lulas):"));
              frame.getContentPane().add(wCells);
              frame.getContentPane().add(btnOk);
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setSize(300, 165);
              frame.setResizable(false);
             frame.setVisible(true);
         public Map openMap (){
              //Abre somente arquivos XML
              JFileChooser fc = new JFileChooser();
              FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", "xml" );
              fc.addChoosableFileFilter(filter);
              fc.showOpenDialog(MainWindow.returnMainWindow().getFrame());
              //TO DO: manipular o mapa aberto
              return new Map();          
         public void save(){
         public void saveAs(){
              //Abre somente arquivos XML
              JFileChooser fc = new JFileChooser();
              FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", "xml" );
              fc.addChoosableFileFilter(filter);
              fc.showSaveDialog(MainWindow.returnMainWindow().getFrame());
              //TO DO: Salvar o mapa aberto
         public void exit(){
              System.exit(0);          
         public void copy(){
         public void paste(){
    package main;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.KeyStroke;
    public class MenuBar implements ActionListener{
         private JMenuBar menuBar;
         private final Color color = new Color(250,255,245);
         private String []menuNames = {"Arquivo","Editar"};
         private JMenu []menus = new JMenu[menuNames.length];
         private String []arquivoMenuItemNames = {"Novo","Abrir", "Salvar","Salvar Como...","Sair" };
         private KeyStroke []arquivoMenuItemHotkeys = {KeyStroke.getKeyStroke(KeyEvent.VK_N,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_A,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.SHIFT_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_F4,ActionEvent.ALT_MASK)};
         private JMenuItem []arquivoMenuItens = new JMenuItem[arquivoMenuItemNames.length];
         private String []editarMenuItemNames = {"Copiar","Colar"};
         private KeyStroke []editarMenuItemHotKeys = {KeyStroke.getKeyStroke(KeyEvent.VK_C,ActionEvent.CTRL_MASK),
                                                                 KeyStroke.getKeyStroke(KeyEvent.VK_V,ActionEvent.CTRL_MASK)};
         private JMenuItem[]editarMenuItens = new JMenuItem[editarMenuItemNames.length];
         private static MenuBar instance = null;
         public JMenuItem lastAction;
         private MenuBar()
         public static MenuBar createMenuBar()
              if(instance == null)
                   instance = new MenuBar();
                   return instance;                    
              else
                   return instance;
         public JMenuBar create()
              //cria a barra de menu
              menuBar = new JMenuBar();
              //adiciona items a barra de menu
              for(int i=0; i < menuNames.length ; i++)
                   menus[i] = new JMenu(menuNames);
                   menuBar.add(menus[i]);
              //seta a hotkey da barra como F10
              menus[0].setMnemonic(KeyEvent.VK_F10);
              //adiciona items ao menu arquivo
              for(int i=0; i < arquivoMenuItemNames.length ; i++)
                   arquivoMenuItens[i] = new JMenuItem(arquivoMenuItemNames[i]);
                   arquivoMenuItens[i].setAccelerator(arquivoMenuItemHotkeys[i]);
                   menus[0].add(arquivoMenuItens[i]);
                   arquivoMenuItens[i].setBackground(color);
                   arquivoMenuItens[i].addActionListener(this);
              //adiciona items ao menu editar
              for(int i=0; i < editarMenuItemNames.length ; i++)
                   editarMenuItens[i] = new JMenuItem(editarMenuItemNames[i]);
                   editarMenuItens[i].setAccelerator(editarMenuItemHotKeys[i]);
                   menus[1].add(editarMenuItens[i]);
                   editarMenuItens[i].setBackground(color);
                   editarMenuItens[i].addActionListener(this);
              menuBar.setBackground(color);
              return menuBar;                    
         @Override
         public void actionPerformed(ActionEvent e) {
              lastAction = (JMenuItem) e.getSource();
              MenuActions action = new MenuActions();
              if(lastAction.getText().equals("Novo"))
                   action.newMap();
              else if(lastAction.getText().equals("Abrir"))
                   action.openMap();
              else if(lastAction.getText().equals("Salvar"))
                   action.save();               
              else if(lastAction.getText().equals("Salvar Como..."))
                   action.saveAs();               
              else if(lastAction.getText().equals("Sair"))
                   action.exit();               
              else if(lastAction.getText().equals("Copiar"))
                   action.copy();               
              else if(lastAction.getText().equals("Colar"))
                   action.paste();               
    package main;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JComponent;
    public class Cell extends JComponent{
         public float presSub = 0;
         public double errPressInfer = 0.02;
         public double errPressSup = 0.02;
         public float profundidade = 1;
         public Rectangle2D r ;
         public Cell(double x, double y, double pixel)
              r = new Rectangle2D.Double(x,y,pixel,pixel);          
    Edited by: xnunes on May 3, 2008 6:26 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Help!! How to put more than one JComponent on one JFrame

    Hi!
    I'm having a big problem. I'm trying to create an animation that is composed of various images. In one JComponent I have an animation of a sprite moving left and right on the screen(Which works right now). On another JComponent I have a still image that I want to put somewhere on the screen. For some reason I can only see what I add last to the JFrame. Can somebody help me? Thanks
    P.S I don't want to have all the images on the same JComponent. I want to have different classes for different images or animations. You can get the sprites I use from here http://www.flickr.com/photos/59719950@N00/
    import java.awt.Color;
    import javax.swing.JFrame;
    public class ScreenSaverViewer
         public static void main(String[] args)
         Character characterGame = new Character();
         basketballHoop hoopz = new basketballHoop();
         //Clock clock = new Clock();
         JFrame app = new JFrame("Screensaver");
            app.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            app.getContentPane().add(hoopz);
            //app.getContentPane().add(clock);
            app.getContentPane().add(characterGame);
            app.setSize (450,450);
            app.setBackground (Color.black);
            app.setLocation (300,200);
            app.setVisible (true);
            characterGame.run();
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    import java.util.ArrayList;
    public class Character extends JComponent
        BufferedImage backbuffer;
        int sliderSpeed = 1;
        int sliderX = 1;
        int sliderY = 1;
        int direction = 1;
        Image myImg = Toolkit.getDefaultToolkit().getImage ("/home/climatewarrior/Sprites_gabriel/muneco_0.png");
        private Image fetchImage(int x)
             ArrayList<Image> images = new ArrayList<Image>();
             for (int i = 0; i < 4; i++)
                  images.add(i, Toolkit.getDefaultToolkit().getImage ("/home/climatewarrior/Sprites_gabriel/muneco_" + i + ".png"));
             return images.get(x);
        private void displayGUI()
            int appWidth = getWidth();
            int appHeight = getHeight();
            backbuffer = (BufferedImage) createImage (appWidth, appHeight);
            Graphics2D g2 = backbuffer.createGraphics();
            g2.setRenderingHint (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.drawImage (myImg, sliderX, sliderY, getWidth() / 2 * direction, getHeight() / 2, this);
            g2.dispose();
            repaint();
        public void paintComponent (Graphics g)
            super.paintComponent(g);
            if (backbuffer == null)
                 displayGUI();
            g.drawImage(backbuffer, 0, 0, this);
       public void run ()
            while(true)
                   sliderX = -(getWidth() - getWidth()/2);
                   sliderY = getHeight()/3;
                   int x = 0;
                   int increment = 1;
                   do
                   sliderX += increment;
                   if (sliderX % 30 == 0)
                             myImg = fetchImage(x);
                             direction = -1;
                             x++;
                             if (x == 4)
                             x = 0;
                   displayGUI();
                   } while (sliderX <= getWidth() + (getWidth() - getWidth()/2));
                   do
                   sliderX -= increment;
                   if (sliderX % 30 == 0)
                        myImg = fetchImage(x);
                        direction = 1;
                        x++;
                        if (x == 4)
                             x = 0;
                   displayGUI();
                   } while (sliderX >= -(getWidth() - getWidth()/2));
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class Clock extends JComponent
        BufferedImage backbuffer;
        Image myImg = Toolkit.getDefaultToolkit().getImage("/home/climatewarrior/Sprites_gabriel/score_board.png");
        public void paintComponent (Graphics g)
             g.drawImage(myImg, 250, 100, getWidth()/2, getHeight()/3, null);
             super.paintComponent (g);
             repaint();
    }

    Here's a file I had hanging around. It's about as simple as they come, hopefully not too simple!
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    class SimpleAnimationPanel extends JPanel
        private static final int DELAY = 20;
        public static final int X_TRANSLATION = 2;
        public static final int Y_TRANSLATION = 2;
        private static final String DUKE_FILE = "http://java.sun.com/" +
                  "products/plugin/images/duke.wave.med.gif";
        private Point point = new Point(5, 32);
        private BufferedImage duke = null;
        private Timer timer = new Timer(DELAY, new TimerAction());
        public SimpleAnimationPanel()
            try
                // borrow an image from sun.com
                duke = ImageIO.read(new URL(DUKE_FILE));
            catch (MalformedURLException e)
                e.printStackTrace();
            catch (IOException e)
                e.printStackTrace();
            setPreferredSize(new Dimension(600, 400));
            timer.start();
        // do our drawing here in the paintComponent override
        @Override
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            if (duke != null)
                g.drawImage(duke, point.x, point.y, this);
        private class TimerAction implements ActionListener
            public void actionPerformed(ActionEvent e)
                int x = point.x;
                int y = point.y;
                Dimension size = SimpleAnimationPanel.this.getSize();
                if (x > size.width)
                    x = 0;
                else
                    x += X_TRANSLATION;
                if (y > size.height)
                    y = 0;
                else
                    y += Y_TRANSLATION;
                point.setLocation(new Point(x, y)); // update the point
                SimpleAnimationPanel.this.repaint();
        private static void createAndShowUI()
            JFrame frame = new JFrame("SimpleAnimationPanel");
            frame.getContentPane().add(new SimpleAnimationPanel());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }

  • Printing problem with Graphics2D

    Hi, Ive got a problem with printing.
    I have a JPanel and it has among other things a button to print the component which is an instance of the class its in. This is a drawing in Graphics2D. here is the following code that is meant to do the printing:-
         if(e.getActionCommand().equals("print")){
              System.out.println("print pressed " + title);
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if(printJob.printDialog()){
    try { printJob.print(); }
    catch (Exception PrinterExeption) { PrinterExeption.printStackTrace();}
    public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
    if (pi >= 1) {
    System.out.println("print failed");
    return Printable.NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D) g;
    g2.translate(pf.getImageableX(), pf.getImageableY());
    g2.setColor(Color.black);
    this.paintAll(g2);
    System.out.println("print successful");
    return Printable.PAGE_EXISTS;
    However it doesnt print and comes up with the following long message..
    java.awt.image.ImagingOpException: Unable to transform src image
    at java.awt.image.AffineTransformOp.filter(AffineTransformOp.java:263)
    at sun.java2d.pipe.DrawImage.transformImage(DrawImage.java:304)
    at sun.java2d.pipe.DrawImage.scaleBufferedImage(DrawImage.java:453)
    at sun.java2d.pipe.DrawImage.scaleImage(DrawImage.java:531)
    at sun.java2d.pipe.DrawImage.scaleImage(DrawImage.java:801)
    at sun.java2d.pipe.ValidatePipe.scaleImage(ValidatePipe.java:171)
    at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2875)
    at sun.print.PSPathGraphics.drawImageToPS(PSPathGraphics.java:998)
    at sun.print.PSPathGraphics.drawImage(PSPathGraphics.java:495)
    at sun.print.PSPathGraphics.drawImage(PSPathGraphics.java:406)
    at sun.print.PSPathGraphics.drawImage(PSPathGraphics.java:345)
    at sun.print.PSPathGraphics.drawImage(PSPathGraphics.java:288)
    at sun.print.PSPathGraphics.drawImage(PSPathGraphics.java:197)
    at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4781)
    at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4724)
    at javax.swing.JComponent.paint(JComponent.java:798)
    at java.awt.Component.lightweightPaint(Component.java:2382)
    at java.awt.Container.lightweightPaint(Container.java:1390)
    at java.awt.GraphicsCallback$PeerPaintCallback.run(GraphicsCallback.java:67)
    at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:60)
    at java.awt.Component.paintAll(Component.java:2367)
    at DrawingMethods.print(DrawingMethods.java:833)
    at sun.print.RasterPrinterJob.printPage(RasterPrinterJob.java:1506)
    at sun.print.RasterPrinterJob.print(RasterPrinterJob.java:1078)
    at sun.print.RasterPrinterJob.print(RasterPrinterJob.java:979)
    at DrawingMethods.actionPerformed(DrawingMethods.java:817)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1764)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1817)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:419)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
    at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:227)
    at java.awt.Component.processMouseEvent(Component.java:5093)
    at java.awt.Component.processEvent(Component.java:4890)
    at java.awt.Container.processEvent(Container.java:1566)
    at java.awt.Component.dispatchEventImpl(Component.java:3598)
    at java.awt.Container.dispatchEventImpl(Container.java:1623)
    at java.awt.Component.dispatchEvent(Component.java:3439)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
    at java.awt.Container.dispatchEventImpl(Container.java:1609)
    at java.awt.Window.dispatchEventImpl(Window.java:1585)
    at java.awt.Component.dispatchEvent(Component.java:3439)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    I dont know how to get it to work and either does a PHD mate of mine.
    Please help
    All I need is a guarenteed way to get a Graphics2D component to print
    cheers
    pmiggy

    Um I dont know if im doing something daft but I tried this like you said
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if(printJob.printDialog()){
    try {
              PageFormat pageFormat = printJob.defaultPage();
              if (pageFormat.getOrientation() == PageFormat.PORTRAIT) {
              landscape = 0;} else {
                   landscape = 1;}
              System.out.println("THE ORIENTATION IS "+ landscape);
              printJob.print(); }
    catch (Exception PrinterExeption) { PrinterExeption.printStackTrace();}
    and it doesnt seem to work as I tried it both as landscape and portrait in the print dialog but landscape is always 0.
    cheers
    pmiggy

  • JTable display cell previous/last selected/edited/clicked value/JComponent

    I have a problem with the minesweeper I made,
    The game board is a JTable containing custom gadgets in the cells,
    The first game goes without problem, but I press the JButton starting a new game,
    I randomly refill the JTable with new custom gadgets,
    My problem is that the last cell I clicked in the JTable is still in the clicked state with the previous value and I cannot click or see the new custom gadget that ought to be there ...
    The custom gadgets extends JLabel and use custom AbstractCellEditor and custom TableCellRenderer, but I think it is not related to my custom gadgets,
    I work on OSX,
    Any hint to my problem's origin?
    Any solutions?

    My code included not related classes I eliminated to use only standard java classes,
    here is is the minimal code for my mine sweeper reproducing the problem on the third launch
    any hint? :
    import java.awt.Container;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseEvent;
    import java.util.Random;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableModel;
    public class MyMineSweeper
       private class JTableCellRenderer implements javax.swing.table.TableCellRenderer
          private javax.swing.table.TableCellRenderer defaultRenderer;
          public JTableCellRenderer(javax.swing.table.TableCellRenderer aRenderer)
             defaultRenderer = aRenderer;
          public java.awt.Component getTableCellRendererComponent(javax.swing.JTable aTable, Object anElement, boolean isSelected, boolean hasFocus, int aRow, int aColumn)
             if(anElement instanceof javax.swing.JComponent)
                return (javax.swing.JComponent)anElement;
             return defaultRenderer.getTableCellRendererComponent(aTable, anElement, isSelected, hasFocus, aRow, aColumn);
       private class JTableCellEditor extends javax.swing.AbstractCellEditor implements javax.swing.table.TableCellEditor
          private javax.swing.JComponent component;
          private int theClickCountToStart = 0;
          public java.awt.Component getTableCellEditorComponent(javax.swing.JTable aTable, Object anElement, boolean isSelected, int aRow, int aColumn)
             component = (javax.swing.JComponent) anElement;
             return component;
          public Object getCellEditorValue()
             return component;
          public boolean isCellEditable(java.util.EventObject anEvent)
             if(anEvent instanceof java.awt.event.MouseEvent)
                return ((java.awt.event.MouseEvent)anEvent).getClickCount() >= theClickCountToStart;
             return true;
          public int getClickCountToStart()
             return theClickCountToStart;
          public void setClickCountToStart(int aClickCountToStart)
             theClickCountToStart = aClickCountToStart;
       private class Tile extends javax.swing.JLabel
          public class JTileMouseListener implements java.awt.event.MouseListener
             public void mouseClicked(MouseEvent e)
                if(isRevealed()==false)
                   reveal();
             public void mousePressed(MouseEvent e)
             public void mouseReleased(MouseEvent e)
             public void mouseEntered(MouseEvent e)
             public void mouseExited(MouseEvent e)
            public void reveal(int aY, int anX)
               Tile tile = ((Tile)theMapModel.getValueAt(aY, anX));
               if(tile.isRevealed()==false)
                  tile.reveal();
            public void changed()
               if(theNeighbourCount==0)
                  if(theX>0)
                     if(theY>0)
                        reveal(theY-1, theX-1);
                     reveal(theY, theX-1);
                     if(theY<theMapModel.getRowCount()-1)
                        reveal(theY+1, theX-1);
                  if(theY>0)
                     reveal(theY-1, theX);
                  if(theY<theMapModel.getRowCount()-1)
                     reveal(theY+1, theX);
                  if(theX<theMapModel.getColumnCount()-1)
                     if(theY>0)
                        reveal(theY-1, theX+1);
                     reveal(theY, theX+1);
                     if(theY<theMapModel.getRowCount()-1)
                         reveal(theY+1, theX+1);
                   setBackground(java.awt.Color.WHITE);
                else if(theNeighbourCount==9)
                   setText("*");
                   setBackground(java.awt.Color.RED);
                   System.out.println("no!");
                   theMap.setEnabled(false);
                else
                   setText(String.valueOf(theNeighbourCount));
                   setBackground(java.awt.Color.WHITE);
                setBorder(javax.swing.BorderFactory.createEmptyBorder());
                if(isFinished()==true)
                   System.out.println("victory!");
                   theMap.setEnabled(false);
                theMapModel.fireTableCellUpdated(theY,theX);
          private DefaultTableModel theMapModel;
          private int theX;
          private int theY;
          private short theNeighbourCount;
          protected boolean revealed = false;
          public Tile(int aYIndex, int anXIndex, short aNeighbourCount)
             theMapModel = (DefaultTableModel)theMap.getModel();
             theX = anXIndex;
             theY = aYIndex;
             theNeighbourCount = aNeighbourCount;
             addMouseListener(new JTileMouseListener());
             setOpaque(true);
             setHorizontalAlignment(CENTER);
             setBackground(java.awt.Color.LIGHT_GRAY);
             setBorder(javax.swing.BorderFactory.createRaisedBevelBorder());
             setSize(getHeight(), getHeight());
          public void reveal()
             revealed = true;
             theRevealedTileCount +=1;
             changed();
          public boolean isRevealed()
             return revealed;
       private JFrame theFrame;
       private JTable theMap;
       private int theMapSize = 10;
       private int theTrapCount = 5;
       private int theRevealedTileCount = 0;
       private void startGame()
          Point[] traps = new Point[theTrapCount];
          Random generator = new Random();
          for(int trapIndex = 0; trapIndex<theTrapCount; trapIndex+=1)
             Point newPoint = null;
             boolean alreadyTrapped = true;
             while(alreadyTrapped==true)
                newPoint = new Point(generator.nextInt(theMapSize-1), generator.nextInt(theMapSize-1));
                alreadyTrapped = false;
                for(int existingTrapIndex= 0; existingTrapIndex<trapIndex;existingTrapIndex++)
                   if(newPoint.equals(traps[existingTrapIndex])) alreadyTrapped = true;
             traps[trapIndex] = newPoint;
          TableModel mapModel = theMap.getModel();
          for(int yIndex = 0; yIndex<theMapSize; yIndex+=1)
             for(int xIndex = 0; xIndex<theMapSize; xIndex+=1)
                short neighbours = 0;
                int x = 0;
                int y = 0;
                for(int trapIndex = 0; trapIndex<theTrapCount; trapIndex+=1)
                   x = traps[trapIndex].x - xIndex;
                   y = traps[trapIndex].y - yIndex;
                   if(x==0 && y==0)
                      trapIndex = theTrapCount;
                   else if((x==1 || x==-1) && (y==1 || y==-1))
                      neighbours += 1;
                   else if((x==0) && (y==1 || y==-1))
                      neighbours += 1;
                   else if((x==1 || x==-1) && (y==0))
                      neighbours += 1;
                if(x==0 && y==0)
                   mapModel.setValueAt(new Tile(yIndex, xIndex, (short) 9), yIndex, xIndex);
                else
                   mapModel.setValueAt(new Tile(yIndex, xIndex, neighbours), yIndex, xIndex);
          theRevealedTileCount  = 0;
          theMap.setEnabled(true);
       private boolean isFinished()
          return ((theMapSize*theMapSize)-theRevealedTileCount)==theTrapCount;
       public MyMineSweeper()
          theFrame = new javax.swing.JFrame("mine sweeper");
          JPanel cp = new JPanel();
          theMap = new JTable(new DefaultTableModel(10,10)
             public Class getColumnClass(int column)
                return getValueAt(0, column).getClass();
          theMap.setDefaultRenderer(JComponent.class, new JTableCellRenderer(theMap.getDefaultRenderer(JComponent.class)));
          JTableCellEditor editor = new JTableCellEditor();
          theMap.setDefaultEditor(JComponent.class, editor);
          editor.setClickCountToStart(0);
          theMap.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
          startGame();
          cp.add(theMap);
          Action newGameAction = new AbstractAction("new game")
             public void actionPerformed(ActionEvent e)
                startGame();
          JButton newGameTrigger = new JButton(newGameAction);
          cp.add(newGameTrigger);
          theFrame.getContentPane().add(cp);
          theFrame.pack();
          theFrame.show();
       public JFrame getFrame()
          return theFrame;
      }

  • How painting behind a JComponent ?

    Hi all,
    I'm trying to paint stuff like shadows, frames (not borders), etc. behind JComponents.
    So every shape only intersects with the relative JComponent's one.
    Cannot paint these stuff in the container's paintComponent() method since more widgets can have one or more of them, so I guess It should be better do the job in every child's paintComponent() method.
    What follows was the code I tested but doesn't work.
    Any hints ? Thanks in advance.
    Lucio
    import java.awt.*;
    import javax.swing.*;
    public class UpButton extends JButton {
        Dimension dimension = new Dimension(100, 100);
        Point point = new Point(100, 100);
        public UpButton(String text) {
         setSize(dimension);
         setLocation(point);
         setBackground(new Color(255,186,26));
         setText(text);
        public void paintComponent(Graphics g) {
         Component c = (Component) getParent();
         Graphics2D g2 = (Graphics2D)
                                      c.getGraphics().create(0,0,dimension.width,dimension.height);
         g2.translate(-(point.x + 10), -(point.y + 5));
         g2.setPaint(Color.gray);
         g2.fill(new Rectangle(dimension));
         g2.dispose();
         super.paintComponent(g);
        public static void main(String[] args) {
         JFrame jFrame = new JFrame();
         jFrame.getContentPane().setLayout(null);
         jFrame.add(new UpButton("Test"));
         jFrame.setSize(300,300);
         jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jFrame.setVisible(true);
    }

    I'm very grateful to you, weebib
    I was missing the setClip method, now perfectly works.
    It doesn't seems to me too difficult (now ;-)
    Here my modified version :
    import java.awt.*;
    import javax.swing.*;
    public class UpButton extends JButton {
        Dimension dimension = new Dimension(100, 100);
        Point point = new Point(100, 100);
        public UpButton(String text) {
         setSize(dimension);
         setLocation(point);
         setBackground(new Color(255,186,26));
         setText(text);
        public void paintComponent(Graphics g) {
         Graphics2D g2 = (Graphics2D) g.create();
         g2.translate(10, 5);
         g2.setClip(0, 0, 100, 100);
         g2.setPaint(Color.gray);
         g2.fill(new Rectangle(dimension));
         g2.dispose();
         super.paintComponent(g);
        public static void main(String[] args) {
         JFrame jFrame = new JFrame();
         jFrame.getContentPane().setLayout(null);
         jFrame.add(new UpButton("Test"));
         jFrame.setSize(300,300);
         jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jFrame.setVisible(true);
    }

  • Flush parameter of jsp:include has no effect on servlet code

    I am running 9.0.3 and my jsp code looks like:
    &lt;jsp:include page =".." flush="false"/&gt;
    but the resulting servlet code is:
    pageContext.include( __url);
    Which defaults to flushing the buffer!
    Does anyone know a work around or if Oracle is going to fix this?
    Thanks,
    Mike

    Try:
    public class ...  extends ...
        private static final boolean antialias = Boolean.getBoolean ("swing.aatext");
        private static Map hintsMap = null;
        @SuppressWarnings("unchecked")
        static final Map getHints() {
           if (hintsMap == null) {
                hintsMap = (Map)(Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints")); //NOI18N
                 if (hintsMap == null) {
                    hintsMap = new HashMap();
                     if (antialias) {
                          hintsMap.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
           return hintsMap;
    ... later in class ...
        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.addRenderingHints(getHints());
            super.paintComponent(g);
            ...needed this so custom paint would use AA. In my app I wrote text in my component and it was not AA, this turned it on.
    I don't think I had the same problem you, as my jlabels were always aa.
    Edited by: 805835 on Oct 27, 2010 5:06 PM
    Edited by: 805835 on Oct 27, 2010 5:07 PM

  • Inserting any JComponent in a JEditorPane

    Hi, I'm having some trouble using JEditorPane and JTextPane. I would like to include some JComponent of my own into them.
    With JTextPane, no problem, let's create a style with
    StyleConstants.setComponent(myStyle, myComponent);
    then insert a space char in the Document using this style. Good.
    Problem comes when I want to insert my components into an HTML document, using JEditorPane. This method raises no runtime problem but does nothing visible. Why ? Even more surprising, if I force the JEditorPane to a simple DefaultStyledDocument
    JEditorPane editorPane = new JTextPane();
    editorPane.setDocument(new DefaultStyledDocument());
    it doesn't work better. In such a case, ain't we in exactly the same configuration than with JTextPane ? BTW, why is JTextPane derived from JEditorPane if we cannot retreive parent's behaviour (HTML or RTF rendering) in the child class ?
    Yes, I'm confused...
    If your mind is clearer than mine on those topic, could you give me a piece of advice, or a link to a solution or an exemple on all of this ? Thanks,
    Matthieu

    No idea anybody on how I could insert JComponents of my own in a JEditorPane ?
    Why the simple Document.insertString () don't work in a JEditorPane if the style is not HTML ?
    Is it possible to tweak JTextPane to make it render HTML (using a Kit) then insert my own styles in it ?
    Thx.
    Matthieu

  • Problem change Graphics2D into jpg

    this is part of the code i have
    private void drawPawn(Graphics2D gr, Integer pawn, Color c) {
              Coordinate coord = parent.getGameCore().currentBoard().getCoordinate(
                        pawn);
              int y = coord.getLine();
              int x = coord.getRow();
    // Image Image1; <-------------------------this is first try
    // Toolkit toolkit = Toolkit.getDefaultToolkit();
    // Image1 = toolkit.getImage("kangaroo.jpg");
    // BufferedImage Image1 = null ; <--------------------------this is second try
    // try {
    // Image1 = ImageIO.read(new File("kangaroo.jpg"));
    // } catch (IOException e) {
    ImageIcon Image1 = new ImageIcon("kangaroo.jpg"); <--------------------------and last try but it doesnt work(cant view the jpg)
              gr.setColor(borderPawnsColor);
              gr.fillOval(horizontalBorder + x * slotWidth, verticalBorder + y
                        * slotHeight, pawnDiameter + pawnBorderSize, pawnDiameter
                        + pawnBorderSize);
              gr.setColor(c);
              gr.fillOval(horizontalBorder + x * slotWidth, verticalBorder + y
                        * slotHeight, pawnDiameter, pawnDiameter);
    gr.drawImage(Image1.getImage(), horizontalBorder + x * slotWidth, verticalBorder + y
                        * slotHeight, this); <--------------------------this is where the problem place
    ive try different ways to view "kangaroo.jpg".but it doesnt work.anyone could help me?
    i get this code from googling.

    forent wrote:
    sorry..when i change the root into "E:/My Documents/NetBeansProjects/Bordeaux/src/gui/kangaroo.jpg".but why this happen?
    it solve my problem.
    yeah it called from paintcomponent().
    thanks.. :-DThat is not the root of your project, it is a direct path to your JPG. IT happened bacause your code was correct, but your JPG is in the wrong place. Your project is in "E:/MY Documents/NetBeansProjects/Bordeaux", put your JPG in there and you can access it then by just the name "kangaroo.jpg", but if you JAR your file, then you'll have to loadresource and include the JPG in your JAR to get it to work that way. In any case a direct path to your JPG will work, but you lose the ability to move your JAR freely from machine to machine as a self contained unit able to run on any appropriate JVM--you will always be requred to have that hard path "E:/My Documents/NetBeansProjects/Bordeaux/src/gui/kangaroo.jpg" to your JPG and if your friends don't have an E drive, they are just out of luck.

Maybe you are looking for