Search Results

Search found 83 results on 4 pages for 'jtextarea'.

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

  • Changing JTextArea to JScrollPane Causes it to not be visible

    - by user1806716
    I am having an issue with JScrollPanes and JTextArea objects and getting them to work together. If I just add a JTextArea to my JPanel, it works fine and shows up where I tell it to. However, if I change the contentPane.add(textArea) to contentPane.add(new JScrollPane(textArea)), the textArea is not longer visible and there is no sign of the textarea either. Here is my code: public docToolGUI() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 611, 487); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); textField = new JTextField(); textField.setBounds(253, 323, 86, 20); contentPane.add(textField); textField.setColumns(10); JLabel lblEnterRootDirectory = new JLabel("Enter Root Directory"); lblEnterRootDirectory.setBounds(253, 293, 127, 20); contentPane.add(lblEnterRootDirectory); JButton btnGo = new JButton("Go"); btnGo.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { new ToolWorker().execute(); } }); btnGo.setBounds(253, 361, 89, 23); contentPane.add(btnGo); textArea = new JTextArea(); textArea.setWrapStyleWord(true); textArea.setEditable(false); textArea.setBounds(25, 11, 560, 276); contentPane.add(new JScrollPane(textArea)); }

    Read the article

  • Maintaing JTextArea scroll position

    - by Sami
    I have a JScrollPane with a JTextArea set as its view port. I update the (multi line) text shown on the JTextArea continously about once a second. Each time the text updates, JScrollPane goes all the way to the bottom of the text. Instead, I'd like to figure out the line number that is currently shown as the first line in the original text, and have that line be the first line shown when the text has been updated (or if the new text doesn't have that many lines, then scroll all the way to the bottom). My first attempt of doing this was to get the current caret position, figure the line based on that, and then set the text area to show that line: int currentPos = textArea.getCaretPosition(); int currentLine = 0; try { for(int i = 0; i < textArea.getLineCount(); i++) { if((currentPos >= textArea.getLineStartOffset(i)) && (currentPos < gameStateTextArea.getLineEndOffset(i))) { currentLine = i; break; } } } catch(Exception e) { } textArea.setText(text); int newLine = Math.min(currentLine, textArea.getLineCount()); int newOffset = 0; try { newOffset = textArea.getLineStartOffset(newLine); } catch(Exception e) { } textArea.setCaretPosition(newOffset); This was almost acceptable for my needs, but requires the user to click inside the text area to change the caret position, so that the scrolling will maintain state (which isn't nice). How would I do this using the (vertical) scroll position instead ?

    Read the article

  • Can't get my Jscrollpane working in my Jtextarea

    - by Bobski
    I've looked around quite a lot on google and followed several examples however I can't seem to get my JScrollPane working on a textarea in a JPanel. import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.lang.*; import javax.swing.event.*; class main { public static void main(String Args[]) { frame f1 = new frame(); } } class frame extends JFrame { JButton B = new JButton("B"); JButton button = new JButton("A"); JTextArea E = new JTextArea("some lines", 10, 20); JScrollPane scrollBar = new JScrollPane(E); JPanel grid = new JPanel (); frame() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(500,800); setTitle("Mobile Phone App"); setLocationRelativeTo(null); E.setLineWrap(true); E.setEditable(false); grid.add(button); button.addActionListener(new action()); grid.add(B); B.addActionListener(new action()); //grid.add(E); grid.getContentPane().add(scrollBar); add(grid); setVisible(true); } class action implements ActionListener { public void actionPerformed(ActionEvent e) { String V = E.getText(); if(e.getSource() == button) { E.setText(V + "A is pressed"); } if(e.getSource() == B) { E.setText(V + "B is pressed"); } } } } Would be great if someone can see where I am going wrong. I added JscrollPane in which I added the text area "e" in it.

    Read the article

  • Java InputReader. Detect if file being read is binary?

    - by Trizicus
    I had posted a question in regards to this code. I found that JTextArea does not support the binary type data that is loaded. So my new question is how can I go about detecting the 'bad' file and canceling the file I/O and telling the user that they need to select a new file? class Open extends SwingWorker<Void, String> { File file; JTextArea jta; Open(File file, JTextArea jta) { this.file = file; this.jta = jta; } @Override protected Void doInBackground() throws Exception { BufferedReader br = null; try { br = new BufferedReader(new FileReader(file)); String line = br.readLine(); while(line != null) { publish(line); line = br.readLine(); } } finally { try { br.close(); } catch (IOException e) { } } return null; } @Override protected void process(List<String> chunks) { for(String s : chunks) jta.append(s + "\n"); } }

    Read the article

  • How To Keep Size Of JTextArea constant?

    - by Supereme
    Hi! I'm using an object of JTextArea in my application which deals with sending sms. I've used a DocumentFilter so as to allow only 160 characters to be typed in the textarea but now, I want the size of the textarea to be constant. it goes on increasing if I keep writing on the same line without pressing 'enter' key or even when I keep on pressing only 'enter' key. I tried once using 'scrollbar' too but the problem remains same. Suggest me something over this.

    Read the article

  • GroupLayout: JScrollPane in TextArea is not working

    - by Dozent
    i'm new in java and recently started to develop an simple application. For the moment i have a problem with JScrollPanne, it's not able to scroll down (or up) when the text in textarea more than size of area. I have looked to some solutions, but all of them were for FlowLayot (GridLayout and BoxLayout), but not for GroupLayout. Here is the code: JPanel conent_p = new JPanel(); conent_p.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null)); JLabel lblItemName = new JLabel("Item name:"); itemField = new JTextField(); itemField.setColumns(10); JLabel lblMxPrice = new JLabel("Max price:"); mpriceField = new JTextField(); mpriceField.setColumns(10); JLabel lblQuantity = new JLabel("Quantity:"); quanField = new JTextField(); quanField.setColumns(10); JLabel lblDelivery = new JLabel("Delivery:"); delivField = new JTextField(); delivField.setColumns(10); JLabel lblLogcat = new JLabel("LogCat:"); final JTextArea txtConsole = new JTextArea(); txtConsole.setEditable(false); txtConsole.setLineWrap(true); txtConsole.setWrapStyleWord(true); sbrText = new JScrollPane(txtConsole); sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); // Now create a new TextAreaOutputStream to write to our JTextArea control and wrap a // PrintStream around it to support the println/printf methods. PrintStream out = new PrintStream(new TextAreaOutputStream(txtConsole)); // redirect standard output stream to the TextAreaOutputStream System.setOut(out); // redirect standard error stream to the TextAreaOutputStream System.setErr(out); GroupLayout gl_conent_p = new GroupLayout(conent_p); gl_conent_p.setHorizontalGroup( gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createSequentialGroup() .addContainerGap() .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING) .addComponent(lblMxPrice, Alignment.TRAILING) .addComponent(lblItemName, Alignment.TRAILING) .addComponent(lblLogcat, Alignment.TRAILING)) .addGap(18) .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createSequentialGroup() .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING, false) .addComponent(itemField, GroupLayout.PREFERRED_SIZE, 365, GroupLayout.PREFERRED_SIZE) .addGroup(gl_conent_p.createSequentialGroup() .addComponent(mpriceField, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(lblQuantity) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(quanField, 0, 0, Short.MAX_VALUE) .addGap(18) .addComponent(lblDelivery) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(delivField, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED))) .addGap(100)) .addGroup(gl_conent_p.createSequentialGroup() .addComponent(txtConsole, GroupLayout.PREFERRED_SIZE, 345, GroupLayout.PREFERRED_SIZE) .addComponent(sbrText) .addContainerGap()))) ); gl_conent_p.setVerticalGroup( gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createSequentialGroup() .addContainerGap() .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblItemName) .addComponent(itemField, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)) .addGap(20) .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblDelivery) .addComponent(delivField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblMxPrice) .addComponent(mpriceField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblQuantity) .addComponent(quanField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) .addGap(55) .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblLogcat) .addComponent(txtConsole, GroupLayout.PREFERRED_SIZE, 200, GroupLayout.PREFERRED_SIZE) .addComponent(sbrText)) .addContainerGap()) ); conent_p.setLayout(gl_conent_p); getContentPane().add(conent_p, BorderLayout.NORTH); JButton btnBuy = new JButton("Buy"); btnBuy.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ev) { try { String title = itemField.getText().trim(); String mprice = mpriceField.getText().trim(); String quantity = quanField.getText().trim(); String deliver = delivField.getText().trim(); Item_CONCEPT item = new Item_CONCEPT(); item.setName(title); item.setDelivery(Integer.parseInt(deliver)); item.setStartPrice(0); item.setMaxPrice(Integer.parseInt(mprice)); myAgent.existsSeller(item); Date date = new Date(); DateFormat df = new SimpleDateFormat("dd.MM.yy HH:mm"); System.out.println(df.format(date)+": Buyer orders an item: "+item.getName()); //Clearing all fields itemField.setText(""); quanField.setText(""); delivField.setText(""); //txtConsole.setText(""); mpriceField.setText(""); } catch (Exception e) { JOptionPane.showMessageDialog(BuyerGUI.this, "A field is filled incorrectly. "+e.getMessage()+" is invalid.", "Error", JOptionPane.ERROR_MESSAGE); } } } );![enter image description here][1]

    Read the article

  • Java Swingworker: Not as encapsulated class

    - by Thomas Matthews
    I'm having problems passing information, updating progress and indicating "done" with a SwingWorker class that is not an encapsulated class. I have a simple class that processes files and directories on a hard drive. The user clicks on the Start button and that launches an instance of the SwingWorker. I would like to print the names of the files that are processed on the JTextArea in the Event Driven Thread from the SwingWorker as update a progress bar. All the examples on the web are for an nested class, and the nested class accesses variables in the outer class (such as the done method). I would also like to signal the Event Driven Thread that the SwingWorker is finished so the EDT can perform actions such as enabling the Start button (and clearing fields). Here are my questions: 1. How does the SwingWorker class put text into the JTextArea of the Event Driven Thread and update a progress bar? How does the EDT determine when the {external} SwingWorker thread is finished? {I don't want the SwingWorker as a nested class because there is a lot of code (and processing) done.}

    Read the article

  • Java redirected system output to jtext area, doesnt update until calculation is finished

    - by user1806716
    I have code that redirects system output to a jtext area, but that jtextarea doesnt update until the code is finished running. How do I modify the code to make the jtextarea update in real time during runtime? private void updateTextArea(final String text) { SwingUtilities.invokeLater(new Runnable() { public void run() { consoleTextAreaInner.append(text); } }); } private void redirectSystemStreams() { OutputStream out = new OutputStream() { @Override public void write(int b) throws IOException { updateTextArea(String.valueOf((char) b)); } @Override public void write(byte[] b, int off, int len) throws IOException { updateTextArea(new String(b, off, len)); } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } }; System.setOut(new PrintStream(out, true)); System.setErr(new PrintStream(out, true)); } The rest of the code is mainly just an actionlistener for a button: private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: String shopRoot = this.shopRootDirTxtField.getText(); String updZipPath = this.updateZipTextField.getText(); this.mainUpdater = new ShopUpdater(new File(shopRoot), updZipPath); this.mainUpdater.update(); } That update() method begins the process of copying+pasting files on the file system and during that process uses system.out.println to provide an up-to-date status on where the program is currently at in reference to how many more files it has to copy.

    Read the article

  • Java Appending a character to a textarea

    - by adam08
    I'm looking to appends a character to a textarea in. I have a simple GUI designed to look like like a mobile phone and I want to be able to click on one of the buttons and update the textarea with that character. If I click another button, I want to be able to append that character to the first. How do I do this? Obviously right now it is just setting the character for that button in the textarea and will be replaced when another button is clicked. public void actionPerformed(ActionEvent e) { String source = e.getActionCommand(); if (source.equals("1")) { TextArea.setText("1"); } else if (source.equals("2abc")) { TextArea.setText("a"); } else if (source.equals("3def")) { TextArea.setText("e"); } else if (source.equals("4ghi")) { TextArea.setText("i"); } else if (source.equals("5jkl")) { TextArea.setText("k"); } else if (source.equals("6mno")) { TextArea.setText("o"); } else if (source.equals("7pqrs")) { TextArea.setText("s"); } else if (source.equals("8tuv")) { TextArea.setText("t"); } else if (source.equals("9wxyz")) { TextArea.setText("x"); }

    Read the article

  • how to run/compile java code from JTextArea at Runtime? ----urgent!!! college project

    - by Lokesh Kumar
    I have a JInternalFrame painted with a BufferedImage and contained in the JDesktopPane of a JFrame.I also have a JTextArea where i want to write some java code (function) that takes the current JInternalFrame's painted BufferedImage as an input and after doing some manipulation on this input it returns another manipulated BufferedImage that paints the JInternalFrame with new manipulated Image again!!. Manipulation java code of JTextArea:- public BufferedImage customOperation(BufferedImage CurrentInputImg) { Color colOld; Color colNew; BufferedImage manipulated=new BufferedImage(CurrentInputImg.getWidth(),CurrentInputImg.getHeight(),BufferedImage.TYPE_INT_ARGB); //make all Red pixels of current image black for(int i=0;i< CurrentInputImg.getWidth();i++) { for(int j=0;j< CurrentInputImg.getHeight(),j++) { colOld=new Color(CurrentInputImg.getRGB(i,j)); colNew=new Color(0,colOld.getGreen(),colOld.getBlue(),colOld.getAlpha()); manipulated.setRGB(i,j,colNew.getRGB()); } } return manipulated; } so,how can i run/compile this JTextArea java code at runtime and get a new manipulated image for painting on JInternalFrame???????   Here is my Main class: (This class is not actual one but i have created it for u for basic interfacing containing JTextArea,JInternalFrame,Apply Button) import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.JInternalFrame; import javax.swing.JDesktopPane; import java.awt.image.*; import javax.imageio.*; import java.io.*; import java.io.File; import java.util.*; class MyCustomOperationSystem extends JFrame **{** public JInternalFrame ImageFrame; public BufferedImage CurrenFrameImage; public MyCustomOperationSystem() **{** setTitle("My Custom Image Operations"); setSize((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(),(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()); JDesktopPane desktop=new JDesktopPane(); desktop.setPreferredSize(new Dimension((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(),(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight())); try{ CurrenFrameImage=ImageIO.read(new File("c:/Lokesh.png")); }catch(Exception exp) { System.out.println("Error in Loading Image"); } ImageFrame=new JInternalFrame("Image Frame",true,true,false,true); ImageFrame.setMinimumSize(new Dimension(CurrenFrameImage.getWidth()+10,CurrenFrameImage.getHeight()+10)); ImageFrame.getContentPane().add(CreateImagePanel()); ImageFrame.setLayer(1); ImageFrame.setLocation(100,100); ImageFrame.setVisible(true); desktop.setOpaque(true); desktop.setBackground(Color.darkGray); desktop.add(ImageFrame); this.getContentPane().setLayout(new BorderLayout()); this.getContentPane().add("Center",desktop); this.getContentPane().add("South",ControlPanel()); pack(); setVisible(true); **}** public JPanel CreateImagePanel(){ JPanel tempPanel=new JPanel(){ public void paintComponent(Graphics g) { g.drawImage(CurrenFrameImage,0,0,this); } }; tempPanel.setPreferredSize(new Dimension(CurrenFrameImage.getWidth(),CurrenFrameImage.getHeight())); return tempPanel; } public JPanel ControlPanel(){ JPanel controlPan=new JPanel(new FlowLayout(FlowLayout.LEFT)); JButton customOP=new JButton("Custom Operation"); customOP.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evnt){ JFrame CodeFrame=new JFrame("Write your Code Here"); JTextArea codeArea=new JTextArea("Your Java Code Here",100,70); JScrollPane codeScrollPan=new JScrollPane(codeArea,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); CodeFrame.add(codeScrollPan); CodeFrame.setVisible(true); } }); JButton Apply=new JButton("Apply Code"); Apply.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event){ // What should I do!!! Here!!!!!!!!!!!!!!! } }); controlPan.add(customOP); controlPan.add(Apply); return controlPan; } public static void main(String s[]) { new MyCustomOperationSystem(); } } Note: in above class JInternalFrame (ImageFrame) is not visible even i have declared it visible. so, ImageFrame is not visible while compiling and running above class. U have to identify this problem before running it.

    Read the article

  • How to send audio data from Java Applet to Rails controller

    - by cooldude
    Hi, I have to send the audio data in byte array obtain by recording from java applet at the client side to rails server at the controller in order to save. So, what encoding parameters at the applet side be used and in what form the audio data be converted like String or byte array so that rails correctly recieve data and then I can save that data at the rails in the file. As currently the audio file made by rails controller is not playing. It is the following ERROR : LAVF_header: av_open_input_stream() failed while playing with the mplayer. Here is the Java Code: package networksocket; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JApplet; import java.net.*; import java.io.*; import java.awt.event.*; import java.awt.*; import java.sql.*; import javax.swing.*; import javax.swing.border.*; import java.awt.*; import java.util.Properties; import javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager; import sun.awt.HorizBagLayout; import sun.awt.VerticalBagLayout; import sun.misc.BASE64Encoder; /** * * @author mukand */ public class Urlconnection extends JApplet implements ActionListener { /** * Initialization method that will be called after the applet is loaded * into the browser. */ public BufferedInputStream in; public BufferedOutputStream out; public String line; public FileOutputStream file; public int bytesread; public int toread=1024; byte b[]= new byte[toread]; public String f="FINISH"; public String match; public File fileopen; public JTextArea jTextArea; public Button refreshButton; public HttpURLConnection urlConn; public URL url; OutputStreamWriter wr; BufferedReader rd; @Override public void init() { // TODO start asynchronous download of heavy resources //textField= new TextField("START"); //getContentPane().add(textField); JPanel p = new JPanel(); jTextArea= new JTextArea(1500,1500); p.setLayout(new GridLayout(1,1, 1,1)); p.add(new JLabel("Server Details")); p.add(jTextArea); Container content = getContentPane(); content.setLayout(new GridBagLayout()); // Used to center the panel content.add(p); jTextArea.setLineWrap(true); refreshButton = new java.awt.Button("Refresh"); refreshButton.reshape(287,49,71,23); refreshButton.setFont(new Font("Dialog", Font.PLAIN, 12)); refreshButton.addActionListener(this); add(refreshButton); Properties properties = System.getProperties(); properties.put("http.proxyHost", "netmon.iitb.ac.in"); properties.put("http.proxyPort", "80"); } @Override public void actionPerformed(ActionEvent e) { try { url = new URL("http://localhost:3000/audio/audiorecieve"); urlConn = (HttpURLConnection)url.openConnection(); //String login = "mukandagarwal:rammstein$"; //String encodedLogin = new BASE64Encoder().encodeBuffer(login.getBytes()); //urlConn.setRequestProperty("Proxy-Authorization",login); urlConn.setRequestMethod("POST"); // urlConn.setRequestProperty("Content-Type", //"application/octet-stream"); //urlConn.setRequestProperty("Content-Type","audio/mpeg");//"application/x-www- form-urlencoded"); //urlConn.setRequestProperty("Content-Type","application/x-www- form-urlencoded"); //urlConn.setRequestProperty("Content-Length", "" + // Integer.toString(urlParameters.getBytes().length)); urlConn.setRequestProperty("Content-Language", "UTF-8"); urlConn.setDoOutput(true); urlConn.setDoInput(true); byte bread[]=new byte[2048]; int iread; char c; String data=URLEncoder.encode("key1", "UTF-8")+ "="; //String data="key1="; FileInputStream fileread= new FileInputStream("//home//mukand//Hellion.ogg");//Dogs.mp3");//Desktop//mausam1.mp3"); while((iread=fileread.read(bread))!=-1) { //data+=(new String()); /*for(int i=0;i<iread;i++) { //c=(char)bread[i]; System.out.println(bread[i]); }*/ data+= URLEncoder.encode(new String(bread,iread), "UTF-8");//new String(new String(bread));// // data+=new String(bread,iread); } //urlConn.setRequestProperty("Content-Length",Integer.toString(data.getBytes().length)); System.out.println(data); //data+=URLEncoder.encode("mukand", "UTF-8"); //data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8"); //data="key1="; wr = new OutputStreamWriter(urlConn.getOutputStream());//urlConn.getOutputStream(); //if((iread=fileread.read(bread))!=-1) // wr.write(bread,0,iread); wr.write(data); wr.flush(); fileread.close(); jTextArea.append("Send"); // Get the response rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); while ((line = rd.readLine()) != null) { jTextArea.append(line); } wr.close(); rd.close(); //jTextArea.append("click"); } catch (MalformedURLException ex) { Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void start() { } @Override public void stop() { } @Override public void destroy() { } // TODO overwrite start(), stop() and destroy() methods } Here is the Rails controller function for recieving: def audiorecieve puts "///////////////////////////////////////******RECIEVED*******////" puts params[:key1]#+" "+params[:key2] data=params[:key1] #request.env('RAW_POST_DATA') file=File.new("audiodata.ogg", 'w') file.write(data) file.flush file.close puts "////**************DONE***********//////////////////////" end Please reply quickly

    Read the article

  • Basic example of placing two component on one JPanel container?

    - by Bernard
    Here is my code to add to component (JTextArea and JList) to a panel and put it on the frame. Can I divide half/half by BorderLayout? If yes why mine looks messy one stays up one down? What is the other alternative? Regards, Bernard import java.awt.*; import javax.swing.BorderFactory; import javax.swing.border.Border; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.JPanel; import javax.swing.JFrame; import javax.swing.JTextArea; public class SimpleBorder { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(500,500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Border etched = (Border) BorderFactory.createEtchedBorder(); String[] items = {"A", "B", "C", "D"}; JList list = new JList(items); JTextArea text = new JTextArea(10, 40); JScrollPane scrol = new JScrollPane(text); JScrollPane scrol2 = new JScrollPane(list); JPanel panel= new JPanel(); panel.add(scrol2,BorderLayout.WEST); panel.add(scrol, BorderLayout.EAST); panel.setBorder(etched); frame.add(panel); frame.setVisible(true); } }

    Read the article

  • JFrame is not acting as expected!

    - by DasWood
    This is my first time using a JFrame. I can't get the window to display the text areas I've nested inside the JFrame. I am trying to get the text field with my name in it to display above the tabulated results, which I have omitted the formatting for until I can get the JFrame to work. public void printResults(String[] names, int[] temp, int[][] scores, float[] averages, char[] letters){ JTextArea outarea= new JTextArea(5,20); JTextArea name = new JTextArea(5,20); Font font = new Font("Tahoma", Font.BOLD, 48); name.setFont(font); name.setText("Made By Durka Durka"); JFrame window = new JFrame(); window.getContentPane().add(name); window.getContentPane().add(outarea); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.pack(); window.getContentPane().setVisible(true) String out = "twat"; outarea.setText(out); //JOptionPane.showMessageDialog(null,window); }

    Read the article

  • Problem with extending JPanel

    - by Halo
    I have an abstract entity: public abstract class Entity extends JPanel implements FocusListener And I have a TextEntity: public class TextEntity extends Entity Inside TextEntity's constructor I want to put a JTextArea that will cover the panel: textArea = new JTextArea(); textArea.setSize(getWidth(),getHeight()); add(textArea); But getWidth() and getHeight() returns 0. Is it a problem with the inheritance or the constructor?

    Read the article

  • Restore previously serialized JFrame-object, how?

    - by elementz
    Hi all. I have managed to serialize my very basic GUI-object containing a JTextArea and a few buttons to a file 'test.ser'. Now, I would like to completely restore the previously saved state from 'test.ser', but seem to have a misconception of how to properly deserialize an objects state. The class MyFrame creates the JFrame and serializes it. public class MyFrame extends JFrame implements ActionListener { // Fields JTextArea textArea; String title; static MyFrame gui = new MyFrame(); private static final long serialVersionUID = 1125762532137824262L; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub gui.run(); } // parameterless default contructor public MyFrame() { } // constructor with title public MyFrame(String title) { } // creates Frame and its Layout public void run() { JFrame frame = new JFrame(title); JPanel panel_01 = new JPanel(); JPanel panel_02 = new JPanel(); JTextArea textArea = new JTextArea(20, 22); textArea.setLineWrap(true); JScrollPane scrollPane = new JScrollPane(textArea); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); panel_01.add(scrollPane); // Buttons JButton saveButton = new JButton("Save"); saveButton.addActionListener(this); JButton loadButton = new JButton("Load"); loadButton.addActionListener(this); panel_02.add(loadButton); panel_02.add(saveButton); // Layout frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(BorderLayout.CENTER, panel_01); frame.getContentPane().add(BorderLayout.SOUTH, panel_02); frame.setSize(300, 400); frame.setVisible(true); } /* * */ public void serialize() { try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("test.ser")); oos.writeObject(gui); oos.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } public void actionPerformed(ActionEvent ev) { System.out.println("Action received!"); gui.serialize(); } } Here I try to do the deserialization: public class Deserialize { static Deserialize ds; static MyFrame frame; public static void main(String[] args) { try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.ser")); frame = (MyFrame) ois.readObject(); ois.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Maybe somebody could point me into the direction where my misconception is? Thx in advance!

    Read the article

  • How do I ensure that a JPanel Shrinks when the parent frame is resized?

    - by dah
    I have a basic notes panel that I'm looking to shrink the width of when the parent jframe is resized but it isn't happening. I'm using nested gridbaglayouts. package com.protocase.notes.views; import com.protocase.notes.controller.NotesController; import com.protocase.notes.model.Subject; import com.protocase.notes.model.Note; import com.protocase.notes.model.database.PMSNotesAdapter; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; /** * @author DavidH */ public class NotesViewer extends JPanel { // <editor-fold defaultstate="collapsed" desc="Attributes"> private Subject subject; private NotesController controller; //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Getters N' Setters"> /** * Gets back the current subject. * @return */ public Subject getSubject() { return subject; } public NotesController getController() { return controller; } public void setController(NotesController controller) { this.controller = controller; } /** * Should clear the panel of the current subject and load the details for * the other object. * @param subject */ public void setSubject(Subject subject) { this.subject = subject; } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Constructor"> /** * -- Sets up a note viewer with a subject and a controller. Likely this * would be the constructor used if you were passing off from another * NoteViewer or something else that used a notes adapter or controller. * @param subject * @param controller */ public NotesViewer(Subject subject, NotesController controller) { this.subject = subject; this.controller = controller; initComponents(); } /** * -- Sets up a note view with a subject and creates a new controller. This * would be the constructor typically chosen if choosing notes was * infrequent and only one or two notes needs to be displayed. * @param subject */ public NotesViewer(Subject subject) { this(subject, new NotesController(new PMSNotesAdapter())); } /** * -- Sets up a note view without a subject and creates a new controller. * This would be for a note viewer without any notes, perhaps populating * as you choose values in another form. * @param subject */ public NotesViewer() { this(null); } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="initComponents()"> /** * Sets up the view for the NotesViewer */ private void initComponents() { // -- Make a new panel for the header JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.fill = GridBagConstraints.HORIZONTAL; c.gridy = 0; c.weightx = .5; //c.anchor = GridBagConstraints.NORTHWEST; JLabel label = new JLabel("Viewing Notes for [Subject]"); label.setAlignmentX(JLabel.LEFT_ALIGNMENT); label.setBorder(BorderFactory.createLineBorder(Color.YELLOW)); panel.add(label); JButton newNoteButton = new JButton("New"); c = new GridBagConstraints(); // c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 0; c.weightx = .5; c.anchor = GridBagConstraints.EAST; panel.add(newNoteButton, c); // -- NotePanels c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1; c.weighty = 1; c.gridx = 0; c.gridwidth = 2; int y = 1; for (Note n : subject.getNotes()) { c.gridy = y++; panel.add(new NotesPanel(n, controller), c); } this.setLayout(new GridBagLayout()); GridBagConstraints pc = new GridBagConstraints(); pc.gridx = 0; pc.gridy = 0; pc.weightx = 1; pc.weighty = 1; pc.fill = GridBagConstraints.BOTH; panel.setBackground(Color.blue); JScrollPane scroll = new JScrollPane(); scroll.setViewportView(panel); //scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); this.add(scroll, pc); //this.add(panel, pc); // -- Add it all to the layout } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="private methods"> //</editor-fold> } package com.protocase.notes.views; import com.protocase.notes.controller.NotesController; import com.protocase.notes.model.Note; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.BevelBorder; import javax.swing.border.Border; import javax.swing.border.MatteBorder; /** * @author dah01 */ public class NotesPanel extends JPanel { // <editor-fold defaultstate="collapsed" desc="Attributes"> private Note note; private NotesController controller; private CardLayout cardLayout; private JTextArea viewTextArea; private JTextArea editTextArea; //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Getters N' Setters"> public NotesController getController() { return controller; } public void setController(NotesController controller) { this.controller = controller; } public Note getNote() { return note; } public void setNote(Note note) { this.note = note; } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Constructor"> /** * Sets up a note panel that shows everything about the note. * @param note */ public NotesPanel(Note note, NotesController controller) { this.note = note; cardLayout = new CardLayout(); this.setLayout(cardLayout); // -- Setup the layout manager. this.setBackground(new Color(199, 187, 192)); this.setBorder(new BevelBorder(BevelBorder.RAISED)); // -- ViewPanel this.add("ViewPanel", initViewPanel()); this.add("EditPanel", initEditPanel()); } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="EditPanel"> private JPanel initEditPanel() { JPanel editPanel = new JPanel(); editPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.gridy = 0; c.weightx = 1; c.weighty = 0.3; editPanel.add(initCreatorLabel(), c); c.gridy++; editPanel.add(initEditTextScroll(), c); c.gridy++; c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.NONE; editPanel.add(initEditorLabel(), c); c.gridx++; c.anchor = GridBagConstraints.EAST; editPanel.add(initSaveButton(), c); return editPanel; } private JScrollPane initEditTextScroll() { this.editTextArea = new JTextArea(note.getContents()); editTextArea.setLineWrap(true); editTextArea.setWrapStyleWord(true); JScrollPane scrollPane = new JScrollPane(editTextArea); scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT); Border b = scrollPane.getViewportBorder(); MatteBorder mb = BorderFactory.createMatteBorder(2, 2, 2, 2, Color.BLUE); scrollPane.setBorder(mb); return scrollPane; } private JButton initSaveButton() { final CardLayout l = this.cardLayout; final JPanel p = this; final NotesController c = this.controller; final Note n = this.note; final JTextArea noteText = this.viewTextArea; final JTextArea textToSubmit = this.editTextArea; ActionListener al = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //controller.saveNote(n); noteText.setText(textToSubmit.getText()); l.next(p); } }; JButton saveButton = new JButton("Save"); saveButton.addActionListener(al); saveButton.setPreferredSize(new Dimension(62, 26)); return saveButton; } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="ViewPanel"> private JPanel initViewPanel() { JPanel viewPanel = new JPanel(); viewPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL ; c.gridy = 0; c.weightx = 1; c.weighty = 0.3; viewPanel.add(initCreatorLabel(), c); c.gridy++; viewPanel.add(this.initNoteTextArea(), c); c.fill = GridBagConstraints.NONE; c.anchor = GridBagConstraints.WEST; c.gridy++; viewPanel.add(initEditorLabel(), c); c.gridx++; c.anchor = GridBagConstraints.EAST; viewPanel.add(initEditButton(), c); return viewPanel; } private JLabel initCreatorLabel() { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); if (note != null) { String noteBy = "Note by " + note.getCreator(); String noteCreated = formatter.format(note.getDateCreated()); JLabel creatorLabel = new JLabel(noteBy + " @ " + noteCreated); creatorLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT); return creatorLabel; } else { System.out.println("NOTE IS NULL"); return null; } } private JScrollPane initNoteTextArea() { // -- Setup the notes area. this.viewTextArea = new JTextArea(note.getContents()); viewTextArea.setEditable(false); viewTextArea.setLineWrap(true); viewTextArea.setWrapStyleWord(true); JScrollPane scrollPane = new JScrollPane(viewTextArea); scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT); return scrollPane; } private JLabel initEditorLabel() { // -- Setup the edited by label. JLabel editorLabel = new JLabel(" -- Last edited by " + note.getLastEdited() + " at " + note.getDateModified()); editorLabel.setAlignmentX(Component.LEFT_ALIGNMENT); return editorLabel; } private JButton initEditButton() { final CardLayout l = this.cardLayout; final JPanel p = this; ActionListener ar = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { l.next(p); } }; JButton editButton = new JButton("Edit"); editButton.setPreferredSize(new Dimension(62,26)); editButton.addActionListener(ar); return editButton; } //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Grow Width When Resized"> @Override public Dimension getPreferredSize() { int fw = this.getParent().getSize().width; int fh = super.getPreferredSize().height; return new Dimension(fw,fh); } //</editor-fold> }

    Read the article

  • Swing - how to mix JTextField and JTextAreas and have same visual appearance?

    - by I82Much
    I am using miglayout to create a form in which there are JTextFields (short input answers) as well as JTextAreas (Longer answers). The problem is twofold. The border placed around a Scrollpane wrapped text area does not match that of a Text Field. The width and placement of the textarea/textfield differ, causing them not to line up correctly. Source code: package test2; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import net.miginfocom.swing.MigLayout; public class Test extends JPanel { private static final int NUM_CHARACTERS_WIDTH = 20; private static final int NUM_ROWS = 5; public Test() { setLayout(new MigLayout( "wrap 2", // Align text labels on the so their right edge meets left edge of the text fields "[right][left]" )); add(new JLabel("Text field:")); add(new JTextField(NUM_CHARACTERS_WIDTH)); add(new JLabel("No scrollpane text area:")); add(new JTextArea(NUM_ROWS, NUM_CHARACTERS_WIDTH)); add(new JLabel("Scrollpane text area:")); add(new JScrollPane(new JTextArea(NUM_ROWS, NUM_CHARACTERS_WIDTH))); add(new JLabel("Text field:")); add(new JTextField(NUM_CHARACTERS_WIDTH)); } public static void main(String[] args) { JFrame frame = new JFrame(""); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new Test(); frame.add(panel); frame.pack(); frame.setVisible(true); } } What's the preferred way to mix and match jtextfield and jtextareas, while still maintaining visual harmony? I notice now that the text field has a blue highlight around it when focus is in it, as opposed to the text area... another source of visual discontinuity.

    Read the article

  • Swingworker producing duplicate output/output out of order?

    - by Stefan Kendall
    What is the proper way to guarantee delivery when using a SwingWorker? I'm trying to route data from an InputStream to a JTextArea, and I'm running my SwingWorker with the execute method. I think I'm following the example here, but I'm getting out of order results, duplicates, and general nonsense. Here is my non-working SwingWorker: class InputStreamOutputWorker extends SwingWorker<List<String>,String> { private InputStream is; private JTextArea output; public InputStreamOutputWorker(InputStream is, JTextArea output) { this.is = is; this.output = output; } @Override protected List<String> doInBackground() throws Exception { byte[] data = new byte[4 * 1024]; int len = 0; while ((len = is.read(data)) > 0) { String line = new String(data).trim(); publish(line); } return null; } @Override protected void process( List<String> chunks ) { for( String s : chunks ) { output.append(s + "\n"); } } }

    Read the article

  • Is it Possible to show a previously hidden JFrame using a keylistener

    - by JIM
    here is my code, i basically just did a tester for the most common listeners, which i might later use in future projects, the main problem is in the keylistener at the bottom, i am trying to re-show the frame but i think it just cant be done that way, please help ps: no idea why the imports dont show up right. package newpackage; import java.awt.Color; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JSeparator; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.UIManager; public class NewClass1 extends JFrame { private JLabel item1,infomouse,infoclicks,infoKeys,writehere; private JButton button1,button2,button3; private JTextArea text1,status,KeyStatus; private JTextField text2,text3,mouse,clicks,test; private JSeparator sep1; private int clicknumber; public NewClass1() { super("Listener Tests"); setLayout(null); sep1 = new JSeparator(); button1 = new JButton("Button1"); button2 = new JButton("Button2"); button3 = new JButton("Button3"); item1 = new JLabel("Button Status :"); infomouse = new JLabel("Mouse Status :"); infoclicks = new JLabel("Nº of clicks :"); infoKeys = new JLabel("Keyboard status:"); writehere = new JLabel("Write here: "); text1 = new JTextArea(); text2 = new JTextField(20); text3 = new JTextField(20); status = new JTextArea(); mouse = new JTextField(20); clicks = new JTextField(4); KeyStatus = new JTextArea(); test = new JTextField(3); clicks.setText(String.valueOf(clicknumber)); text1.setEditable(true); text2.setEditable(false); text3.setEditable(false); status.setEditable(false); mouse.setEditable(false); clicks.setEditable(false); KeyStatus.setEditable(false); text1.setBounds(135, 310, 150, 20); text2.setBounds(135, 330, 150, 20); text3.setBounds(135, 350, 150, 20); status.setBounds(15, 20, 240, 20); infomouse.setBounds(5,45,120,20); infoKeys.setBounds(5,90,120,20); KeyStatus.setBounds(15,115,240,85); test.setBounds(15,225,240,20); mouse.setBounds(15,70,100,20); infoclicks.setBounds(195, 45, 140, 20); clicks.setBounds(195, 70, 60, 20); item1.setBounds(5, 0, 120, 20); button1.setBounds(10, 310, 115, 20); button2.setBounds(10, 330, 115, 20); button3.setBounds(10, 350, 115, 20); sep1.setBounds(5, 305, 285, 10); sep1.setBackground(Color.BLACK); status.setBackground(Color.LIGHT_GRAY); button1.addActionListener(new button1list()); button2.addActionListener(new button1list()); button3.addActionListener(new button1list()); button1.addMouseListener(new MouseList()); button2.addMouseListener(new MouseList()); button3.addMouseListener(new MouseList()); getContentPane().addMouseListener(new MouseList()); test.addKeyListener(new KeyList()); this.addKeyListener(new KeyList()); test.requestFocus(); add(item1); add(button1); add(button2); add(button3); add(text1); add(text2); add(text3); add(status); add(infomouse); add(mouse); add(infoclicks); add(clicks); add(infoKeys); add(KeyStatus); add(test); add(sep1); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch (Exception e){System.out.println("Error");} SwingUtilities.updateComponentTreeUI(this); setSize(300, 400); setResizable(false); setVisible(true); test.setFocusable(true); test.setFocusTraversalKeysEnabled(false); setLocationRelativeTo(null); } public class button1list implements ActionListener { public void actionPerformed(ActionEvent e) { String buttonpressed = e.getActionCommand(); if (buttonpressed.equals("Button1")) { text1.setText("just"); } else if (buttonpressed.equals("Button2")) { text2.setText(text2.getText()+"testing "); } else if (buttonpressed.equals("Button3")) { text3.setText("this"); } } } public class MouseList implements MouseListener{ public void mouseEntered(MouseEvent e){ if(e.getSource()==button1){ status.setText("button 1 hovered"); } else if(e.getSource()==button2){ status.setText("button 2 hovered"); } else if(e.getSource()==button3){ status.setText("button 3 hovered"); } } public void mouseExited(MouseEvent e){ status.setText(""); } public void mouseReleased(MouseEvent e){ if(!status.getText().equals("")){ status.replaceRange("", 0, 22); } } public void mousePressed(MouseEvent e){ if(e.getSource()==button1){ status.setText("button 1 being pressed"); } else if(e.getSource()==button2){ status.setText("button 2 being pressed"); } else if(e.getSource()==button3){ status.setText("button 3 being pressed"); } } public void mouseClicked(MouseEvent e){ clicknumber++; mouse.setText("mouse working"); clicks.setText(String.valueOf(clicknumber)); } } public class KeyList implements KeyListener{ public void keyReleased(KeyEvent e){} public void keyPressed(KeyEvent e){ KeyStatus.setText(""); test.setText(""); String full = e.paramString(); String [] temp = null; temp = full.split(","); for(int i=0; i<7 ;i++){ KeyStatus.append(temp[i] + "\n"); } if(e.getKeyChar()=='h'){setVisible(false); test.requestFocus(); } if(e.getKeyChar()=='s'){setVisible(true);} } public void keyTyped(KeyEvent e){} } }

    Read the article

  • How to remove duplicate line in a file

    - by Abs
    Hi I'm using the below method to write to a file from the Jtextarea and I call this method every 30 second within a Timer but instead to add only new line in file it rewrite the entire lines contained in Jtextarea so then I have duplicate lines. I want to avoid this and update the file just with new lines. Could you help me please. public void loger() { FileWriter writer = null; try { writer = new FileWriter("MBM_Log_"+date()+".txt" , true); textArea.write(writer); } catch (IOException exception) { System.err.println("log error"); exception.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (IOException exception) { System.err.println("Error closing writer"); exception.printStackTrace(); } } } }

    Read the article

  • Java Box Class: Unsolvable: aligning components to the left or right

    - by user323186
    I have been trying to left align buttons contained in a Box to the left, with no success. They align left alright, but for some reason dont shift all the way left as one would imagine. I attach the code below. Please try compiling it and see for yourself. Seems bizarre to me. Thanks, Eric import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class MainGUI extends Box implements ActionListener{ //Create GUI Components Box centerGUI=new Box(BoxLayout.X_AXIS); Box bottomGUI=new Box(BoxLayout.X_AXIS); //centerGUI subcomponents JTextArea left=new JTextArea(), right=new JTextArea(); JScrollPane leftScrollPane = new JScrollPane(left), rightScrollPane = new JScrollPane(right); //bottomGUI subcomponents JButton encrypt=new JButton("Encrypt"), decrypt=new JButton("Decrypt"), close=new JButton("Close"), info=new JButton("Info"); //Create Menubar components JMenuBar menubar=new JMenuBar(); JMenu fileMenu=new JMenu("File"); JMenuItem open=new JMenuItem("Open"), save=new JMenuItem("Save"), exit=new JMenuItem("Exit"); int returnVal =0; public MainGUI(){ super(BoxLayout.Y_AXIS); initCenterGUI(); initBottomGUI(); initFileMenu(); add(centerGUI); add(bottomGUI); addActionListeners(); } private void addActionListeners() { open.addActionListener(this); save.addActionListener(this); exit.addActionListener(this); encrypt.addActionListener(this); decrypt.addActionListener(this); close.addActionListener(this); info.addActionListener(this); } private void initFileMenu() { fileMenu.add(open); fileMenu.add(save); fileMenu.add(exit); menubar.add(fileMenu); } public void initCenterGUI(){ centerGUI.add(leftScrollPane); centerGUI.add(rightScrollPane); } public void initBottomGUI(){ bottomGUI.setAlignmentX(LEFT_ALIGNMENT); //setBorder(BorderFactory.createLineBorder(Color.BLACK)); bottomGUI.add(encrypt); bottomGUI.add(decrypt); bottomGUI.add(close); bottomGUI.add(info); } @Override public void actionPerformed(ActionEvent arg0) { // find source of the action Object source=arg0.getSource(); //if action is of such a type do the corresponding action if(source==close){ kill(); } else if(source==open){ //CHOOSE FILE File file1 =chooseFile(); String input1=readToString(file1); System.out.println(input1); left.setText(input1); } else if(source==decrypt){ //decrypt everything in Right Panel and output in left panel decrypt(); } else if(source==encrypt){ //encrypt everything in left panel and output in right panel encrypt(); } else if(source==info){ //show contents of info file in right panel doInfo(); } else { System.out.println("Error"); //throw new UnimplementedActionException(); } } private void doInfo() { // TODO Auto-generated method stub } private void encrypt() { // TODO Auto-generated method stub } private void decrypt() { // TODO Auto-generated method stub } private String readToString(File file) { FileReader fr = null; try { fr = new FileReader(file); } catch (FileNotFoundException e1) { e1.printStackTrace(); } BufferedReader br=new BufferedReader(fr); String line = null; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } String input=""; while(line!=null){ input=input+"\n"+line; try { line=br.readLine(); } catch (IOException e) { e.printStackTrace(); } } return input; } private File chooseFile() { //Create a file chooser final JFileChooser fc = new JFileChooser(); returnVal = fc.showOpenDialog(fc); return fc.getSelectedFile(); } private void kill() { System.exit(0); } public static void main(String[] args) { // TODO Auto-generated method stub MainGUI test=new MainGUI(); JFrame f=new JFrame("Tester"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setJMenuBar(test.menubar); f.setPreferredSize(new Dimension(600,400)); //f.setUndecorated(true); f.add(test); f.pack(); f.setVisible(true); } }

    Read the article

  • Java text to applet converter ... is there such a thing?

    - by Jahkr
    Let's say you have this program: public class sample public static void main(String args[]) { System.out.println("Hello world!"); } } ... is there a converter that will turn it into this: import java.applet.Applet; import javax.swing.*; public class sample extends JApplet { public static JTextArea area; public void init() { area = new JTextArea(); add(area); area.append("Hello world!"); } } I mean, I can do it by hand... but it would take some time.

    Read the article

  • problems with scrolling a java TextArea

    - by Jonathan
    All, I am running into an issue using JTextArea and JScrollPane. For some reason the scroll pane appears to not recognize the last line in the document, and will only scroll down to the line before it. The scroll bar does not even change to a state where I can slide it until the lines in the document are two greater than the number of lines the textArea shows (it should happen as soon as it is one greater). Has anyone run into this before? What would be a good solution (I want to avoid having to add an extra 'blank' line to the end of the document, which I would have to remove every time I add a new line)? Here is how I instantiate the TextArea and ScrollPane: JFrame frame = new JFrame("Java Chat Program"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container pane = frame.getContentPane(); if (!(pane.getLayout() instanceof BorderLayout)) { System.err.println("Error: UI Container does not implement BorderLayout."); System.exit(-1); } textArea = new JTextArea(); textArea.setPreferredSize(new Dimension(500, 100)); textArea.setEditable(false); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); JScrollPane scroller = new JScrollPane(textArea); scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); pane.add(scroller, BorderLayout.CENTER); Here is the method I use to add a new line to textArea: public void println(String a) { textArea.append(" "+a+"\n"); textArea.setCaretPosition(textArea.getDocument().getLength()); } Thanks for your help, Jonathan EDIT: Also, as a side note, with the current code I have to manually scroll down. I assumed that setCaretPosition(doc.getLength()) in the println(line) method would automatically set the page to the bottom after a line is entered... Should that be the case, or do I need to do something differently?

    Read the article

  • JTree events seem misordered

    - by MeBigFatGuy
    It appears to me that tree selection events should happen after focus events, but this doesn't seem to be the case. Assume you have a JTree and a JTextField, where the JTextField is populated by what is selected in the tree. When the user changes the text field, on focus lost, you update the tree from the text field. however, the tree selection is changed before the focus is lost on the text field. this is incorrect, right? Any ideas? Here is some sample code: import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public class Focus extends JFrame { public static void main(String[] args) { Focus f = new Focus(); f.setLocationRelativeTo(null); f.setVisible(true); } public Focus() { Container cp = getContentPane(); cp.setLayout(new BorderLayout()); final JTextArea ta = new JTextArea(5, 10); cp.add(new JScrollPane(ta), BorderLayout.SOUTH); JSplitPane sp = new JSplitPane(); cp.add(sp, BorderLayout.CENTER); JTree t = new JTree(); t.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent tse) { ta.append("Tree Selection changed\n"); } }); t.addFocusListener(new FocusListener() { public void focusGained(FocusEvent fe) { ta.append("Tree focus gained\n"); } public void focusLost(FocusEvent fe) { ta.append("Tree focus lost\n"); } }); sp.setLeftComponent(new JScrollPane(t)); JTextField f = new JTextField(10); sp.setRightComponent(f); pack(); f.addFocusListener(new FocusListener() { public void focusGained(FocusEvent fe) { ta.append("Text field focus gained\n"); } public void focusLost(FocusEvent fe) { ta.append("Text field focus lost\n"); } }); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }

    Read the article

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