Search Results

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

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

  • Unable to use certain Fonts programatically in ASP.Net

    - by TooFat
    I am trying to programatically create a bitmap with a specified font in ASP.Net. The idea is that the text, font name, size color etc. will be passed in from variables and a bitmap of the text using the font etc will be returned. However, I have been finding that I am only able to do so using the following code with certain fonts. <div> <% string fontName = "Segoe Script"; //Change Font here System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(100, 100); System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(bmp); System.Drawing.Font fnt = new System.Drawing.Font(fontName, 20); System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(System.Drawing.Color.Red); graph.DrawString("Help", fnt, brush, new System.Drawing.Point(10, 10)); bmp.Save(@"C:\Development\Path\image1.bmp"); this.Image1.ImageUrl = "http://mysite/Images/image1.bmp"; %> <asp:Label ID="Label1" runat="server" Text="Label" Font-Names="Segoe Script"> <%Response.Write("Help"); %></asp:Label> //Change font here <asp:Image ID="Image1" runat="server" /> </div> If I change the font name in the areas indicated by the comments to Arial or Verdana both the image and the label appear with the correct font. If however, I change the font name in both locations to something "Segoe Script" the Label will show up in Segoe Script but the image is in what looks like Arial.

    Read the article

  • XNA: What can cause SpriteBatch.End() to throw a NRE?

    - by Rosarch
    I don't understand what I'm doing wrong here: public void Draw(GameTime gameTime) // in ScreenManager { SpriteBatch.Begin(SpriteBlendMode.AlphaBlend); for (int i = 0; i < Screens.Count; i++) { if (Screens[i].State == Screen.ScreenState.HIDDEN) continue; Screens[i].Draw(gameTime); } SpriteBatch.End(); // null ref exception } SpriteBatch itself is not null. Some more context: public class MasterEngine : Microsoft.Xna.Framework.Game { public MasterEngine() { graphicsDeviceManager = new GraphicsDeviceManager(this); Components.Add(new GamerServicesComponent(this)); // ... spriteBatch = new SpriteBatch(graphicsDeviceManager.GraphicsDevice); screenManager = new ScreenManager(assets, gameEngine, graphicsDeviceManager.GraphicsDevice, spriteBatch); } //... protected override void Draw(GameTime gameTime) { screenManager.Draw(gameTime); // calls the problematic method base.Draw(gameTime); } } Am I failing to initialize something properly? UPDATE: As an experiment, I tried this to the constructor of MasterEngine: spriteBatch = new SpriteBatch(graphicsDeviceManager.GraphicsDevice); spriteBatch.Begin(); spriteBatch.DrawString(assets.GetAsset<SpriteFont>("calibri"), "ftw", new Vector2(), Color.White); spriteBatch.End(); This does not cause a NRE. hmm.... UPDATE 2: This does cause an NRE: protected override void Draw(GameTime gameTime) { spriteBatch.Begin(); spriteBatch.End(); // boned here //screenManager.Draw(gameTime); base.Draw(gameTime); }

    Read the article

  • Convert Justified Paragraph To Image

    - by rsrobbins
    I need to convert a paragraph of text into an image. Converting the text into an image is no problem. I have the code to do that. But the text must be shown as a paragraph with each line centered. That is a problem! Currently I can convert the text into a left justified paragraph because there are carriage returns in the text string. I suppose it could be center justified with spaces in the string but it would be hard to calculate the required spaces. There must be an easier way. What I need is some way to format the text into a paragraph and then convert it back into a string, preserving spaces. This needs to be done in VB.NET for an ASP.NET web application. Any ideas? I could get the paragraph justified in Rich Text Format but I don't know if it can be converted back into a string, preserving spaces. Creating a PDF is another possibility. The image created from the text needs to be 300 DPI with a transparent background. I'm using the DrawString method of a Graphics object to create the image.

    Read the article

  • GDI: Dynamical Multiple Graphics in a page?

    - by SirLenz0rlot
    Hi all, I'm quite new to drawing shapes, graphics, bitmaps etc. I googled for a few days,but still havent got a real clue what to do, so please help me: I want to draw a floorplan with certain objects(represented as circles) moving on it. When I click on a object, it needs to show something. So far, I ve been able to draw some circles on a graphic and been able to move the dots by clearing the graphic every time. Ofcourse, this isnt a real solution, since I cant keep track of the different objects on the floorplan (which i need for my clickevent and movings). I hope I explained my problem ok here. This is the (stripped version of the) sourcecode that gets called every second: (dev (of type Device) is the object i want to draw) Graphics gfx = FloorplanTabPage.CreateGraphics(); gfx.Clear(Color.White); foreach (Device dev in _deviceList) { Pen myPen = new Pen(Color.Black) { Width = 10 }; dev.InRoom != null) { myPen.Color = Color.DarkOrchid; int x = dev.InRoom.XPos + (dev.InRoom.Width / 2) - 5; int y = (dev.InRoom.YPos + (dev.InRoom.Height / 2) - 5; if (dev.ToRoom != null) { x = (x + (dev.ToRoom.XPos + (dev.ToRoom.Width / 2)) / 2; y = (y + (dev.ToRoom.YPos + (dev.ToRoom.Height / 2)) / 2; } gfx.DrawEllipse(myPen, x, y, 10, 10); gfx.DrawString(dev.Name, new Font("Arial", 10), Brushes.Purple, x, y - 15); } }

    Read the article

  • C# XNA: What can cause SpriteBatch.End() to throw a NRE?

    - by Rosarch
    I don't understand what I'm doing wrong here: public void Draw(GameTime gameTime) // in ScreenManager { SpriteBatch.Begin(SpriteBlendMode.AlphaBlend); for (int i = 0; i < Screens.Count; i++) { if (Screens[i].State == Screen.ScreenState.HIDDEN) continue; Screens[i].Draw(gameTime); } SpriteBatch.End(); // null ref exception } SpriteBatch itself is not null. Some more context: public class MasterEngine : Microsoft.Xna.Framework.Game { public MasterEngine() { graphicsDeviceManager = new GraphicsDeviceManager(this); Components.Add(new GamerServicesComponent(this)); // ... spriteBatch = new SpriteBatch(graphicsDeviceManager.GraphicsDevice); screenManager = new ScreenManager(assets, gameEngine, graphicsDeviceManager.GraphicsDevice, spriteBatch); } //... protected override void Draw(GameTime gameTime) { screenManager.Draw(gameTime); // calls the problematic method base.Draw(gameTime); } } Am I failing to initialize something properly? UPDATE: As an experiment, I tried this to the constructor of MasterEngine: spriteBatch = new SpriteBatch(graphicsDeviceManager.GraphicsDevice); spriteBatch.Begin(); spriteBatch.DrawString(assets.GetAsset<SpriteFont>("calibri"), "ftw", new Vector2(), Color.White); spriteBatch.End(); This does not cause a NRE. hmm.... UPDATE 2: This does cause an NRE: protected override void Draw(GameTime gameTime) { spriteBatch.Begin(); spriteBatch.End(); // boned here //screenManager.Draw(gameTime); base.Draw(gameTime); }

    Read the article

  • Barcode not generated in C# web forms?

    - by Sinsil Mathew
    I am trying for create a barcode in my web form.for that i download font IDAutomationHC39M and install in my system,then i run my wesite in localhost but barcode cannot be generated.This is my code protected void Button1_Click1(object sender, EventArgs e) { string barCode = TextBox1.Text; System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image(); using (Bitmap bitMap = new Bitmap(barCode.Length * 40, 80)) { using (Graphics graphics = Graphics.FromImage(bitMap)) { Font oFont = new Font("IDAutomationHC39M", 16); PointF point = new PointF(2f, 2f); SolidBrush blackBrush = new SolidBrush(Color.Black); SolidBrush whiteBrush = new SolidBrush(Color.White); graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height); graphics.DrawString("*" + barCode + "*", oFont, blackBrush, point); } using (MemoryStream ms = new MemoryStream()) { bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); byte[] byteImage = ms.ToArray(); Convert.ToBase64String(byteImage); imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage); } plBarCode.Controls.Add(imgBarCode); } And the result is appear like that code

    Read the article

  • Java Graphics not displaying on successive function calls, why?

    - by primehunter326
    Hi, I'm making a visualization for a BST implementation (I posted another question about it the other day). I've created a GUI which displays the viewing area and buttons. I've added code to the BST implementation to recursively traverse the tree, the function takes in coordinates along with the Graphics object which are initially passed in by the main GUI class. My idea was that I'd just have this function re-draw the tree after every update (add, delete, etc...), drawing a rectangle over everything first to "refresh" the viewing area. This also means I could alter the BST implementation (i.e by adding a balance operation) and it wouldn't affect the visualization. The issue I'm having is that the draw function only works the first time it is called, after that it doesn't display anything. I guess I don't fully understand how the Graphics object works since it doesn't behave the way I'd expect it to when getting passed/called from different functions. I know the getGraphics function has something to do with it. Relevant code: private void draw(){ Graphics g = vPanel.getGraphics(); tree.drawTree(g,ORIGIN,ORIGIN); } vPanel is what I'm drawing on private void drawTree(Graphics g, BinaryNode<AnyType> n, int x, int y){ if( n != null ){ drawTree(g, n.left, x-10,y+10 ); if(n.selected){ g.setColor(Color.blue); } else{ g.setColor(Color.gray); } g.fillOval(x,y,20,20); g.setColor(Color.black); g.drawString(n.element.toString(),x,y); drawTree(g,n.right, x+10,y+10); } } It is passed the root node when it is called by the public function. Do I have to have: Graphics g = vPanel.getGraphics(); ...within the drawTree function? This doesn't make sense!! Thanks for your help.

    Read the article

  • C# XNA: What can cause SpriteBatch.End() to throw a NPE?

    - by Rosarch
    I don't understand what I'm doing wrong here: public void Draw(GameTime gameTime) // in ScreenManager { SpriteBatch.Begin(SpriteBlendMode.AlphaBlend); for (int i = 0; i < Screens.Count; i++) { if (Screens[i].State == Screen.ScreenState.HIDDEN) continue; Screens[i].Draw(gameTime); } SpriteBatch.End(); // null ref exception } SpriteBatch itself is not null. Some more context: public class MasterEngine : Microsoft.Xna.Framework.Game { public MasterEngine() { graphicsDeviceManager = new GraphicsDeviceManager(this); Components.Add(new GamerServicesComponent(this)); // ... spriteBatch = new SpriteBatch(graphicsDeviceManager.GraphicsDevice); screenManager = new ScreenManager(assets, gameEngine, graphicsDeviceManager.GraphicsDevice, spriteBatch); } //... protected override void Draw(GameTime gameTime) { screenManager.Draw(gameTime); // calls the problematic method base.Draw(gameTime); } } Am I failing to initialize something properly? UPDATE: As an experiment, I tried this to the constructor of MasterEngine: spriteBatch = new SpriteBatch(graphicsDeviceManager.GraphicsDevice); spriteBatch.Begin(); spriteBatch.DrawString(assets.GetAsset<SpriteFont>("calibri"), "ftw", new Vector2(), Color.White); spriteBatch.End(); This does not cause a NRE. hmm....

    Read the article

  • GDI+ not clearing my window on repaint for vista

    - by Michael
    on WM_PAINT i do the following: //RectF mNameRect; //WCHAR* mName; //HWND mWin; // this is the window handle { PAINTSTRUCT ps; HDC hdc = BeginPaint(mWin, &ps); Graphics g(hdc); g.Clear(Color::White); StringFormat stringForm; stringForm.SetLineAlignment(StringAlignmentCenter); stringForm.SetAlignment(StringAlignmentCenter); // set the rectangle to the size of the whole window mNameRect.Width = static_cast<float>(size.cx); mNameRect.Height = static_cast<float>(size.cy); g.DrawString(mName, -1, &mNameFont, mNameRect, &stringForm, &mNameBrush); EndPaint(mWin, &ps); } In XP this works fine, the mName is displayed in the middle of the window. However on Vista the text doesn't move, it stays in its location no matter how I resize the window. the g.Clear(Color::White) doesn't seem to do any difference. The text doesn't even change position when the window is hidden behind another window and on focus needs to be repainted again. How do I make mName change position in Vista?

    Read the article

  • Stepping outside Visual Studio IDE [Part 1 of 2] with Eclipse

    - by mbcrump
    “If you're walking down the right path and you're willing to keep walking, eventually you'll make progress." – Barack Obama In my quest to become a better programmer, I’ve decided to start the process of learning Java. I will be primary using the Eclipse Language IDE. I will not bore you with the history just what is needed for a .NET developer to get up and running. I will provide links, screenshots and a few brief code tutorials. Links to documentation. The Official Eclipse FAQ’s Links to binaries. Eclipse IDE for Java EE Developers the Galileo Package (based on Eclipse 3.5 SR2)  Sun Developer Network – Java Eclipse officially recommends Java version 5 (also known as 1.5), although many Eclipse users use the newer version 6 (1.6). That's it, nothing more is required except to compile and run java. Installation Unzip the Eclipse IDE for Java EE Developers and double click the file named Eclipse.exe. You will probably want to create a link for it on your desktop. Once, it’s installed and launched you will have to select a workspace. Just accept the defaults and you will see the following: Lets go ahead and write a simple program. To write a "Hello World" program follow these steps: Start Eclipse. Create a new Java Project: File->New->Project. Select "Java" in the category list. Select "Java Project" in the project list. Click "Next". Enter a project name into the Project name field, for example, "HW Project". Click "Finish" Allow it to open the Java perspective Create a new Java class: Click the "Create a Java Class" button in the toolbar. (This is the icon below "Run" and "Window" with a tooltip that says "New Java Class.") Enter "HW" into the Name field. Click the checkbox indicating that you would like Eclipse to create a "public static void main(String[] args)" method. Click "Finish". A Java editor for HW.java will open. In the main method enter the following line.      System.out.println("This is my first java program and btw Hello World"); Save using ctrl-s. This automatically compiles HW.java. Click the "Run" button in the toolbar (looks like a VCR play button). You will be prompted to create a Launch configuration. Select "Java Application" and click "New". Click "Run" to run the Hello World program. The console will open and display "This is my first java program and btw Hello World". You now have your first java program, lets go ahead and make an applet. Since you already have the HW.java open, click inside the window and remove all code. Now copy/paste the following code snippet. Java Code Snippet for an applet. 1: import java.applet.Applet; 2: import java.awt.Graphics; 3: import java.awt.Color; 4:  5: @SuppressWarnings("serial") 6: public class HelloWorld extends Applet{ 7:  8: String text = "I'm a simple applet"; 9:  10: public void init() { 11: text = "I'm a simple applet"; 12: setBackground(Color.GREEN); 13: } 14:  15: public void start() { 16: System.out.println("starting..."); 17: } 18:  19: public void stop() { 20: System.out.println("stopping..."); 21: } 22:  23: public void destroy() { 24: System.out.println("preparing to unload..."); 25: } 26:  27: public void paint(Graphics g){ 28: System.out.println("Paint"); 29: g.setColor(Color.blue); 30: g.drawRect(0, 0, 31: getSize().width -1, 32: getSize().height -1); 33: g.setColor(Color.black); 34: g.drawString(text, 15, 25); 35: } 36: } The Eclipse IDE should look like Click "Run" to run the Hello World applet. Now, lets test our new java applet. So, navigate over to your workspace for example: “C:\Users\mbcrump\workspace\HW Project\bin” and you should see 2 files. HW.class java.policy.applet Create a HTML page with the following code: 1: <HTML> 2: <BODY> 3: <APPLET CODE=HW.class WIDTH=200 HEIGHT=100> 4: </APPLET> 5: </BODY> 6: </HTML> Open, the HTML page in Firefox or IE and you will see your applet running.  I hope this brief look at the Eclipse IDE helps someone get acquainted with Java Development. Even if your full time gig is with .NET, it will not hurt to have another language in your tool belt. As always, I welcome any suggestions or comments.

    Read the article

  • Why are only some of my objects being rendered?

    - by BleedObsidian
    Every time I create a new asteroid the previous one is no longer rendered? I did some debugging and printed out the size of Array-List 'Small' and when a new asteroid is created it doesn't go down, so the thread is still there it's just not being rendered, Why? StatePlay: package me.bleedobsidian.astroidjump; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; public class StatePlay extends BasicGameState { int stateID = 10; Player player; Asteroids asteroids; StatePlay(int stateID) { this.stateID = stateID; } @Override public int getID() { return stateID; } @Override public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { ResManager.loadImages(); player = new Player(); asteroids = new Asteroids(); } @Override public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException { g.setAntiAlias(true); player.render(g); asteroids.render(g); g.drawString("Asteroids: " + Asteroids.small.size(), 10, 25); } @Override public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException { player.update(gc, delta); asteroids.update(delta); } } Asteroids: package me.bleedobsidian.astroidjump; import java.util.ArrayList; import java.util.Timer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SpriteSheet; public class Asteroids { public static ArrayList<Asteroid_Small> small = new ArrayList<Asteroid_Small>(); static SpriteSheet small_sprites = new SpriteSheet(ResManager.asteroids_small_ss, 32, 32); static Image small_1 = small_sprites.getSubImage(0, 0); static Image small_2 = small_sprites.getSubImage(1, 0); static Image small_3 = small_sprites.getSubImage(2, 0); static Image small_4 = small_sprites.getSubImage(3, 0); static boolean asteroids = true; static int diff = 0; Asteroids() { Task_Asteroids TaskA = new Task_Asteroids(); Timer timer = new Timer("Asteroids"); if(diff == 0) { timer.schedule(TaskA, 0, 4000); } else if(diff == 1) { timer.schedule(TaskA, 0, 3000); } } public static Image chooseSmallImage(int i) { if(i == 0) { return small_1; } else if(i == 1) { return small_2; } else if(i == 2) { return small_3; } else if(i == 3) { return small_4; } else { return small_1; } } public static void level_manager(float x) { if(x < 1000) { diff = 0; } else if(x < 2000) { diff = 1; } else if(x < 3000) { diff = 2; } else if(x < 5000) { diff = 3; } else if(x < 10000) { diff = 4; } else { diff = 5; } } public void update(int delta) { for(int s = 0; s < small.size(); s++) { Asteroid_Small as = small.get(s); as.update(delta); } } public void render(Graphics g) { for(int s = 0; s < small.size(); s++) { Asteroid_Small as = small.get(s); as.render(g); } } public static void setAsteroids(boolean tf) { asteroids = tf; } } Asteroid_Small: package me.bleedobsidian.astroidjump; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; public class Asteroid_Small { private static Image me; private static float x = 0; private static float y = 0; private static float speed = 0; private static float rotation = 0; private static float rotation_speed = 0; Asteroid_Small(Image i, float x, float y, float rs, float sp) { me = i; Asteroid_Small.x = x; Asteroid_Small.y = y; Asteroid_Small.rotation_speed = rs; Asteroid_Small.speed = sp; } public void update(int delta) { x -= speed * delta; rotation += rotation_speed * delta; me.setRotation(rotation); } public void render(Graphics g) { g.drawImage(me, x, y); } } Task_Asteroid: package me.bleedobsidian.astroidjump; import java.util.TimerTask; public class Task_Asteroids extends TimerTask { public void run() { if(Asteroids.diff == 0) { int randImage = (int) (Math.random() * 4); int randHeight = (int) (Math.random() * 480); Asteroids.small.add(new Asteroid_Small(Asteroids.chooseSmallImage(randImage), Player.x + 960, randHeight, 0.05f, 0.04f)); } } }

    Read the article

  • How to create Captcha in ASP.NET

    - by Samir R. Bhogayta
    1. Create one page with name "Captcha.aspx" 2. No any control require in this page 3. Go to Captcha.aspx.vb write the below code Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load         'create object of Bitmap Class and set its width and height.         Dim objBMP As Bitmap = New Bitmap(180, 51)         'Create Graphics object and assign bitmap object to graphics' object.         Dim objGraphics As Graphics = Graphics.FromImage(objBMP)         objGraphics.Clear(Color.White)         objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias         Dim objFont As Font = New Font("arial", 30, FontStyle.Bold)         'genetating random 6 digit random number         Dim randomStr As String = GeneratePassword()         'set this random number in session         Session.Add("randomStr", randomStr)         Session.Add("randomStrCountry", randomStr)         objGraphics.DrawString(randomStr, objFont, Brushes.Black, 2, 2)         Response.ContentType = "image/GIF"         objBMP.Save(Response.OutputStream, ImageFormat.Gif)         objFont.Dispose()         objGraphics.Dispose()         objBMP.Dispose()     End Sub     Public Function GeneratePassword() As String         ' Below code describes how to create random numbers.some of the digits and letters         ' are ommited because they look same like "i","o","1","0","I","O".         Dim allowedChars As String = "a,b,c,d,e,f,g,h,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,"         allowedChars += "A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z,"         allowedChars += "2,3,4,5,6,7,8,9"         Dim sep() As Char = {","c}         Dim arr() As String = allowedChars.Split(sep)         Dim passwordString As String = ""         Dim temp As String         Dim rand As Random = New Random()         Dim i As Integer         For i = 0 To 5 - 1 Step i + 1             temp = arr(rand.Next(0, arr.Length))             passwordString += temp         Next         Return passwordString     End Function 4. Use this page in you aspx page like this img alt="" border="0" src="Captcha.aspx" style="cursor: move; height: 60px; width: 200px;" //                                   your textbox to insert code by user.

    Read the article

  • Why keylistener is not working here?

    - by swift
    i have implemented keylistener interface and implemented all the needed methods but when i press the key nothing happens here, why? package swing; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLayeredPane; import javax.swing.JPanel; import javax.swing.JTextArea; class Paper extends JPanel implements MouseListener,MouseMotionListener,ActionListener,KeyListener { static BufferedImage image; String shape; Color color=Color.black; Point start; Point end; Point mp; Button elipse=new Button("elipse"); int x[]=new int[50]; int y[]=new int[50]; 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"); ImageIcon erasericon=new ImageIcon("images/eraser.gif"); JButton erase=new JButton(erasericon); JButton[] colourbutton=new JButton[9]; String selected; Point label; String key; int ex,ey;//eraser //DatagramSocket dataSocket; JButton button = new JButton("test"); JLayeredPane layerpane; Point p=new Point(); int w,h; public Paper() { JFrame frame=new JFrame("Whiteboard"); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(640, 480); frame.setBackground(Color.black); layerpane=frame.getLayeredPane(); setWidth(539,444); setBounds(69,0,555,444); layerpane.add(this,new Integer(2)); layerpane.add(this.addButtons(),new Integer(0)); setLayout(null); setOpaque(false); addMouseListener(this); addMouseMotionListener(this); setFocusable(true); addKeyListener(this); System.out.println(isFocusable()); 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.drawPolygon(x,y,2); } } catch(Exception e) {} } //Function to draw the shape on image public void draw() { Graphics2D g2 = image.createGraphics(); 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.drawPolygon(x,y,2); } if(label!=null) { JTextArea textarea=new JTextArea(); if(selected==("text")) { textarea.setBounds(label.x, label.y, 50, 50); textarea.setMaximumSize(new Dimension(100,100)); textarea.setBackground(new Color(237,237,237)); add(textarea); g2.drawString("key",label.x,label.y); } } start=null; repaint(); g2.dispose(); } public void text() { System.out.println(label); } //Function which provides the erase functionality public void erase() { Graphics2D pic=(Graphics2D) image.getGraphics(); Color erasecolor=new Color(237,237,237); pic.setPaint(erasecolor); if(start!=null) pic.fillRect(start.x, start.y, 10, 10); } //To set the size of the image public void setWidth(int x,int y) { System.out.println("("+x+","+y+")"); w=x; h=y; image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); } //Function to add buttons into the panel, calling this function returns a panel public JPanel addButtons() { JPanel buttonpanel=new JPanel(); buttonpanel.setMaximumSize(new Dimension(70,70)); JPanel shape=new JPanel(); JPanel colourbox=new JPanel(); shape.setLayout(new GridLayout(4,2)); shape.setMaximumSize(new Dimension(70,140)); colourbox.setLayout(new GridLayout(3,3)); colourbox.setMaximumSize(new Dimension(70,70)); buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS)); elipse.addActionListener(this); elipse.setToolTipText("Elipse"); rectangle.addActionListener(this); rectangle.setToolTipText("Rectangle"); line.addActionListener( this); line.setToolTipText("Line"); erase.addActionListener(this); erase.setToolTipText("Eraser"); roundrect.addActionListener(this); roundrect.setToolTipText("Round rect"); polygon.addActionListener(this); polygon.setToolTipText("Polygon"); text.addActionListener(this); text.setToolTipText("Text"); shape.add(elipse); shape.add(rectangle); shape.add(line); shape.add(erase); shape.add(roundrect); shape.add(polygon); shape.add(text); buttonpanel.add(shape); for(int i=0;i<9;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); colourbutton[i].addActionListener(this); } buttonpanel.add(colourbox); buttonpanel.setBounds(0, 0, 70, 210); return buttonpanel; } public void mouseClicked(MouseEvent e) { if(selected=="text") { label=new Point(); label=e.getPoint(); draw(); } } @Override public void mouseEntered(MouseEvent arg0) { } public void mouseExited(MouseEvent arg0) { } public void mousePressed(MouseEvent e) { if(selected=="line"||selected=="erase"||selected=="text") { start=e.getPoint(); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { mp = e.getPoint(); } else if(selected=="poly") { x[0]=e.getX(); y[0]=e.getY(); } } public void mouseReleased(MouseEvent e) { if(start!=null) { if(selected=="line") { end=e.getPoint(); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); } else if(selected=="poly") { x[1]=e.getX(); y[1]=e.getY(); } draw(); } } public void mouseDragged(MouseEvent e) { if(end==null) end = new Point(); if(start==null) start = new Point(); if(selected=="line") { end=e.getPoint(); } else if(selected=="erase") { start=e.getPoint(); erase(); } 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()); } else if(selected=="poly") { x[1]=e.getX(); y[1]=e.getY(); } repaint(); } public void mouseMoved(MouseEvent arg0) {} 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"; System.out.println(selected); erase(); } else if(e.getSource()==roundrect) selected="rrect"; else if(e.getSource()==polygon) selected="poly"; else if(e.getSource()==text) selected="text"; if(e.getSource()==colourbutton[0]) color=Color.black; else if(e.getSource()==colourbutton[1]) color=Color.white; else if(e.getSource()==colourbutton[2]) color=Color.red; else if(e.getSource()==colourbutton[3]) color=Color.orange; else if(e.getSource()==colourbutton[4]) color=Color.blue; else if(e.getSource()==colourbutton[5]) color=Color.green; else if(e.getSource()==colourbutton[6]) color=Color.pink; else if(e.getSource()==colourbutton[7]) color=Color.magenta; else if(e.getSource()==colourbutton[8]) color=Color.cyan; } @Override public void keyPressed(KeyEvent e) { System.out.println("pressed"); } @Override public void keyReleased(KeyEvent e) { System.out.println("key released"); } @Override public void keyTyped(KeyEvent e) { System.out.println("Typed"); } public static void main(String[] a) { new Paper(); } } class Button extends JButton { String name; public Button(String name) { this.name=name; } 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",5, 22); } }

    Read the article

  • Drawing a TextBox in an extended Glass Frame (C# w/o WPF)

    - by Lazlo
    I am trying to draw a TextBox on the extended glass frame of my form. I won't describe this technique, it's well-known. Here's an example for those who haven't heard of it: http://www.danielmoth.com/Blog/Vista-Glass-In-C.aspx The thing is, it is complex to draw over this glass frame. Since black is considered to be the 0-alpha color, anything black disappears. There are apparently ways of countering this problem: drawing complex GDI+ shapes are not affected by this alpha-ness. For example, this code can be used to draw a Label on glass (note: GraphicsPath is used instead of DrawString in order to get around the horrible ClearType problem): public class GlassLabel : Control { public GlassLabel() { this.BackColor = Color.Black; } protected override void OnPaint(PaintEventArgs e) { GraphicsPath font = new GraphicsPath(); font.AddString( this.Text, this.Font.FontFamily, (int)this.Font.Style, this.Font.Size, Point.Empty, StringFormat.GenericDefault); e.Graphics.SmoothingMode = SmoothingMode.HighQuality; e.Graphics.FillPath(new SolidBrush(this.ForeColor), font); } } Similarly, such an approach can be used to create a container on the glass area. Note the use of the polygons instead of the rectangle - when using the rectangle, its black parts are considered as alpha. public class GlassPanel : Panel { public GlassPanel() { this.BackColor = Color.Black; } protected override void OnPaint(PaintEventArgs e) { Point[] area = new Point[] { new Point(0, 1), new Point(1, 0), new Point(this.Width - 2, 0), new Point(this.Width - 1, 1), new Point(this.Width -1, this.Height - 2), new Point(this.Width -2, this.Height-1), new Point(1, this.Height -1), new Point(0, this.Height - 2) }; Point[] inArea = new Point[] { new Point(1, 1), new Point(this.Width - 1, 1), new Point(this.Width - 1, this.Height - 1), new Point(this.Width - 1, this.Height - 1), new Point(1, this.Height - 1) }; e.Graphics.FillPolygon(new SolidBrush(Color.FromArgb(240, 240, 240)), inArea); e.Graphics.DrawPolygon(new Pen(Color.FromArgb(55, 0, 0, 0)), area); base.OnPaint(e); } } Now my problem is: How can I draw a TextBox? After lots of Googling, I came up with the following solutions: Subclassing the TextBox's OnPaint method. This is possible, although I could not get it to work properly. It should involve painting some magic things I don't know how to do yet. Making my own custom TextBox, perhaps on a TextBoxBase. If anyone has good, valid and working examples, and thinks this could be a good overall solution, please tell me. Using BufferedPaintSetAlpha. (http://msdn.microsoft.com/en-us/library/ms649805.aspx). The downsides of this method may be that the corners of the textbox might look odd, but I can live with that. If anyone knows how to implement that method properly from a Graphics object, please tell me. I personally don't, but this seems the best solution so far. Thanks!

    Read the article

  • JLabel animation in JPanel

    - by Trizicus
    After scratching around I found that it's best to implement a custom image component by extending a JLabel. So far that has worked great as I can add multiple "images" (jlabels without the layout breaking. I just have a question that I hope someone can answer for me. I noticed that in order to animate JLabels across the screen I need to setlayout(null); and setbounds of the component and then to animate eventually setlocation(x,y);. Is this a best practice or a terrible way to animate a component? I plan on eventually making an animation class but I don't want to do so and end up having to chuck it. I have included relevant code for a quick review check. import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel; import javax.swing.Timer; public class GraphicsPanel extends JPanel { private Timer timer; private long startTime = 0; private int numFrames = 0; private float fps = 0.0f; private int x = 0; GraphicsPanel() { final Entity ent1 = new Entity(); ent1.setBounds(x, 0, ent1.getWidth(), ent1.getHeight()); add(ent1); //ESSENTIAL setLayout(null); //GAMELOOP timer = new Timer(30, new ActionListener() { public void actionPerformed(ActionEvent e) { getFPS(); incX(); ent1.setLocation(x, 0); repaint(); } }); timer.start(); } public void incX() { x++; } @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; } } } } Thank you!

    Read the article

  • My ashx stopped working (Works locally, but not online)

    - by Madi D.
    i have a simple ASHX file that returns pictures upon request (mainly a counter), previously the code simply fetched pre-made pictures(already uploaded and available) and sent them to the requester.. i just modified the code,so it would take a base picture, do some modifications on it, save it to the server, then serve it to the user.. tested it locally and it worked like a charm. however when i uploaded the code to my hosting service (Godaddy..) it didnt work. Can someone point the problem out to me? Note: ASHX worked with me before,so i know the web.config and IIS are handling them properly, however i think i am missing something .. Code: <%@ WebHandler Language="C#" Class="NWEmpPhotoHandler" %> using System; using System.Web; using System.IO; using System.Drawing; using System.Drawing.Imaging; public class NWEmpPhotoHandler : IHttpHandler { public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext ctx) { try { //Some Code to fetch # of vistors from DB int x = 10,000; // # of Vistors, fetched from DB string numberOfVistors = (1000 + x).ToString(); string filePath = ctx.Server.MapPath("counter.jpg"); Bitmap myBitmap = new Bitmap(filePath); Graphics g = Graphics.FromImage(myBitmap); g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; StringFormat strFormat = new StringFormat(); g.DrawString(numberOfVistors , new Font("Tahoma", 24), Brushes.Maroon, new RectangleF(55, 82, 500, 500),null); string PathToSave = ctx.Server.MapPath("counter-" + numberOfVistors + ".jpg"); saveJpeg(PathToSave, myBitmap, 100); if (File.Exists(PathToSave)) { ctx.Response.ContentType = "image/jpg"; ctx.Response.WriteFile(PathToSave); //ctx.Response.OutputStream.Write(picByteArray, 0, picByteArray.Length); } } catch (ArgumentException exe) { } } private ImageCodecInfo getEncoderInfo(string mimeType) { // Get image codecs for all image formats ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); // Find the correct image codec for (int i = 0; i < codecs.Length; i++) if (codecs[i].MimeType == mimeType) return codecs[i]; return null; } private void saveJpeg(string path, Bitmap img, long quality) { // Encoder parameter for image quality EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality); // Jpeg image codec ImageCodecInfo jpegCodec = this.getEncoderInfo("image/jpeg"); if (jpegCodec == null) return; EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; img.Save(path, jpegCodec, encoderParams); } }

    Read the article

  • Please Critique Code (Java, Java2D, javax.swing.Timer)

    - by Trizicus
    Learn by practice right? Please critique and suggest anything! Thanks :) import java.awt.EventQueue; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.JFrame; public class MainWindow { public static void main(String[] args) { new MainWindow(); } JFrame frame; 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); gp.addMouseListener(new MouseListener() { 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) {} }); gp.addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent e) {} public void mouseMoved(MouseEvent e) {} }); frame.add(gp); } }); } } GraphicsPanel: import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel; import javax.swing.Timer; public class GraphicsPanel extends JPanel { Test t; Timer test; GraphicsPanel() { t = new Test(); setLayout(new BorderLayout()); add(t, BorderLayout.CENTER); test = new Timer(17, new Gameloop(this)); test.start(); } class Gameloop implements ActionListener { GraphicsPanel gp; Gameloop(GraphicsPanel gp) { this.gp = gp; } public void actionPerformed(ActionEvent e) { try { t.incX(); gp.repaint(); } catch (Exception ez) { } } } } Test: import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import javax.swing.JComponent; public class Test extends JComponent { Toolkit tk; Image img; int x, y; Test() { tk = Toolkit.getDefaultToolkit(); img = tk.getImage(getClass().getResource("images.jpg")); this.setPreferredSize(new Dimension(15, 15)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.setColor(Color.red); g2d.drawString("x: " + x, 350, 50); g2d.drawImage(img, x, 80, null); g2d.dispose(); } public void incX() { x++; } }

    Read the article

  • RMI-applets - Cannot understand error message

    - by aeter
    In a simple RMI game I'm writing (an assignment in uni), I reveice: java.rmi.MarshalException: error marshalling arguments; nested exception is: java.net.SocketException: Broken pipe at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:138) at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:178) at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:132) at $Proxy2.drawWorld(Unknown Source) at PlayerServerImpl$1.actionPerformed(PlayerServerImpl.java:180) at javax.swing.Timer.fireActionPerformed(Timer.java:271) at javax.swing.Timer$DoPostEvent.run(Timer.java:201) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209) at java.awt.EventQueue.dispatchEvent(EventQueue.java:597) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) The error message appears after the second Player is registered with the RMI Server and the server starts to send the image (the array of pixels) to the 2 applets. The PlayerImpl and the PlayerServerImpl both extend UnicastRemoteObject. I have been struggling with other error messages for some time now, but I cannot understand how to troubleshoot this one. Please help. The relevant parts of the code are: PlayerServerImpl.java: ... timer = new Timer(10, new ActionListener() { // every 10 milliseconds do: @Override public void actionPerformed(ActionEvent e) { ... BufferedImage buff_image = new BufferedImage(GAME_APPLET_WIDTH, GAME_APPLET_HEIGHT, BufferedImage.TYPE_INT_RGB); // create a graphics context on the buffered image Graphics buff_g = buff_image.createGraphics(); ... // draw the score somewhere on the screen buff_g.drawString(score, GAME_APPLET_WIDTH - 20, 10); ... int[] rgbs = new int[GAME_APPLET_WIDTH * GAME_APPLET_HEIGHT]; int imgPixelsGrabbed[] = buff_image.getRGB(0,0,GAME_APPLET_WIDTH,GAME_APPLET_HEIGHT,rgbs,0,GAME_APPLET_WIDTH); // send the new state to the applets for (Player player : players) { player.drawWorld(imgPixelsGrabbed); System.out.println("Sent image to player"); } PlayerImpl.java: private PlayerApplet applet; public PlayerImpl(PlayerApplet applet) throws RemoteException { super(); this.applet = applet; } ... @Override public void drawWorld(int[] imgPixelsGrabbed) throws RemoteException { applet.setWorld(imgPixelsGrabbed); applet.repaint(); } ... PlayerApplet.java: ... private int[] world; // an array of pixels for the new image to be drawn ... // register players player = new PlayerImpl(applet); String serverIPAddressPort = ipAddressField.getText(); if (validateIPAddressPort(serverIPAddressPort)) { server = (PlayerServer) Naming.lookup("rmi://" + serverIPAddressPort + "/PlayerServer"); server.register(player); idPlayer = server.sendPlayerID(); ... @Override public void update(Graphics g) { buff_img = createImage((ImageProducer) new MemoryImageSource(getWidth(), getHeight(), world, 0, getWidth())); Graphics gr = buff_img.getGraphics(); paint(gr); g.drawImage(buff_img, 0, 0, this); } public void setWorld(int[] world) { this.world = world; }

    Read the article

  • Getting my string value from my form into my class( not another form)

    - by jovany
    Hello all, I have a question regarding the some data which is being transfered from one form to my class. It's not going quite the way i'd like to , so I figured maybe there is someone who could help me. This is my code in my class Public Class DrawableTextBox Inherits Drawable Dim i_testString As Integer Private s_InsertLabel As String Private drawFont As Font Public Sub New(ByVal fore_color As Color, ByVal fill_color As Color, Optional ByVal line_width As Integer = 0, Optional ByVal new_x1 As Integer = 0, Optional ByVal new_y1 As Integer = 0, Optional ByVal new_x2 As Integer = 1, Optional ByVal new_y2 As Integer = 1) MyBase.New(fore_color, fill_color, line_width) X1 = new_x1 Y1 = new_y1 X2 = new_x2 Y2 = new_y2 Trace.WriteLine(s_InsertLabel) End Sub Friend WriteOnly Property _textBox() As String Set(ByVal Value As String) s_InsertLabel = Value Trace.WriteLine(s_InsertLabel) End Set End Property ' Draw the object on this Graphics surface. Public Overrides Sub Draw(ByVal gr As System.Drawing.Graphics) ' Make a Rectangle representing this rectangle. Dim rect As Rectangle = GetBounds() ' Fill the rectangle as usual. Dim fill_brush As New SolidBrush(FillColor) gr.FillRectangle(fill_brush, rect) fill_brush.Dispose() ' See if we're selected. If IsSelected Then ' Draw the rectangle highlighted. Dim highlight_pen As New Pen(Color.Yellow, LineWidth) gr.DrawRectangle(highlight_pen, rect) highlight_pen.Dispose() ' Draw grab handles. Trace.WriteLine("drawing the lines for my textbox") DrawGrabHandle(gr, X1, Y1) DrawGrabHandle(gr, X1, Y2) DrawGrabHandle(gr, X2, Y2) DrawGrabHandle(gr, X2, Y1) Else 'TextBox() Dim fg_pen As New Pen(Color.Red, LineWidth) 'Dim fontSize As Single = 0.1 + ((Y2 - Y1) / 2) Dim fontSize As Single = 20 Try Dim drawFont As New Font("Arial", fontSize, FontStyle.Bold) Trace.WriteLine(s_InsertLabel) gr.DrawString(s_InsertLabel, drawFont, Brushes.Brown, X1, Y1) Catch ex As ArgumentException End Try gr.DrawRectangle(Pens.Azure, rect) ' gr.DrawRectangle(fg_pen, rect) fg_pen.Dispose() End If End Sub Public Function GetValueString(ByVal ValueType As String) Return ValueType End Function ' Return the object's bounding rectangle. Public Overrides Function GetBounds() As System.Drawing.Rectangle Return New Rectangle( _ Min(X1, X2), _ Min(Y1, Y2), _ Abs(100), _ Abs(30)) Trace.WriteLine("don't forget to make variables in GetBounds DrawableTextbox") End Function ' Return True if this point is on the object. Public Overrides Function IsAt(ByVal x As Integer, ByVal y As Integer) As Boolean Return (x >= Min(X1, X2)) AndAlso _ (x <= Max(X1, X2)) AndAlso _ (y >= Min(Y1, Y2)) AndAlso _ (y <= Max(Y1, Y2)) End Function ' Move the second point. Public Overrides Sub NewPoint(ByVal x As Integer, ByVal y As Integer) X2 = x Y2 = y End Sub ' Return True if the object is empty (e.g. a zero-length line). Public Overrides Function IsEmpty() As Boolean Return (X1 = X2) AndAlso (Y1 = Y2) End Function End Class I've got a form with a textbox( form1) in which the text is being inserted and passed through a buttonclick (al via properties). As you can see I've placed several traces and in the property of the class my trace works fine , however if I look in my Draw function it is already gone. And I get a blank trace. Does anyone know what's happening here. thanks in advance. (forgive me I'm new )

    Read the article

  • How do I catch the error from my printer with PrintDocument?

    - by Scottie
    I am using the PrintDocument class to print to my Brother label printer. When I execute the Print() method, the printer starts flashing a red error light, but everything else returns successful. I can run this same code on my laser printer and everything works fine. How can I see what is causing the error on my label printer? Code: public class Test { private Font printFont; private List<string> _documentLinesToPrint = new List<string>(); public void Run() { _documentLinesToPrint.Add("Test1"); _documentLinesToPrint.Add("Test2"); printFont = new Font("Arial", 10); var pd = new PrintDocument(); pd.DefaultPageSettings.Margins = new Margins(25, 25, 25, 25); pd.DefaultPageSettings.PaperSize = new PaperSize("Label", 400, 237); var printerSettings = new System.Drawing.Printing.PrinterSettings(); printerSettings.PrinterName ="Brother QL-570 LE"; pd.PrinterSettings = printerSettings; pd.PrinterSettings.Copies = 1; pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage); pd.Print(); } // The PrintPage event is raised for each page to be printed. private void pd_PrintPage(object sender, PrintPageEventArgs ev) { float linesPerPage = 0; float yPos = 0; int count = 0; float leftMargin = ev.MarginBounds.Left; float topMargin = ev.MarginBounds.Top; string line = null; // Calculate the number of lines per page. linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics); // Print each line of the file. while ((count < linesPerPage) && (count < _documentLinesToPrint.Count)) { line = _documentLinesToPrint[count]; yPos = topMargin + (count * printFont.GetHeight(ev.Graphics)); ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat()); line = null; count++; } // If more lines exist, print another page. if (line != null) ev.HasMorePages = true; else ev.HasMorePages = false; } }

    Read the article

  • How to set Foreground Color in a ListBox single element?

    - by user1038056
    I'm doing a game. I have a list of users (nicks): List<string> users; This list is used to show to the users on a ListBox, call listaJogadores. public delegate void actualizaPlayersCallback(List<string> users); public void actualizaPlayers(List<string> users) { listaJogadores.BeginInvoke(new actualizaPlayersCallback(this.actualizarListaPlayers), new object[] { users }); } public void actualizarListaPlayers(List<string> users) { listaJogadores.Items.Clear(); for (int i = 0; i < users.Count; i++) { listaJogadores.Items.Add(users.ElementAt(i)); } } When a user is playing, then it have is nick on the list of games: List<Game> games; What I want is when a player enter in a game, the color of is nick show in listaJogadores, must be Red! When I have only one player in a game, everything is ok, all the players see the nick of that player in red, but when another player go to a game, then I get an ArgumentOutOfRangeException in the instruction string nick = tmp.players.ElementAt(i).getNick(); This is my code... Give me some ideas/help please! I think that the problem is the for(), but how can I manipulate an entire list without doing a loop? listaJogadores.DrawMode = DrawMode.OwnerDrawFixed; private void listaJogadores_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); Brush textBrush = SystemBrushes.ControlText; Font drawFont = e.Font; for (int i = 0; i < games.Count; i++) { Game tmp; tmp = games.ElementAt(i); for (int j = 0; j < tmp.players.Count; j++) { string nick = tmp.players.ElementAt(i).getNick(); if (listaJogadores.Items[e.Index].ToString() == nick) { textBrush = Brushes.Red;//RED.... if ((e.State & DrawItemState.Selected) > 0) drawFont = new Font(drawFont.FontFamily, drawFont.Size, FontStyle.Bold); } else if ((e.State & DrawItemState.Selected) > 0) { textBrush = SystemBrushes.HighlightText; } } } e.Graphics.DrawString(listaJogadores.Items[e.Index].ToString(), drawFont, textBrush, e.Bounds); }

    Read the article

  • JProgressBar.stringPainted(true); is not working

    - by Mirza Ghalib
    This is a part of my java code, in this code I have written that when I click the button the value of JProgressBar should becomes 0 and stringPainted(); becomes true, but "string painted" is not visible when I click the button, please help. import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JProgressBar; public class R implements ActionListener { static int y; CustomProgressBar b = new CustomProgressBar(); public static void main(String arg[]) throws Exception { new R(); } public R() throws Exception { JFrame f = new JFrame(); JButton btn = new JButton("Click"); f.setExtendedState(JFrame.MAXIMIZED_BOTH); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setUndecorated(true); f.setLayout(new FlowLayout()); btn.addActionListener(this); f.add(b); f.add(btn); f.setVisible(true); } class CustomProgressBar extends JProgressBar{ private static final long serialVersionUID = 1L; private boolean isStringToBePainted = false; public CustomProgressBar() { super(JProgressBar.VERTICAL,0,100); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if(isStringToBePainted ) { Dimension size = CustomProgressBar.this.getSize(); if( CustomProgressBar.this.getPercentComplete()<0.9 ) R.y = (int)( size.height - size.height * CustomProgressBar.this.getPercentComplete() ); String text = getString(); g.setColor(Color.BLACK ); g.drawString(text, 0, R.y); } } @Override public void setStringPainted(boolean b) { isStringToBePainted=b; } } @Override public void actionPerformed(ActionEvent e) { b.setValue(0); b.setStringPainted(true); } }

    Read the article

  • Request URL in Javascript, Fetch URL Content using Java Applet, return to Javascript?

    - by Sam G
    I'm in the process of making a little experiment, it grabs a YouTube page, and returns the highest quality MP4 link, then plays this in a HTML 5 Video element. Now I was using PHP with cURL to get the URL content (YouTube), but that only works on my local server (MP4 link is locked to IP address). I can't think of any other way to get the page content due to cross domain rules except a Java applet. So I've built a Java applet that should return the content of a URL. Java import java.applet.Applet; import java.awt.*; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class URLFetcherabc extends Applet { public void init() { } public void paint(Graphics g) { g.drawString("Java loaded. Waiting for URL", 0, 10); } public String getURL(String url, String httpMethod) { try { URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection)u.openConnection(); conn.setRequestMethod(httpMethod); InputStream is = conn.getInputStream(); ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; for (int bytesRead = 0; (bytesRead = is.read(buffer)) != -1; ) { output.write(buffer, 0, bytesRead); } return output.toString(); } catch (Exception e) { }return null; } } Now I've got the applet on the page, but every-time I call the function it returns nothing. Heres my HTML for including the applet. HTML <applet id="URLFetcher" name="URLFetcher" code="URLFetcherabc.class" archive="URLFetcher.jar" height="200" width="200" mayscript=""></applet> Java-Script function fetchurl(urltofetch) { var URLFetcher = document.getElementById("URLFetcher"); var result = URLFetcher.getURL(urltofetch); //Result = URL Content return result; } The function always returns null, in Java the function does work when passed a variable via other means (parameter etc). I've tried running other functions through Javascript and the Java applet does respond. I'm new to Java applets and communicating with them via Javascript, so I'm probably making either a small mistake somewhere or its completely wrong. Any ideas? Thanks

    Read the article

  • Using JDialog with Tabbed Pane to draw different pictures [migrated]

    - by Bryam Ulloa
    I am using NetBeans, and I have a class that extends to JDialog, inside that Dialog box I have created a Tabbed Pane. The Tabbed Pane contains 6 different tabs, with 6 different panels of course. What I want to do is when I click on the different tabs, a diagram is supposed to be drawn with the paint method. My question is how can I draw on the different panels with just one paint method in another class being called from the Dialog class? Here is my code for the Dialog class: package GUI; public class NewJDialog extends javax.swing.JDialog{ /** * Creates new form NewJDialog */ public NewJDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("FCFS", jPanel1); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("SSTF", jPanel2); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("LOOK", jPanel3); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("LOOK C", jPanel4); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("SCAN", jPanel5); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("SCAN C", jPanel6); getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER); jLabel1.setText("Distancia:"); jLabel2.setText("___________"); javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); jPanel7.setLayout(jPanel7Layout); jPanel7Layout.setHorizontalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addContainerGap(331, Short.MAX_VALUE)) ); jPanel7Layout.setVerticalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2)) .addContainerGap(15, Short.MAX_VALUE)) ); getContentPane().add(jPanel7, java.awt.BorderLayout.PAGE_START); pack(); }// </editor-fold> /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { NewJDialog dialog = new NewJDialog(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JTabbedPane jTabbedPane1; // End of variables declaration } This is another class that I have created for the paint method: package GUI; import java.awt.Graphics; import javax.swing.JPanel; /** * * @author TOSHIBA */ public class Lienzo { private int width = 5; private int height = 5; private int y = 5; private int x = 0; private int x1 = 0; public Graphics Draw(Graphics g, int[] pistas) { //Im not sure if this is the correct way to do it //The diagram gets drawn according to values from an array //The array is not always the same thats why I used the different Panels for (int i = 0; i < pistas.length; i++) { x = pistas[i]; x1 = pistas[i + 1]; g.drawOval(x, y, width, height); g.drawString(Integer.toString(x), x, y); g.drawLine(x, y, x1, y); } return g; } } I hope you guys understand what I am trying to do with my program.

    Read the article

  • Collide with rotation of the object

    - by Lahiru
    I'm developing a mirror for lazer beam(Ball sprite). There I'm trying to redirect the laze beam according to the ration degree of the mirror(Rectangle). How can I collide the ball to the correct angle if the colliding object is with some angle(45 deg) rather than colliding back. here is an screen shot of my work here is my code using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace collision { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Texture2D ballTexture; Rectangle ballBounds; Vector2 ballPosition; Vector2 ballVelocity; float ballSpeed = 30f; Texture2D blockTexture; Rectangle blockBounds; Vector2 blockPosition; private Vector2 origin; KeyboardState keyboardState; //Font SpriteFont Font1; Vector2 FontPos; private String displayText; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here ballPosition = new Vector2(this.GraphicsDevice.Viewport.Width / 2, this.GraphicsDevice.Viewport.Height * 0.25f); blockPosition = new Vector2(this.GraphicsDevice.Viewport.Width / 2, this.GraphicsDevice.Viewport.Height /2); ballVelocity = new Vector2(0, 1); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); ballTexture = Content.Load<Texture2D>("ball"); blockTexture = Content.Load<Texture2D>("mirror"); //create rectangles based off the size of the textures ballBounds = new Rectangle((int)(ballPosition.X - ballTexture.Width / 2), (int)(ballPosition.Y - ballTexture.Height / 2), ballTexture.Width, ballTexture.Height); blockBounds = new Rectangle((int)(blockPosition.X - blockTexture.Width / 2), (int)(blockPosition.Y - blockTexture.Height / 2), blockTexture.Width, blockTexture.Height); origin.X = blockTexture.Width / 2; origin.Y = blockTexture.Height / 2; // TODO: use this.Content to load your game content here Font1 = Content.Load<SpriteFont>("SpriteFont1"); FontPos = new Vector2(graphics.GraphicsDevice.Viewport.Width - 100, 20); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> /// private float RotationAngle; float circle = MathHelper.Pi * 2; float angle; protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // TODO: Add your update logic here //check for collision between the ball and the block, or if the ball is outside the bounds of the screen if (ballBounds.Intersects(blockBounds) || !GraphicsDevice.Viewport.Bounds.Contains(ballBounds)) { //we have a simple collision! //if it has hit, swap the direction of the ball, and update it's position ballVelocity = -ballVelocity; ballPosition += ballVelocity * ballSpeed; } else { //move the ball a bit ballPosition += ballVelocity * ballSpeed; } //update bounding boxes ballBounds.X = (int)ballPosition.X; ballBounds.Y = (int)ballPosition.Y; blockBounds.X = (int)blockPosition.X; blockBounds.Y = (int)blockPosition.Y; keyboardState = Keyboard.GetState(); float val = 1.568017f/90; if (keyboardState.IsKeyDown(Keys.Space)) RotationAngle = RotationAngle + (float)Math.PI; if (keyboardState.IsKeyDown(Keys.Left)) RotationAngle = RotationAngle - val; angle = (float)Math.PI / 4.0f; // 90 degrees RotationAngle = angle; // RotationAngle = RotationAngle % circle; displayText = RotationAngle.ToString(); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Add your drawing code here spriteBatch.Begin(); // Find the center of the string Vector2 FontOrigin = Font1.MeasureString(displayText) / 2; spriteBatch.DrawString(Font1, displayText, FontPos, Color.White, 0, FontOrigin, 1.0f, SpriteEffects.None, 0.5f); spriteBatch.Draw(ballTexture, ballPosition, Color.White); spriteBatch.Draw(blockTexture, blockPosition,null, Color.White, RotationAngle,origin, 1.0f, SpriteEffects.None, 0f); spriteBatch.End(); base.Draw(gameTime); } } }

    Read the article

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