Search Results

Search found 82 results on 4 pages for 'paintcomponent'.

Page 1/4 | 1 2 3 4  | Next Page >

  • JPanel: both implementing my own paintComponent() and rendering children doesn't work

    - by Paul Marshall
    I'm extending a JPanel to display a game board, and adding a JEditorPane at the bottom to hold some status text. Unfortunately, the game board renders just fine, but the JEditorPane is just a blank gray area until I highlight the text in it, when it will render whatever text is highlighted (but not the rest). If I'm understanding Swing right, it should work, because super.paintComponent(g) should render the other children (i.e., the JEditorPane). Tell me, o great stackoverflow, what bonehead mistake am I making? public GameMap extends JPanel { public GameMap() { JEditorPane statusLines = new JEditorPane("text/plain","Stuff"); this.setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS)); this.add(new Box.Filler(/*enough room to draw my game board*/)); this.add(statusLines); } public void paintComponent(Graphics g){ super.paintComponent(g); for ( all rows ){ for (all columns){ //paint one tile } } } }

    Read the article

  • paintComponent on JPanel, image flashes and then disappears

    - by mark
    I have a JApplet (MainClass extends JApplet), a JPanel (ChartWindow extends JPanel) and a Grafico class. The problem is that the Grafico class instance has 2 JPanel that should show 2 images (1 for each panel) but the images are shown and after a little while they disappears: instead of them i get a gray background (like an empty JPanel). This happens for every repaint() call (that are made in the ChartWindow class) the MainClass init() contains chartwindow=new ChartWindow(); add(chartwindow) chartwindow has a Grafico instance. it's the ChartWindow's paintComponent (override) paintComponent(Graphics g) { super.paintComponent(g); Image immagineGrafico=createImage(grafico.pannelloGrafico.getWidth() ,grafico.pannelloGrafico.getHeight()); Image immagineVolumi=createImage(grafico.pannelloVolumi.getWidth() ,grafico.pannelloVolumi.getHeight()); Graphics2D imgGrafico=(Graphics2D)immagineGrafico.getGraphics(); Graphics2D imgVolumi=(Graphics2D)immagineVolumi.getGraphics(); grafico.draw(imgGrafico,imgVolumi,mouseX,mouseY); ((Graphics2D)grafico.pannelloGrafico.getGraphics()).drawImage(immagineGrafico,0,0,this); ((Graphics2D)grafico.pannelloVolumi.getGraphics()).drawImage(immagineVolumi,0,0,this); } grafico's JPanels are added this way in the ChartWindow's constructor grafico=new Grafico() ................ add(grafico.pannelloGrafico); add(grafico.pannelloVolumi); Tell me if you need more information, thank you very much :-)

    Read the article

  • paintComponent method is not displaying anything on the panel

    - by Captain Gh0st
    I have been trying to debug this for hours. The program is supposed to be a grapher that graphs coordinates, but i cannot get anything to display not even a random line, but if i put a print statement there it works. It is a problem with the paintComponent Method. When I out print statement before g.drawLine then it prints, but it doesn't draw any lines even if i put a random line with coordinates (1,3), (2,4). import java.awt.*; import java.util.*; import javax.swing.*; public abstract class XYGrapher { abstract public Coordinate xyStart(); abstract public double xRange(); abstract public double yRange(); abstract public Coordinate getPoint(int pointNum); public class Paint extends JPanel { public void paintGraph(Graphics g, int xPixel1, int yPixel1, int xPixel2, int yPixel2) { super.paintComponent(g); g.setColor(Color.black); g.drawLine(xPixel1, yPixel1, xPixel2, yPixel2); } public void paintXAxis(Graphics g, int xPixel, int pixelsWide, int pixelsHigh) { super.paintComponent(g); g.setColor(Color.green); g.drawLine(xPixel, 0, xPixel, pixelsHigh); } public void paintYAxis(Graphics g, int yPixel, int pixelsWide, int pixelsHigh) { super.paintComponent(g); g.setColor(Color.green); g.drawLine(0, yPixel, pixelsWide, yPixel); } } public void drawGraph(int xPixelStart, int yPixelStart, int pixelsWide, int pixelsHigh) { JFrame frame = new JFrame(); Paint panel = new Paint(); panel.setPreferredSize(new Dimension(pixelsWide, pixelsHigh)); panel.setMinimumSize(new Dimension(pixelsWide, pixelsHigh)); panel.setMaximumSize(new Dimension(pixelsWide, pixelsHigh)); frame.setLocation(frame.getToolkit().getScreenSize().width / 2 - pixelsWide / 2, frame.getToolkit().getScreenSize().height / 2 - pixelsHigh / 2); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.add(panel); frame.pack(); frame.setVisible(true); double xRange = xRange(); double yRange = yRange(); Coordinate xyStart = xyStart(); int xPixel = xPixelStart - (int) (xyStart.getX() * (pixelsWide / xRange)); int yPixel = yPixelStart + (int) ((xyStart.getY() + yRange) * (pixelsHigh / yRange)); System.out.println(xPixel + " " + yPixel); if(yPixel > 0 && (yPixel < pixelsHigh)) { System.out.println("y"); panel.paintYAxis(panel.getGraphics(), yPixel, pixelsWide, pixelsHigh); } if(xPixel > 0 && (xPixel < pixelsHigh)) { System.out.println("x"); panel.paintXAxis(panel.getGraphics(), xPixel, pixelsWide, pixelsHigh); } for(int i = 0; i>=0; i++) { Coordinate point1 = getPoint(i); Coordinate point2 = getPoint(i+1); if(point2 == null) { break; } else { if(point1.drawFrom() && point2.drawTo()) { int xPixel1 = (int) (xPixelStart + (point1.getX() - xyStart.getX()) * (pixelsWide / xRange)); int yPixel1 = (int) (yPixelStart + (xyStart.getY() + yRange-point1.getY()) * (pixelsHigh / yRange)); int xPixel2 = (int) (xPixelStart + (point2.getX() - xyStart.getX()) * (pixelsWide / xRange)); int yPixel2 = (int) (yPixelStart + (xyStart.getY() + yRange - point2.getY()) * (pixelsHigh / yRange)); panel.paintGraph(panel.getGraphics(), xPixel1, yPixel1, xPixel2, yPixel2); } } } frame.pack(); } } This is how i am testing it is supposed to be a square, but nothing shows up. public class GrapherTester extends XYGrapher { public Coordinate xyStart() { return new Coordinate(-2,2); } public double xRange() { return 4; } public double yRange() { return 4; } public Coordinate getPoint(int pointNum) { switch(pointNum) { case 0: return new Coordinate(-1,-1); case 1: return new Coordinate(1,-1); case 2: return new Coordinate(1,1); case 3: return new Coordinate(-1,1); case 4: return new Coordinate(-1,-1); } return null; } public static void main(String[] args) { new GrapherTester().drawGraph(100, 100, 500, 500); } } Coordinate class so if any of you want to run and try it out. That is all you would need. public class Coordinate { float x; float y; boolean drawTo; boolean drawFrom; Coordinate(double x, double y) { this.x = (float) x; this.y = (float) y; drawFrom = true; drawTo = true; } Coordinate(double x, double y, boolean drawFrom, boolean drawTo) { this.x = (float) x; this.y = (float) y; this.drawFrom = drawFrom; this.drawTo = drawTo; } public double getX() { return x; } public double getY() { return y; } public boolean drawTo() { return drawTo; } public boolean drawFrom() { return drawFrom; } }

    Read the article

  • java/Swing issue with paintComponent

    - by user310254
    The issue I'm having is issue with is I'm trying to get the paintComponent to draw the circle only when the mouse is clicked, dragged, then let go. However inside my paintPanel class I have to initialize the object I've created (ex. movedCircle myCircle = new movedCircle(0,0,0,0);) just creating the object movedCircle myCircle; gives an error until I actually fully initialize the object with a value. What I'm looking for: What's considered the best practice for this issue. I don't want to draw anything unnecessary before it is needed. The way I know how to fix it: boolean values inside of paintComponent so that way it doesn't draw until somethings actually there. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class drawCircle extends JFrame{ private JPanel myPanel = new paintPanel(); public drawCircle(){ add(myPanel); } private class paintPanel extends JPanel{ private int x1, y1, x2, y2; movedText myText = new movedText(0,0,0,0); movedCircle myCircle = new movedCircle(0,0,0,0); public paintPanel(){ addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ x1 = e.getX(); y1 = e.getY(); myCircle = new movedCircle(x1, y1, 0, 0); repaint(); } public void mouseReleased(MouseEvent e){ x2 = e.getX(); y2 = e.getY(); myCircle = new movedCircle(x1, y1, x2, y2); repaint(); } }); addMouseMotionListener(new MouseMotionAdapter(){ public void mouseDragged(MouseEvent e){ x2 = e.getX(); y2 = e.getY(); myText = new movedText(x1, y1, x2, y2); myCircle = new movedCircle(x1, y1, x2, y2); repaint(); } public void mouseMoved(MouseEvent e){ x1 = e.getX(); y1 = e.getY(); x2 = 0; y2 = 0; myText = new movedText(x1, y1, x2, y2); repaint(); } }); } protected void paintComponent(Graphics g){ super.paintComponent(g); //draw oval after mouse released myText.paintText(g); myCircle.paintCircle(g); } } class movedCircle{ private int x1, y1, x2, y2; public movedCircle(int x1, int y1, int x2, int y2){ this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public void paintCircle(Graphics g){ g.drawOval(x1, y1, x2 - x1, y2 - y1); } } class movedText{ private int x1, y1, x2, y2; public movedText(int x1, int y1, int x2, int y2){ this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public void paintText(Graphics g){ g.drawString("x1: "+x1+" y1: "+y1+" x2: "+x2+" y2: "+y2, x1, y1); } } class RedSquare{ private int xPos = 50; private int yPos = 50; private int width = 20; private int height = 20; public void setX(int xPos){ this.xPos = xPos; } public int getX(){ return xPos; } public void setY(int yPos){ this.yPos = yPos; } public int getY(){ return yPos; } public int getWidth(){ return width; } public int getHeight(){ return height; } public void paintSquare(Graphics g){ g.setColor(Color.RED); g.fillRect(xPos,yPos,width,height); g.setColor(Color.BLACK); g.drawRect(xPos,yPos,width,height); } } public static void main(String[] args){ JFrame frame = new drawCircle(); frame.setTitle("Is in ellipse? Demo"); frame.setSize(400, 400); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }

    Read the article

  • Using addMouseListener() and paintComponent() for JPanel

    - by Alex
    This is a follow-up to my previous question. I've simplified things as much as I could, and it still doesn't work! Although the good thing I got around using getGraphics(). A detailed explanation on what goes wrong here is massively appreciated. My suspicion is that something's wrong with the the way I used addMouseListener() method here. import java.awt.Color; import java.awt.Graphics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JPanel; public class MainClass1{ private static PaintClass22 inst2 = new PaintClass22(); public static void main(String args[]){ JFrame frame1 = new JFrame(); frame1.add(inst2); frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame1.setTitle("NewPaintToolbox"); frame1.setSize(200, 200); frame1.setLocationRelativeTo(null); frame1.setVisible(true); } } class PaintClass11 extends MouseAdapter{ int xvar; int yvar; static PaintClass22 inst1 = new PaintClass22(); public PaintClass11(){ inst1.addMouseListener(this); inst1.addMouseMotionListener(this); } @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub xvar = arg0.getX(); yvar = arg0.getY(); inst1.return_paint(xvar, yvar); } } class PaintClass22 extends JPanel{ private static int varx; private static int vary; public void return_paint(int input1, int input2){ varx = input1; vary = input2; repaint(varx,vary,10,10); } public void paintComponent(Graphics g){ super.paintComponents(g); g.setColor(Color.RED); g.fillRect(varx, vary, 10, 10); } }

    Read the article

  • Background image in a JFrame.

    - by thepandaatemyface
    Hi, This question has been asked a lot but everywhere the answers fall short. I can get a JFrame to display a background image just fine by extending JPanel and overriding paintComponent, like so: class BackgroundPanel extends JPanel { private ImageIcon imageIcon; public BackgroundPanel() { this.imageIcon = Icons.getIcon("foo"); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(imageIcon.getImage(), 0,0,imageIcon.getIconWidth(),imageIcon.getIconHeight(),this); } } But now, how do you add a component on top of that background? When I go JFrame w = new JFrame() ; Container cp = w.getContentPane(); cp.setLayout(null); BackgroundPanel bg = new BackgroundPanel(); cp.add(bg); JPanel b = new JPanel(); b.setSize(new Dimension(30, 40)); b.setBackground(Color.red); cp.add(b); w.pack() w.setVisible(true) It shows the little red square (or any other component) and not the background, but when I remove cp.setLayout(null);, the background shows up but not my other component. I'm guessing this has something to do with the paintComponent not being called by the null LayoutManager, but I'm not at all familiar with how LayoutManagers work (this is a project for college and the assignment specifically says not to use a LayoutManager) When i make the image the background has to display null (and so, transparant (??)) the red square shows up so it might be that the background is actually above my other components) Does anyone anyone have any ideas? Thanks

    Read the article

  • java 2D and swing

    - by user384706
    Hi, I have trouble understanding a fundamental concept in Java 2D. To give a specific example: One can customize a swing component via implementing it's own version of the method paintComponent(Graphics g) Graphics is available to the body of the method. Question: What is exactly this Graphics object, I mean how it is related to the object that has the method paintComponent? Ok, I understand that you can do something like: g.setColor(Color.GRAY); g.fillOval(0, 0, getWidth(), getHeight()); To get a gray oval painted. What I can not understand is how is the Graphics object related to the component and the canvas. How is this drawing actually done? Another example: public class MyComponent extends JComponent { protected void paintComponent(Graphics g) { System.out.println("Width:"+getWidth()+", Height:"+getHeight()); } public static void main(String args[]) { JFrame f = new JFrame("Some frame"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(200, 90); MyComponent component = new MyComponent (); f.add(component); f.setVisible(true); } } This prints Width:184, Height:52 What does this size mean? I have not added anything to the frame of size(200,90). Any help on this is highly welcome Thanks

    Read the article

  • why PaintComponent event in Java happen everytime I use its Graphics Event?

    - by Pooya
    Consider this code: public class StateChartPanel extends JPanel { private LightContext LC; public StateChartPanel(LightContext lc){ LC=lc; } public void paintComponent( Graphics G ){ super.paintComponent( G ); LC.DrawStateChart((Graphics2D)G); } } StateChartPanel is a panel to draw something (a state chart). It sends its Graphics object to LC which use it to draw shapes but whenever it draws something the PaintComponent event of StateChartPanel happens again and it causes my application to hang.

    Read the article

  • How do I make a rectangle move in an image?

    - by alicedimarco
    Basically I have an image loaded, and when I click a portion of the image, a rectangle (with no fill) shows up. If I click another part of the image again, that rectangle will show up once more. With each click, the same rectangle should appear. So far I have this code, now I don't know how to make the image appear. My image from my file directory. I have already made the code to get the image from my file directory. import java.awt.Color; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class MP2 extends JPanel implements MouseListener{ JFrame frame; JPanel panel; int x = 0; int y = 0; String input; public MP2(){ } public static void main(String[] args){ JFrame frame = new JFrame(); MP2 panel = new MP2(); panel.addMouseListener(panel); frame.add(panel); frame.setSize(200,200); frame.setVisible(true); } public void mouseClicked(MouseEvent event) { // TODO Auto-generated method stub this.x = event.getX(); this.y = event.getY(); this.repaint(); input = JOptionPane.showInputDialog("Something pops out"); System.out.println(input); } public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } public void paintComponent(Graphics g){ super.paintComponent(g); // this.setBackground(Color.white); *Sets the bg color of the panel g.setColor(new Color(255,0,0)); g.drawRect(x, y, 100, 100); } }

    Read the article

  • JTabbedPane: only first tab is drawn, the second is always empty (newbie Q)

    - by paul
    I created a very simple JTabbedPane by first creating an empty JTabbedPane object, then 2 JPanels that I later add. Each JPanel is holding a object that extends JButton and implements MouseListener. Each of these holds a different image loaded from a file; the image is held locally as a buffered image and as an image icon, etc., all of which works great. The point of all that is to allow resizing of the image when the button is resized (using getscaledinstance()), because the panel is resized, because the JTabbedPane is resized, etc., within the JFrame that holds everything. I override paintComponent() to accomplish this in the class that extends JButton. I am using MigLayout Manager, and all is well on that front controlling layout constraints, growing, filling, initial sizes, preferred sizes, etc. The images the buttons hold are of different sizes and proportions, but this caused no trouble before. Up until 2 days ago everything worked fairly well. I made some changes trying to tweak some resizing issues as I was picking up MigLayout manager. At the time I was playing around with setting various min, max, and preferred sizes using the methods provided for by the components, not the layout manager. I also fooled a bit with pack(), validate(), visible(), opaque() etc., and yes I read the article about Swing and AWT painting here: http://java.sun.com/products/jfc/tsc/articles/painting/ , and I switched to relying more and more on MigLayout. On an unrelated note, it appears JFrame's do not honor maxsize? Somehow, today, with and without using any of these methods provided by swing, with or without using MigLayout manager to handle some of these matters instead, I now have a JTabbedPane that correctly displays the FIRST JPanel I add, but NOT THE SECOND JPanel--which, while present as a tab--does not show when selected. I have switched the order of which panel is added first, and this still holds true regardless of which JPanel I add first, telling me the JPanels are ok, and the problem is most likely in the JTabbedPane. I click on the second tab, the JTabbedPane switches, but I have what appears to be a blank button in the JPanel. A few console system-out statements reveal the following: a) that the second panel and its button are constructed b) no mouse events are being captured when I click on where the second panel and button should reside, as if it didn't exist at that point; c) when I switch to the second tab, the overrided paintComponent() method of the button within that second JPanel is never called, so it is in fact never being painted despite the tab in which it resides becoming visible; d) the JTabbpedPane getComponentCount() returns a correct value of 2 after adding the 2nd panel; e) MigLayout manager actually rocks, but I digress... I cannot now revert to my older code, and despite my best efforts to undo whatever changes caused this, I cannot fix my new problem. I've commented out everything but the most essential calls: constructors for each object--with MigLayout; add() for placing the buttons on the panels using string-arguments appropriate for MigLayout; add() for placing the panels on the JTabbedPane, also with MigLayout string arguments; setting the default op on close for the JFrame; and setting the JFrame visible. This means I do not fiddle with optimization settings, double buffering settings, opaque settings, but leave them as default, and still, no fix; the second panel will not show itself. Each panel, I should add, when it is the first to be loaded, works fine, again re-affirming that the panels and buttons are themselves ok. Here is part of what I am doing: //Note: BuildaButton is a class that merely constructs my instances File f = new File("/foo.jpg"); button1 = new BuildaButton().BuildaButton(f).buildfoo1Button(); f = new File("/foo2.jpg"); button2 = new BuildaButton().BuildaButton(f).buildfoo2Button(); MigLayout ml = new MigLayout("wrap 1", "[fill, grow]0[fill, grow]", "[fill, grow]0[fill, grow]"); MigLayout ml2 = new MigLayout("wrap 2", "[fill, grow]5[fill, grow]", "[fill, grow]0[fill, grow]"); foo1panel = new JPanel(ml); foo1panel.add(button1, "w 234:945:, h 200:807:"); foo2panel = new JPanel(ml); foo2panel.add(button2, "w 186:752:, h 200:807:"); tabs.add("foo1", foo1panel); tabs.add("foo2", foo2panel); System.out.println("contents of tabs: " + tabs.getComponentCount() + " elements"); mainframe.setLayout(ml2); mainframe.setMinimumSize(new Dimension(850,800)); mainframe.add(tabs, "w 600:800:, h 780:780:"); //controlpanel is a still blank jpanel that holds nothing--it is a space holder for now & will be utilized mainframe.add(controlpanel, "w 200:200:200, h 780:780:"); mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainframe.setVisible(true); Thank you in advance for any help you can give.

    Read the article

  • Java Swing NullPointerException when drawing

    - by juFo
    I'm using a custom JLayeredPane. I have several Shapes which needed to be drawn on different layers in the JLayeredPane. To test this I create a JPanel and ask its graphics. Then I draw a test rectangle on that JPanel (preparing the graphics) and in my paintComponent method from the JLayeredPane I finally draw everything. But this fails (NullPointerException). public class MyCustomPanel extends JLayeredPane { // test JPanel testpane; Graphics g2; // test // constructor public MyCustomPanel() { testpane = new JPanel(); this.add(testpane, new Integer(14)); g2 = testpane.getGraphics(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g2.drawRect(10, 10, 300, 300); } } // run: //Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException // at view.MyCustomPanel.paintComponent(MyCustomPanel.java:65) Why can't I draw on such a JPanel from within my JLayeredPane? I can draw directly on my JLayeredPane from within my paintComponent method but that's on the default Panel from the JLayeredPane. I need to create and draw on several layers which are added in my JLayeredPane. What am I doing wrong? :s

    Read the article

  • Java repaint is slow under certain conditions.

    - by Gabriel A. Zorrilla
    I'm doing a simple grid which each square is highlighted by the cursor: They are a couple of JPanels, mapgrid and overlay inside a JLayeredPane, with mapgrid on the bottom. Mapgrid just draws on initialization the grid, its paint metodh is: public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { g2d.setColor(new Color(128, 128, 128, 255)); g2d.drawRect(tileSize * j, i * tileSize, tileSize, tileSize); } } In the overlay JPanel is where the highlighting occurs, this is what is repainted when the mouse is moved: public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setColor(new Color(255, 255, 128, 255)); g2d.drawRect((pointerX/tileSize)*tileSize,(pointerY/ tileSize)*tileSize, tileSize, tileSize); } I noticed that even though the base layer (mapgrid) is NOT repainted when the mouse moves, just the transparent overlay layer, the performance is lacking. If i give the overlay JPanel a background, its way faster. If i remove the mapgrid Antialiasing, its a bit faster too. I don't know why giving a background to the overlay layer (and thus, hiding the mapgrid) or disabling antialiasing in the mapgrid leads to much better performance. Is there a better way to do this? Why does this happen?

    Read the article

  • fast java2d translucency

    - by mdriesen
    I'm trying to draw a bunch of translucent circles on a Swing JComponent. This isn't exactly fast, and I was wondering if there is a way to speed it up. My custom JComponent has the following paintComponent method: public void paintComponent(Graphics g) { Rectangle view = g.getClipBounds(); VolatileImage image = createVolatileImage(view.width, view.height); Graphics2D buffer = image.createGraphics(); // translate to camera location buffer.translate(-cx, -cy); // renderables contains all currently visible objects for(Renderable r : renderables) { r.paint(buffer); } g.drawImage(image.getSnapshot(), view.x, view.y, this); } The paint method of my circles is as follows: public void paint(Graphics2D graphics) { graphics.setPaint(paint); graphics.fillOval(x, y, radius, radius); } The paint is just an rgba color with a < 255: Color(int r, int g, int b, int a) It works fast enough for opaque objects, but is there a simple way to speed this up for translucent ones?

    Read the article

  • Custom JComponent not displaying in Custom JPanel

    - by Trizicus
    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. import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JComponent; public class Test extends JComponent { Test() { setOpaque(false); setBackground(Color.white); } @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(); } } import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.geom.Rectangle2D; import javax.swing.JPanel; public class GraphicsTest extends JPanel implements MouseListener { private Graphics2D g2d; private String state; private int x, y; GraphicsTest() { add(new Test()); } @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(); } public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }

    Read the article

  • Multiple Graphics2D Objects

    - by Trizicus
    I have a Graphics object of JPanel and that is working fine: 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; @Override public void paintComponent(Graphics g) { super.paintComponent(g); g2d = (Graphics2D) g; g2d.setClip(0, 0, getWidth(), getHeight()); 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); Test t = new Test(); super.add(t); repaint(); } public void setState(String state) { this.state = state; } public String getState() { return state; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } } I was experimenting with a new Graphics component and when I instantiate a new Test and add it in GraphicsTest nothing happens. What is it that I am doing wrong? import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import javax.swing.JComponent; public class Test extends JComponent { private Graphics2D g2d; private String state; private int x, y; @Override public void paintComponent(Graphics g) { super.paintComponent(g); g2d = (Graphics2D) g.create(); g2d.setColor(Color.GREEN); g2d.fill(new Rectangle2D.Double(60, 60, 10, 10)); repaint(); } public void setState(String state) { this.state = state; } public String getState() { return state; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } } Thanks!

    Read the article

  • Custom Swing component: questions on approach

    - by phatmanace
    Hi Folks, I'm trying to build a new java swing component, I realise that I might be able to find one that does what I need on the web, but this is partly an exercise for me to learn ow to do this. I want to build a swing component that represents a Gantt chart. it would be good (though not essential for people to be able to interact with it (e.g slide the the tasks around to adjust timings) it feels like the best approach for this is to subclass JComponent, and override PaintComponent() to 'draw a picture' of what the chart should look like, as opposed to doing something like trying to jam everything into a custom JTable. I've read a couple of books on the subject, and also looked at a few examples (most notably things like JXGraph) - but I'm curious about a few things When do I have to switch to using UI delegates, and when can I stick to just fiddling around in paintcomponent() to render what I want? if I want other swing components as sub-elements of my component (e.g I wanted a text box on my gantt chart) can I no longer use paintComponent()? can I arbitrarily position them within my Gantt chart, or do I have to use a normal swing layout manager many thanks in advance. -Ace

    Read the article

  • JTable cells not rendering shapes properly

    - by Andrew
    I'm trying to render my JTable cells with a subclassed JPanel and the cells should appear as coloured rectangles with a circle drawn on them. When the table displays initially everything looks OK but then when a dialog or something is displayed over the cells when it is removed the cells that have been covered do not rendered properly and the circles are broken up etc. I then have to move the scroll bar or extend the window to get them to redraw properly. The paintComponent method of the component I'm using to render the cells is below: protected void paintComponent(Graphics g) { setOpaque(true); super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; GradientPaint gradientPaint = new GradientPaint(new Point2D.Double(0, 0), Color.WHITE, new Point2D.Double(0, getHeight()), paintRatingColour); g2d.setPaint(gradientPaint); g2d.fillRect(0, 0, getWidth(), getHeight()); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); Rectangle clipBounds = g2d.getClipBounds(); int x = new Double(clipBounds.getWidth()).intValue() - 15; int y = (new Double(clipBounds.getHeight()).intValue() / 2) - 6; if (level != null) { g2d.setColor(iconColour); g2d.drawOval(x, y, width, height); g2d.fillOval(x, y, width, height); } }

    Read the article

  • What is the error in this java code ? What changes should I do to remove it ?

    - by mekasperasky
    import javax.swing.*; // For JPanel, etc. import java.awt.*; // For Graphics, etc. import java.awt.geom.*; // For Ellipse2D, etc. public class ShapeExample extends JPanel { private Ellipse2D.Double circle = new Ellipse2D.Double(10, 10, 350, 350); private Rectangle2D.Double square = new Rectangle2D.Double(10, 10, 350, 350); public void paintComponent(Graphics g) { clear(g); Graphics2D g2d = (Graphics2D)g; g2d.fill(circle); g2d.draw(square); } // super.paintComponent clears offscreen pixmap, // since we're using double buffering by default. protected void clear(Graphics g) { super.paintComponent(g); } protected Ellipse2D.Double getCircle() { return(circle); } public static void main(String[] args) { WindowUtilities.openInJFrame(new ShapeExample(), 100, 100); } } The error I am getting is this . symbol : variable WindowUtilities location: class ShapeExample WindowUtilities.openInJFrame(new ShapeExample(), 100, 100); ^ 1 error What is wrong in the code? r

    Read the article

  • Move multiple BufferedImage in Java2D?

    - by zo0mbie
    How can I mousedrag different BufferedImages in Java2D? For instance, if I have ten or more images, how can I move that images which my mouse is over? Now I'm importing an BufferedImage with BufferedImage img = new BufferdImage(new File("filename")); And I'm painting this with Graphics2D with public void paintComponent(Graphics g) { super.paintComponent(g); g2d = (Graphics2D) g; g2d.drawImage(img, x1, y1, null); g2d.drawImage(img2, x2, y2,null); } Everytime I'm moving on a image I'm repaint()-ing the entire screen. My mousemove class is as follows class MouseMotionHandler extends MouseMotionAdapter { @Override public void mouseDragged(MouseEvent e) { x1 = e.getX() - (img.getWidth() / 2); y1 = e.getY() - (img.getHeight() / 2); repaint(); } } With this method I'm able to "drag" one picture, but what to do when I will drag more individually?

    Read the article

  • JPanel Layout Image Cutoff

    - by Trizicus
    I am adding images to a JPanel but the images are getting cut off. I was originally trying BorderLayout but that only worked for one image and adding others added image cut-off. So I switched to other layouts and the best and closest I could get was BoxLayout however that adds a very large cut-off which is not acceptable either. So basically; How can I add images (from a custom JComponent) to a custom JPanel without bad effects such as the one present in the code. Custom JPanel: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.BoxLayout; import javax.swing.JPanel; import javax.swing.Timer; public class GraphicsPanel extends JPanel implements MouseListener { private Entity test; private Timer timer; private long startTime = 0; private int numFrames = 0; private float fps = 0.0f; GraphicsPanel() { test = new Entity("test.png"); Thread t1 = new Thread(test); t1.start(); Entity ent2 = new Entity("images.jpg"); ent2.setX(150); ent2.setY(150); Thread t2 = new Thread(ent2); t2.start(); Entity ent3 = new Entity("test.png"); ent3.setX(0); ent3.setY(150); Thread t3 = new Thread(ent3); t3.start(); //ESSENTIAL setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); add(test); add(ent2); add(ent3); //GAMELOOP timer = new Timer(30, new Gameloop(this)); timer.start(); addMouseListener(this); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); g2.setClip(0, 0, getWidth(), getHeight()); g2.setColor(Color.BLACK); g2.drawString("FPS: " + fps, 1, 15); } public void getFPS() { ++numFrames; if (startTime == 0) { startTime = System.currentTimeMillis(); } else { long currentTime = System.currentTimeMillis(); long delta = (currentTime - startTime); if (delta > 1000) { fps = (numFrames * 1000) / delta; numFrames = 0; startTime = currentTime; } } } public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } class Gameloop implements ActionListener { private GraphicsPanel gp; Gameloop(GraphicsPanel gp) { this.gp = gp; } public void actionPerformed(ActionEvent e) { try { gp.getFPS(); gp.repaint(); } catch (Exception ez) { } } } } Main class: import java.awt.EventQueue; import javax.swing.JFrame; public class MainWindow { public static void main(String[] args) { new MainWindow(); } private JFrame frame; private GraphicsPanel gp = new GraphicsPanel(); MainWindow() { EventQueue.invokeLater(new Runnable() { public void run() { frame = new JFrame("Graphics Practice"); frame.setSize(680, 420); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(gp); } }); } } Custom JComponent import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import javax.swing.JComponent; public class Entity extends JComponent implements Runnable { private BufferedImage bImg; private int x = 0; private int y = 0; private int entityWidth, entityHeight; private String filename; Entity(String filename) { this.filename = filename; } public void run() { bImg = loadBImage(filename); entityWidth = bImg.getWidth(); entityHeight = bImg.getHeight(); setPreferredSize(new Dimension(entityWidth, entityHeight)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.drawImage(bImg, x, y, null); g2d.dispose(); } public BufferedImage loadBImage(String filename) { try { bImg = ImageIO.read(getClass().getResource(filename)); } catch (Exception e) { } return bImg; } public int getEntityWidth() { return entityWidth; } public int getEntityHeight() { return entityHeight; } public int getX() { return x; } public int getY() { return y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } }

    Read the article

  • Make text appear briefly in a JPanel

    - by Roo
    Hi, I am trying to make text appear briefly before it disappears. It would be along the lines of 1) Set color to black 2) wait x amount of seconds 3) set color to background color The method I call is repaint(), which then calls paintComponent(Graphics painter). repaint() is called only if I press the space-bar. I thought of trying repaint();Thread.sleep(1000);repaint(); (I do catch the Interrupt exception, just not shown), but it only calls paintComponent once per space-bar . Is there an easy way to do this or is this something that is a bit challenging?

    Read the article

  • saving and retrieving a text file in java?

    - by user3319432
    import java.sql. ; import java.awt.; import javax.swing.; import java.awt.event.; public class saving extends JFrame implements ActionListener{ JTextField edpno=new JTextField(10); JLabel l0= new JLabel ("EDP Number: "); JComboBox fname = new JComboBox(); JLabel l1= new JLabel("First Name: "); JTextField lname= new JTextField(20); JLabel l2= new JLabel("Last Name: "); // JTextField contno= new JTextField(20); // JLabel l3= new JLabel("Contact Number: "); JComboBox contno = new JComboBox(); JLabel l3 = new JLabel ("Contact Number: "); JButton bOK = new JButton("Save"); JButton bRetrieve = new JButton("Retrieve"); private ImageIcon icon; JPanel C=new JPanel(){ protected void paintComponent(Graphics g){ g.drawImage(icon.getImage(),0,0,null); super.paintComponent(g); } }; public Search Record (){ icon=new ImageIcon("images/canres.png"); C.setOpaque(false); C.setLayout(new GridLayout(5,2,4,4)); setTitle("Search Record"); C.add (l0); C.add (edpno); edpno.addActionListener(this); C.add (l1); C.add (fname); fname.setForeground(Color.BLUE); fname.setFont(new Font(" ", Font.BOLD,15)); C.add (l2); C.add (lname); C.add (l3); C.add (contno); contno.setForeground(Color.BLUE); contno.setFont(new Font(" ", Font.BOLD,15)); C.add(bOK); bOK.addActionListener(this); C.add (bRetrieve); bRetrieve.addActionListener(this); bOK.setBackground(Color.white); bRetrieve.setBackground(Color.white); } public void saverecord(){ try{ //Connect to the Database Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String path ="jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ=Database/roomassign.mdb"; String DBPassword =""; String DBUserName =""; Connection con = DriverManager.getConnection(path,"",""); Statement s = con.createStatement(); s.executeQuery("select firstname, Lastname, contact number from name WHERE edpno ='"+edpno.getText()+"'"); ResultSet rs = s.getResultSet(); ResultSetMetaData md = rs.getMetaData(); while(rs.next()) { fname.setSelectedItem(rs.getString(1)); lname.setText(rs.getString(2)); contno.setSelectedItem(rs.getString(3)); // crs.setSelectedItem(rs.getString(4)); } s.close(); con.close(); } catch(Exception Q) { JOptionPane.showMessageDialog(this,Q); } } public void SaveRecord(){ try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String path = "jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ=Database/roomassign.mdb"; String DBPassword =""; String DBUsername =""; Connection con = DriverManager.getConnection(path,"",""); Statement s = con.createStatement(); String sql = "UPDATE rooms SET Firstname='"+fname.getSelectedItem()+"',Lastname='"+lname.getText()+"',Contactnumber='"+contno.getSelectedItem()+"' WHERE '"+edpno.getText()+"'=edpno"; s.executeUpdate(sql); JOptionPane.showMessageDialog(this,"New room Record has been successfully saved"); dispose(); s.close(); con.close(); } catch(Exception Mismatch){ JOptionPane.showMessageDialog(this,Mismatch); } } public void actionPerformed (ActionEvent ako){ if (ako.getSource() == bRetrieve){ dispose(); } else if (ako.getSource() == bOK){ SaveRecord(); } } public static void main (String [] awtsave){ new Search(); } }

    Read the article

  • Animation Trouble with Java Swing Timer - Also, JFrame Will Not Exit_On_Close

    - by forgotton_semicolon
    So, I am using a Java Swing Timer because putting the animation code in a run() method of a Thread subclass caused an insane amount of flickering that is really a terrible experience for any video game player. Can anyone give me any tips on: Why there is no animation... Why the JFrame will not close when it is coded to Exit_On_Close 2 times My code is here: import java.awt.; import java.awt.event.; import javax.swing.*; import java.net.URL; //////////////////////////////////////////////////////////////// TFQ public class TFQ extends JFrame { DrawingsInSpace dis; //========================================================== constructor public TFQ() { dis = new DrawingsInSpace(); JPanel content = new JPanel(); content.setLayout(new FlowLayout()); this.setContentPane(dis); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setTitle("Plasma_Orbs_Off_Orion"); this.setSize(500,500); this.pack(); //... Create timer which calls action listener every second.. // Use full package qualification for javax.swing.Timer // to avoid potential conflicts with java.util.Timer. javax.swing.Timer t = new javax.swing.Timer(500, new TimePhaseListener()); t.start(); } /////////////////////////////////////////////// inner class Listener thing class TimePhaseListener implements ActionListener, KeyListener { // counter int total; // loop control boolean Its_a_go = true; //position of our matrix int tf = -400; //sprite directions int Sprite_Direction; final int RIGHT = 1; final int LEFT = 2; //for obstacle Rectangle mega_obstacle = new Rectangle(200, 0, 20, HEIGHT); public void actionPerformed(ActionEvent e) { //... Whenever this is called, repaint the screen dis.repaint(); addKeyListener(this); while (Its_a_go) { try { dis.repaint(); if(Sprite_Direction == RIGHT) { dis.matrix.x += 2; } // end if i think if(Sprite_Direction == LEFT) { dis.matrix.x -= 2; } } catch(Exception ex) { System.out.println(ex); } } // end while i think } // end actionPerformed @Override public void keyPressed(KeyEvent arg0) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent event) { // TODO Auto-generated method stub if (event.getKeyChar()=='f'){ Sprite_Direction = RIGHT; System.out.println("matrix should be animating now "); System.out.println("current matrix position = " + dis.matrix.x); } if (event.getKeyChar()=='d') { Sprite_Direction = LEFT; System.out.println("matrix should be going in reverse"); System.out.println("current matrix position = " + dis.matrix.x); } } } //================================================================= main public static void main(String[] args) { JFrame SafetyPins = new TFQ(); SafetyPins.setVisible(true); SafetyPins.setSize(500,500); SafetyPins.setResizable(true); SafetyPins.setLocationRelativeTo(null); SafetyPins.setDefaultCloseOperation(EXIT_ON_CLOSE); } } class DrawingsInSpace extends JPanel { URL url1_plasma_orbs; URL url2_matrix; Image img1_plasma_orbs; Image img2_matrix; // for the plasma_orbs Rectangle bbb = new Rectangle(0,0, 0, 0); // for the matrix Rectangle matrix = new Rectangle(-400, 60, 430, 200); public DrawingsInSpace() { //load URLs try { url1_plasma_orbs = this.getClass().getResource("plasma_orbs.png"); url2_matrix = this.getClass().getResource("matrix.png"); } catch(Exception e) { System.out.println(e); } // attach the URLs to the images img1_plasma_orbs = Toolkit.getDefaultToolkit().getImage(url1_plasma_orbs); img2_matrix = Toolkit.getDefaultToolkit().getImage(url2_matrix); } public void paintComponent(Graphics g) { super.paintComponent(g); // draw the plasma_orbs g.drawImage(img1_plasma_orbs, bbb.x, bbb.y,this); //draw the matrix g.drawImage(img2_matrix, matrix.x, matrix.y, this); } } // end class enter code here

    Read the article

  • Rotate a Swing JLabel

    - by Johannes Rössel
    I am currently trying to implement a Swing component, inheriting from JLabel which should simply represent a label that can be oriented vertically. Beginning with this: public class RotatedLabel extends JLabel { public enum Direction { HORIZONTAL, VERTICAL_UP, VERTICAL_DOWN } private Direction direction; I thought it's be a nice idea to just alter the results from getPreferredSize(): @Override public Dimension getPreferredSize() { // swap size for vertical alignments switch (getDirection()) { case VERTICAL_UP: case VERTICAL_DOWN: return new Dimension(super.getPreferredSize().height, super .getPreferredSize().width); default: return super.getPreferredSize(); } } and then simply transform the Graphics object before I offload painting to the original JLabel: @Override protected void paintComponent(Graphics g) { Graphics2D gr = (Graphics2D) g.create(); switch (getDirection()) { case VERTICAL_UP: gr.translate0, getPreferredSize().getHeight()); gr.transform(AffineTransform.getQuadrantRotateInstance(-1)); break; case VERTICAL_DOWN: // TODO break; default: } super.paintComponent(gr); } } It seems to work—somehow—in that the text is now displayed vertically. However, placement and size are off: Actually, the width of the background (orange in this case) is identical with the height of the surrounding JFrame which is ... not quite what I had in mind. Any ideas how to solve that in a proper way? Is delegating rendering to superclasses even encouraged?

    Read the article

  • How to draw a circle in java with a radius and points around the edge

    - by windopal
    Hi, I'm really stuck on how to go about programming this. I need to draw a circle within a JFrame with a radius and points around the circumference. i can mathematically calculate how to find the coordinates of the point around the edge but i cant seem to be able to program the circle. I am currently using a Ellipse2D method but that doesn't seem to work and doesn't return a radius, as under my understanding, it doesn't draw the circle from the center rather from a starting coordinate using a height and width. My current code is on a separate frame but i need to add it to my existing frame. import java.awt.*; import javax.swing.*; import java.awt.geom.*; public class circle extends JFrame { public circle() { super("circle"); setSize(410, 435); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Panel sp = new Panel(); Container content = getContentPane(); content.add(sp); setContentPane(content); setVisible(true); } public static void main (String args[]){ circle sign = new circle(); } } class Panel extends JPanel { public void paintComponent(Graphics comp) { super.paintComponent(comp); Graphics2D comp2D = (Graphics2D) comp; comp2D.setColor(Color.red); Ellipse2D.Float sign1 = new Ellipse2D.Float(0F, 0F, 350F, 350F); comp2D.fill(sign1); } }

    Read the article

1 2 3 4  | Next Page >