Search Results

Search found 37239 results on 1490 pages for 'javax swing text'.

Page 56/1490 | < Previous Page | 52 53 54 55 56 57 58 59 60 61 62 63  | Next Page >

  • How to change the value of a JLabel in runtime?

    - by user365465
    I want to change the image a JLabel is viewing during runtime, but I keep getting NullPointerExceptions or nothing happens when I press the magic button that's supposed to do things. Is it even possible in Java? Here is my code in its entirety: import java.text.*; import javax.swing.text.*; import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public class Shell implements ActionListener, MenuKeyListener { JFrame frame; JWindow window; JButton PSubmit; JPanel pane1, pane2; JRadioButton R1, R2, R3; ButtonGroup PGroup; JTabbedPane layout; String result; String border = "Border.png"; String DF = "Frame.png"; String list []; Driver driver; public Shell() { driver = new Driver(); list = new String [6]; } public void setFrame() { frame = new JFrame("Pokemon Program 3 by Systems Ready"); frame.setSize(600, 600); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.getContentPane().setLayout(new BorderLayout()); } public void frameLayout() { layout = new JTabbedPane(); JPanel pane1 = new JPanel(); JPanel pane2 = new JPanel(); JLabel label = new JLabel("Please choose the restrictions:"); JLabel imgLabel1 = new JLabel(new ImageIcon(border)); JLabel notiLabel1 = new JLabel("The Pokemon chosen with these restrictions are: "); JLabel notiLabel2 = new JLabel("'No Restrictions': No restrictions for the kind of Pokemon chosen based on species or items."); JLabel notiLabel3 = new JLabel("'Battle Revolution': All Pokemon must have unique items."); JLabel notiLabel4 = new JLabel("'Battle Tower': All Pokemon must have unique items, Uber and Event Legendaries banned."); JLabel label2 = new JLabel("Please choose possible Pokemon:"); pane1.add(label); pearlButtons(); pane1.add(R1); pane1.add(R2); pane1.add(R3); pane1.add(PSubmit); pane1.add(notiLabel2); pane1.add(notiLabel3); pane1.add(notiLabel4); pane1.add(imgLabel1); pane1.add(notiLabel1); JLabel pokeLabel1 = new JLabel(new ImageIcon(DF)); JLabel pokeLabel2 = new JLabel(new ImageIcon(DF)); JLabel pokeLabel3 = new JLabel(new ImageIcon(DF)); JLabel pokeLabel4 = new JLabel(new ImageIcon(DF)); JLabel pokeLabel5 = new JLabel(new ImageIcon(DF)); JLabel pokeLabel6 = new JLabel(new ImageIcon(DF)); pane1.add(pokeLabel1); pane1.add(pokeLabel2); pane1.add(pokeLabel3); pane1.add(pokeLabel4); pane1.add(pokeLabel5); pane1.add(pokeLabel6); pane2.add(label2); layout.add("Pearl Version", pane1); layout.add("SoulSilver Version", pane2); frame.add(layout); } public void pearlButtons() { PGroup = new ButtonGroup(); R1 = new JRadioButton("No Restrictions", true); R1.setActionCommand("N"); R1.setVisible(true); R2 = new JRadioButton("Battle Revolution"); R2.setActionCommand("BR"); R2.setVisible(true); R3 = new JRadioButton("Battle Tower"); R3.setActionCommand("B"); R3.setVisible(true); PGroup.add(R1); PGroup.add(R2); PGroup.add(R3); PSubmit = new JButton("Submit"); PSubmit.setActionCommand("pstart"); PSubmit.setVisible(true); PSubmit.addActionListener(this); } public void pearlProcessing() { //The "list" array has a bunch of string names that get .png affixed to them (and I named the image files as such when I name them) String file1 = list[0] + ".png"; String file2 = list[1] + ".png"; String file3 = list[2] + ".png"; String file4 = list[3] + ".png"; String file5 = list[4] + ".png"; String file6 = list[5] + ".png"; /*-------------------------------------------------------------------------------// This is where the method's supposed to go to change the image... I've tried pokeLabel = new JLabel(new ImageIcon(file1));, but that yields a NullPointerException. //-----------------------------------------------------------------------------------*/ } public static void main(String[] args) { Shell test = new Shell(); test.setFrame(); test.frameLayout(); test.frame.setVisible(true); } public void actionPerformed(ActionEvent e) { if ("pstart".equals(e.getActionCommand())) { result = PGroup.getSelection().getActionCommand(); if (result.equals("N")) { list = driver.Prandom(); pearlProcessing(); } else System.out.println("Not done yet! ;)"); } } public void menuKeyPressed(MenuKeyEvent e) { System.out.println("pressed"); } public void menuKeyReleased(MenuKeyEvent e) { System.out.println("menuKeyReleased"); } public void menuKeyTyped(MenuKeyEvent e) { System.out.println("menuKeyTyped"); } }

    Read the article

  • Python win32com - Automating Word - How to replace text in a text box?

    - by Greg
    I'm trying to automate word to replace text in a word document using Python. (I'm on word 2003 if that matters and Python 2.4) The first part of my replace method below works on everything except text in text boxes. The text just doesn't get selected. I notice when I go into Word manually and hit ctrl-A all of the text gets selected except for the text box. Here's my code so far: class Word: def __init__(self,visible=0,screenupdating=0): pythoncom.CoInitialize() self.app=gencache.EnsureDispatch(WORD) self.app.Visible = visible self.app.DisplayAlerts = 0 self.app.ScreenUpdating = screenupdating print 'Starting word' def open(self,doc): self.opendoc=os.path.basename(doc) self.app.Documents.Open(FileName=doc) def replace(self,source,target): if target=='':target=' ' alltext=self.app.Documents(self.opendoc).Range(Start=0,End=self.app.Documents(self.opendoc).Characters.Count) #select all alltext.Find.Text = source alltext.Find.Replacement.Text = target alltext.Find.Execute(Replace=1,Forward=True) #Special handling to do replace in text boxes #http://word.tips.net/Pages/T003879_Updating_a_Field_in_a_Text_Box.html for shp in self.app.Documents(self.opendoc).Shapes: if shp.TextFrame.HasText: shp.TextFrame.TextRange.Find.Text = source shp.TextFrame.TextRange.Find.Replacement.Text = target shp.TextFrame.TextRange.Find.Execute(Replace=1,Forward=True) #My Usage word=Word(visible=1,screenupdating=1) word.open(r'C:\Invoice Automation\testTB.doc') word.replace('[PGN]','1') The for shp in self.app .. section is my attempt to hit the text boxes. It seems to find the text box, but it doesn't replace anything.

    Read the article

  • JScrollPane content to image

    - by Sebastian Ikaros Rizzo
    I'm trying to save the main viewport and headers of a JScrollPane (larger than screen) to PNG image files. I created 3 classes extending JPanel (MainTablePanel, MapsHeaderPanel and ItemsHeaderPanel) and set them to the viewports. Each of them has this method: public BufferedImage createImage() { BufferedImage bi = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_ARGB); Graphics g = bi.createGraphics(); paint(g); g.dispose(); return bi; } Each class has also a paint method, which paints the background and then call the super.paint() to paint some label. For example: public void paint(Graphics g){ g.setColor(Color.BLACK); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(new Color(255, 255, 0, 50)); // for loop that paints some vertical yellow lines for(int i=0; i<getWidth(); i+=K.mW){ g.fillRect(i-1, 0, 2, getHeight()); if(i%(K.mW*5)==0){ g.fillRect(i-2, 0, 4, getHeight()); } } // called to pain some rotated JLabels super.paint(g); } From an external JFrame I then tried to save them to PNG file, using this code: BufferedImage tableImg = mainTableP.createImage(); BufferedImage topImg = mapsHeaderP.createImage(); BufferedImage leftImg = itemsHeaderP.createImage(); ImageIO.write(tableImg, "png", new File(s.homeDir+"/table.png")); ImageIO.write(topImg, "png", new File(s.homeDir+"/top.png")); ImageIO.write(leftImg, "png", new File(s.homeDir+"/left.png")); This is a screenshot of the application running: screenshot And this is the header exported: top If I comment the "super.paint(g)" instruction, I obtain a correct image (thus without all JLables, clearly). It seems like the second paint (super.paint(g)) is painted shifted into the BufferedImage and taking elements outside its JPanel. Somebody could explain me this behaviour? Thank you. ========== EDIT for SSCCE ==================================== This should compile. You can execute it as it is, and in c:\ you'll find two images (top.png and left.png) that should be the same as the two headers. Unfortunately, they are not. Background is not painted. Moreover (especially if you look at left.png) you can see that the labels are painted twice and shifted (note, for example, "Left test 21"). import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import javax.swing.*; public class Main { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setLayout(null); frame.setSize(800, 600); JScrollPane scrollP = new JScrollPane(); scrollP.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollP.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); MyPanel top = new MyPanel(); for(int i=0; i<30; i++){ JLabel label = new JLabel("Test "+i); label.setOpaque(false); label.setBounds(50*i, 40, 50, 20); label.setForeground(Color.GREEN); top.add(label); } top.setLayout(null); top.setOpaque(false); top.setPreferredSize(new Dimension(50*30, 200)); top.validate(); MyPanel left = new MyPanel(); for(int i=0; i<30; i++){ JLabel label = new JLabel("Left test "+i); label.setBounds(0, 50*i, 100, 20); label.setForeground(Color.RED); left.add(label); } left.setLayout(null); left.setOpaque(false); left.setPreferredSize(new Dimension(200, 50*30)); MyPanel center = new MyPanel(); center.setLayout(null); center.setOpaque(false); center.setPreferredSize(new Dimension(50*30, 50*30)); scrollP.setViewportView(center); scrollP.setColumnHeaderView(top); scrollP.setRowHeaderView(left); scrollP.setBounds(0, 50, 750, 500); frame.add(scrollP); frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); frame.setVisible(true); try{ BufferedImage topImg = top.createImage(); ImageIO.write(topImg, "png", new File("C:/top.png")); BufferedImage leftImg = left.createImage(); ImageIO.write(leftImg, "png", new File("C:/left.png")); }catch(Exception e){ e.printStackTrace(); } } } class MyPanel extends JPanel{ public void paint(Graphics g){ g.setColor(Color.BLACK); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(new Color(255, 255, 0, 50)); for(int i=0; i<getWidth(); i+=50){ g.fillRect(i-1, 0, 2, getHeight()); } super.paint(g); // COMMENT this line to obtain background images } public BufferedImage createImage() { BufferedImage bi = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_ARGB); Graphics g = bi.createGraphics(); paint(g); g.dispose(); return bi; } }

    Read the article

  • Exporting WPF DataGrid to a text file in a nice looking format. Text file must be easy to read.

    - by Andrew
    Hi, Is there a simple way to export a WPF DataGrid to a text file and a .csv file? I've done some searching and can't see that there is a simple DataGrid method to do so. I have got something working (barely) by making use of the ItemsSource of the DataGrid. In my case, this is an array of structs. I do something with StreamWriters and StringBuilders (details available) and basically have: StringBuilder destination = new StringBuilder(); destination.Append(row.CreationDate); destination.Append(seperator); // seperator is '\t' or ',' for csv file destination.Append(row.ProcId); destination.Append(seperator); destination.Append(row.PartNumber); destination.Append(seperator); I do this for each struct in the array (in a loop). This works fine. The problem is that it's not easy to read the text file. The data can be of different lengths within the same column. I'd like to see something like: 2007-03-03 234238423823 823829923 2007-03-03 66 99 And of course, I get something like: 2007-03-03 234238423823 823829923 2007-03-03 66 99 It's not surprising giving that I'm using Tab delimiters, but I hope to do better. It certainly is easy to read in the DataGrid! I could of course have some logic to pad short values with spaces, but that seems quite messy. I thought there might be a better way. I also have a feeling that this is a common problem and one that has probably been solved before (hopefully within the .NET classes themselves). Thanks.

    Read the article

  • Using Rich Text Editor (WYSIWYG) in ASP.NET MVC

    - by imran_ku07
       Introduction:          In ASP.NET MVC forum I found some question regarding a sample HTML Rich Text Box Editor(also known as wysiwyg).So i decided to create a sample ASP.NET MVC web application which will use a Rich Text Box Editor. There are are lot of Html Editors are available, but for creating a sample application, i decided to use cross-browser WYSIWYG editor from openwebware. In this article I will discuss what changes needed to work this editor with ASP.NET MVC. Also I had attached the sample application for download at http://www.speedfile.org/155076. Also note that I will only show the important features, not discuss every feature in detail.   Description:          So Let's start create a sample ASP.NET MVC application. You need to add the following script files,         jquery-1.3.2.min.js        jquery_form.js        wysiwyg.js        wysiwyg-settings.js        wysiwyg-popup.js          Just put these files inside Scripts folder. Also put wysiwyg.css in your Content Folder and add the following folders in your project        addons        popups          Also create a empty folder Uploads to store the uploaded images. Next open wysiwyg.js and set your configuration                  // Images Directory        this.ImagesDir = "/addons/imagelibrary/images/";                // Popups Directory        this.PopupsDir = "/popups/";                // CSS Directory File        this.CSSFile = "/Content/wysiwyg.css";              Next create a simple View TextEditor.aspx inside View / Home Folder and add the folllowing HTML.        <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">        <html >            <head runat="server">                <title>TextEditor</title>                <script src="../../Scripts/wysiwyg.js" type="text/javascript"></script>                <script src="../../Scripts/wysiwyg-settings.js" type="text/javascript"></script>                <script type="text/javascript">                            WYSIWYG.attach('text', full);                            </script>            </head>            <body>                <% using (Html.BeginForm()){ %>                    <textarea id="text" name="test2" style="width:850px;height:200px;">                    </textarea>                    <input type="submit" value="submit" />                <%} %>            </body>        </html>                  Here i have just added a text area control and a submit button inside a form. Note the id of text area and WYSIWYG.attach function's first parameter is same and next to watch is the HomeController.cs        using System;        using System.Collections.Generic;        using System.Linq;        using System.Web;        using System.Web.Mvc;        using System.IO;        namespace HtmlTextEditor.Controllers        {            [HandleError]            public class HomeController : Controller            {                public ActionResult Index()                {                    ViewData["Message"] = "Welcome to ASP.NET MVC!";                    return View();                }                    public ActionResult About()                {                                return View();                }                        public ActionResult TextEditor()                {                    return View();                }                [AcceptVerbs(HttpVerbs.Post)]                [ValidateInput(false)]                public ActionResult TextEditor(string test2)                {                    Session["html"] = test2;                            return RedirectToAction("Index");                }                        public ActionResult UploadImage()                {                    if (Request.Files[0].FileName != "")                    {                        Request.Files[0].SaveAs(Server.MapPath("~/Uploads/" + Path.GetFileName(Request.Files[0].FileName)));                        return Content(Url.Content("~/Uploads/" + Path.GetFileName(Request.Files[0].FileName)));                    }                    return Content("a");                }            }        }          So simple code, just save the posted Html into Session. Here the parameter of TextArea action is test2 which is same as textarea control name of TextArea.aspx View. Also note ValidateInputAttribute is false, so it's up to you to defends against XSS. Also there is an Action method which simply saves the file inside Upload Folder.          I am uploading the file using Jquery Form Plugin. Here is the code which is found in insert_image.html inside addons folder,        function ChangeImage() {            var myform=document.getElementById("formUpload");                    $(myform).ajaxSubmit({success: function(responseText){                insertImage(responseText);                        window.close();                }            });        }          and here is the Index View which simply renders the html of Editor which was saved in Session        <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>        <asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">            Home Page        </asp:Content>        <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">            <h2><%= Html.Encode(ViewData["Message"]) %></h2>            <p>                To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.            </p>            <%if (Session["html"] != null){                  Response.Write(Session["html"].ToString());            } %>                    </asp:Content>   Summary:          Hopefully you will enjoy this article. Just download the code and see the effect. From security point, you must handle the XSS attack your self. I had uploaded the sample application in http://www.speedfile.org/155076

    Read the article

  • Importing data from text file to specific columns using BULK INSERT

    - by Dinesh Asanka
    Bulk insert is much faster than using other techniques such as  SSIS. However, when you are using bulk insert you can’t insert to specific columns. If, for example, there are five columns in a table you should have five values for each record in the text file you are importing from. This is an issue when you are expecting default values to be inserted into tables. Let us say you have table as below: In this table, you are expecting ID, Status and CreatedDate to be updated automatically, so your text file may only have   FirstName  LastName  values as below: Dinesh,Asanka Saman,Liyanage Ruwan,Silva Susantha,Bathige Jude,Peires Sanjeewa,Jayawickrama If you use bulk insert to this table like follows, You will be returned an error: Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 1 (ID). To avoid this you will need to create a view with the columns you are expecting to fill and use bulk insert against it. If you check the table now, you will see table with values in the text file and the default values.

    Read the article

  • Switch Gmail Icons Back to Text Labels

    - by Jason Fitzpatrick
    If Gmail’s icon-based buttons annoy you, it’s now possible to switch them back to the old text labels with a simple settings toggle. At MakeUseOf they highlight the new option in Gmail and how you can switch back to the old button layout: So how do you make that happen? All you have to do is click on the cog button, choose “Settings”, and go to the the General tab. Scroll down to find the “Button labels” setting, and change it from icons to text. I know what I’ll be doing shortly; text-based button labels here I come. [via MakeUseOf] Make Your Own Windows 8 Start Button with Zero Memory Usage Reader Request: How To Repair Blurry Photos HTG Explains: What Can You Find in an Email Header?

    Read the article

  • Text selection CTRL+SHIFT+Cursor Keys?

    - by mark
    Hi, I'm used to this Windows behavior that using CTRL+SHIFT+Cursor Keys I can select text word-wise. CTRL+Cursor Keys jumps word-wise and I use that a lot in combination with SHIFT to select text. This seems to be a "Windows thing" because it just works in all application. Now turning to Ubuntu 10.04, it doesn't work. CTRL+SHIFT+Cursor Keys just behaves like CTRL+Cursor Keys, i.e. I jump between the words but I can't select them that way. Another gotcha: I use CTRL+Cursor Keys to move fast between words, press down SHIFT, release CTRL and move the Cursor Keys to select text char by char and it doesn't work either. I need to release both keys complete. Is there a way to enable this?

    Read the article

  • what's wrong with this Lua code (creating text inside listener in Corona)

    - by Greg
    If you double/triple click on the myObject here the text does NOT disappear. Why is this not working when there are multiple events being fired? That is, are there actually multiple "text" objects, with some existing but no longer having a reference to them held by the local "myText" variable? Do I have to manually removeSelf() on the local "myText" field before assigning it another "display.newText(...)"? display.setStatusBar( display.HiddenStatusBar ) local myText local function hideMyText(event) print ("hideMyText") myText.isVisible = false end local function showTextListener(event) if event.phase == "began" then print("showTextListener") myText = display.newText("Hello World!", 0, 0, native.systemFont, 30) timer.performWithDelay(1000, hideMyText, 1 ) end end -- Display object to press to show text local myObject = display.newImage( "inventory_button.png", display.contentWidth/2, display.contentHeight/2) myObject:addEventListener("touch", showTextListener) Question 2 - Also why is it the case that if I add a line BEFORE "myText = ..." of: a) "if myText then myText:removeSelf() end" = THIS FIXES THINGS, whereas b) "if myText then myText=nil end" = DOES NOT FIX THINGS Interested in hearing how Lua works here re the answer...

    Read the article

  • Simple alternating text in Visual Basic 2008

    - by Josh Grate
    I have a simple completed program, but i would like to add one more feature to it but I'm not sure how. I have it set up to send a message automatically every 7 seconds when a text field is selected, repeating the message of course. What I would like for it to do is alternate between two separate messages, instead just repeating the one. I would like the new program to post at an interval of 12 seconds. Can you help me? Here is my coding. Public Class Form1 Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick SendKeys.Send(TextBox1.Text) SendKeys.Send("{ENTER}") End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Timer1.Enabled = True Timer1.Interval = (TextBox2.Text) End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Timer1.Enabled = False End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Timer1.Enabled = False End Sub End Class

    Read the article

  • Processing Text and Binary (Blob, ArrayBuffer, ArrayBufferView) Payload in WebSocket - (TOTD #185)

    - by arungupta
    The WebSocket API defines different send(xxx) methods that can be used to send text and binary data. This Tip Of The Day (TOTD) will show how to send and receive text and binary data using WebSocket. TOTD #183 explains how to get started with a WebSocket endpoint using GlassFish 4. A simple endpoint from that blog looks like: @WebSocketEndpoint("/endpoint") public class MyEndpoint { public void receiveTextMessage(String message) { . . . } } A message with the first parameter of the type String is invoked when a text payload is received. The payload of the incoming WebSocket frame is mapped to this first parameter. An optional second parameter, Session, can be specified to map to the "other end" of this conversation. For example: public void receiveTextMessage(String message, Session session) {     . . . } The return type is void and that means no response is returned to the client that invoked this endpoint. A response may be returned to the client in two different ways. First, set the return type to the expected type, such as: public String receiveTextMessage(String message) { String response = . . . . . . return response; } In this case a text payload is returned back to the invoking endpoint. The second way to send a response back is to use the mapped session to send response using one of the sendXXX methods in Session, when and if needed. public void receiveTextMessage(String message, Session session) {     . . .     RemoteEndpoint remote = session.getRemote();     remote.sendString(...);     . . .     remote.sendString(...);    . . .    remote.sendString(...); } This shows how duplex and asynchronous communication between the two endpoints can be achieved. This can be used to define different message exchange patterns between the client and server. The WebSocket client can send the message as: websocket.send(myTextField.value); where myTextField is a text field in the web page. Binary payload in the incoming WebSocket frame can be received if ByteBuffer is used as the first parameter of the method signature. The endpoint method signature in that case would look like: public void receiveBinaryMessage(ByteBuffer message) {     . . . } From the client side, the binary data can be sent using Blob, ArrayBuffer, and ArrayBufferView. Blob is a just raw data and the actual interpretation is left to the application. ArrayBuffer and ArrayBufferView are defined in the TypedArray specification and are designed to send binary data using WebSocket. In short, ArrayBuffer is a fixed-length binary buffer with no format and no mechanism for accessing its contents. These buffers are manipulated using one of the views defined by one of the subclasses of ArrayBufferView listed below: Int8Array (signed 8-bit integer or char) Uint8Array (unsigned 8-bit integer or unsigned char) Int16Array (signed 16-bit integer or short) Uint16Array (unsigned 16-bit integer or unsigned short) Int32Array (signed 32-bit integer or int) Uint32Array (unsigned 16-bit integer or unsigned int) Float32Array (signed 32-bit float or float) Float64Array (signed 64-bit float or double) WebSocket can send binary data using ArrayBuffer with a view defined by a subclass of ArrayBufferView or a subclass of ArrayBufferView itself. The WebSocket client can send the message using Blob as: blob = new Blob([myField2.value]);websocket.send(blob); where myField2 is a text field in the web page. The WebSocket client can send the message using ArrayBuffer as: var buffer = new ArrayBuffer(10);var bytes = new Uint8Array(buffer);for (var i=0; i<bytes.length; i++) { bytes[i] = i;}websocket.send(buffer); A concrete implementation of receiving the binary message may look like: @WebSocketMessagepublic void echoBinary(ByteBuffer data, Session session) throws IOException {    System.out.println("echoBinary: " + data);    for (byte b : data.array()) {        System.out.print(b);    }    session.getRemote().sendBytes(data);} This method is just printing the binary data for verification but you may actually be storing it in a database or converting to an image or something more meaningful. Be aware of TYRUS-51 if you are trying to send binary data from server to client using method return type. Here are some references for you: JSR 356: Java API for WebSocket - Specification (Early Draft) and Implementation (already integrated in GlassFish 4 promoted builds) TOTD #183 - Getting Started with WebSocket in GlassFish TOTD #184 - Logging WebSocket Frames using Chrome Developer Tools, Net-internals and Wireshark Subsequent blogs will discuss the following topics (not necessary in that order) ... Error handling Custom payloads using encoder/decoder Interface-driven WebSocket endpoint Java client API Client and Server configuration Security Subprotocols Extensions Other topics from the API

    Read the article

  • Unit testing a text index

    - by jplot
    Consider a text index such as a suffix tree or a suffix array supporting Count queries (number of occurrences of a pattern) and Locate queries (the positions of all the occurrences of a pattern) over a given text. How would you go about unit testing such a class ? What I have in mind is to generate a big random string then extract a random substring from this big string and compare the results of both queries with naive implementations (such as string::find). Another idea I have is to find the most frequent substring of length l appearing in the original string (using perhaps a naive method) and use these substrings for testing the index. This isn't the best way, so what would be a good design of the unit tests for a text index ? In case it matters, this is in C++ using google test.

    Read the article

  • Recognizing text fields according to their label value

    - by Pierpaolo Bagnasco
    I have an application who has text fields (not select, not checkbox or other types) where an user can enter some value, like this: ISBN and E-Mail are the label of each input. Now I have to automatically test these inputs according to their label. The question is: how to recognize that, for example, the first input requires an ISBN code? I programmed something like this: turn the label value to lowercase check if the label value contains isbn if so set the field value to a random ISBN code (i.e.: 1234567890), else set it to a random value (default) For the email field: turn the label value to lowercase check if the label value contains e-mail or email or mail if so set the field value to a random email (i.e.: [email protected]), else set it to a random value (default) And so on for each text field I encounter. Is that reliable? How can I improve the "recognizing part"? I know only the label value and the field value (what is already written in the field by default) for each text input.

    Read the article

  • Size Mismatch Between Swing Fonts and Printable Fonts in Java

    - by Caleb Rackliffe
    Hi All, I've got a panel displaying a JTextPane backed by a StyledDocument. When I print a string of text in, say Arial 16, the text it prints is of a different size than the Arial 16 Word prints. Is there some sort of flaw in the translation of Swing fonts to Windows system fonts or something of the sort that makes it difficult (or impossible) to print accurately? I can achieve an approximation by scaling down the size of my font before printing, but this never quite gets me the results I would like, as it's not possible in all cases to reproduce things like equivalent numbers of words on a line, etc. Has anybody run into this before?

    Read the article

  • iphone sdk - problem pasting into current text location

    - by norskben
    Hi guys I'm trying to paste text right into where the cursor currently is. I have been trying to do what it says at: - http://dev.ragfield.com/2009/09/insert-text-at-current-cursor-location.html The main deal is that I can't just go textbox1.text (etc) because the textfield is in the middle of a custom cell. I want to just have some text added to where the cursor is (when I press a custom key on a keyboard). -I just want to paste a decimal into the textbox... The error I get is: 2010-05-15 22:37:20.797 PageControl[37962:207] * -[MyDetailController paste:]: unrecognized selector sent to instance 0x1973d10 2010-05-15 22:37:20.797 PageControl[37962:207] Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '** -[MyDetailController paste:]: unrecognized selector sent to instance 0x1973d10' Note: I have access to the textfield tag (if that helps?) I'm a little past the beginner stage in objective-c, but still not great. My code is currently below, and at https://gist.github.com/d634329e5ddf52945989 Thanks all. MyDetailController.h @interface MyDetailController : UITableViewController <UITextFieldDelegate,UINavigationControllerDelegate> { //...(lots in here) } @end @interface UIResponder(UIResponderInsertTextAdditions) - (void) insertText: (NSString*) text; @end MyDetailController.m @implementation MyDetailController //.... (lots in here) - (void)addDecimal:(NSNotification *)notification { // Apend the Decimal to the TextField. //savedAmount.text = [savedAmount.text stringByAppendingString:@"."]; NSLog(@"Decimal Pressed"); NSLog(@"tagClicked: %d",tagClicked); switch (tagClicked) { case 7: //savedAmount.text = [savedAmount.text stringByAppendingString:@"."]; break; case 8: //goalAmount.text = [goalAmount.text stringByAppendingString:@"."]; break; case 9: //incrementAmount.text = [incrementAmount.text stringByAppendingString:@"."]; break; case 10: //incrementAmount.text = [incrementAmount.text stringByAppendingString:@"."]; break; } [self insertText:@"."]; } -(void)textFieldDidBeginEditing:(UITextField *)textfield{ //UITextField *theCell = (UITextField *)sender; tagClicked = textfield.tag; NSLog(@"textfield changed. tagClicked: %d",tagClicked); } @end @implementation UIResponder(UIResponderInsertTextAdditions) - (void) insertText: (NSString*) text { // Get a refererence to the system pasteboard because that's // the only one @selector(paste:) will use. UIPasteboard* generalPasteboard = [UIPasteboard generalPasteboard]; // Save a copy of the system pasteboard's items // so we can restore them later. NSArray* items = [generalPasteboard.items copy]; // Set the contents of the system pasteboard // to the text we wish to insert. generalPasteboard.string = text; // Tell this responder to paste the contents of the // system pasteboard at the current cursor location. [self paste: self]; // Restore the system pasteboard to its original items. generalPasteboard.items = items; // Free the items array we copied earlier. [items release]; } @end

    Read the article

  • Occasional InterruptedException when quitting a Swing application

    - by Joonas Pulakka
    I recently updated my computer to a more powerful one, with a quad-core hyperthreading processor (i7), thus plenty of real concurrency available. Now I'm occasionally getting the following error when quitting (System.exit(0)) an application (with a Swing GUI) that I'm developing: Exception while removing reference: java.lang.InterruptedException java.lang.InterruptedException at java.lang.Object.wait(Native Method) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134) at sun.java2d.Disposer.run(Disposer.java:125) at java.lang.Thread.run(Thread.java:619) Well, given that it started to happen with a more concurrency-capable hardware, and it has to do with threads, and it happens occasionally, it's obviously some kind of timing thing. But the problem is that the stack trace is so short. All I have is the listing above. It doesn't include my own code at all, so it's somewhat hard to guess where the bug is. Has anyone experienced something like this before? Any ideas how to start solving it?

    Read the article

  • Java/Swing offscreen rendering (Cobra HTMLPanel -> BufferedImage) Problem: Component doesn't finish

    - by Alterscape
    I'm trying to render the contents of a the Java/Swing Cobra HTML renderer to an offscreen BufferedImage, for use elsewhere in my app: slideViewPanel.setDocument(document, rendererContext); BufferedImage test = new BufferedImage(300,300,BufferedImage.TYPE_INT_RGB); Graphics g = test.getGraphics(); slideViewPanel.paint(g); The resulting image in g shows a partially rendered page -- sometimes the contents of the HTMLFrame before the new document was set; sometimes a half-rendered version of the new document. I gather this is because Cobra's setDocument method just schedules the document for re-rendering, but I'm stepping through in the debugger and I don't see a second thread to do re-rendering. Anyone have any insight into what might be happening here?

    Read the article

  • netbeans + hibernate for java swing application

    - by blow
    Hi all, im developing a java swing app and i would use hibernate for persistance. Im totally new in jpa, hibernate and ORM in general. Im follow this tutorial, its easy but the problem is the java class that descrive a table in db are made from the table with reverse enginering. I want do the opposite process: i want make db table from the java class. The question is, how can i do this with netbeans? There are some tutorial?

    Read the article

  • calling database driver in java app [basically a swing app]

    - by user993250
    I have made a java application that allows a user to choose from certain standards and then allows him to customize those standards according to his needs. Now, the customization [via a swing application] that has been made needs to be persistent. For this we use a database [mysql/access] and hook it to the application so that with each customization made, a table [if non-existent] is created [thus making it runtime and we can not pre-determine the table names or the keys of table etc] and an appropriate entry in the table is made. I have written the driver for this connection. How do I call it in the java application and what approach should I take? I would much appreciate that if somebody can refer me some example that not only shows a sample connection being made via driver but its appropriate calls to the database as well so that i can use it as a guide.

    Read the article

  • Exception for java Swing application?

    - by Rich Fluckiger
    For some reason this is locking up the java application. Did I handle the exception correctly? private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) { double amount, interest,rateCalc, a, b, c, payment; int years, months; while (true){ try{ amount = Double.valueOf(loanAmount.getText()); interest = Double.valueOf(interestRate.getText()); years = Integer.valueOf(loanYears.getText()); rateCalc = (interest/12); months = (years*12); a = Math.pow((1+rateCalc),months); b = (a*rateCalc); c = (a-1); payment = (amount *(b/c)); monthlyPayment.setText("Mortgage Payment $ = " + payment); } catch (NumberFormatException nfe){ javax.swing.JOptionPane.showMessageDialog(null, "Please enter numbers and not letters"); return; } } } monthlyPayment returns to the java app.

    Read the article

  • Java swing center JDialog over parent

    - by Chris Drappier
    I have a Java swing application with a button that produces a popup window when a certain action is performed. I'd like to align the center point of the popup window with the center point of the parent window when it is rendered. How can I calculate the x,y coordinates to plug into setLocation() for the popup window? EDIT: just to clarify. I do not want the behavior of setLocationRelativeTo() because that sets the top-left pixel of the popup over the center pixel of the parent frame. I want to set the center pixel of the popup over the center pixel of the parent frame. Also, I'm not interested in whether or not a popup window is good practice. I'm past that now. thanks

    Read the article

  • How can I filter a JTable?

    - by Jonas
    I would like to filter a JTable, but I don't understand how I can do it. I have read How to Use Tables - Sorting and Filtering and I have tried with the code below, but with that filter, no rows at all is shown in my table. And I don't understand what column it is filtered on. private void myFilter() { RowFilter<MyModel, Object> rf = null; try { rf = RowFilter.regexFilter(filterFld.getText(), 0); } catch (java.util.regex.PatternSyntaxException e) { return; } sorter.setRowFilter(rf); } MyModel has three columns, the first two are strings and the last column is of type Integer. How can I apply the filter above, consider the text in filterFld.getText() and only filter the rows where the text is matched on the second column? I would like to show all rows that starts with the text specified by filterFld.getText(). I.e. if the text is APP then the JTable should contain the rows where the second column starts with APPLE, APPLICATION but not the rows where the second column is CAR, ORANGE. I have also tried with this filter: RowFilter<MyModel, Integer> itemFilter = new RowFilter<MyModel, Integer>(){ public boolean include(Entry<? extends MyModel, ? extends Integer> entry){ MyModel model = entry.getModel(); MyItem item = model.getRecord(entry.getIdentifier()); if (item.getSecondColumn().startsWith("APP")) { return true; } else { return false; } } }; How can I write a filter that is filtering the JTable on the second column, specified by my textfield?

    Read the article

  • How to force an HTML JLabel in a JTree to resize when the font changes

    - by Mike
    I'm updating a Java Swing application to support the user switching the app's font from normal size to a larger size (so the user can switch between the two sizes at runtime). One problem I'm having is with a JTree that uses HTML for the tree nodes to underline the text in some nodes (the HTML is just embedded in the JLabel of each tree node). One extra thing to know about the nodes is that they're a custom component, adding a JCheckBox in front of each JLabel. The problem is that once the JTree is visible, increasing the font size causes the nodes (containing underlined text) to not resize. The HTML for those nodes seems to prevent the node from becoming wider, so when the font changes, the text becomes truncated. I think my options are to either: 1) use another approach to make the text underlined, since removing the HTML from the JLabel causes it to resize properly when the font size changes, or 2) keep the HTML formatting and somehow force the JTree/JLabels to resize when the font size is updated (possibly by firing a property change event?). The code already calls SwingUtilities.updateComponentTreeUI() on the parent JFrame when the font size gets updated. Any help would be greatly appreciated. Thanks in advance! -Mike

    Read the article

  • java 7 upgrade and hibernate annotation processor error

    - by Bill Turner
    I am getting the following warning, which seems to be triggering a subsequent warning and an error. I have been googling like mad, though have not found anything that makes it clear what it is I should do to resolve this. This issue occurs when I execute an Ant build. I am trying to migrate our project to Java 7. I have changed all the source='1.6' and target="1.6" to 1.7. I did find this related article: Forward compatible Java 6 annotation processor and SupportedSourceVersion It seems to indicate that I should build the Hibernate annotation processor jar myself, compiling it with with 1.7. It does not seem I should be required to do so. The latest version of the class in question (in hibernate-validator-annotation-processor-5.0.1.Final.jar) has been compiled with 1.6. Since the code in said class refers to SourceVersion.latestSupported(), and the 1.6 of that returns only RELEASE_6, there does not seem to be a generally available solution. Here is the warning: [javac] warning: Supported source version 'RELEASE_6' from annotation processor 'org.hibernate.validator.ap.ConstraintValidationProcessor' less than -source '1.7' And, here are the subsequent warnings/error. [javac] warning: No processor claimed any of these annotations: javax.persistence.PersistenceContext,javax.persistence.Column,org.codehaus.jackson.annotate.JsonIgnore,javax.persistence.Id,org.springframework.context.annotation.DependsOn,com.trgr.cobalt.infrastructure.datasource.Bucketed,org.codehaus.jackson.map.annotate.JsonDeserialize,javax.persistence.DiscriminatorColumn,com.trgr.cobalt.dataroom.authorization.secure.Secured,org.hibernate.annotations.GenericGenerator,javax.annotation.Resource,com.trgr.cobalt.infrastructure.spring.domain.DomainField,org.codehaus.jackson.annotate.JsonAutoDetect,javax.persistence.DiscriminatorValue,com.trgr.cobalt.dataroom.datasource.config.core.CoreTransactionMandatory,org.springframework.stereotype.Repository,javax.persistence.GeneratedValue,com.trgr.cobalt.dataroom.datasource.config.core.CoreTransactional,org.hibernate.annotations.Cascade,javax.persistence.Table,javax.persistence.Enumerated,org.hibernate.annotations.FilterDef,javax.persistence.OneToOne,com.trgr.cobalt.dataroom.datasource.config.core.CoreEntity,org.springframework.transaction.annotation.Transactional,com.trgr.cobalt.infrastructure.util.enums.EnumConversion,org.springframework.context.annotation.Configuration,com.trgr.cobalt.infrastructure.spring.domain.UpdatedFields,com.trgr.cobalt.infrastructure.spring.documentation.SampleValue,org.springframework.context.annotation.Bean,org.codehaus.jackson.annotate.JsonProperty,javax.persistence.Basic,org.codehaus.jackson.map.annotate.JsonSerialize,com.trgr.cobalt.infrastructure.spring.validation.Required,com.trgr.cobalt.dataroom.datasource.config.core.CoreTransactionNever,org.springframework.context.annotation.Profile,com.trgr.cobalt.infrastructure.spring.stereotype.Persistor,javax.persistence.Transient,com.trgr.cobalt.infrastructure.spring.validation.NotNull,javax.validation.constraints.Size,javax.persistence.Entity,javax.persistence.PrimaryKeyJoinColumn,org.hibernate.annotations.BatchSize,org.springframework.stereotype.Service,org.springframework.beans.factory.annotation.Value,javax.persistence.Inheritance [javac] error: warnings found and -Werror specified TIA!

    Read the article

  • JDesktop Integration Components binary has stopped working

    - by rot
    I googled it but not able to find the solution. I am working on swing APIs org.jdesktop.jdic.browser.*. When I am clicking on link displayed in java browser created using bove APIs, it gives windows error pop-up message: JDesktop Integration Components binary has stopped working JDK version I am using is: 1.6.0_31-b05. Please let me know work around or show to solve issue. Thanks in advance.

    Read the article

< Previous Page | 52 53 54 55 56 57 58 59 60 61 62 63  | Next Page >