Search Results

Search found 116 results on 5 pages for 'swift'.

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

  • Inheritance Mapping Strategies with Entity Framework Code First CTP5 Part 1: Table per Hierarchy (TPH)

    - by mortezam
    A simple strategy for mapping classes to database tables might be “one table for every entity persistent class.” This approach sounds simple enough and, indeed, works well until we encounter inheritance. Inheritance is such a visible structural mismatch between the object-oriented and relational worlds because object-oriented systems model both “is a” and “has a” relationships. SQL-based models provide only "has a" relationships between entities; SQL database management systems don’t support type inheritance—and even when it’s available, it’s usually proprietary or incomplete. There are three different approaches to representing an inheritance hierarchy: Table per Hierarchy (TPH): Enable polymorphism by denormalizing the SQL schema, and utilize a type discriminator column that holds type information. Table per Type (TPT): Represent "is a" (inheritance) relationships as "has a" (foreign key) relationships. Table per Concrete class (TPC): Discard polymorphism and inheritance relationships completely from the SQL schema.I will explain each of these strategies in a series of posts and this one is dedicated to TPH. In this series we'll deeply dig into each of these strategies and will learn about "why" to choose them as well as "how" to implement them. Hopefully it will give you a better idea about which strategy to choose in a particular scenario. Inheritance Mapping with Entity Framework Code FirstAll of the inheritance mapping strategies that we discuss in this series will be implemented by EF Code First CTP5. The CTP5 build of the new EF Code First library has been released by ADO.NET team earlier this month. EF Code-First enables a pretty powerful code-centric development workflow for working with data. I’m a big fan of the EF Code First approach, and I’m pretty excited about a lot of productivity and power that it brings. When it comes to inheritance mapping, not only Code First fully supports all the strategies but also gives you ultimate flexibility to work with domain models that involves inheritance. The fluent API for inheritance mapping in CTP5 has been improved a lot and now it's more intuitive and concise in compare to CTP4. A Note For Those Who Follow Other Entity Framework ApproachesIf you are following EF's "Database First" or "Model First" approaches, I still recommend to read this series since although the implementation is Code First specific but the explanations around each of the strategies is perfectly applied to all approaches be it Code First or others. A Note For Those Who are New to Entity Framework and Code-FirstIf you choose to learn EF you've chosen well. If you choose to learn EF with Code First you've done even better. To get started, you can find a great walkthrough by Scott Guthrie here and another one by ADO.NET team here. In this post, I assume you already setup your machine to do Code First development and also that you are familiar with Code First fundamentals and basic concepts. You might also want to check out my other posts on EF Code First like Complex Types and Shared Primary Key Associations. A Top Down Development ScenarioThese posts take a top-down approach; it assumes that you’re starting with a domain model and trying to derive a new SQL schema. Therefore, we start with an existing domain model, implement it in C# and then let Code First create the database schema for us. However, the mapping strategies described are just as relevant if you’re working bottom up, starting with existing database tables. I’ll show some tricks along the way that help you dealing with nonperfect table layouts. Let’s start with the mapping of entity inheritance. -- The Domain ModelIn our domain model, we have a BillingDetail base class which is abstract (note the italic font on the UML class diagram below). We do allow various billing types and represent them as subclasses of BillingDetail class. As for now, we support CreditCard and BankAccount: Implement the Object Model with Code First As always, we start with the POCO classes. Note that in our DbContext, I only define one DbSet for the base class which is BillingDetail. Code First will find the other classes in the hierarchy based on Reachability Convention. public abstract class BillingDetail  {     public int BillingDetailId { get; set; }     public string Owner { get; set; }             public string Number { get; set; } } public class BankAccount : BillingDetail {     public string BankName { get; set; }     public string Swift { get; set; } } public class CreditCard : BillingDetail {     public int CardType { get; set; }                     public string ExpiryMonth { get; set; }     public string ExpiryYear { get; set; } } public class InheritanceMappingContext : DbContext {     public DbSet<BillingDetail> BillingDetails { get; set; } } This object model is all that is needed to enable inheritance with Code First. If you put this in your application you would be able to immediately start working with the database and do CRUD operations. Before going into details about how EF Code First maps this object model to the database, we need to learn about one of the core concepts of inheritance mapping: polymorphic and non-polymorphic queries. Polymorphic Queries LINQ to Entities and EntitySQL, as object-oriented query languages, both support polymorphic queries—that is, queries for instances of a class and all instances of its subclasses, respectively. For example, consider the following query: IQueryable<BillingDetail> linqQuery = from b in context.BillingDetails select b; List<BillingDetail> billingDetails = linqQuery.ToList(); Or the same query in EntitySQL: string eSqlQuery = @"SELECT VAlUE b FROM BillingDetails AS b"; ObjectQuery<BillingDetail> objectQuery = ((IObjectContextAdapter)context).ObjectContext                                                                          .CreateQuery<BillingDetail>(eSqlQuery); List<BillingDetail> billingDetails = objectQuery.ToList(); linqQuery and eSqlQuery are both polymorphic and return a list of objects of the type BillingDetail, which is an abstract class but the actual concrete objects in the list are of the subtypes of BillingDetail: CreditCard and BankAccount. Non-polymorphic QueriesAll LINQ to Entities and EntitySQL queries are polymorphic which return not only instances of the specific entity class to which it refers, but all subclasses of that class as well. On the other hand, Non-polymorphic queries are queries whose polymorphism is restricted and only returns instances of a particular subclass. In LINQ to Entities, this can be specified by using OfType<T>() Method. For example, the following query returns only instances of BankAccount: IQueryable<BankAccount> query = from b in context.BillingDetails.OfType<BankAccount>() select b; EntitySQL has OFTYPE operator that does the same thing: string eSqlQuery = @"SELECT VAlUE b FROM OFTYPE(BillingDetails, Model.BankAccount) AS b"; In fact, the above query with OFTYPE operator is a short form of the following query expression that uses TREAT and IS OF operators: string eSqlQuery = @"SELECT VAlUE TREAT(b as Model.BankAccount)                       FROM BillingDetails AS b                       WHERE b IS OF(Model.BankAccount)"; (Note that in the above query, Model.BankAccount is the fully qualified name for BankAccount class. You need to change "Model" with your own namespace name.) Table per Class Hierarchy (TPH)An entire class hierarchy can be mapped to a single table. This table includes columns for all properties of all classes in the hierarchy. The concrete subclass represented by a particular row is identified by the value of a type discriminator column. You don’t have to do anything special in Code First to enable TPH. It's the default inheritance mapping strategy: This mapping strategy is a winner in terms of both performance and simplicity. It’s the best-performing way to represent polymorphism—both polymorphic and nonpolymorphic queries perform well—and it’s even easy to implement by hand. Ad-hoc reporting is possible without complex joins or unions. Schema evolution is straightforward. Discriminator Column As you can see in the DB schema above, Code First has to add a special column to distinguish between persistent classes: the discriminator. This isn’t a property of the persistent class in our object model; it’s used internally by EF Code First. By default, the column name is "Discriminator", and its type is string. The values defaults to the persistent class names —in this case, “BankAccount” or “CreditCard”. EF Code First automatically sets and retrieves the discriminator values. TPH Requires Properties in SubClasses to be Nullable in the Database TPH has one major problem: Columns for properties declared by subclasses will be nullable in the database. For example, Code First created an (INT, NULL) column to map CardType property in CreditCard class. However, in a typical mapping scenario, Code First always creates an (INT, NOT NULL) column in the database for an int property in persistent class. But in this case, since BankAccount instance won’t have a CardType property, the CardType field must be NULL for that row so Code First creates an (INT, NULL) instead. If your subclasses each define several non-nullable properties, the loss of NOT NULL constraints may be a serious problem from the point of view of data integrity. TPH Violates the Third Normal FormAnother important issue is normalization. We’ve created functional dependencies between nonkey columns, violating the third normal form. Basically, the value of Discriminator column determines the corresponding values of the columns that belong to the subclasses (e.g. BankName) but Discriminator is not part of the primary key for the table. As always, denormalization for performance can be misleading, because it sacrifices long-term stability, maintainability, and the integrity of data for immediate gains that may be also achieved by proper optimization of the SQL execution plans (in other words, ask your DBA). Generated SQL QueryLet's take a look at the SQL statements that EF Code First sends to the database when we write queries in LINQ to Entities or EntitySQL. For example, the polymorphic query for BillingDetails that you saw, generates the following SQL statement: SELECT  [Extent1].[Discriminator] AS [Discriminator],  [Extent1].[BillingDetailId] AS [BillingDetailId],  [Extent1].[Owner] AS [Owner],  [Extent1].[Number] AS [Number],  [Extent1].[BankName] AS [BankName],  [Extent1].[Swift] AS [Swift],  [Extent1].[CardType] AS [CardType],  [Extent1].[ExpiryMonth] AS [ExpiryMonth],  [Extent1].[ExpiryYear] AS [ExpiryYear] FROM [dbo].[BillingDetails] AS [Extent1] WHERE [Extent1].[Discriminator] IN ('BankAccount','CreditCard') Or the non-polymorphic query for the BankAccount subclass generates this SQL statement: SELECT  [Extent1].[BillingDetailId] AS [BillingDetailId],  [Extent1].[Owner] AS [Owner],  [Extent1].[Number] AS [Number],  [Extent1].[BankName] AS [BankName],  [Extent1].[Swift] AS [Swift] FROM [dbo].[BillingDetails] AS [Extent1] WHERE [Extent1].[Discriminator] = 'BankAccount' Note how Code First adds a restriction on the discriminator column and also how it only selects those columns that belong to BankAccount entity. Change Discriminator Column Data Type and Values With Fluent API Sometimes, especially in legacy schemas, you need to override the conventions for the discriminator column so that Code First can work with the schema. The following fluent API code will change the discriminator column name to "BillingDetailType" and the values to "BA" and "CC" for BankAccount and CreditCard respectively: protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) {     modelBuilder.Entity<BillingDetail>()                 .Map<BankAccount>(m => m.Requires("BillingDetailType").HasValue("BA"))                 .Map<CreditCard>(m => m.Requires("BillingDetailType").HasValue("CC")); } Also, changing the data type of discriminator column is interesting. In the above code, we passed strings to HasValue method but this method has been defined to accepts a type of object: public void HasValue(object value); Therefore, if for example we pass a value of type int to it then Code First not only use our desired values (i.e. 1 & 2) in the discriminator column but also changes the column type to be (INT, NOT NULL): modelBuilder.Entity<BillingDetail>()             .Map<BankAccount>(m => m.Requires("BillingDetailType").HasValue(1))             .Map<CreditCard>(m => m.Requires("BillingDetailType").HasValue(2)); SummaryIn this post we learned about Table per Hierarchy as the default mapping strategy in Code First. The disadvantages of the TPH strategy may be too serious for your design—after all, denormalized schemas can become a major burden in the long run. Your DBA may not like it at all. In the next post, we will learn about Table per Type (TPT) strategy that doesn’t expose you to this problem. References ADO.NET team blog Java Persistence with Hibernate book a { text-decoration: none; } a:visited { color: Blue; } .title { padding-bottom: 5px; font-family: Segoe UI; font-size: 11pt; font-weight: bold; padding-top: 15px; } .code, .typeName { font-family: consolas; } .typeName { color: #2b91af; } .padTop5 { padding-top: 5px; } .padTop10 { padding-top: 10px; } p.MsoNormal { margin-top: 0in; margin-right: 0in; margin-bottom: 10.0pt; margin-left: 0in; line-height: 115%; font-size: 11.0pt; font-family: "Calibri" , "sans-serif"; }

    Read the article

  • What is the importance of the .DFSFolderLink

    - by Swift
    I am currently building a new DFS namespace setup. My folder E:\CommonStuff\ is already shared on the fileserver. And now it is also shared as \DOMAIN\CommonStuff I got 3 questions: I see .DFSFolderLink records in all folders I create in the DFS Managment console. But all folders that was in E:\CommonStuff allready does not contain these records. Are the .DFSFolderLink records important? Does it make any difference if I create subfolders "the old way" in the E:\Commonstuff\ or if I do it within the DFS Managment console?

    Read the article

  • Windows XP - Power surge on hub port

    - by Swift-Tuttle
    Since last few weeks I constantly get this error, as status bar balloon: Power Surge on Hub Port - A USB device has exceeded the power limits of its hub port. Due to this now I am unable to access any USB devices properly, they get disconnected intermittently. I did quite a few things to resolve this problem, firstly obviously through the Windows help. I even tried all the things told on the Microsoft website(which essentially says is to check and update the driver) but in vain. One suggestion, I found when I google'd was to disable the USB2 controller through the Device Manager and since at every startup the System configuration comes up complaining that it has been changed etc.(On that same site it is mentioned to ignore this message.) But after everything I still cant solve this problem. Any help is much appreciated. The system is installed with Windows XP service Pack 3 and all the updates till last month. Please let me know if any other hardware info is required. **UPDATE** My laptop is about 5 years old now, its an HP with Celeron 1.4G processor. Windows XP SP3 installed. All latest windows updates installed. 2 USB ports available. BIOS is HP 68DTD ver F.0A Do I need to update my BIOS from somewhere ? or is this a hardware problem altogether?

    Read the article

  • What are "Excess Fragments" in defragmenting a hard drive?

    - by Andrew Swift
    I'm defragmenting my hard drive (XP SP3) with PerfectDisk 7.0, and it finds 816,659 excess fragments when I ask for an analysis. [update] Specifically, it shows that the 1TB disk is 14% fragmented with 19693 fragments and 816,659 excess fragments. About 20% of the disk is still free space. What does excess fragments refer to? What is the difference between fragments and excess fragments? I have had problems in the past where I defragmented a fragmented disk and many files were corrupted. It seemed as though "excess fragments" referred to orphan pieces, where the program couldn't find out where to put them. If that was true, then defragmenting a disk resulted in many incomplete files, and in fact I defragmented a disk full of MP3's and got a lot of corrupted files as a result. Instead, I started to simply format a separate disk and copy everything from one to the other. That way there were no orphan bits, and no file corruption. Does anybody know what "excess fragments" really are?

    Read the article

  • Writing an internal disk from IMG, what XP software to use?

    - by Andrew Swift
    I am trying to install the Chromium OS on an EEE PC 901, and I have succeeded in using Image Writer for Windows 0.2r23 to copy the IMG file to an SDHC card. Since the OS speed is limited by slow card access, I'd like to install the Chromium OS on the second, unused, internal SSD Drive, D:. However, Image Writer doesn't allow me to restore an internal drive from an IMG file. To be clear: I boot in XP on C: then run Image Writer to install the Chromium OS. Does anyone know how I can either convince Image Writer that D: is a removable drive or know of alternative program that will let me restore D: from an IMG file (non-windows file system)?

    Read the article

  • Install Chromium OS to SECOND internal drive on EEE 901?

    - by Andrew Swift
    I am trying to install the Chromium OS on an EEE PC 901, and I have succeeded in using Image Writer for Windows 0.2r23 to copy the IMG file to an SDHC card. Since the OS speed is limited by slow card access, I'd like to install the Chromium OS on the second, unused, internal SSD Drive, D:. However, Image Writer doesn't allow me to restore an internal drive from an IMG file. To be clear: I boot in XP on C: then run Image Writer to install the Chromium OS. Does anyone know how I can either convince Image Writer that D: is a removable drive or know of alternative program that will let me restore D: from an IMG file (non-windows file system)?

    Read the article

  • How to select text in Pico when I don't have a carat character?

    - by Andrew Swift
    I am using Pico via Terminal/SSH on an iPad with a French bluetooth keyboard. There is no way to type the carat (^) key to select text (control-carat to start selection). The carat on the keyboard is used to type a circonflex accent (août), and only becomes active when one types a letter after pressing it. There is therefore no way to type control-^. When I do type ctrl-^ in Pico, the cursor moves to the previous line. Is there an alternate way to select text in Pico? I can't see how to use it without finding a solution.

    Read the article

  • Difficult to point-and-click target with Apple Magic Trackpad?

    - by Andrew Swift
    My Magic Trackpad is great for most things involving dragging and gestures, but for simple point-and-click use it is starting to get really annoying. For example, my bank has a numeric code that I need to enter from a visual grid on the screen, by clicking on the six numbers in order. To do this is quite difficult with the Magic Trackpad. Idea 1: it is because when you start dragging on the touchpad, there is a brief delay before the mouse starts to move. The delay might be enough to screw up my anticipation of where the cursor is going to go. Idea 2: it may have to do with the cursor acceleration. If I move it a little, the cursor moves a little. If I move it a lot, it goes much faster. I have tried various settings in the preference pane, and although the cursor does move more or less quickly, it doesn't seem any more or less easy to hit a given target. As I am writing this post, I tried a brief experiment -- I chose a spot on the page (the bracket in the superuser logo) and tried to move the cursor there in one quick movement. It's extremely difficult, even though I've been using Macs and touchpads since 1999. There is something about the behavior of the trackpad that is making it impossible for me to learn how to accurately predict where the cursor will end up. Does anyone else have this problem?

    Read the article

  • Is is possible to hide label colors in list view in Mac OS 10.X Finder? I use labels as star ratings

    - by Andrew Swift
    I have modified the first five label names in OS X Lion to be ? through ?????. This way I can easily tag photos etc. in the finder. However, I find that Apple's rendering of the colored bars is horrendously ugly. I'd like to keep the labels (to be able to sort by label) but not see the colors. I know it was possible to change the colors with Label X, but Unsanity has not issued an update for Lion. I don't need to change the colors, just find a way to hide them in the finder.

    Read the article

  • Difficult to point-and-click target with Apple Magic Trackpad?

    - by Andrew Swift
    My Magic Trackpad is great for most things involving dragging and gestures, but for simple point-and-click use it is starting to get really annoying. For example, my bank has a numeric code that I need to enter from a visual grid on the screen, by clicking on the six numbers in order. To do this is quite difficult with the Magic Trackpad. Idea 1: it is because when you start dragging on the touchpad, there is a brief delay before the mouse starts to move. The delay might be enough to screw up my anticipation of where the cursor is going to go. Idea 2: it may have to do with the cursor acceleration. If I move it a little, the cursor moves a little. If I move it a lot, it goes much faster. I have tried various settings in the preference pane, and although the cursor does move more or less quickly, it doesn't seem any more or less easy to hit a given target. As I am writing this post, I tried a brief experiment -- I chose a spot on the page (the bracket in the superuser logo) and tried to move the cursor there in one quick movement. It's extremely difficult, even though I've been using Macs and touchpads since 1999. There is something about the behavior of the trackpad that is making it impossible for me to learn how to accurately predict where the cursor will end up. Does anyone else have this problem?

    Read the article

  • Colors less saturated in Snow Leopard Finder, Preview & Safari than in Chrome -- why?

    - by Andrew Swift
    If I look at the picture here in Safari, Preview or the finder, the shades of blue are significantly different than if I look at the picture in Google Chrome (they are less saturated than in Chrome). Since I am a photographer and need to prepare pictures for publication online, I need to know what a jpeg should really look like, in order to color-correct it. I have an excellent Eizo monitor that is correctly calibrated. If I open the same image in Photoshop CS3, I get the Chrome colors if I use Monitor RGB under view proof setup, and I get the Safari colors if I use Macintosh RGB. Can anyone explain the difference between these two settings, and the difference between Safari and Chrome? Which colors are correct? Photos that I prepared under Windows (during the past five years) now seem washed out in the Apple Finder and Preview, even though I had correctly prepared them. Is there a setting on the Macintosh for color calibration, besides the monitor calibration control panel?

    Read the article

  • Can I use the Airport Express as a an uplink between two networks?

    - by Ant Swift
    I have two separate networks using different IP ranges, 192.168.0.* for the wired only, isolated network and 192.160.1.* for the wireless only network which is connected to the internet. The wired network has a network printer setup and working and I want to be able to share it out to members of the wireless network (see diagram below). In short I need some kind of uplink between the two networks. Currently running a cable is out since there is no suitable route. I have a spare Airport Express and I am wondering if I could attach it to the wired network and have it join the wireless and act as the uplink between the two. Anyone know if the device is capable of this?

    Read the article

  • How can I combine 30,000 images into a timelapse movie?

    - by Swift
    I have taken 30,000 still images that I want to combine into a timelapse movie. I have tried QuickTime Pro, TimeLapse 3, and Windows Movie Maker, but with such a huge amount of images, each of the programs fail (I tried SUPER ©, but couldn't get it to work either...?). It seems that all of these programs crash after a few thousand pictures. The images I have are all in .JPG format, at a resolution of 1280x800, and I'm looking for a program that can put these images into a timelapse movie in some kind of lossless format (raw/uncompressed AVI would be fine) for further editing. Does anyone have any ideas, or has anyone tried anything like this with a similar number of pictures?

    Read the article

  • How can I combine 30,000 images into a timelapse movie?

    - by Swift
    I have taken 30,000 still images that I want to combine into a timelapse movie. I have tried QuickTime Pro, TimeLapse 3, and Windows Movie Maker, but with such a huge amount of images, each of the programs fail (I tried SUPER ©, but couldn't get it to work either...?). It seems that all of these programs crash after a few thousand pictures. The images I have are all in .JPG format, at a resolution of 1280x800, and I'm looking for a program that can put these images into a timelapse movie in some kind of lossless format (raw/uncompressed AVI would be fine) for further editing. Does anyone have any ideas, or has anyone tried anything like this with a similar number of pictures?

    Read the article

  • Windows XP - Power surge on hub port

    - by Swift-Tuttle
    Hi, Since last few weeks I constantly get this error, as status bar balloon: Power Surge on Hub Port - A USB device has exceeded the power limits of its hub port. Due to this now I am unable to access any USB devices properly, they get disconnected intermittently. I did quite a few things to resolve this problem, firstly obviously through the Windows help. I even tried all the things told on the Microsoft website(which essentially says is to check and update the driver) but in vain. One suggestion, I found when I google'd was to disable the USB2 controller through the Device Manager and since at every startup the System configuration comes up complaining that it has been changed etc.(On that same site it is mentioned to ignore this message.) But after everything I still cant solve this problem. Any help is much appreciated. The system is installed with Windows XP service Pack 3 and all the updates till last month. Please let me know if any other hardware info is required. **UPDATE** My laptop is about 5 years old now, its an HP with Celeron 1.4G processor. Windows XP SP3 installed. All latest windows updates installed. 2 USB ports available. BIOS is HP 68DTD ver F.0A Do I need to update my BIOS from somewhere ? or is this a hardware problem altogether?

    Read the article

  • Problem with my whiteboard application

    - by swift
    I have to develop a whiteboard application in which both the local user and the remote user should be able to draw simultaneously, is this possible? If possible then any logic? I have already developed a code but in which i am not able to do this, when the remote user starts drawing the shape which i am drawing is being replaced by his shape and co-ordinates. This problem is only when both draw simultaneously. any idea guys? Here is my code class Paper extends JPanel implements MouseListener,MouseMotionListener,ActionListener { static BufferedImage image; int bpressed; Color color; Point start; Point end; Point mp; Button elipse=new Button("elipse"); Button rectangle=new Button("rect"); Button line=new Button("line"); Button empty=new Button(""); JButton save=new JButton("Save"); JButton erase=new JButton("Erase"); String selected; int ex,ey;//eraser DatagramSocket dataSocket; JButton button = new JButton("test"); Client client; Point p=new Point(); int w,h; public Paper(DatagramSocket dataSocket) { this.dataSocket=dataSocket; client=new Client(dataSocket); System.out.println("paper"); setBackground(Color.white); addMouseListener(this); addMouseMotionListener(this); color = Color.black; setBorder(BorderFactory.createLineBorder(Color.black)); //save.setPreferredSize(new Dimension(100,20)); save.setMaximumSize(new Dimension(75,27)); erase.setMaximumSize(new Dimension(75,27)); } public void paintComponent(Graphics g) { try { g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; g2.setPaint(Color.black); 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==("line")) g2.drawLine(start.x,start.y,end.x,end.y); } catch(Exception e) {} } //Function to draw the shape on image public void draw() { Graphics2D g2 = image.createGraphics(); g2.setPaint(color); if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); if(selected=="elipse") g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); if(selected=="rect") g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); repaint(); g2.dispose(); start=null; } //To add the point to the board which is broadcasted by the server public synchronized void addPoint(Point ps,String varname,String shape,String event) { try { if(end==null) end = new Point(); if(start==null) start = new Point(); if(shape.equals("elipse")) selected="elipse"; else if(shape.equals("line")) selected="line"; else if(shape.equals("rect")) selected="rect"; else if(shape.equals("erase")) { selected="erase"; erase(); } if(end!=null && start!=null) { if(varname.equals("end")) end=ps; if(varname.equals("mp")) mp=ps; if(varname.equals("start")) start=ps; if(event.equals("drag")) repaint(); else if(event.equals("release")) draw(); } } catch(Exception e) { e.printStackTrace(); } } //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_RGB); Graphics2D g2 = image.createGraphics(); g2.setPaint(Color.white); g2.fillRect(0,0,w,h); g2.dispose(); } //Function which provides the erase functionality public void erase() { Graphics2D pic=(Graphics2D) image.getGraphics(); pic.setPaint(Color.white); pic.fillRect(start.x, start.y, 10, 10); } //Function to add buttons into the panel, calling this function returns a panel public JPanel addButtons() { JPanel buttonpanel=new JPanel(); JPanel row1=new JPanel(); JPanel row2=new JPanel(); JPanel row3=new JPanel(); JPanel row4=new JPanel(); buttonpanel.setPreferredSize(new Dimension(80,80)); //buttonpanel.setMinimumSize(new Dimension(150,150)); row1.setLayout(new BoxLayout(row1,BoxLayout.X_AXIS)); row1.setPreferredSize(new Dimension(150,150)); row2.setLayout(new BoxLayout(row2,BoxLayout.X_AXIS)); row3.setLayout(new BoxLayout(row3,BoxLayout.X_AXIS)); row4.setLayout(new BoxLayout(row4,BoxLayout.X_AXIS)); buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS)); elipse.addActionListener(this); rectangle.addActionListener(this); line.addActionListener( this); save.addActionListener( this); erase.addActionListener( this); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row1.add(elipse); row1.add(Box.createRigidArea(new Dimension(5,0))); row1.add(rectangle); buttonpanel.add(row1); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row2.add(line); row2.add(Box.createRigidArea(new Dimension(5,0))); row2.add(empty); buttonpanel.add(row2); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row3.add(save); buttonpanel.add(row3); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row4.add(erase); buttonpanel.add(row4); return buttonpanel; } //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 arg0) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent arg0) { } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent e) { if(selected=="line"||selected=="erase") { start=e.getPoint(); client.broadcast(start,"start", selected,"press"); } else if(selected=="elipse"||selected=="rect") { mp = e.getPoint(); client.broadcast(mp,"mp", selected,"press"); } } public void mouseReleased(MouseEvent e) { if(start!=null) { if(selected=="line") { end=e.getPoint(); client.broadcast(end,"end", selected,"release"); } else if(selected=="elipse"||selected=="rect") { end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); client.broadcast(end,"end", selected,"release"); } draw(); } //start=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"); } else if(selected=="erase") { start=e.getPoint(); erase(); client.broadcast(start,"start", selected,"drag"); } else if(selected=="elipse"||selected=="rect") { 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"); client.broadcast(end,"end", selected,"drag"); } repaint(); } @Override public void mouseMoved(MouseEvent arg0) { // TODO Auto-generated method stub } public void actionPerformed(ActionEvent e) { if(e.getSource()==elipse) selected="elipse"; if(e.getSource()==line) selected="line"; if(e.getSource()==rectangle) selected="rect"; if(e.getSource()==save) save(); if(e.getSource()==erase) { selected="erase"; erase(); } } } class Button extends JButton { String name; public Button(String name) { this.name=name; Dimension buttonSize = new Dimension(35,35); setMaximumSize(buttonSize); } 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); } }

    Read the article

  • Why Look and feel is not getting updated properly?

    - by swift
    I’m developing a swing application in which I have an option to change the Look and feel of the application on click of a button. Now my problem is when I click the button to change the theme it’s not properly updating the L&F of my app, say my previous theme is “noire” and I choose “MCWin” after it, but the style of the noire theme is still there Here is sample working code: package whiteboard; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import javax.swing.JFrame; import javax.swing.JLayeredPane; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.WindowConstants; public class DiscussionBoard extends JFrame implements ComponentListener,ActionListener { // Variables declaration private JMenuItem audioMenuItem; private JMenuItem boardMenuItem; private JMenuItem exitMenuItem; private JMenuItem clientsMenuItem; private JMenuItem acryl; private JMenuItem hifi; private JMenuItem aero; private JMenuItem aluminium; private JMenuItem bernstein; private JMenuItem fast; private JMenuItem graphite; private JMenuItem luna; private JMenuItem mcwin; private JMenuItem noire; private JMenuItem smart; private JMenuBar boardMenuBar; private JMenuItem messengerMenuItem; private JMenu openMenu; private JMenu saveMenu; private JMenu themesMenu; private JMenuItem saveMessengerMenuItem; private JMenuItem saveWhiteboardMenuItem; private JMenu userMenu; JLayeredPane layerpane; /** Creates new form discussionBoard * @param connection */ public DiscussionBoard() { initComponents(); setLocationRelativeTo(null); addComponentListener(this); } private void initComponents() { boardMenuBar = new JMenuBar(); openMenu = new JMenu(); themesMenu = new JMenu(); messengerMenuItem = new JMenuItem(); boardMenuItem = new JMenuItem(); audioMenuItem = new JMenuItem(); saveMenu = new JMenu(); saveMessengerMenuItem = new JMenuItem(); saveWhiteboardMenuItem = new JMenuItem(); userMenu = new JMenu(); clientsMenuItem = new JMenuItem(); exitMenuItem = new JMenuItem(); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(new GridBagLayout()); setResizable(false); setTitle("Discussion Board"); openMenu.setText("Open"); saveMenu.setText("Save"); themesMenu.setText("Themes"); acryl = new JMenuItem("Acryl"); hifi = new JMenuItem("HiFi"); aero = new JMenuItem("Aero"); aluminium = new JMenuItem("Aluminium"); bernstein = new JMenuItem("Bernstein"); fast = new JMenuItem("Fast"); graphite = new JMenuItem("Graphite"); luna = new JMenuItem("Luna"); mcwin = new JMenuItem("MCwin"); noire = new JMenuItem("Noire"); smart = new JMenuItem("Smart"); hifi.addActionListener(this); acryl.addActionListener(this); aero.addActionListener(this); aluminium.addActionListener(this); bernstein.addActionListener(this); fast.addActionListener(this); graphite.addActionListener(this); luna.addActionListener(this); mcwin.addActionListener(this); noire.addActionListener(this); smart.addActionListener(this); messengerMenuItem.setText("Messenger"); openMenu.add(messengerMenuItem); openMenu.add(boardMenuItem); audioMenuItem.setText("Audio Messenger"); openMenu.add(audioMenuItem); exitMenuItem.setText("Exit"); exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); openMenu.add(exitMenuItem); boardMenuBar.add(openMenu); saveMessengerMenuItem.setText("Messenger"); saveMenu.add(saveMessengerMenuItem); saveWhiteboardMenuItem.setText("Whiteboard"); saveMenu.add(saveWhiteboardMenuItem); boardMenuBar.add(saveMenu); userMenu.setText("Users"); clientsMenuItem.setText("Current Session"); userMenu.add(clientsMenuItem); themesMenu.add(acryl); themesMenu.add(hifi); themesMenu.add(aero); themesMenu.add(aluminium); themesMenu.add(bernstein); themesMenu.add(fast); themesMenu.add(graphite); themesMenu.add(luna); themesMenu.add(mcwin); themesMenu.add(noire); themesMenu.add(smart); boardMenuBar.add(userMenu); boardMenuBar.add(themesMenu); saveMessengerMenuItem.setEnabled(false); saveWhiteboardMenuItem.setEnabled(false); setJMenuBar(boardMenuBar); setSize(1024, 740); setVisible(true); } protected void exitMenuItemActionPerformed(ActionEvent evt) { System.exit(0); } @Override public void componentHidden(ComponentEvent arg0) { } @Override public void componentMoved(ComponentEvent e) { } @Override public void componentResized(ComponentEvent arg0) { } @Override public void componentShown(ComponentEvent arg0) { } @Override public void actionPerformed(ActionEvent e) { try { if(e.getSource()==hifi) { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.hifi.HiFiLookAndFeel"); enableTheme(); hifi.setEnabled(false); } else if(e.getSource()==acryl) { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.acryl.AcrylLookAndFeel"); enableTheme(); acryl.setEnabled(false); } else if(e.getSource()==aero) { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.aero.AeroLookAndFeel"); enableTheme(); aero.setEnabled(false); } else if(e.getSource()==aluminium) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.aluminium.AluminiumLookAndFeel"); enableTheme(); aluminium.setEnabled(false); } else if(e.getSource()==bernstein) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.bernstein.BernsteinLookAndFeel"); enableTheme(); bernstein.setEnabled(false); } else if(e.getSource()==fast) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.fast.FastLookAndFeel"); enableTheme(); fast.setEnabled(false); } else if(e.getSource()==graphite) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.graphite.GraphiteLookAndFeel"); enableTheme(); graphite.setEnabled(false); } else if(e.getSource()==luna) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.luna.LunaLookAndFeel"); enableTheme(); luna.setEnabled(false); } else if(e.getSource()==mcwin) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.mcwin.McWinLookAndFeel"); enableTheme(); mcwin.setEnabled(false); } else if(e.getSource()==noire) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.noire.NoireLookAndFeel"); enableTheme(); noire.setEnabled(false); } else if(e.getSource()==smart) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel"); enableTheme(); smart.setEnabled(false); } SwingUtilities.updateComponentTreeUI(getRootPane()); } catch (Exception ex) { ex.printStackTrace(); } } private void enableTheme() { acryl.setEnabled(true); hifi.setEnabled(true); aero.setEnabled(true); aluminium.setEnabled(true); bernstein.setEnabled(true); fast.setEnabled(true); graphite.setEnabled(true); luna.setEnabled(true); mcwin.setEnabled(true); noire.setEnabled(true); smart.setEnabled(true); } public static void main(String []ar) { try { UIManager.setLookAndFeel("com.jtattoo.plaf.acryl.AcrylLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } new DiscussionBoard(); } } What’s the problem here? why its not getting updated? There is a demo application here which is exactly doing what i want but i cant get a clear idea of it.

    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

  • 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

  • JPanel paint method is not being called, why?

    - by swift
    When i run this code the paintComponent method is not being called It may be very simple error but i dont know why this, plz. package test; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.image.BufferedImage; import javax.swing.BorderFactory; import javax.swing.JPanel; class Userboard extends JPanel { static BufferedImage image; String shape; Point start; Point end; Point mp; String selected; int ex,ey;//eraser int w,h; public Userboard() { setOpaque(false); System.out.println("paper"); setBackground(Color.white); setBorder(BorderFactory.createLineBorder(Color.black)); } public void paintComponent(Graphics g) { System.out.println("userboard-paint"); try { //g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; g2.setPaint(Color.black); if(start!=null && end!=null) { if(selected==("elipse")) { System.out.println("userboard-elipse"); g2.drawOval(start.x, start.y,(end.x-start.x),(end.y-start.y)); System.out.println("userboard-elipse drawn"); } else if(selected==("rect")) g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("line")) g2.drawLine(start.x,start.y,end.x,end.y); } } catch(Exception e) {} } //Function to draw the shape on image public void draw() { System.out.println("Userboard-draw"); System.out.println(selected); System.out.println(start); System.out.println(end); Graphics2D g2 = image.createGraphics(); g2.setPaint(Color.black); if(start!=null && end!=null) { if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); else if(selected=="elipse") { System.out.println("userboard-elipse"); g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); System.out.println("userboard-elipse drawn"); } else if(selected=="rect") g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); } start=null; repaint(); g2.dispose(); } //To add the point to the board which is broadcasted by the server public void addPoint(Point ps,String varname,String shape,String event) { try { if(end==null) end = new Point(); if(start==null) start = new Point(); if(shape.equals("elipse")) this.selected="elipse"; else if(shape.equals("line")) this.selected="line"; else if(shape.equals("rect")) this.selected="rect"; else if(shape.equals("erase")) erase(); if(end!=null && start!=null) { if(varname.equals("end")) end=ps; else if(varname.equals("mp")) mp=ps; else if(varname.equals("start")) start=ps; if(event.equals("drag")) repaint(); else if(event.equals("release")) draw(); } repaint(); } catch(Exception e) { e.printStackTrace(); } } //Function which provides the erase functionality public void erase() { Graphics2D pic=(Graphics2D) image.getGraphics(); pic.setPaint(Color.white); 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 }

    Read the article

  • How to use third party themes in swing application?

    - by swift
    I want to use some third party themes (like synthetica http://www.javasoft.de/synthetica/themes/) in my swing appliaction. i am using eclipse ide, got the jar file of theme and did the following modification(according to the readme file from the theme) in my code try { UIManager.setLookAndFeel(new SyntheticaBlackMoonLookAndFeel()); } catch (Exception e) { e.printStackTrace(); } but after this modification its showing the following error The type de.javasoft.plaf.synthetica.SyntheticaLookAndFeel cannot be resolved. It is indirectly referenced from required .class files what does this mean? i tried searching on net but cant really find any useful answers Contents of Readme file: System Requirements =================== Java SE 5 (JRE 1.5.0) or above Synthetica V2.2.0 or above Integration =========== 1. Ensure that your classpath contains all Synthetica libraries (including Synthetica's core library 'synthetica.jar'). 2. Enable the Synthetica Look and Feel at startup time in your application: import de.javasoft.plaf.synthetica.SyntheticaBlackMoonLookAndFeel; try { UIManager.setLookAndFeel(new SyntheticaBlackMoonLookAndFeel()); } catch (Exception e) { e.printStackTrace(); }

    Read the article

  • How to set custom size for cursor in swing?

    - by swift
    I am using the below code to set a custom cursor for JPanel, but its enlarging the image which i set for cursor. Is there a way to set a customized cursor size ? Toolkit toolkit = Toolkit.getDefaultToolkit(); BufferedImage erasor=new BufferedImage(10,10, BufferedImage.TYPE_INT_RGB); Graphics2D g2d=(Graphics2D) erasor.createGraphics(); g2d.setPaint(Color.red); g2d.drawRect(e.getX(),e.getY() ,10, 10); toolkit.getBestCursorSize(10, 10); Cursor mcursor=toolkit.createCustomCursor(erasor, new Point(10,10), "Eraser"); setCursor(mcursor);

    Read the article

  • PHP Transferring Photos From One Oracle Database Table to Another

    - by Jonathan Swift
    I am attempting to transfer a set of photos (blobs) from one table to another across databases. I'm nearly there, except for binding the photo parameter. I have the following code: $conn_db1 = oci_pconnect('username', 'password', 'db1'); $conn_db2 = oci_pconnect('username', 'password', 'db2'); $parse_db1_select = oci_parse($conn_db1, "SELECT REF PID, BINARY_OBJECT PHOTOGRAPH FROM BLOBS"); $parse_db2_insert = oci_parse($conn_db2, "INSERT INTO PHOTOGRAPHS (PID, PHOTOGRAPH) VALUES (:pid, :photo)"); oci_execute($parse_db1_select); while ($row = oci_fetch_assoc($parse_db1_select)) { $pid = $row['PID']; $photo = $row['PHOTOGRAPH']; oci_bind_by_name($parse_db2_insert, ':pid', $pid, -1, OCI_B_INT); // This line causes an error oci_bind_by_name($parse_db_insert, ':photo', $photo, -1, OCI_B_BLOB); oci_execute($parse_db2_insert); } oci_close($db1); oci_close($db2); But I get the following error, on the error line commented above: Warning: oci_execute() [function.oci-execute]: ORA-03113: end-of-file on communication channel Process ID: 0 Session ID: 790 Serial number: 118 Does anyone know the right way to do this?

    Read the article

  • MySQL import in phpmyadmin (CSV) chokes on quotes

    - by Andrew Swift
    I am trying to import a .csv file into a MySQL table via phpMyAdmin. The .csv file is separated by pipes, formated like this: data|d'ata|d'a"ta|dat"a| data|"da"ta|data|da't'a| dat'a|data|da"ta"|da'ta| The data contains quotes. I have no control over the format in which I recieve the data -- it is generated by a third party. The problem comes when there is a | followed by a double quote. I always get an "invalid field count in CSV input on line N" error. I am uploading the file from the import page, using Latin1, CSV, terminated by |, separated by ". I would like to just change the "enclosed by" character, but I keep getting "Invalid parameter for CSV import: Fields enclosed by". I have tried various characters with no success. How can I tell MySQL to accept this format in phpMyAdmin? Setting up these tables is the first step in writing a program that will use uploaded gzipped .csv files to maintain the catalog of an e-commerce site.

    Read the article

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