Search Results

Search found 140 results on 6 pages for 'drawstring'.

Page 2/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • 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

  • Django and Reportlab Question

    - by Hellnar
    Hello, I have written this small Django view to return pdf. @login_required def code_view(request,myid): try: deal = Deal.objects.get(id=myid) except: raise Http404 header = deal.header code = deal.code response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=code.pdf' p = canvas.Canvas(response) p.drawString(10, 800, header) p.drawString(10, 700, code) p.showPage() p.save() return response And my questions: Utf-8 characters are not shown correctly within the pdf. How can I include an image ? How can I include a very basic html such as: . <ul> <li>List One</li> <li>List Two</li> <li>List Three</li> </ul>

    Read the article

  • How do I remove the time from printpreview dialog?

    - by Albo Best
    Here is my code: Imports System.Data.OleDb Imports System.Drawing.Printing Namespace Print Public Class Form1 Inherits System.Windows.Forms.Form Dim PrintC As PrinterClass Dim conn As OleDb.OleDbConnection Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\db1.mdb" Dim sql As String = String.Empty Dim ds As DataSet Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load FillDataGrid() '//create printerclass object PrintC = New PrinterClass(PrintDocument1, dataGrid) End Sub Private Sub FillDataGrid() Try Dim dt As New DataTable Dim ds As New DataSet ds.Tables.Add(dt) Dim da As New OleDbDataAdapter con.Open() da = New OleDbDataAdapter("SELECT * from klient ", con) da.Fill(dt) con.Close() dataGrid.DataSource = dt.DefaultView Dim dTable As DataTable For Each dTable In ds.Tables Dim dgStyle As DataGridTableStyle = New DataGridTableStyle dgStyle.MappingName = dTable.TableName dataGrid.TableStyles.Add(dgStyle) Next ' DataGrid settings dataGrid.CaptionText = "TE GJITHE KLIENTET" dataGrid.HeaderFont = New Font("Verdana", 12) dataGrid.TableStyles(0).GridColumnStyles(0).Width = 60 dataGrid.TableStyles(0).GridColumnStyles(1).Width = 140 dataGrid.TableStyles(0).GridColumnStyles(2).Width = 140 dataGrid.TableStyles(0).GridColumnStyles(3).Width = 140 dataGrid.TableStyles(0).GridColumnStyles(4).Width = 140 dataGrid.TableStyles(0).GridColumnStyles(5).HeaderText = "" dataGrid.TableStyles(0).GridColumnStyles(5).Width = -1 Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click 'create printerclass object PrintC = New PrinterClass(PrintDocument1, dataGrid) PrintDocument1.Print() End Sub Private Sub btnPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPreview.Click 'create printerclass object PrintC = New PrinterClass(PrintDocument1, dataGrid) ''preview Dim ps As New PaperSize("A4", 840, 1150) ps.PaperName = PaperKind.A4 PrintDocument1.DefaultPageSettings.PaperSize = ps PrintPreviewDialog1.WindowState = FormWindowState.Normal PrintPreviewDialog1.StartPosition = FormStartPosition.CenterScreen PrintPreviewDialog1.ClientSize = New Size(600, 600) PrintPreviewDialog1.ShowDialog() End Sub Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage 'print grid Dim morepages As Boolean = PrintC.Print(e.Graphics) If (morepages) Then e.HasMorePages = True End If End Sub End Class End Namespace This is how data looks in DataGrid (that's perfect)... and here is how it looks when I click PrintPreview. (I don't want the time to appear there, the "12:00:00" part. in database the date is stored as Short Date (10-Dec-12) Can somebody suggest a way around that? Imports System Imports System.Windows.Forms Imports System.Drawing Imports System.Drawing.Printing Imports System.Collections Imports System.Data Namespace Print Public Class PrinterClass '//clone of Datagrid Dim PrintGrid As Grid '//printdocument for initial printer settings Private PrintDoc As PrintDocument '//defines whether the grid is ordered right to left Private bRightToLeft As Boolean '//Current Top Private CurrentY As Single = 0 '//Current Left Private CurrentX As Single = 0 '//CurrentRow to print Private CurrentRow As Integer = 0 '//Page Counter Public PageCounter As Integer = 0 '/// <summary> '/// Constructor Class '/// </summary> '/// <param name="pdocument"></param> '/// <param name="dgrid"></param> Public Sub New(ByVal pdocument As PrintDocument, ByVal dgrid As DataGrid) 'MyBase.new() PrintGrid = New Grid(dgrid) PrintDoc = pdocument '//The grid columns are right to left bRightToLeft = dgrid.RightToLeft = RightToLeft.Yes '//init CurrentX and CurrentY CurrentY = pdocument.DefaultPageSettings.Margins.Top CurrentX = pdocument.DefaultPageSettings.Margins.Left End Sub Public Function Print(ByVal g As Graphics, ByRef currentX As Single, ByRef currentY As Single) As Boolean '//use predefined area currentX = currentX currentY = currentY PrintHeaders(g) Dim Morepages As Boolean = PrintDataGrid(g) currentY = currentY currentX = currentX Return Morepages End Function Public Function Print(ByVal g As Graphics) As Boolean CurrentX = PrintDoc.DefaultPageSettings.Margins.Left CurrentY = PrintDoc.DefaultPageSettings.Margins.Top PrintHeaders(g) Return PrintDataGrid(g) End Function '/// <summary> '/// Print the Grid Headers '/// </summary> '/// <param name="g"></param> Private Sub PrintHeaders(ByVal g As Graphics) Dim sf As StringFormat = New StringFormat '//if we want to print the grid right to left If (bRightToLeft) Then CurrentX = PrintDoc.DefaultPageSettings.PaperSize.Width - PrintDoc.DefaultPageSettings.Margins.Right sf.FormatFlags = StringFormatFlags.DirectionRightToLeft Else CurrentX = PrintDoc.DefaultPageSettings.Margins.Left End If Dim i As Integer For i = 0 To PrintGrid.Columns - 1 '//set header alignment Select Case (CType(PrintGrid.Headers.GetValue(i), Header).Alignment) Case HorizontalAlignment.Left 'left sf.Alignment = StringAlignment.Near Case HorizontalAlignment.Center sf.Alignment = StringAlignment.Center Case HorizontalAlignment.Right sf.Alignment = StringAlignment.Far End Select '//advance X according to order If (bRightToLeft) Then '//draw the cell bounds (lines) and back color g.FillRectangle(New SolidBrush(PrintGrid.HeaderBackColor), CurrentX - PrintGrid.Headers(i).Width, CurrentY, PrintGrid.Headers(i).Width, PrintGrid.Headers(i).Height) g.DrawRectangle(New Pen(PrintGrid.LineColor), CurrentX - PrintGrid.Headers(i).Width, CurrentY, PrintGrid.Headers(i).Width, PrintGrid.Headers(i).Height) '//draw the cell text g.DrawString(PrintGrid.Headers(i).CText, PrintGrid.Headers(i).Font, New SolidBrush(PrintGrid.HeaderForeColor), New RectangleF(CurrentX - PrintGrid.Headers(i).Width, CurrentY, PrintGrid.Headers(i).Width, PrintGrid.Headers(i).Height), sf) '//next cell CurrentX -= PrintGrid.Headers(i).Width Else '//draw the cell bounds (lines) and back color g.FillRectangle(New SolidBrush(PrintGrid.HeaderBackColor), CurrentX, CurrentY, PrintGrid.Headers(i).Width, PrintGrid.Headers(i).Height) g.DrawRectangle(New Pen(PrintGrid.LineColor), CurrentX, CurrentY, PrintGrid.Headers(i).Width, PrintGrid.Headers(i).Height) '//draw the cell text g.DrawString(PrintGrid.Headers(i).CText, PrintGrid.Headers(i).Font, New SolidBrush(PrintGrid.HeaderForeColor), New RectangleF(CurrentX, CurrentY, PrintGrid.Headers(i).Width, PrintGrid.Headers(i).Height), sf) '//next cell CurrentX += PrintGrid.Headers(i).Width End If Next '//reset to beginning If (bRightToLeft) Then '//right align CurrentX = PrintDoc.DefaultPageSettings.PaperSize.Width - PrintDoc.DefaultPageSettings.Margins.Right Else '//left align CurrentX = PrintDoc.DefaultPageSettings.Margins.Left End If '//advance to next row CurrentY = CurrentY + CType(PrintGrid.Headers.GetValue(0), Header).Height End Sub Private Function PrintDataGrid(ByVal g As Graphics) As Boolean Dim sf As StringFormat = New StringFormat PageCounter = PageCounter + 1 '//if we want to print the grid right to left If (bRightToLeft) Then CurrentX = PrintDoc.DefaultPageSettings.PaperSize.Width - PrintDoc.DefaultPageSettings.Margins.Right sf.FormatFlags = StringFormatFlags.DirectionRightToLeft Else CurrentX = PrintDoc.DefaultPageSettings.Margins.Left End If Dim i As Integer For i = CurrentRow To PrintGrid.Rows - 1 Dim j As Integer For j = 0 To PrintGrid.Columns - 1 '//set cell alignment Select Case (PrintGrid.Cell(i, j).Alignment) '//left Case HorizontalAlignment.Left sf.Alignment = StringAlignment.Near Case HorizontalAlignment.Center sf.Alignment = StringAlignment.Center '//right Case HorizontalAlignment.Right sf.Alignment = StringAlignment.Far End Select '//advance X according to order If (bRightToLeft) Then '//draw the cell bounds (lines) and back color g.FillRectangle(New SolidBrush(PrintGrid.BackColor), CurrentX - PrintGrid.Cell(i, j).Width, CurrentY, PrintGrid.Cell(i, j).Width, PrintGrid.Cell(i, j).Height) g.DrawRectangle(New Pen(PrintGrid.LineColor), CurrentX - PrintGrid.Cell(i, j).Width, CurrentY, PrintGrid.Cell(i, j).Width, PrintGrid.Cell(i, j).Height) '//draw the cell text g.DrawString(PrintGrid.Cell(i, j).CText, PrintGrid.Cell(i, j).Font, New SolidBrush(PrintGrid.ForeColor), New RectangleF(CurrentX - PrintGrid.Cell(i, j).Width, CurrentY, PrintGrid.Cell(i, j).Width, PrintGrid.Cell(i, j).Height), sf) '//next cell CurrentX -= PrintGrid.Cell(i, j).Width Else '//draw the cell bounds (lines) and back color g.FillRectangle(New SolidBrush(PrintGrid.BackColor), CurrentX, CurrentY, PrintGrid.Cell(i, j).Width, PrintGrid.Cell(i, j).Height) g.DrawRectangle(New Pen(PrintGrid.LineColor), CurrentX, CurrentY, PrintGrid.Cell(i, j).Width, PrintGrid.Cell(i, j).Height) '//draw the cell text '//Draw text by alignment g.DrawString(PrintGrid.Cell(i, j).CText, PrintGrid.Cell(i, j).Font, New SolidBrush(PrintGrid.ForeColor), New RectangleF(CurrentX, CurrentY, PrintGrid.Cell(i, j).Width, PrintGrid.Cell(i, j).Height), sf) '//next cell CurrentX += PrintGrid.Cell(i, j).Width End If Next '//reset to beginning If (bRightToLeft) Then '//right align CurrentX = PrintDoc.DefaultPageSettings.PaperSize.Width - PrintDoc.DefaultPageSettings.Margins.Right Else '//left align CurrentX = PrintDoc.DefaultPageSettings.Margins.Left End If '//advance to next row CurrentY += PrintGrid.Cell(i, 0).Height CurrentRow += 1 '//if we are beyond the page margin (bottom) then we need another page, '//return true If (CurrentY > PrintDoc.DefaultPageSettings.PaperSize.Height - PrintDoc.DefaultPageSettings.Margins.Bottom) Then Return True End If Next Return False End Function End Class End Namespace

    Read the article

  • int cannot be dereferenced

    - by Overlord
    Hello, I am beginning in java (I'm learning in microedition) and I got this error: "int cannot be dereferenced" in the following class: class DCanvas extends Canvas{ public DCanvas(){ } public void drawString(String str, int x, int y, int r, int g, int b){ g.setColor(r, g, b); //The error is here g.drawString(str, x, y, 0); //and here } public void paint(Graphics g){ g.setColor(100, 100, 220); g.fillRect(0, 0, getWidth(), getHeight()); } } What am I doing wrong here? Well I came from PHP and ECMAScripts where I was able to pass my function arguments this way so I really don't understand this error.

    Read the article

  • Read Text From Windows Form

    - by omghai2u
    I would like, if for no other reason that an academic exercise, to be able to read text written to a form on a Windows Application. The program appears to be written in non-.NET, but in .NET terms, I think you would describe the program as having a Form with a Label and I would like to read the text from that label. I believe I can see that text being written to the screen with the User32!TextOut (and in other areas User32!DrawString) function. However, it would be nice if I didn't have to hook that function to get the information I'm looking for, but instead if I could just read it from the form directly. So, given a handle to a Window, is it possible to read the text that has been written to that window with functions like TextOut and DrawString using some similar API or other clever means? Or am I going about this the wrong way? Should I just hook the function and look for the text in every call and pray? Thanks!

    Read the article

  • Getting problem in threading in JAVA

    - by chetans
    In this program i want to stop GenerateImage & MovingImage Thread both... And i want to start those threads from begining. Can u send me the solution? Here is the code........ package Game; import java.applet.Applet; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.MediaTracker; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.net.MalformedURLException; import java.net.URL; public class ThreadInApplet extends Applet implements KeyListener { private static final long serialVersionUID = 1L; Image[] asteroidImage; Image spaceshipImage; String levelstr="Easy Level"; int[] XPos,YPos; int number=0,XPosOfSpaceship,YPosOfSpaceship,NoOfObstacles=5,speed=1,level=1,spaceBtnPressdCntr=0; boolean gameStart=false,pauseGame=false,collideUp=false,collideDown=false,collideLeft=false,collideRight=false; private Image offScreenImage; private Dimension offScreenSize; private Graphics offScreenGraphics; Thread GenerateImages,MoveImages; public void init() { try { GenerateImages=new Thread () //thread to create obstacles { synchronized public void run () { for(int g=0;g<NoOfObstacles;g++) { try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } number++; // Temporary counter to count the no of obstacles created } } } ; MoveImages=new Thread () //thread to move obstacles { @SuppressWarnings("deprecation") synchronized public void run () { while(YPos[NoOfObstacles-1]!=600) { pauseGame=false; if(collide()==true) { GenerateImages.suspend(); repaint(); } else GenerateImages.resume(); for(int l=0;l<number;l++) { if(collide()==false) YPos[l]++; else GenerateImages.suspend(); } repaint(); try { sleep(speed); } catch (InterruptedException e) { e.printStackTrace(); } } if(YPos[NoOfObstacles-1]>=600) //level complete state { level++; try { levelUpdation(level); System.out.println("aahe"); } catch (MalformedURLException e) { e.printStackTrace(); } repaint(); } } }; initialPos(); spaceshipImage=getImage(new URL(getCodeBase(),"images/space.png")); for(int i=0;i<NoOfObstacles;i++) { asteroidImage[i]=getImage(new URL(getCodeBase(),"images/asteroid.png")); XPos[i]=(int) (Math.random()*700); YPos[i]=0; } MediaTracker tracker = new MediaTracker (this); for(int i=0;i<NoOfObstacles;i++) { tracker.addImage (asteroidImage[i], 0); } } catch (MalformedURLException e) { e.printStackTrace(); } setBackground(Color.black); addKeyListener(this); } //Sets initial positions of spaceship & obstacle images------------------------------------------------------ public void initialPos() throws MalformedURLException { asteroidImage=new Image[NoOfObstacles]; XPos=new int[NoOfObstacles]; YPos=new int[NoOfObstacles]; XPosOfSpaceship=getWidth()/2-35; YPosOfSpaceship=getHeight()-100; collideUp = false; collideDown=false; collideLeft=false; collideRight=false; } //level finished updations------------------------------------------------------------------------------ @SuppressWarnings("deprecation") public void levelUpdation(int level) throws MalformedURLException { NoOfObstacles=NoOfObstacles+20; speed=speed-3; System.out.println(NoOfObstacles+" "+speed); pauseGame=true; initialPos(); repaint(); } //paint method of graphics to print the messages--------------------------------------------------------- public void paint(Graphics g) { g.setColor(Color.white); if(gameStart==false) { g.drawString("SPACE to start", (getWidth()/2)-15, getHeight()/2); g.drawString(levelstr, (getWidth()/2), getHeight()/2+20); } if(level>1) { if(level==2) levelstr="Medium Level"; else levelstr="High Level"; g.drawString("Level Complete ", (getWidth()/2)-15, getHeight()/2); g.drawString(levelstr, (getWidth()/2), getHeight()/2+20); //g.drawString("SPACE to start", (getWidth()/2)-15, getHeight()/2+40); } for(int n=0;n<number;n++) { if(n>0) g.drawImage(asteroidImage[n],XPos[n],YPos[n],this); } g.drawImage(spaceshipImage,XPosOfSpaceship,YPosOfSpaceship,this); } //update method of graphics to print the messages--------------------------------------------------------- @SuppressWarnings("deprecation") public void update(Graphics g) { Dimension d = size(); if((offScreenImage == null) || (d.width != offScreenSize.width) || (d.height != offScreenSize.height)) { offScreenImage = createImage(d.width, d.height); offScreenSize = d; offScreenGraphics = offScreenImage.getGraphics(); } offScreenGraphics.clearRect(0, 0, d.width, d.height); paint(offScreenGraphics); g.drawImage(offScreenImage, 0, 0, null); } public void keyReleased(KeyEvent arg0){} public void keyTyped(KeyEvent arg0) {} //---------------------Key pressed event to start game & to move the spaceship-------------------------------------- public void keyPressed(KeyEvent e) { if(e.getKeyCode()==32) { spaceBtnPressdCntr++; if(spaceBtnPressdCntr==1) { gameStart=true; GenerateImages.start(); MoveImages.start(); } } if(gameStart==true) { if(e.getKeyCode()==37) { new Thread () { @SuppressWarnings("deprecation") synchronized public void run () { for(int cnt1=1;cnt1<=10;cnt1++) { if(collide()==true && collideLeft == true) { GenerateImages.suspend(); } else { if(XPosOfSpaceship>0) XPosOfSpaceship--; } } repaint(); } }.start(); } if(e.getKeyCode()==38) { new Thread () { @SuppressWarnings("deprecation") synchronized public void run () { for(int cnt1=1;cnt1<=10;cnt1++) { if(collide()==true && collideUp == true) { GenerateImages.suspend(); } else { if(YPosOfSpaceship>10) YPosOfSpaceship--; } } repaint(); } }.start(); } if(e.getKeyCode()==39) { new Thread () { @SuppressWarnings("deprecation") synchronized public void run () { for(int cnt1=1;cnt1<=10;cnt1++) { if(collide()==true && collideRight == true) { GenerateImages.suspend(); } else { if(XPosOfSpaceship<750) XPosOfSpaceship++; } } repaint(); } }.start(); } if(e.getKeyCode()==40) { new Thread () { @SuppressWarnings("deprecation") synchronized public void run () { for(int cnt1=1;cnt1<=10;cnt1++) { if(collide()==true && collideDown == true) { GenerateImages.suspend(); } else { if(YPosOfSpaceship<550) YPosOfSpaceship++; } } repaint(); } }.start(); } } } //------------------------------Collision checking between Spaceship & obstacles------------------------------ public boolean collide() { int x1,y1,x2,y2,x3,y3,x4,y4; //coordinates of obstacles int a1,b1,a2,b2,a3,b3,a4,b4; //coordinates of spaceship a1 =XPosOfSpaceship; b1=YPosOfSpaceship; a2=a1+spaceshipImage.getWidth(this); b2=b1; a3=a1; b3=b1+spaceshipImage.getHeight(this); a4=a2; b4=b3; for(int a=0;a<number;a++) { x1 =XPos[a]; y1=YPos[a]; x2=x1+asteroidImage[a].getWidth(this); y2=y1; x3=x1; y3=y1+asteroidImage[a].getHeight(this); x4=x2; y4=y3; /********checking asteroid touch spaceship from up direction********/ if(y3==b1 && x4>=a1 && x4<=a2) { collideUp = true; collideDown=false; collideLeft=false; collideRight=false; return(true); } if(y3==b1 && x3>=a1 && x3<=a2) { collideUp = true; collideDown=false; collideLeft=false; collideRight=false; return(true); } /********checking asteroid touch spaceship from left direction******/ if(x2==a1 && y4>=b1 && y4<=b3) { collideLeft=true; collideUp = false; collideDown=false; collideRight=false; return(true); } if(x2==a1 && y2>=b1 && y2<=b3) { collideLeft=true; collideUp = false; collideDown=false; collideRight=false; return(true); } /********checking asteroid touch spaceship from right direction*****/ if(x1==a2 && y3>=b2 && y3<=b4) { collideRight=true; collideLeft=false; collideUp = false; collideDown=false; return(true); } if(x1==a2 && y1>=b2 && y1<=b4) { collideRight=true; collideLeft=false; collideUp = false; collideDown=false; return(true); } /********checking asteroid touch spaceship from down direction*****/ if(y1==b3 && x2>=a3 && x2<=a4) { collideDown=true; collideRight=false; collideLeft=false; collideUp = false; return(true); } if(y1==b3 && x1>=a3 && x1<=a4) { collideDown=true; collideRight=false; collideLeft=false; collideUp = false; return(true); } } return(false); } }

    Read the article

  • won't repaint a different Month after pressing button in my calendar

    - by DarkStar123
    I'm trying to build a Calendar in Java as a little project I thought of, But I can't seem to change the name of the Month every time I click the Next button. here's my code! package drawing; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Drawing_something extends JPanel{ int[] calender_squares = {1, 2, 3, 4, 5, 6, 7}; String[] Month = {"January", "February", "March", "April","May","June","July", "August","September","October","November","December"}; int i = 0; Graphics c; @Override public void paintComponent(Graphics c){ super.paintComponent(c); this.setBackground(Color.WHITE); int WIDTH = 55, HEIGHT = 65; for (int in: calender_squares) { for (int counter = 0; counter < 7; counter++){ c.drawRect(50, 50, 100, 100); c.drawRect(50, 50, 700, 500); c.copyArea(50, 50, 600, 500, 100, 0); c.copyArea(50, 50, 600, 400, 0, 100); } } for (int date = 1; date <= 30; date++) { String s = String.valueOf(date); c.drawString(s, WIDTH, HEIGHT); if (date <= 6){ WIDTH += 100; } else if (date == 7){ WIDTH = 55; HEIGHT = 165; }else if (date <= 13){ WIDTH += 100; }else if (date == 14){ WIDTH = 55; HEIGHT = 265; }else if (date <= 20){ WIDTH += 100; }else if (date == 21){ WIDTH = 55; HEIGHT = 365; }else if (date <= 27){ WIDTH += 100; }else if (date == 28){ WIDTH = 55; HEIGHT = 465; }else if (date <= 30){ WIDTH += 100; } } c.setFont(new Font("default", Font.BOLD, 40)); c.drawString(Month[i], 320, 45); } public Drawing_something(){ setLayout(new BorderLayout()); JButton N = new JButton("NEXT"); JButton B = new JButton("BACK"); JPanel P = new JPanel(); P.add(B); P.add(N); add(P, BorderLayout.SOUTH); B.addActionListener(new HandlerClass()); N.addActionListener(new NextClass()); } public class HandlerClass implements ActionListener{ public void actionPerformed(ActionEvent e){ } } public class NextClass implements ActionListener{ public void actionPerformed(ActionEvent e){ if (i == 11){ i = 0; } i = i + 1; c.drawString(Month[i], 320, 45); } } public static void main(String[] args){ JFrame mainFrame = new JFrame("Calender"); mainFrame.add(new Drawing_something()); mainFrame.setSize(850, 650); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setVisible(true); } } if anyone could help that would be much appreciated!! Thanks in advance!!

    Read the article

  • How to save image drawn on a JPanel?

    - by swift
    I have a panel with transparent background which i use to draw an image. now problem here is when i draw anything on panel and save the image as a JPEG file its saving the image with black background but i want it to be saved as same, as i draw on the panel. what should be done for this? plz guide me j Client.java public class Client extends Thread { static DatagramSocket datasocket; static DatagramSocket socket; Point point; Whiteboard board; Virtualboard virtualboard; JLayeredPane layerpane; BufferedImage image; public Client(DatagramSocket datasocket) { Client.datasocket=datasocket; } //This function is responsible to connect to the server public static void connect() { try { socket=new DatagramSocket (9000); //client connection socket port= 9000 datasocket=new DatagramSocket (9005); //client data socket port= 9002 ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baos); //this is to tell server that this is a connection request dos.writeChar('c'); dos.close(); byte[]data=baos.toByteArray(); //Server IP address InetAddress ip=InetAddress.getByName("10.123.97.154"); //create the UDP packet DatagramPacket packet=new DatagramPacket(data, data.length,ip , 8000); socket.send(packet); Client client=new Client(datasocket); client.createFrame(); client.run(); } catch(Exception e) { e.printStackTrace(); } } //This function is to create the JFrame public void createFrame() { JFrame frame=new JFrame("Whiteboard"); frame.setVisible(true); frame.setBackground(Color.black); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(680,501); frame.addWindowListener(new WindowAdapter() { public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) { close(); } }); layerpane=frame.getLayeredPane(); board= new Whiteboard(datasocket); image = new BufferedImage(590,463, BufferedImage.TYPE_INT_ARGB); board.setBounds(74,2,590,463); board.setImage(image); virtualboard=new Virtualboard(); virtualboard.setImage(image); virtualboard.setBounds(74,2,590,463); layerpane.add(virtualboard,new Integer(2));//Panel where remote user draws layerpane.add(board,new Integer(3)); layerpane.add(board.colourButtons(),new Integer(1)); layerpane.add(board.shapeButtons(),new Integer(0)); //frame.add(paper.addButtons(),BorderLayout.WEST); } /* * This function is overridden from the thread class * This function listens for incoming packets from the server * which contains the points drawn by the other client */ public void run () { while (true) { try { byte[] buffer = new byte[512]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); datasocket.receive(packet); InputStream in=new ByteArrayInputStream(packet.getData(), packet.getOffset(),packet.getLength()); DataInputStream din=new DataInputStream(in); int x=din.readInt(); int y=din.readInt(); String varname=din.readLine(); String var[]=varname.split("-",4); point=new Point(x,y); virtualboard.addPoint(point, var[0], var[1],var[2],var[3]); } catch (IOException ex) { ex.printStackTrace(); } } } //This function is to broadcast the newly drawn point to the server public void broadcast (Point p,String varname,String shape,String event, String color) { try { ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baos); dos.writeInt(p.x); dos.writeInt(p.y); dos.writeBytes(varname); dos.writeBytes("-"); dos.writeBytes(shape); dos.writeBytes("-"); dos.writeBytes(event); dos.writeBytes("-"); dos.writeBytes(color); dos.close(); byte[]data=baos.toByteArray(); InetAddress ip=InetAddress.getByName("10.123.97.154"); DatagramPacket packet=new DatagramPacket(data, data.length,ip , 8002); datasocket.send(packet); } catch (Exception e) { e.printStackTrace(); } } //This function is to close the client's connection with the server public void close() { try { ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baos); //This is to tell server that this is request to remove the client dos.writeChar('r'); dos.close(); byte[]data=baos.toByteArray(); //Server IP address InetAddress ip=InetAddress.getByName("10.123.97.154"); DatagramPacket packet=new DatagramPacket(data, data.length,ip , 8000); socket.send(packet); System.out.println("closed"); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { connect(); } } Whiteboard.java class Whiteboard extends JPanel implements MouseListener,MouseMotionListener,ActionListener,KeyListener { BufferedImage image; Boolean tooltip=false; int post; String shape; String selectedcolor="black"; Color color=Color.black; //Color color=Color.white; Point start; Point end; Point mp; Point tip; int keycode; String fillshape; Point fillstart=new Point(); Point fillend=new Point(); int noofside; Button r=new Button("rect"); Button rectangle=new Button("rect"); Button line=new Button("line"); Button roundrect=new Button("roundrect"); Button polygon=new Button("poly"); Button text=new Button("text"); JButton save=new JButton("Save"); Button elipse=new Button("elipse"); ImageIcon fillicon=new ImageIcon("images/fill.jpg"); JButton fill=new JButton(fillicon); ImageIcon erasericon=new ImageIcon("images/eraser.gif"); JButton erase=new JButton(erasericon); JButton[] colourbutton=new JButton[28]; String selected; Point label; String key=""; int ex,ey;//eraser DatagramSocket dataSocket; JButton button = new JButton("test"); Client client; Boolean first; int w,h; public Whiteboard(DatagramSocket dataSocket) { try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } setLayout(null); setOpaque(false); setBackground(new Color(237,237,237)); this.dataSocket=dataSocket; client=new Client(dataSocket); addKeyListener(this); addMouseListener(this); addMouseMotionListener(this); setBorder(BorderFactory.createLineBorder(Color.black)); } public void paintComponent(Graphics g) { try { super.paintComponent(g); g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; if(color!=null) g2.setPaint(color); if(start!=null && end!=null) { if(selected==("elipse")) g2.drawOval(start.x, start.y,(end.x-start.x),(end.y-start.y)); else if(selected==("rect")) g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("rrect")) g2.drawRoundRect(start.x, start.y, (end.x-start.x),(end.y-start.y),11,11); else if(selected==("line")) g2.drawLine(start.x,start.y,end.x,end.y); else if(selected==("poly")) { g2.drawLine(start.x,start.y,end.x,end.y); client.broadcast(start, "start", "poly", "drag", selectedcolor); client.broadcast(end, "end", "poly", "drag", selectedcolor); } } if(tooltip==true) { System.out.println(selected); if(selected=="text") { g2.drawString("|", tip.x, tip.y-5); g2.drawString("Click to add text", tip.x+10, tip.y+23); g2.drawString("__", label.x+post, label.y); } if(selected=="erase") { g2.setPaint(new Color(237,237,237)); g2.fillRect(tip.x-10,tip.y-10,10,10); g2.setPaint(color); g2.drawRect(tip.x-10,tip.y-10,10,10); } } } catch(Exception e) {} } //Function to draw the shape on image public void draw() { Graphics2D g2 = (Graphics2D) image.createGraphics(); Font font=new Font("Times New Roman",Font.PLAIN,14); g2.setFont(font); g2.setPaint(color); if(start!=null && end!=null) { if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); else if(selected=="elipse") g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected=="rect") g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("rrect")) g2.drawRoundRect(start.x, start.y, (end.x-start.x),(end.y-start.y),11,11); else if(selected==("poly")) { g2.drawLine(start.x,start.y,end.x,end.y); client.broadcast(start, "start", "poly", "release", selectedcolor); client.broadcast(end, "end", "poly", "release", selectedcolor); } fillstart=start; fillend=end; fillshape=selected; } if(selected!="poly") { start=null; end=null; } if(label!=null) { if(selected==("text")) { g2.drawString(key,label.x,label.y); client.broadcast(label, key, "text", "release", selectedcolor); } } repaint(); g2.dispose(); } //Function which provides the erase functionality public void erase() { Graphics2D pic=(Graphics2D) image.createGraphics(); Color erasecolor=new Color(237,237,237); pic.setPaint(erasecolor); if(start!=null) pic.fillRect(start.x-10, start.y-10, 10, 10); } //To set the size of the image public void setImage(BufferedImage image) { this.image = image; } //Function to add buttons into the panel, calling this function returns a panel public JPanel shapeButtons() { JPanel shape=new JPanel(); shape.setBackground(new Color(181, 197, 210)); shape.setLayout(new GridLayout(5,2,2,4)); shape.setBounds(0, 2, 74, 166); rectangle.addActionListener(this); rectangle.setToolTipText("Rectangle"); line.addActionListener( this); line.setToolTipText("Line"); erase.addActionListener(this); erase.setToolTipText("Eraser"); roundrect.addActionListener(this); roundrect.setToolTipText("Round edge Rectangle"); polygon.addActionListener(this); polygon.setToolTipText("Polygon"); text.addActionListener(this); text.setToolTipText("Text"); fill.addActionListener(this); fill.setToolTipText("Fill with colour"); elipse.addActionListener(this); elipse.setToolTipText("Elipse"); save.addActionListener(this); shape.add(elipse); shape.add(rectangle); shape.add(roundrect); shape.add(polygon); shape.add(line); shape.add(text); shape.add(fill); shape.add(erase); shape.add(save); return shape; } public JPanel colourButtons() { JPanel colourbox=new JPanel(); colourbox.setBackground(new Color(181, 197, 210)); colourbox.setLayout(new GridLayout(8,2,8,8)); colourbox.setBounds(0,323,70,140); //colourbox.add(empty); for(int i=0;i<16;i++) { colourbutton[i]=new JButton(); colourbox.add(colourbutton[i]); if(i==0) colourbutton[0].setBackground(Color.black); else if(i==1) colourbutton[1].setBackground(Color.white); else if(i==2) colourbutton[2].setBackground(Color.red); else if(i==3) colourbutton[3].setBackground(Color.orange); else if(i==4) colourbutton[4].setBackground(Color.blue); else if(i==5) colourbutton[5].setBackground(Color.green); else if(i==6) colourbutton[6].setBackground(Color.pink); else if(i==7) colourbutton[7].setBackground(Color.magenta); else if(i==8) colourbutton[8].setBackground(Color.cyan); else if(i==9) colourbutton[9].setBackground(Color.black); else if(i==10) colourbutton[10].setBackground(Color.yellow); else if(i==11) colourbutton[11].setBackground(new Color(131,168,43)); else if(i==12) colourbutton[12].setBackground(new Color(132,0,210)); else if(i==13) colourbutton[13].setBackground(new Color(193,17,92)); else if(i==14) colourbutton[14].setBackground(new Color(129,82,50)); else if(i==15) colourbutton[15].setBackground(new Color(64,128,128)); colourbutton[i].addActionListener(this); } return colourbox; } public void fill() { if(selected=="fill") { Graphics2D g2 = (Graphics2D) image.getGraphics(); g2.setPaint(color); System.out.println("Fill"); if(fillshape=="elipse") g2.fillOval(fillstart.x, fillstart.y, (fillend.x-fillstart.x),(fillend.y-fillstart.y)); else if(fillshape=="rect") g2.fillRect(fillstart.x, fillstart.y, (fillend.x-fillstart.x),(fillend.y-fillstart.y)); else if(fillshape==("rrect")) g2.fillRoundRect(fillstart.x, fillstart.y, (fillend.x-fillstart.x),(fillend.y-fillstart.y),11,11); // else if(fillshape==("poly")) // g2.drawPolygon(x,y,2); } repaint(); } //To save the image drawn public void save() { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos); JFileChooser fc = new JFileChooser(); fc.showSaveDialog(this); encoder.encode(image); byte[] jpgData = bos.toByteArray(); FileOutputStream fos = new FileOutputStream(fc.getSelectedFile()+".jpeg"); fos.write(jpgData); fos.close(); //add replce confirmation here } catch (IOException e) { System.out.println(e); } } public void mouseClicked(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent arg0) { } public void mousePressed(MouseEvent e) { if(selected=="line"||selected=="text") { start=e.getPoint(); client.broadcast(start,"start", selected,"press", selectedcolor); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") mp = e.getPoint(); else if(selected=="poly") { if(first==true) { start=e.getPoint(); //client.broadcast(start,"start", selected,"press", selectedcolor); } else if(first==false) { end=e.getPoint(); repaint(); //client.broadcast(end,"end", selected,"press", selectedcolor); } } else if(selected=="erase") { start=e.getPoint(); erase(); } } public void mouseReleased(MouseEvent e) { if(selected=="text") { System.out.println("Reset"); key=""; post=0; label=new Point(); label=e.getPoint(); grabFocus(); } if(start!=null && end!=null) { if(selected=="line") { end=e.getPoint(); client.broadcast(end,"end", selected,"release", selectedcolor); draw(); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); client.broadcast(end,"end", selected,"release", selectedcolor); draw(); } else if(selected=="poly") { draw(); first=false; start=end; end=null; } } } public void mouseDragged(MouseEvent e) { if(end==null) end = new Point(); if(start==null) start = new Point(); if(selected=="line") { end=e.getPoint(); client.broadcast(end,"end", selected,"drag", selectedcolor); } else if(selected=="erase") { start=e.getPoint(); erase(); client.broadcast(start,"start", selected,"drag", selectedcolor); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { start.x = Math.min(mp.x,e.getX()); start.y = Math.min(mp.y,e.getY()); end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); client.broadcast(start,"start", selected,"drag", selectedcolor); client.broadcast(end,"end", selected,"drag", selectedcolor); } else if(selected=="poly") end=e.getPoint(); System.out.println(tooltip); if(tooltip==true) { if(selected=="erase") { Graphics2D g2=(Graphics2D) getGraphics(); tip=e.getPoint(); g2.drawRect(tip.x-10,tip.y-10,10,10); } } repaint(); } public void mouseMoved(MouseEvent e) { if(selected=="text" ||selected=="erase") { tip=new Point(); tip=e.getPoint(); tooltip=true; repaint(); } } public void actionPerformed(ActionEvent e) { if(e.getSource()==elipse) selected="elipse"; else if(e.getSource()==line) selected="line"; else if(e.getSource()==rectangle) selected="rect"; else if(e.getSource()==erase) { selected="erase"; tooltip=true; System.out.println(selected); erase(); } else if(e.getSource()==roundrect) selected="rrect"; else if(e.getSource()==polygon) { selected="poly"; first=true; start=null; } else if(e.getSource()==text) { selected="text"; tooltip=true; } else if(e.getSource()==fill) { selected="fill"; fill(); } else if(e.getSource()==save) save(); if(e.getSource()==colourbutton[0]) { color=Color.black; selectedcolor="black"; } else if(e.getSource()==colourbutton[1]) { color=Color.white; selectedcolor="white"; } else if(e.getSource()==colourbutton[2]) { color=Color.red; selectedcolor="red"; } else if(e.getSource()==colourbutton[3]) { color=Color.orange; selectedcolor="orange"; } else if(e.getSource()==colourbutton[4]) { selectedcolor="blue"; color=Color.blue; } else if(e.getSource()==colourbutton[5]) { selectedcolor="green"; color=Color.green; } else if(e.getSource()==colourbutton[6]) { selectedcolor="pink"; color=Color.pink; } else if(e.getSource()==colourbutton[7]) { selectedcolor="magenta"; color=Color.magenta; } else if(e.getSource()==colourbutton[8]) { selectedcolor="cyan"; color=Color.cyan; } } @Override public void keyPressed(KeyEvent e) { //System.out.println(e.getKeyChar()+" : "+e.getKeyCode()); if(label!=null) { if(e.getKeyCode()==10) //Check for Enter key { label.y=label.y+14; key=""; post=0; repaint(); } else if(e.getKeyCode()==8) //Backspace { try{ Graphics2D g2 = (Graphics2D) image.getGraphics(); g2.setPaint(new Color(237,237,237)); g2.fillRect(label.x+post-7, label.y-13, 14, 17); if(post>0) post=post-6; keycode=0; key=key.substring(0, key.length()-1); System.out.println(key.substring(0, key.length())); repaint(); Point broadcastlabel=new Point(); broadcastlabel.x=label.x+post-7; broadcastlabel.y=label.y-13; client.broadcast(broadcastlabel, key, "text", "backspace", selectedcolor); } catch(Exception ex) {} } //Block invalid keys else if(!(e.getKeyCode()>=16 && e.getKeyCode()<=20 || e.getKeyCode()>=112 && e.getKeyCode()<=123 || e.getKeyCode()>=33 && e.getKeyCode()<=40 || e.getKeyCode()>=144 && e.getKeyCode()<=145 || e.getKeyCode()>=524 && e.getKeyCode()<=525 ||e.getKeyCode()==27||e.getKeyCode()==155 ||e.getKeyCode()==127)) { key=key+e.getKeyChar(); post=post+6; draw(); } } } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } } class Button extends JButton { String name; int i; public Button(String name) { this.name=name; try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } } public Button(int i) { this.i=i; } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //g2.setStroke(new BasicStroke(1.2f)); if (name == "line") g.drawLine(5,5,30,30); if (name == "elipse") g.drawOval(5,7,25,20); if (name== "rect") g.drawRect(5,5,25,23); if (name== "roundrect") g.drawRoundRect(5,5,25,23,10,10); int a[]=new int[]{20,9,20,23,20}; int b[]=new int[]{9,23,25,20,9}; if (name== "poly") g.drawPolyline(a, b, 5); if (name== "text") g.drawString("Text",8, 24); } }

    Read the article

  • C# : changing listbox row color?

    - by Meko
    HI. I am trying to changing backround colorof some rows on listbox.I have 2 list that one has all names and it shown on listbox.And second list has some same value with first list.I want to show that when clicking button it will search in listbox and in second list then will change color where found value. I may search in list box like for (int i = 0; i < listBox1.Items.Count; i++) { for (int j = 0; j < students.Count; j++) if (listBox1.Items[i].ToString().Contains(students[j].ToString())) { } } But I don't know which method to change appearances of row.Any help? *EDIT: * HI I made my code like private void ListBox1_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); Graphics g = e.Graphics; Brush myBrush = Brushes.Black; Brush myBrush2 = Brushes.Red; g.FillRectangle(new SolidBrush(Color.Silver), e.Bounds); e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, myBrush, e.Bounds, StringFormat.GenericDefault); for (int i = 0; i < listBox1.Items.Count; i++) { for (int j = 0; j < existingStudents.Count; j++) if (listBox1.Items[i].ToString().Contains(existingStudents[j])) { e.Graphics.DrawString(listBox1.Items[i].ToString(), e.Font, myBrush2, e.Bounds, StringFormat.GenericDefault); } } e.DrawFocusRectangle(); } Now it draws my list on listbox.But when I click button first it shows only student that in list with red color but when I click on listbox it again draws all elements.I want that it will show all element ,when I click button it will show all elements and founded element in list with red color.Whre is my mistake?

    Read the article

  • How to draw multiple rectangles using c#

    - by Nivas
    I have drawn and saved the Rectangle on the image i loaded in the picture box. How i like to draw multiple rectangles for that i tried array in the rectangle but it gives error ("Object reference not set to an instance of an object." (Null reference Exception was unhandled). private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { if (mybitmap == null) { mybitmap = new Bitmap(sz.Width, sz.Height); } rect[count] = new Rectangle(e.X, e.Y, 0, 0); this.Invalidate(); } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (stayToolStripMenuItem.Checked == true) { switch (e.Button) { case MouseButtons.Left: { rect[count] = new Rectangle(rect[count].Left, rect[count].Top, e.X - rect[count].Left, e.Y - rect[count].Top); pictureBox1.Invalidate(); count++: break; } } } } private void pictureBox1_Paint(object sender, PaintEventArgs e) { if (stayToolStripMenuItem.Checked == true) { button1.Visible = true; button2.Visible = true; if (mybitmap == null) { return; } using (g = Graphics.FromImage(mybitmap)) { using (Pen pen = new Pen(Color.Red, 2)) { //g.Clear(Color.Transparent); e.Graphics.DrawRectangle(pen, rect); label1.Top = rect[count].Top; label1[count].Left = rect[count].Left; label1.Width = rect[count].Width; label1.Height = rect[count].Height; if (label1.TextAlign == ContentAlignment.TopLeft) { e.Graphics.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), rect); g.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), rect); g.DrawRectangle(pen, rect[count]); } } } } } How can i do this.....

    Read the article

  • How to draw mutiple rectangles using c#

    - by Nivas
    I have drawn and saved the Rectangle on the image i loaded in the picture box. How i like to draw multiple rectangles for that i tried array in the rectangle but it gives error ("Object reference not set to an instance of an object." (Null reference Exception was unhandled). enter code here private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { if (mybitmap == null) { mybitmap = new Bitmap(sz.Width, sz.Height); } rect = new Rectangle(e.X, e.Y, 0, 0); this.Invalidate(); } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (stayToolStripMenuItem.Checked == true) { switch (e.Button) { case MouseButtons.Left: { rect = new Rectangle(rect.Left, rect.Top, e.X - rect.Left, e.Y - rect.Top); pictureBox1.Invalidate(); break; } } } } private void pictureBox1_Paint(object sender, PaintEventArgs e) { if (stayToolStripMenuItem.Checked == true) { button1.Visible = true; button2.Visible = true; if (mybitmap == null) { return; } using (g = Graphics.FromImage(mybitmap)) { using (Pen pen = new Pen(Color.Red, 2)) { //g.Clear(Color.Transparent); e.Graphics.DrawRectangle(pen, rect); label1.Top = rect.Top; label1.Left = rect.Left; label1.Width = rect.Width; label1.Height = rect.Height; if (label1.TextAlign == ContentAlignment.TopLeft) { e.Graphics.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), rect); g.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), rect); g.DrawRectangle(pen, rect); } } } } } How can i do this.....

    Read the article

  • XNA 4.0 SpriteFont not displaying all Characters

    - by Iain Brown
    Am looking for a little help and trying to use SpriteFont in my XNA 4.0 game but the problem is am displaying to string "This is a test" but all that's displayed on the screen is "This is st" so the "a te" are missing from the screen. The space is there for the characters but the letters are not. The code am using is: spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); spriteBatch.DrawString(font,"this is a test",new Vector2(692,372),Color.White); spriteBatch.Draw(texture,new Rectangle(0,0,100,100),Color.White); spriteBatch.End(); Any help with this would be great!

    Read the article

  • How do I make a dialog box? [on hold]

    - by bill
    By dialog box I mean when player talks to someone, a box shows up with text on it. I haven't found much about this topic online, so I created a basic dialog box: //in dialog box i have only two methods public void createBox(int x, int y, int width, int height, String txt) { this.x = x; this.y = y; this.width = width; this.height = height; this.txt = txt; } //draw dialog box public void draw(Graphics2D g) { if (txt != null) { g.setColor(Color.red); g.drawRect(x,y,width,height); g.setColor(Color.black); g.fillRect(x, y, width, height); g.setColor(Color.white); g.drawString(txt, x + 10, y + 10); } } I wanted to now can I make this better?

    Read the article

  • Cant full read querystring data in mvc4 application using a class array as input to action

    - by Anders Lindén
    I have made a mvc4 application and I have a Controller that outputs a png file like this: using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Drawing.Text; using System.IO; using System.Web.Mvc; using Foobar.Classes; namespace Foobar.Controllers { public class ImageController : Controller { public ActionResult Index(Label[] labels) { var bmp = new Bitmap(400, 300); var pen = new Pen(Color.Black); var font = new Font("arial", 20); var g = Graphics.FromImage(bmp); g.SmoothingMode = SmoothingMode.HighQuality; g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; if (labels != null) { g.DrawString("" + labels.Length, font, pen.Brush, 20, 20); if (labels.Length > 0) { g.DrawString("" + labels[0].label, font, pen.Brush, 20, 40); } } var stream = new MemoryStream(); bmp.Save(stream, ImageFormat.Png); stream.Position = 0; return File(stream, "image/png"); } } } The Label class looks like this: using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Foobar.Classes { public class Label { public string label { get; set; } public int fontsize { get; set; } } } When I run my controller having this in the url: http://localhost:57775/image?labels[0][label]=Text+rad+1&labels[0][fontsize]=5&labels[1][fontsize]=5&labels[2][fontsize]=5 I get the correct amount of labels, so the image will show 3. But the instances of Label will not get its data members fill in. I have also tried to do this using plain variables (not properties). If they were filled in, the image would actually show "3" and "Text rad 1". So what do I put in the class "Label" to have the properties right? Should there be some kind of annotation? Where do I read about this?

    Read the article

  • what localization changes are needed for Arabic with Java Applet

    - by Tom
    How big task is it to implement support for Arabic localization, our Java 1.5 Applet was designed as fully localizable (european languages) but now we plan to add also arabic as a new language. We are using custom GUI text i/o components inherited from Component class using e.g. Drawstring, how well is arabic supported within Component class ? The keyboard input is done with KeyListener getKeyChar, getKeyCode etc.

    Read the article

  • Preserve Font Size when scaling a Drawing

    - by serhio
    I do the following when drawing: Matrix m = new Matrix() m.Scale(_zoom, _zoom) e.Graphics.Transform = m e.Graphics.DrawLine(...) ' line representation e.Graphics.DrawString(...) ' line text Now, the text became also scaled. Is it possible to avoid it?

    Read the article

  • Thread not behaving correctly

    - by ivor
    Hello, I wonder if anyone can help me to understand where I could be going wrong with this code; Basically I'm working on a turorial and calling the class below from another class - and it is getting the following error; Exception in thread "Thread-1" java.lang.NullPointerException at org.newdawn.spaceinvaders.TCPChat.run(TCPChat.java:322) at java.lang.Thread.run(Unknown Source) I realise the error is beibg flagged in another class- but I have tested the other class with a small class which sets up a separate thread - and it works fine, but as soon as I try and implement a new thread in this class - it causes all sorts of problems. Am I setting up the thread correctly in this class? Basically I can set up a thread in this class, with a test loop and it's fine, but when I bring in the functionality of the rest of the game it sometimes hangs, or does not display at all. Any suggestions on where I could be going wrong would be greatly appreciated. Thanks for looking. package org.newdawn.spaceinvaders; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferStrategy; import java.util.ArrayList; import java.util.Scanner; import java.awt.*;//maybe not needed import javax.swing.*;//maybenot needed import java.util.Random; //import java.io.*; /** * The main hook of our game. This class with both act as a manager * for the display and central mediator for the game logic. * * Display management will consist of a loop that cycles round all * entities in the game asking them to move and then drawing them * in the appropriate place. With the help of an inner class it * will also allow the player to control the main ship. * * As a mediator it will be informed when entities within our game * detect events (e.g. alient killed, played died) and will take * appropriate game actions. * * @author Kevin Glass */ public class Game extends Canvas implements Runnable{ /** The stragey that allows us to use accelerate page flipping */ private BufferStrategy strategy; /** True if the game is currently "running", i.e. the game loop is looping */ private boolean gameRunning = true; /** The list of all the entities that exist in our game */ private ArrayList entities = new ArrayList(); /** The list of entities that need to be removed from the game this loop */ private ArrayList removeList = new ArrayList(); /** The entity representing the player */ private Entity ship; /** The speed at which the player's ship should move (pixels/sec) */ private double moveSpeed = 300; /** The time at which last fired a shot */ private long lastFire = 0; /** The interval between our players shot (ms) */ private long firingInterval = 500; /** The number of aliens left on the screen */ private int alienCount; /** The number of levels progressed */ private double levelCount; /** high score for the user */ private int highScore; /** high score for the user */ private String player = "bob"; //private GetUserInput getPlayer; /** The list of entities that need to be removed from the game this loop */ /** The message to display which waiting for a key press */ private String message = ""; /** True if we're holding up game play until a key has been pressed */ private boolean waitingForKeyPress = true; /** True if the left cursor key is currently pressed */ private boolean leftPressed = false; /** True if the right cursor key is currently pressed */ private boolean rightPressed = false; /** True if we are firing */ private boolean firePressed = false; /** True if game logic needs to be applied this loop, normally as a result of a game event */ private boolean logicRequiredThisLoop = false; //private Thread cThread = new Thread(this); //public Thread t = new Thread(this); //private Thread g = new Thread(this); void setHighscore(int setHS) { highScore = setHS; } public int getHighscore() { return highScore; } public void setPlayer(String setPlayer) { player = setPlayer; } public String getPlayer() { return player; } public void run() { //setup(); System.out.println("hello im running bob"); /*int count = 1; do { System.out.println("Count is: " + count); count++; try{Thread.sleep(1);} catch(InterruptedException e){} } while (count <= 2000000);*/ //Game g =new Game(); //Game g = this; // Start the main game loop, note: this method will not // return until the game has finished running. Hence we are // using the actual main thread to run the game. //setup(); //this.gameLoop(); //try{thread.sleep(1);} //catch{InterruptedException e} } /** * Construct our game and set it running. */ public Game () { //Thread t = new Thread(this);//set up new thread for invaders game //t.run();//run the run method of the game //Game g =new Game(); //setup(); //Thread t = new Thread(this); //thread.start(); //SwingUtilities.invokeLater(this); Thread er = new Thread(this); er.start(); } public void setup(){ //initialise highscore setHighscore(0); // create a frame to contain our game JFrame container = new JFrame("Space Invaders 101"); // get hold the content of the frame and set up the resolution of the game JPanel panel = (JPanel) container.getContentPane(); panel.setPreferredSize(new Dimension(800,600)); //panel.setLayout(null); // setup our canvas size and put it into the content of the frame setBounds(0,0,800,600); panel.add(this); // Tell AWT not to bother repainting our canvas since we're // going to do that our self in accelerated mode setIgnoreRepaint(true); // finally make the window visible container.pack(); container.setResizable(false); container.setVisible(true); // add a listener to respond to the user closing the window. If they // do we'd like to exit the game container.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //cThread.interrupt(); System.exit(0); } }); // add a key input system (defined below) to our canvas // so we can respond to key pressed addKeyListener(new KeyInputHandler()); // request the focus so key events come to us requestFocus(); // create the buffering strategy which will allow AWT // to manage our accelerated graphics createBufferStrategy(2); strategy = getBufferStrategy(); // initialise the entities in our game so there's something // to see at startup initEntities(); } /** * Start a fresh game, this should clear out any old data and * create a new set. */ private void startGame() { // clear out any existing entities and intialise a new set entities.clear(); initEntities(); //initialise highscore setHighscore(0); // blank out any keyboard settings we might currently have leftPressed = false; rightPressed = false; firePressed = false; } /** * Initialise the starting state of the entities (ship and aliens). Each * entitiy will be added to the overall list of entities in the game. */ //private void initEntities() { public void initEntities() { Random randomAlien = new Random(); // create the player ship and place it roughly in the center of the screen //ship = new ShipEntity(this,"sprites/ship.gif",370,550);//orignal ship = new ShipEntity(this,"sprites/ship.gif",700,300);//changed postioning to right hand side entities.add(ship); // create a block of aliens (5 rows, by 12 aliens, spaced evenly) alienCount = 0; levelCount = 1.02; for (int row=0;row<7;row++) {//altered number of rows for (int x=0;x<5;x++) { int r = randomAlien.nextInt(100);//loop added to produce random aliens if (r < 50){ //Entity alien = new AlienEntity(this,"sprites/alien.gif",/*100+*/(x*50),(50)+row*30); Entity alien = new AlienEntity(this,"sprites/alien.gif",100+(x*90),(12)+row*85); entities.add(alien); alienCount++; } } } } //private void initEntities() { public void initAlienEntities() { Random randomAlien = new Random(); // create the player ship and place it roughly in the center of the screen //ship = new ShipEntity(this,"sprites/ship.gif",370,550);//orignal //ship = new ShipEntity(this,"sprites/ship.gif",700,300);//changed postioning to right hand side //entities.add(ship); // create a block of aliens (5 rows, by 12 aliens, spaced evenly) alienCount = 0; levelCount = levelCount + 0.10;//this increases the speed on every level for (int row=0;row<7;row++) {//altered number of rows for (int x=0;x<5;x++) { int r = randomAlien.nextInt(100);//loop added to produce random aliens if (r < 50){//randome check to show alien //Entity alien = new AlienEntity(this,"sprites/alien.gif",/*100+*/(x*50),(50)+row*30); Entity alien = new AlienEntity(this,"sprites/alien.gif",-250+(x*90),(12)+row*85); entities.add(alien); alienCount++; } } } advanceAlienSpeed(levelCount); } /** * Notification from a game entity that the logic of the game * should be run at the next opportunity (normally as a result of some * game event) */ public void updateLogic() { logicRequiredThisLoop = true; } /** * Remove an entity from the game. The entity removed will * no longer move or be drawn. * * @param entity The entity that should be removed */ public void removeEntity(Entity entity) { removeList.add(entity); } /** * Notification that the player has died. */ public void notifyDeath() { message = "Oh no! They got you, try again?"; waitingForKeyPress = true; } /** * Notification that the player has won since all the aliens * are dead. */ public void notifyWin() { message = "Well done! You Win!"; waitingForKeyPress = true; } /** * Notification that an alien has been killed */ public void notifyAlienKilled() { // reduce the alient count, if there are none left, the player has won! alienCount--; if (alienCount == 0) { //notifyWin();win not relevant here... this.initAlienEntities();//call fresh batch of aliens } // if there are still some aliens left then they all need to get faster, so // speed up all the existing aliens advanceAlienSpeed(1.30); } public void advanceAlienSpeed(double speed) { // if there are still some aliens left then they all need to get faster, so // speed up all the existing aliens for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); if (entity instanceof AlienEntity) { // speed up by 2% entity.setHorizontalMovement(entity.getHorizontalMovement() * speed); //entity.setVerticalMovement(entity.getVerticalMovement() * 1.02); } } } /** * Attempt to fire a shot from the player. Its called "try" * since we must first check that the player can fire at this * point, i.e. has he/she waited long enough between shots */ public void tryToFire() { // check that we have waiting long enough to fire if (System.currentTimeMillis() - lastFire < firingInterval) { return; } // if we waited long enough, create the shot entity, and record the time. lastFire = System.currentTimeMillis(); ShotEntity shot = new ShotEntity(this,"sprites/shot.gif",ship.getX()+10,ship.getY()-30); entities.add(shot); } /** * The main game loop. This loop is running during all game * play as is responsible for the following activities: * <p> * - Working out the speed of the game loop to update moves * - Moving the game entities * - Drawing the screen contents (entities, text) * - Updating game events * - Checking Input * <p> */ public void gameLoop() { long lastLoopTime = System.currentTimeMillis(); // keep looping round til the game ends while (gameRunning) { // work out how long its been since the last update, this // will be used to calculate how far the entities should // move this loop long delta = System.currentTimeMillis() - lastLoopTime; lastLoopTime = System.currentTimeMillis(); // Get hold of a graphics context for the accelerated // surface and blank it out Graphics2D g = (Graphics2D) strategy.getDrawGraphics(); g.setColor(Color.black); g.fillRect(0,0,800,600); // cycle round asking each entity to move itself if (!waitingForKeyPress) { for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.move(delta); } } // cycle round drawing all the entities we have in the game for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.draw(g); } // brute force collisions, compare every entity against // every other entity. If any of them collide notify // both entities that the collision has occured for (int p=0;p<entities.size();p++) { for (int s=p+1;s<entities.size();s++) { Entity me = (Entity) entities.get(p); Entity him = (Entity) entities.get(s); if (me.collidesWith(him)) { me.collidedWith(him); him.collidedWith(me); } } } // remove any entity that has been marked for clear up entities.removeAll(removeList); removeList.clear(); // if a game event has indicated that game logic should // be resolved, cycle round every entity requesting that // their personal logic should be considered. if (logicRequiredThisLoop) { //g.drawString("Press any key",(800-g.getFontMetrics().stringWidth("Press any key"))/2,300); for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.doLogic(); } logicRequiredThisLoop = false; } // if we're waiting for an "any key" press then draw the // current message //show highscore at top of screen //show name at top of screen g.setColor(Color.white); g.drawString("Player : "+getPlayer()+" : Score : "+getHighscore(),20,20); if (waitingForKeyPress) { g.setColor(Color.white); g.drawString(message,(800-g.getFontMetrics().stringWidth(message))/2,250); g.drawString("Press any key",(800-g.getFontMetrics().stringWidth("Press any key"))/2,300); } // finally, we've completed drawing so clear up the graphics // and flip the buffer over g.dispose(); strategy.show(); // resolve the movement of the ship. First assume the ship // isn't moving. If either cursor key is pressed then // update the movement appropraitely ship.setVerticalMovement(0);//set to vertical movement if ((leftPressed) && (!rightPressed)) { ship.setVerticalMovement(-moveSpeed);//**took out setHorizaontalMOvement } else if ((rightPressed) && (!leftPressed)) { ship.setVerticalMovement(moveSpeed);//**took out setHorizaontalMOvement } // if we're pressing fire, attempt to fire if (firePressed) { tryToFire(); } // finally pause for a bit. Note: this should run us at about // 100 fps but on windows this might vary each loop due to // a bad implementation of timer try { Thread.sleep(10); } catch (Exception e) {} } } /** * A class to handle keyboard input from the user. The class * handles both dynamic input during game play, i.e. left/right * and shoot, and more static type input (i.e. press any key to * continue) * * This has been implemented as an inner class more through * habbit then anything else. Its perfectly normal to implement * this as seperate class if slight less convienient. * * @author Kevin Glass */ private class KeyInputHandler extends KeyAdapter { /** The number of key presses we've had while waiting for an "any key" press */ private int pressCount = 1; /** * Notification from AWT that a key has been pressed. Note that * a key being pressed is equal to being pushed down but *NOT* * released. Thats where keyTyped() comes in. * * @param e The details of the key that was pressed */ public void keyPressed(KeyEvent e) { // if we're waiting for an "any key" typed then we don't // want to do anything with just a "press" if (waitingForKeyPress) { return; } // if (e.getKeyCode() == KeyEvent.VK_LEFT) { ////leftPressed = true; ///} //// if (e.getKeyCode() == KeyEvent.VK_RIGHT) { //rightPressed = true; if (e.getKeyCode() == KeyEvent.VK_UP) { leftPressed = true; } if (e.getKeyCode() == KeyEvent.VK_DOWN) { rightPressed = true; } if (e.getKeyCode() == KeyEvent.VK_SPACE) { firePressed = true; } } /** * Notification from AWT that a key has been released. * * @param e The details of the key that was released */ public void keyReleased(KeyEvent e) { // if we're waiting for an "any key" typed then we don't // want to do anything with just a "released" if (waitingForKeyPress) { return; } if (e.getKeyCode() == KeyEvent.VK_UP) {//changed from VK_LEFT leftPressed = false; } if (e.getKeyCode() == KeyEvent.VK_DOWN) {//changed from VK_RIGHT rightPressed = false; } if (e.getKeyCode() == KeyEvent.VK_SPACE) { firePressed = false; } } /** * Notification from AWT that a key has been typed. Note that * typing a key means to both press and then release it. * * @param e The details of the key that was typed. */ public void keyTyped(KeyEvent e) { // if we're waiting for a "any key" type then // check if we've recieved any recently. We may // have had a keyType() event from the user releasing // the shoot or move keys, hence the use of the "pressCount" // counter. if (waitingForKeyPress) { if (pressCount == 1) { // since we've now recieved our key typed // event we can mark it as such and start // our new game waitingForKeyPress = false; startGame(); pressCount = 0; } else { pressCount++; } } // if we hit escape, then quit the game if (e.getKeyChar() == 27) { //cThread.interrupt(); System.exit(0); } } } /** * The entry point into the game. We'll simply create an * instance of class which will start the display and game * loop. * * @param argv The arguments that are passed into our game */ //public static void main(String argv[]) { //Game g =new Game(); // Start the main game loop, note: this method will not // return until the game has finished running. Hence we are // using the actual main thread to run the game. //g.gameLoop(); //} }

    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

  • How to draw mixed-formatted text with .Net 2.0

    - by Baldewin
    Hi, is there a way to draw mixed-formatted text in .Net 2.0? I'm looking for something similar to System.Drawing.Graphics.DrawString() My problem with this method is that it allows only one format style for the whole text. But I need to draw text that has different format styles (e.g. a part of the text shall be underlined, another part bold and so on). Thanks a lot! Oliver

    Read the article

  • visualizing enter symbol in java (Serif/SansSerif preferred)

    - by Tom
    How can I display the graphical "enter symbol" within java applet using fonts? I want to show "?", which is U+21B5 DOWNWARDS ARROW WITH CORNER LEFTWARDS. – I want to draw this to applet's screen so that it works in WIN, LINUX, MACOSX, etc. Is there a font available that makes this possible or should I draw it manually somehow? g2d.setFont("SymbolFont??which one"); g2d.drawString(myenterSymbolHere,x,Y);

    Read the article

  • LWJGL Text Rendering

    - by Trixmix
    Currently in my project I am using LWJGL and the Slick2D library to render text onto the screen. Here is a more specific example: Font f = new Font("Times New Roman",Font.BOLD,18); font = new UnicodeFont(f); font.getEffects().add(new ColorEffect(Color.white)); font.addAsciiGlyphs(); try { font.loadGlyphs(); } catch (SlickException e) { e.printStackTrace(); } then i use font.drawString to write onto the screen. This is a quick easy way but it has a lot of disadvantages. for example font.loadGlyphs take a very long time 1-3 seconds. so when i want to change a color or font type then i have to wait 1-3 seconds which means I cannot do it while rendering (ie. cant have different color text on the same screen). My question is what is a better way of drawing multicolored text onto the screen? I use slick2d only for the text rendering so maybe i can fully get rid of the library and draw text some other way... If you have an answer please leave a quick short example. Thanks!

    Read the article

  • how to double buffer in multiple classes with java

    - by kdavis8
    I am creating a Java 2D video game. I can load graphics just fine, but when it gets into double buffering I have issues. My source code package myPackage; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import javax.swing.JFrame; public class GameView extends JFrame { private BufferedImage backbuffer; private Graphics2D g2d; public GameView() { setBounds(0, 0, 500, 500); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); backbuffer = new BufferedImage(getHeight(), getWidth(), BufferedImage.TYPE_INT_BGR); g2d = backbuffer.createGraphics(); Toolkit tk = Toolkit.getDefaultToolkit(); Image img = tk.getImage(this.getClass().getResource("cage.png")); g2d.setColor(Color.red); //g2d.drawString("Hello",100,100); g2d.drawImage(img, 100, 100, this); repaint(); } public static void main(String args[]) { new GameView(); } public void paint(Graphics g) { g2d = (Graphics2D)g; g2d.drawImage(backbuffer, 0, 0, this); } }

    Read the article

  • Using 2D sprites and 3D models together

    - by Sweta Dwivedi
    I have gone through a few posts that talks about changing the GraphicsDevice.BlendState and GraphicsDevice.DepthStencilState (SpriteBatch & Render states). . however even after changing the states .. i cant see my 3D model on the screen.. I see the model for a second before i draw my video in the background. . Here is the code: case GameState.InGame: GraphicsDevice.Clear(Color.AliceBlue); spriteBatch.Begin(); if (player.State != MediaState.Stopped) { videoTexture = player.GetTexture(); } Rectangle screen = new Rectangle(GraphicsDevice.Viewport.X, GraphicsDevice.Viewport.Y, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height); // Draw the video, if we have a texture to draw. if (videoTexture != null) { spriteBatch.Draw(videoTexture, screen, Color.White); if (Selected_underwater == true) { spriteBatch.DrawString(font, "MaxX , MaxY" + maxWidth + "," + maxHeight, new Vector2(400, 10), Color.Red); spriteBatch.Draw(kinectRGBVideo, new Rectangle(0, 0, 100, 100), Color.White); spriteBatch.Draw(butterfly, handPosition, Color.White); foreach (AnimatedSprite a in aSprites) { a.Draw(spriteBatch); } } if(Selected_planet == true) { spriteBatch.Draw(kinectRGBVideo, new Rectangle(0, 0, 100, 100), Color.White); spriteBatch.Draw(butterfly, handPosition, Color.White); spriteBatch.Draw(videoTexture,screen,Color.White); GraphicsDevice.BlendState = BlendState.Opaque; GraphicsDevice.DepthStencilState = DepthStencilState.Default; GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap; foreach (_3DModel m in Solar) { m.DrawModel(); } } spriteBatch.End(); break;

    Read the article

  • XNA C# How to draw fonts in different color

    - by XNA newbie
    I'm doing a simple chat system with XNA C#. It is a chatbox that contains 5 lines of chat typed by the users. Something like a MMORPG chatting system. [User1name] says: Hi [User2name] says: Hello [User1name] says: What are you doing? [User2name] says: I'm fine [System] The time is now 1:03AM. When the user pressed 'ENTER', the text he entered will be added inside an ArrayList chatList.Add(s); For displaying the text he entered, I used for (int i = 0; i < chatList.Count(); i++) { spriteBatch.DrawString(font, chatList[i], new Vector2(40, arr1[i]), Color.Yellow); } *arr1[i] contains 5 y-axis points to print my 5 line of chats in the chatbox Question1: What if I have another type of message which will be added into ChatList (something like a system message). I need the System Message to be printed out in red color. And if the user keeps on chatting, the chat box will be updated according: (MAX 5 LINES) The newest chat will be shown below, and the oldest one will be deleted if they reached the max 5 lines. [User2name] says: Hello [User1name] says: What are you doing? [User2name] says: I'm fine [System] The time is now 1:03AM. [User1name] says: Ok, great to hear that! I'm having trouble to print each line color according to their msg type. For normal msg, it should be yellow. For system msg, it should be red. Question2: And for the next problem, I need the chat texts to be white color, while the names of the user is yellow (like warcraft3 chat system). How do I do that? I have a hard time thinking of a solution for these to work. Advise needed.

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >