C #, выравнивание в текстовом поле [дубликат]

Как уже упоминалось ранее, org.apache.http.client.HttpClient больше не поддерживается:

SDK (уровень API) # 23.

Вы должны использовать java.net.HttpURLConnection.

Если вы хотите сделать свой код (и жизнь) проще при использовании HttpURLConnection, вот Wrapper этого класса, позволит вам выполнять простые операции с GET, POST и PUT с помощью JSON, например, с помощью HTTP PUT.

HttpRequest request = new HttpRequest(API_URL + PATH).addHeader("Content-Type", "application/json");
int httpCode = request.put(new JSONObject().toString());
if (HttpURLConnection.HTTP_OK == httpCode) {
    response = request.getJSONObjectResponse();
} else {
  // log error
}
httpRequest.close()

Не стесняйтесь использовать его.

package com.calculistik.repository;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * <p>
 * Copyright © 2017, Calculistik . All rights reserved.
 * <p>
 * Oracle and Java are registered trademarks of Oracle and/or its
 * affiliates. Other names may be trademarks of their respective owners.
 * <p>
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common
 * Development and Distribution License("CDDL") (collectively, the
 * "License"). You may not use this file except in compliance with the
 * License. You can obtain a copy of the License at
 * https://netbeans.org/cddl-gplv2.html or
 * nbbuild/licenses/CDDL-GPL-2-CP. See the License for the specific
 * language governing permissions and limitations under the License.
 * When distributing the software, include this License Header
 * Notice in each file and include the License file at
 * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this particular file
 * as subject to the "Classpath" exception as provided by Oracle in the
 * GPL Version 2 section of the License file that accompanied this code. If
 * applicable, add the following below the License Header, with the fields
 * enclosed by brackets [] replaced by your own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 * <p>
 * Contributor(s):
 * Created by alejandro tkachuk @aletkachuk
 * www.calculistik.com
 */
public class HttpRequest {

    public static enum Method {
        POST, PUT, DELETE, GET;
    }

    private URL url;
    private HttpURLConnection connection;
    private OutputStream outputStream;
    private HashMap<String, String> params = new HashMap<String, String>();

    public HttpRequest(String url) throws IOException {
        this.url = new URL(url);
        connection = (HttpURLConnection) this.url.openConnection();
    }

    public int get() throws IOException {
        return this.send();
    }

    public int post(String data) throws IOException {
        connection.setDoInput(true);
        connection.setRequestMethod(Method.POST.toString());
        connection.setDoOutput(true);
        outputStream = connection.getOutputStream();
        this.sendData(data);
        return this.send();
    }

    public int post() throws IOException {
        connection.setDoInput(true);
        connection.setRequestMethod(Method.POST.toString());
        connection.setDoOutput(true);
        outputStream = connection.getOutputStream();
        return this.send();
    }

    public int put(String data) throws IOException {
        connection.setDoInput(true);
        connection.setRequestMethod(Method.PUT.toString());
        connection.setDoOutput(true);
        outputStream = connection.getOutputStream();
        this.sendData(data);
        return this.send();
    }

    public int put() throws IOException {
        connection.setDoInput(true);
        connection.setRequestMethod(Method.PUT.toString());
        connection.setDoOutput(true);
        outputStream = connection.getOutputStream();
        return this.send();
    }

    public HttpRequest addHeader(String key, String value) {
        connection.setRequestProperty(key, value);
        return this;
    }

    public HttpRequest addParameter(String key, String value) {
        this.params.put(key, value);
        return this;
    }

    public JSONObject getJSONObjectResponse() throws JSONException, IOException {
        return new JSONObject(getStringResponse());
    }

    public JSONArray getJSONArrayResponse() throws JSONException, IOException {
        return new JSONArray(getStringResponse());
    }

    public String getStringResponse() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        for (String line; (line = br.readLine()) != null; ) response.append(line + "\n");
        return response.toString();
    }

    public byte[] getBytesResponse() throws IOException {
        byte[] buffer = new byte[8192];
        InputStream is = connection.getInputStream();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        for (int bytesRead; (bytesRead = is.read(buffer)) >= 0; )
            output.write(buffer, 0, bytesRead);
        return output.toByteArray();
    }

    public void close() {
        if (null != connection)
            connection.disconnect();
    }

    private int send() throws IOException {
        int httpStatusCode = HttpURLConnection.HTTP_BAD_REQUEST;

        if (!this.params.isEmpty()) {
            this.sendData();
        }
        httpStatusCode = connection.getResponseCode();

        return httpStatusCode;
    }

    private void sendData() throws IOException {
        StringBuilder result = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            result.append((result.length() > 0 ? "&" : "") + entry.getKey() + "=" + entry.getValue());//appends: key=value (for first param) OR &key=value(second and more)
        }
        sendData(result.toString());
    }

    private HttpRequest sendData(String query) throws IOException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(query);
        writer.close();
        return this;
    }

}
13
задан Daniel Hilgarth 2 September 2011 в 15:49
поделиться

4 ответа

Можете ли вы установить шрифт в текстовом поле на моноширинный один?

В коде, сохраняющем тот же размер, что и шрифт по умолчанию:

textBox.Font = new Font(FontFamily.GenericMonospace, textBox.Font.Size);

Или просто измените свойство Font в дизайнере.

30
ответ дан Jon Skeet 17 August 2018 в 20:50
поделиться
  • 1
    Выучили новое слово, что такое моноширинные шрифты? – Mark Lalor 2 September 2011 в 15:49
  • 2
  • 3
    Можно ли использовать шрифт вроде consolas, потому что я думаю, что я сам его установил или все шрифты VS поставляются с картой .net? – Mark Lalor 2 September 2011 в 15:52
  • 4
    @Mark: Кажется, я помню, что Consolas поставляется с Office ... Я не помню, что произойдет, если вы укажете шрифт, которого нет в развернутой системе. Кто ваши пользователи? – Jon Skeet 2 September 2011 в 15:57
  • 5
    Создавая приложение для гитарных аккордов и вкладок, общий ролик кажется прекрасным, но есть способ просто упаковать шрифт с помощью приложения – Mark Lalor 2 September 2011 в 16:00

Вы можете сделать это, используя шрифт с фиксированной шириной. Шрифты Courier Family часто фиксируются.

Вы можете установить шрифт в редакторе свойств для элемента управления текстовым полем. Например, вы можете сохранить свойство шрифта в Courier New, 8.25pt.

5
ответ дан B Pete 17 August 2018 в 20:50
поделиться

Попробуйте использовать шрифты с моноширинной или фиксированной шириной.

0
ответ дан Mark Menchavez 17 August 2018 в 20:50
поделиться

Некоторые шрифты используют разные ширины символов для разных символов. В таких шрифтах «m» будет иметь большую ширину, чем «i». Они называются пропорциональными шрифтами. Эти шрифты имеют приятный вид и их легче читать.

Шрифты, где все символы имеют одинаковую ширину, называются моноширинными шрифтами. Они часто используются для исходного кода, поскольку они позволяют выравнивать функции, такие как комментарии к строке справа от кода.

Использовать моноширинный шрифт!

Вот код, который я использую для получения списка всех установленных моноширинных шрифтов:

using System;
using System.Drawing;
using System.Runtime.InteropServices;

namespace PE.Rendering {

    static class FontHelper {

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        class LOGFONT {
            public int lfHeight;
            public int lfWidth;
            public int lfEscapement;
            public int lfOrientation;
            public int lfWeight;
            public byte lfItalic;
            public byte lfUnderline;
            public byte lfStrikeOut;
            public byte lfCharSet;
            public byte lfOutPrecision;
            public byte lfClipPrecision;
            public byte lfQuality;
            public byte lfPitchAndFamily;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
            public string lfFaceName;
        }

        static bool IsMonospaced(Graphics g, Font f)
        {
            float w1, w2;

                w1 = g.MeasureString("i", f).Width;
                w2 = g.MeasureString("W", f).Width;
                return w1 == w2;
        }

        static bool IsSymbolFont(Font font)
        {
            const byte SYMBOL_FONT = 2;

            LOGFONT logicalFont = new LOGFONT();
            font.ToLogFont(logicalFont);
            return logicalFont.lfCharSet == SYMBOL_FONT;
        }

        /// <summary>
        /// Tells us, if a font is suitable for displaying document.
        /// </summary>
        /// <remarks>Some symbol fonts do not identify themselves as such.</remarks>
        /// <param name="fontName"></param>
        /// <returns></returns>
        static bool IsSuitableFont(string fontName)
        {
            return !fontName.StartsWith("ESRI") && !fontName.StartsWith("Oc_");
        }

        public static List<string> GetMonospacedFontNames()
        {
            List<string> fontList = new List<string>();
            InstalledFontCollection ifc;

            ifc = new InstalledFontCollection();
            using (Bitmap bmp = new Bitmap(1, 1)) {
                using (Graphics g = Graphics.FromImage(bmp)) {
                    foreach (FontFamily ff in ifc.Families) {
                        if (ff.IsStyleAvailable(FontStyle.Regular) && ff.IsStyleAvailable(FontStyle.Bold) 
                            && ff.IsStyleAvailable(FontStyle.Italic) && IsSuitableFont( ff.Name)) {
                            using (Font f = new Font(ff, 10)) {
                                if (IsMonospaced(g,f) && !IsSymbolFont(f)) {
                                    fontList.Add(ff.Name);
                                }
                            }
                        }
                    }
                }
            }
            return fontList;
        }
    }

}
3
ответ дан Olivier Jacot-Descombes 17 August 2018 в 20:50
поделиться
Другие вопросы по тегам:

Похожие вопросы: