protected boolean setDir(JTextField txf, String strValue) { String strTxt = txf.getText(); String strName = txf.getName(); boolean bSet = false; if ((strTxt == null || strTxt.trim().length() == 0 || strTxt.equals(INFOSTR)) && strName.equalsIgnoreCase("value")) { if (timer != null) { timer.cancel(); txf.setForeground(Color.black); } bSet = true; txf.setText(strValue); txf.grabFocus(); } return bSet; }
public void search() { hilit.removeAllHighlights(); String s = entry.getText(); if (s.length() <= 0) { message("Nothing to search"); return; } String content = textArea.getText(); int index = content.indexOf(s, 0); if (index >= 0) { try { int end = index + s.length(); hilit.addHighlight(index, end, painter); textArea.setCaretPosition(end); entry.setBackground(entryBg); message("'" + s + "' found. Press ESC to end search"); } catch (BadLocationException e) { e.printStackTrace(); } } else { entry.setBackground(ERROR_COLOR); message("'" + s + "' found. Press ESC to start a new search"); } }
@Override public void actionPerformed(ActionEvent e) { if (td.getTabCount() > 0) { TextDocument ta = (TextDocument) td.getComponentAt(td.getSelectedIndex()); Pattern pn = Pattern.compile(tf1.getText()); Matcher mt = pn.matcher(ta.getText()); if (e.getSource() == jb2) { // 取代 ta.setText(mt.replaceAll(tf2.getText())); } else if (e.getSource() == jb1) { // 尋找 Highlighter hl = ta.getHighlighter(); hl.removeAllHighlights(); while (mt.find()) { try { hl.addHighlight( mt.start(), mt.end(), new DefaultHighlighter.DefaultHighlightPainter(null)); } catch (Exception ex) { } } // 開啟及關閉介面 } else if (e.getSource() == replace_searchMenuItem) { System.out.println("Replace/Search is show:" + !show); if (show) { getContentPane().remove(jp); show = false; } else { getContentPane().add(jp, BorderLayout.SOUTH); show = true; } validate(); // 刷新容器 } } else if (e.getSource() == replace_searchMenuItem) { JOptionPane.showMessageDialog( null, "尚無檔案,無法使用!", "Repace/Search error", JOptionPane.ERROR_MESSAGE); } }
public void save() { for (String key : fields.keySet()) { JComponent comp = fields.get(key); if (comp instanceof JTextField) { JTextField c = (JTextField) comp; if (c.getText().trim().equals("")) { sketch.configFile.unset(key); } else { sketch.configFile.set(key, c.getText()); } } else if (comp instanceof JTextArea) { JTextArea c = (JTextArea) comp; if (c.getText().trim().equals("")) { sketch.configFile.unset(key); } else { sketch.configFile.set(key, c.getText()); } } } sketch.saveConfig(); }
void jListOnlineUsers_mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { jTextFieldTargetUser.setText(((HostItem) jListOnlineUsers.getSelectedValue()).name); Flasher.instance().flashBackground(jTextFieldTargetUser, Color.yellow, 2); jTextFieldSendMessages.requestFocus(); } }
/** * Will register this server on the port number portNumber. Will not start waiting for * connections. For this you should call waitForConnectionFromClient(). */ private void registerOnPort() { try { serverSocket = new ServerSocket(Integer.parseInt(portNumber.getText())); } catch (IOException e) { serverSocket = null; System.err.println("Cannot open server socket on port number" + portNumber.getText()); System.err.println(e); System.exit(-1); } }
/** Clears all the data previously entered in the form. */ public void clear() { usernameField.setText(""); displayNameField.setText(""); passField.setText(""); retypePassField.setText(""); emailField.setText(""); errorPane.setText(""); remove(errorPane); }
void addTextField(JPanel panel, String key, String label) { JLabel lab = new JLabel(label); lab.setAlignmentX(LEFT_ALIGNMENT); panel.add(lab); JTextField field = new JTextField(); field.setText(sketch.configFile.get(key)); field.setMaximumSize(new Dimension(Integer.MAX_VALUE, field.getPreferredSize().height)); fields.put(key, field); panel.add(field); }
public TextFields() { t1.setDocument(ucd); ucd.addDocumentListener(new T1()); b1.addActionListener(new B1()); b2.addActionListener(new B2()); t1.addActionListener(new T1A()); setLayout(new FlowLayout()); add(b1); add(b2); add(t1); add(t2); add(t3); }
public void receiveMsg(Message msg) { // System.out.println(msg.getSubject() + " : " + msg.getBody()); String subject = msg.getSubject(); if (subject != null) { if (subject.equals("online")) { onlineUsers.addElement(new HostItem(msg.getBody())); displayMessage(msg.getBody() + " : Online", onlineClientAttrSet); } else if (subject.equals("offline")) { onlineUsers.removeElement(new HostItem(msg.getBody())); displayMessage(msg.getBody() + " : Offline", offlineClientAttrSet); } else if (subject.equals("eavesdrop enabled")) { Object[] values = jListOnlineUsers.getSelectedValues(); if (values == null) return; for (int i = 0; i < values.length; i++) { ((HostItem) values[i]).eavesDroppingEnabled = true; } jListOnlineUsers.updateUI(); } else if (subject.equals("eavesdrop disabled")) { Object[] values = jListOnlineUsers.getSelectedValues(); if (values == null) return; for (int i = 0; i < values.length; i++) { ((HostItem) values[i]).eavesDroppingEnabled = false; } jListOnlineUsers.updateUI(); } else if (subject.equals("globaleavesdrop enabled")) { displayMessage("Global Eavesdropping Enabled", onlineClientAttrSet); } else if (subject.equals("globaleavesdrop disabled")) { displayMessage("Global Eavesdropping Disabled", offlineClientAttrSet); } else { String to = msg.getTo(); String from = msg.getFrom() == null ? "server" : msg.getFrom(); String body = msg.getBody() != null ? msg.getBody() : ""; if (jTextFieldUser.getText().equals(to)) { // this message is sent to us displayMessage(subject, from, body, incomingMsgAttrSet); } else { // this is an eavesdrop message displayMessage(subject, to, from, body, eavesdropAttrSet); } } } else { subject = ""; String to = msg.getTo(); String from = msg.getFrom() == null ? "server" : msg.getFrom(); String body = msg.getBody() != null ? msg.getBody() : ""; if (jTextFieldUser.getText().equals(to)) { // this message is sent to us displayMessage(subject, from, body, incomingMsgAttrSet); } else { // this is an eavesdrop message displayMessage(subject, to, from, body, eavesdropAttrSet); } } }
private void setBorder(boolean isEnabled) { JTextField txfTmp = new JTextField(); if (isEnabled) setBorder(txfTmp.getBorder()); else { String strStyle = getAttribute(DISABLE); if (strStyle != null && strStyle.equals(m_arrStrDisAbl[1])) { setBorder(null); setBackground(Util.getBgColor()); } else { setBorder(txfTmp.getBorder()); setBackground(Global.NPCOLOR); } } }
void jTextFieldSendMessages_keyPressed(KeyEvent e) { if (e.getKeyCode() == e.VK_DOWN) { String s = msgHistory.forward(); if (s != null) { jTextFieldSendMessages.setText(s); } } else if (e.getKeyCode() == e.VK_UP) { String s = msgHistory.back(); if (s != null) { jTextFieldSendMessages.setText(s); } } else if (e.getKeyChar() == '\n') { String body = jTextFieldSendMessages.getText(); if (body.length() > 0) { if (body.charAt(body.length() - 1) == '\n') body = body.substring(0, body.length() - 1); String subject = jTextFieldSendSubject.getText(); if (subject.length() > 0) { if (subject.charAt(subject.length() - 1) == '\n') subject = subject.substring(0, subject.length() - 1); } if (session != null && session.isConnected()) { session.postMessage(jTextFieldTargetUser.getText(), subject, body); displaySendMessage(subject, jTextFieldTargetUser.getText(), body, outgoingMsgAttrSet); } msgHistory.add(body); subjectHistory.add(subject); subjectHistory.reset(); msgHistory.reset(); jTextFieldSendMessages.setText(""); jTextFieldSendSubject.setText(""); } } }
void jTextFieldSendSubject_keyPressed(KeyEvent e) { if (e.getKeyCode() == e.VK_DOWN) { String s = subjectHistory.forward(); if (s != null) { jTextFieldSendSubject.setText(s); } } else if (e.getKeyCode() == e.VK_UP) { String s = subjectHistory.back(); if (s != null) { jTextFieldSendSubject.setText(s); } } else if (e.getKeyChar() == '\n') { jTextFieldSendMessages.requestFocus(); } }
/** * The ActionListener implementation * * @param event the event. */ public void actionPerformed(ActionEvent event) { String searchText = textField.getText().trim(); if (searchText.equals("") && !saveAs.isSelected() && (fileLength > 10000000)) { textPane.setText("Blank search text is not allowed for large IdTables."); } else { File outputFile = null; if (saveAs.isSelected()) { outputFile = chooser.getSelectedFile(); if (outputFile != null) { String name = outputFile.getName(); int k = name.lastIndexOf("."); if (k != -1) name = name.substring(0, k); name += ".txt"; File parent = outputFile.getAbsoluteFile().getParentFile(); outputFile = new File(parent, name); chooser.setSelectedFile(outputFile); } if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) System.exit(0); outputFile = chooser.getSelectedFile(); } textPane.setText(""); Searcher searcher = new Searcher(searchText, event.getSource().equals(searchPHI), outputFile); searcher.start(); } }
/** * Method called when a user message has been sent. checks to see if it is a command or regular * message */ private void sendMessage() { String txt = new String(messageText.getText()); if (!txt.equals("")) { if (txt.charAt(0) == '\\' || txt.charAt(0) == '/') { parseCommand(txt.substring(1)); messageText.setText(""); history.add(txt); } else if (server != null && server.connected && username != null) { sendText(username, txt, false); messageText.setText(""); sendChat(txt); history.add(txt); } else { error("Not connected, type \\reconnect to try and reconnect"); } } }
public void appendToPane(String msg, Color c) { if (inputText.isEnabled()) { StyleContext sc = StyleContext.getDefaultStyleContext(); AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c); textArea.setCharacterAttributes(aset, false); textArea.replaceSelection(msg); textArea.setCaretPosition(textArea.getDocument().getLength()); } }
public JFrame buildFrame() { f = new JFrame("AMSA World"); f.setSize(800, 600); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setLayout(new GridBagLayout()); textArea.setFocusable(false); JScrollPane scrollPane = new JScrollPane(textArea); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent evt) { checkInput(); } }; inputText.addActionListener(listener); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(5, 5, 5, 5); c.weightx = 1.0; c.gridwidth = 3; c.weighty = 0.025; c.gridx = 0; c.gridy = 0; f.add(topPanel, c); c.fill = GridBagConstraints.BOTH; c.weighty = 1.0; c.gridwidth = 2; c.gridx = 0; c.gridy = 1; f.add(scrollPane, c); c.fill = GridBagConstraints.BOTH; c.weighty = 1.0; c.gridwidth = 1; c.gridx = 2; c.gridy = 1; f.add(sidePanel, c); sidePanel.setVisible(false); c.fill = GridBagConstraints.HORIZONTAL; c.weighty = 0.025; c.gridwidth = 3; c.gridx = 0; c.gridy = 2; f.add(inputText, c); f.setVisible(true); return f; }
private void handleConnect() { if (jToggleButtonConnect.isSelected() || jMenuItemServerConnect.isEnabled()) try { jTextPaneDisplayMessages.setText(""); session = new Session(); try { String userid = jTextFieldUser.getText(); if (jPasswordFieldPwd.getPassword() != null) { String pwd = String.valueOf(jPasswordFieldPwd.getPassword()).trim(); if (!pwd.equals("")) { userid += ":" + pwd; } } if (session.connect(jTextFieldServer.getText(), userid)) { displayMessage("Connected\n", incomingMsgAttrSet); session.addListener(this); jToggleButtonConnect.setText("Disconnect"); jMenuItemServerConnect.setEnabled(false); jMenuItemServerDisconnect.setEnabled(true); } else { jToggleButtonConnect.setSelected(false); jMenuItemServerConnect.setEnabled(true); jMenuItemServerDisconnect.setEnabled(false); displayMessage("Connection attempt failed\n", offlineClientAttrSet); } } catch (ConnectionException ex1) { jToggleButtonConnect.setSelected(false); jMenuItemServerConnect.setEnabled(true); jMenuItemServerDisconnect.setEnabled(false); displayMessage( "Connection attempt failed: " + ex1.getMessage() + "\n", offlineClientAttrSet); } } catch (Exception ex) { ex.printStackTrace(); } else { disconnect(); jMenuItemServerConnect.setEnabled(true); jMenuItemServerDisconnect.setEnabled(false); displayMessage("Disconnected\n", offlineClientAttrSet); } }
public void paint(Graphics g) { super.paint(g); if (!isEditing) return; Dimension psize = getPreferredSize(); if (isFocused) g.setColor(Color.yellow); else g.setColor(Color.green); g.drawLine(0, 0, psize.width, 0); g.drawLine(0, 0, 0, psize.height); g.drawLine(0, psize.height - 1, psize.width - 1, psize.height - 1); g.drawLine(psize.width - 1, 0, psize.width - 1, psize.height - 1); }
public TextFieldDemo() { initComponents(); InputStream in = getClass().getResourceAsStream("content.txt"); try { textArea.read(new InputStreamReader(in), null); } catch (IOException e) { e.printStackTrace(); } hilit = new DefaultHighlighter(); painter = new DefaultHighlighter.DefaultHighlightPainter(HILIT_COLOR); textArea.setHighlighter(hilit); entryBg = entry.getBackground(); entry.getDocument().addDocumentListener(this); InputMap im = entry.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); ActionMap am = entry.getActionMap(); im.put(KeyStroke.getKeyStroke("ESCAPE"), CANCEL_ACTION); am.put(CANCEL_ACTION, new CancelAction()); }
public void checkInput() { // SwingUtilities.invokeLater(new Runnable() { // public void run() { String text = inputText.getText(); if (!text.equals("")) { appendToPane(text + "\n\n", Color.blue); inputText.setText(""); if (text.startsWith("use ")) { ArrayList<Item> inventory = player.getInventory(); String key = text.substring(4); boolean found = false; for (Item i : inventory) { if (i.getName().equalsIgnoreCase(key)) { found = true; i.use(); break; } } if (!found) { appendToPane("Item does not exist in your iventory.\n\n", Color.black); } else { } } if (text.startsWith("inventory")) { ArrayList<Item> inventory = player.getInventory(); if (inventory.size() > 0) { for (Item i : inventory) { appendToPane(i.getName() + "\n", Color.darkGray); } } else appendToPane("Your iventory is empty.\n\n", Color.black); appendToPane("#", Color.blue); } else { userInput = text; } } // } // }); }
/** * References checked: 8.10.2003 (2.0b2) * * @param editorType editor type, one of this constants * <UL> * <LI>EDITOR_TYPE_DEFAULT * <LI>EDITOR_TYPE_STYLED * <LI>EDITOR_TYPE_SINGLE_LINE * </UL> * * @param controler if not <code>null</code> for <code>EDITOR_TYPE_STYLED</code> editors a toolbar * is created * @see PresentationDetail#PresentationDetail */ TextEditorPanel( int editorType, GraphPanelControler controler, boolean showToolbar, PresentationDetail detail) { this.editorType = editorType; this.controler = controler; this.showToolbar = showToolbar; this.detail = detail; setLayout(new BorderLayout()); // --- build this text editor panel --- switch (editorType) { case EDITOR_TYPE_DEFAULT: textComponent = new JTextArea(); add(new JScrollPane(textComponent)); break; case EDITOR_TYPE_STYLED: textComponent = new JTextPane(); textComponent.setTransferHandler(new TextTransferHandler()); // ### requires Java 1.4 // --- add toolbar --- if (showToolbar) { JPanel bar = new JPanel(); Hashtable actions = DeepaMehtaClientUtils.createActionTable(textComponent); bar.setBackground(COLOR_PROPERTY_PANEL); toolbarButtons = new JButton[3]; addButton(bar, new StyledEditorKit.BoldAction(), actions, controler.boldIcon()); addButton(bar, new StyledEditorKit.ItalicAction(), actions, controler.italicIcon()); addButton(bar, new StyledEditorKit.UnderlineAction(), actions, controler.underlineIcon()); // ### addButton(bar, "H1", CMD_SET_HEADLINE1); // ### addButton(bar, "H2", CMD_SET_HEADLINE2); add(bar, BorderLayout.SOUTH); } add(new JScrollPane(textComponent)); break; case EDITOR_TYPE_SINGLE_LINE: textComponent = new JTextField(); ((JTextField) textComponent).addActionListener(this); add(textComponent); break; default: throw new DeepaMehtaException("unexpected text editor type: " + editorType); } // --- enable automatic drag and drop support --- try { textComponent.setDragEnabled(true); } catch (NoSuchMethodError e) { // requires JDK 1.4 ### } }
public void reshape(int x, int y, int w, int h) { if (inEditMode) { defLoc.x = x; defLoc.y = y; defDim.width = w; defDim.height = h; } curLoc.x = x; curLoc.y = y; curDim.width = w; curDim.height = h; if (!inEditMode) { if ((h != nHeight) || (h < rHeight)) { adjustFont(w, h); } } super.reshape(x, y, w, h); }
private static void insertQuestion(final JTextPane textPane, String str) { Document doc = textPane.getDocument(); try { doc.insertString(doc.getLength(), str, null); final int pos = doc.getLength(); System.out.println(pos); final JTextField field = new JTextField(4) { @Override public Dimension getMaximumSize() { return getPreferredSize(); } }; field.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK)); field.addFocusListener( new FocusListener() { @Override public void focusGained(FocusEvent e) { try { Rectangle rect = textPane.modelToView(pos); rect.grow(0, 4); rect.setSize(field.getSize()); // System.out.println(rect); // System.out.println(field.getLocation()); textPane.scrollRectToVisible(rect); } catch (BadLocationException ex) { ex.printStackTrace(); } } @Override public void focusLost(FocusEvent e) { /* not needed */ } }); Dimension d = field.getPreferredSize(); int baseline = field.getBaseline(d.width, d.height); field.setAlignmentY(baseline / (float) d.height); SimpleAttributeSet a = new SimpleAttributeSet(); StyleConstants.setLineSpacing(a, 1.5f); textPane.setParagraphAttributes(a, true); textPane.insertComponent(field); doc.insertString(doc.getLength(), "\n", null); } catch (BadLocationException e) { e.printStackTrace(); } }
public NewUser() { super("Adding New User"); label1 = new JLabel("Name"); label2 = new JLabel("Category"); username = new JLabel("Username"); password = new JLabel("Password"); confirm = new JLabel("Re-enter Password"); pass1 = new JPasswordField(); pass2 = new JPasswordField(); txtusername = new JTextField(); name = new JTextField(); combo1 = new JComboBox(); button1 = new JButton("Ok", new ImageIcon("Icon/i16x16/ok.png")); button2 = new JButton("Cancel", new ImageIcon("Icon/i16x16/exit.png")); panel1 = new JPanel(new GridLayout(6, 2)); panel1.add(label1); panel1.add(name); panel1.add(label2); panel1.add(combo1); panel1.add(username); panel1.add(txtusername); panel1.add(password); panel1.add(pass1); panel1.add(confirm); panel1.add(pass2); panel1.add(button1); panel1.add(button2); combo1.addItem("Manager"); combo1.addItem("Booking Clerk"); combo1.addItem("Supervisor"); panel2 = new JPanel(); panel2.add(panel1); getContentPane().add(panel2); setSize(350, 195); setVisible(true); setLocation((screen.width - 500) / 2, ((screen.height - 350) / 2)); setResizable(false); name.addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); if (!(Character.isLetter(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_SPACE) || (c == KeyEvent.VK_DELETE))) { getToolkit().beep(); JOptionPane.showMessageDialog( null, "Invalid Character", "ERROR", JOptionPane.DEFAULT_OPTION); e.consume(); } } }); txtusername.addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); if (!(Character.isLetter(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_SPACE) || (c == KeyEvent.VK_DELETE))) { getToolkit().beep(); JOptionPane.showMessageDialog( null, "Invalid Character", "ERROR", JOptionPane.DEFAULT_OPTION); e.consume(); } } }); button1.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { if (name.getText() == null || name.getText().equals("")) { JOptionPane.showMessageDialog( null, "Enter name", "ERROR", JOptionPane.DEFAULT_OPTION); name.requestFocus(); return; } if (txtusername.getText() == null || txtusername.getText().equals("")) { JOptionPane.showMessageDialog( null, "Enter username", "ERROR", JOptionPane.DEFAULT_OPTION); txtusername.requestFocus(); return; } if (pass1.getText() == null || pass1.getText().equals("")) { JOptionPane.showMessageDialog( null, "Enter password", "ERROR", JOptionPane.DEFAULT_OPTION); pass1.requestFocus(); return; } if (pass2.getText() == null || pass2.getText().equals("")) { JOptionPane.showMessageDialog( null, "Confirm your password", "ERROR", JOptionPane.DEFAULT_OPTION); pass2.requestFocus(); return; } if (!pass1.getText().equals(pass2.getText())) { JOptionPane.showMessageDialog( null, "passwords do not match.", "ERROR", JOptionPane.DEFAULT_OPTION); pass2.requestFocus(); return; } try { Statement statement = Connect.getConnection().createStatement(); { String temp = "INSERT INTO users (Name,Category,username, password) VALUES ('" + name.getText() + "', '" + combo1.getSelectedItem() + "', '" + txtusername.getText() + "', '" + pass1.getText() + "')"; int result = statement.executeUpdate(temp); JOptionPane.showMessageDialog( null, "User is succesfully added", "SUCCESS", JOptionPane.DEFAULT_OPTION); dispose(); } } catch (Exception in) { in.printStackTrace(); } } }); button2.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); }
public ReadOnlyTableCellEditor(JTextField tf) { super(tf); tf.addFocusListener(new EditFocusAdapter(this)); tf.addKeyListener(new CopyKeyAdapter()); }
public void toggleTextField(boolean value) { inputText.setEnabled(value); }
/** * Creates this account on the server. * * @return the created account */ public NewAccount createAccount() { // Check if the two passwords match. String pass1 = new String(passField.getPassword()); String pass2 = new String(retypePassField.getPassword()); if (!pass1.equals(pass2)) { showErrorMessage( IppiAccRegWizzActivator.getResources() .getI18NString("plugin.sipaccregwizz.NOT_SAME_PASSWORD")); return null; } NewAccount newAccount = null; try { StringBuilder registerLinkBuilder = new StringBuilder(registerLink); registerLinkBuilder .append(URLEncoder.encode("email", "UTF-8")) .append("=") .append(URLEncoder.encode(emailField.getText(), "UTF-8")) .append("&") .append(URLEncoder.encode("password", "UTF-8")) .append("=") .append(URLEncoder.encode(new String(passField.getPassword()), "UTF-8")) .append("&") .append(URLEncoder.encode("display_name", "UTF-8")) .append("=") .append(URLEncoder.encode(displayNameField.getText(), "UTF-8")) .append("&") .append(URLEncoder.encode("username", "UTF-8")) .append("=") .append(URLEncoder.encode(usernameField.getText(), "UTF-8")) .append("&") .append(URLEncoder.encode("user_agent", "UTF-8")) .append("=") .append(URLEncoder.encode("sip-communicator.org", "UTF-8")); URL url = new URL(registerLinkBuilder.toString()); URLConnection conn = url.openConnection(); // If this is not an http connection we have nothing to do here. if (!(conn instanceof HttpURLConnection)) { return null; } HttpURLConnection httpConn = (HttpURLConnection) conn; int responseCode = httpConn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // Read all the text returned by the server BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String str; StringBuffer stringBuffer = new StringBuffer(); while ((str = in.readLine()) != null) { stringBuffer.append(str); } if (logger.isInfoEnabled()) logger.info("JSON response to create account request: " + stringBuffer.toString()); newAccount = parseHttpResponse(stringBuffer.toString()); } } catch (MalformedURLException e1) { if (logger.isInfoEnabled()) logger.info("Failed to create URL with string: " + registerLink, e1); } catch (IOException e1) { if (logger.isInfoEnabled()) logger.info("Failed to open connection.", e1); } return newAccount; }
public void actionPerformed(ActionEvent e) { saveOld(); area1.setText(""); resetArea2(); try { clientSocket = new Socket(ipaddress.getText(), Integer.parseInt(portNumber.getText())); Random r = new Random(); serverport = 10000 + r.nextInt(8999); // random port :D serverSocket = new ServerSocket(serverport); active = true; editor.setTitleToListen(); connected = true; ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream()); ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream()); output.writeObject(new JoinNetworkRequest(serverport)); ConnectionData data = getConnectionData(clientSocket, input); lc = new LamportClock(data.getId()); lc.setMaxTime(data.getTs()); dec = new DocumentEventCapturer(lc, editor); er = new EventReplayer(editor, dec, lc); ert = new Thread(er); ert.start(); Peer peer = new Peer( editor, er, data.getHostId(), clientSocket, output, input, lc, clientSocket.getInetAddress().getHostAddress(), data.getPort()); dec.addPeer(peer); Thread thread = new Thread(peer); thread.start(); er.setAcknowledgements(data.getAcknowledgements()); er.setEventHistory(data.getEventHistory()); er.setCarets(data.getCarets()); er.addCaretPos(lc.getID(), 0); for (PeerWrapper p : data.getPeers()) { Socket socket; try { socket = connectToPeer(p.getIP(), p.getPort()); ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream()); ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream()); outputStream.writeObject( new NewPeerDataRequest(lc.getID(), serverSocket.getLocalPort(), 0)); Peer newPeer = new Peer( editor, er, p.getId(), socket, outputStream, inputStream, lc, p.getIP(), p.getPort()); dec.addPeer(newPeer); Thread t = new Thread(newPeer); t.start(); } catch (IOException ex) { continue; } } Thread t1 = new Thread( new Runnable() { @Override public void run() { waitForConnection(); } }); t1.start(); area1.setText(data.getTextField()); area1.setCaretPosition(0); setDocumentFilter(dec); dec.sendObjectToAllPeers(new UnlockRequest(lc.getTimeStamp())); changed = false; Connect.setEnabled(false); Disconnect.setEnabled(true); Listen.setEnabled(false); Save.setEnabled(false); SaveAs.setEnabled(false); } catch (NumberFormatException | IOException e1) { setTitle("Unable to connect"); } }
/** Selects the text on gaining the focus. */ public void requestFocus() { super.requestFocus(); selectAll(); }