Форум программистов, компьютерный форум, киберфорум
Java: GUI, графика
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.83/6: Рейтинг темы: голосов - 6, средняя оценка - 4.83
0 / 0 / 0
Регистрация: 26.09.2017
Сообщений: 3

Не выводит текст в JTextArea

26.09.2017, 18:33. Показов 1329. Ответов 1

Студворк — интернет-сервис помощи студентам
Есть простое клиент-серверное приложение на сокетах (парсит математические выражения и выдаёт ответ). При сборке и запуске через jar файлы у клиента не обновляется JTextArea. Хотя при запуске клиента через IDEA всё работает нормально. Сборку делаю через ant.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public class TCPConnection {
 
    private final Socket socket;
    private final Thread thread;
    private final TCPConnectionListener eventListener;
    private final BufferedReader in;
    private final BufferedWriter out;
 
 
    public TCPConnection(TCPConnectionListener eventListener, String ipAddr, int port) throws IOException {
        this(eventListener, new Socket(ipAddr, port));
    }
 
    public TCPConnection(TCPConnectionListener eventListener, Socket socket) throws IOException {
        this.eventListener = eventListener;
        this.socket = socket;
        in = new BufferedReader(new InputStreamReader(socket.getInputStream(), Charset.forName("UTF-8")));
        out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), Charset.forName("UTF-8")));
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    eventListener.onConnectionReady(TCPConnection.this);
                    while (!thread.isInterrupted()) {
                        eventListener.onReceiveString(TCPConnection.this, in.readLine());
                    }
                } catch (IOException e) {
                    eventListener.onException(TCPConnection.this, e);
                }
            }
        });
        thread.start();
    }
 
    public synchronized void sendString(String value) {
        try {
            out.write(value + "\r\n");
            out.flush();
        } catch (IOException e) {
            eventListener.onException(this, e);
            disconnect();
        }
    }
 
    public synchronized void disconnect() {
        thread.interrupt();
        try {
            socket.close();
        } catch (IOException e) {
            eventListener.onException(this, e);
        }
    }
 
    @Override
    public String toString() {
        return "TCPConnection: " + socket.getInetAddress() + ": " + socket.getPort();
    }
 
}
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
public class Client extends JFrame implements ActionListener, TCPConnectionListener {
 
    private static final String IP_ADDRESS = "localhost";
    private static final int PORT = 8189;
    private static int WIDTH = 600;
    private static int HEIGHT = 400;
 
    private TCPConnection connection;
    private int port;
    private String host;
 
    public static void main(String[] args) {
        String address = args.length <= 0 ? IP_ADDRESS : args[0];
        int port = args.length <= 0 ? PORT : Integer.parseInt(args[1]);
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Client(address, port);
            }
        });
    }
 
    private final JTextArea log = new JTextArea();
    private final JTextField fieldInput = new JTextField();
 
    public Client(String host, int port) {
 
        this.port = port;
        this.host = host;
 
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(WIDTH, HEIGHT);
        setLocationRelativeTo(null);
        setVisible(true);
        log.setEditable(false);
        log.setLineWrap(true);
        fieldInput.addActionListener(this);
 
        add(log, BorderLayout.CENTER);
        add(fieldInput, BorderLayout.SOUTH);
        add(new JScrollPane(log), BorderLayout.CENTER);
 
        setVisible(true);
 
        try {
            connection = new TCPConnection(this, host, port);
        } catch (IOException e) {
            printMessage("Connection exception: " + e);
        }
    }
 
    @Override
    public void actionPerformed(ActionEvent e) {
        String msg = fieldInput.getText();
        if (msg.equals("")) return;
        fieldInput.setText("");
        connection.sendString(msg + " = " + Calculator.calculate(msg));
    }
 
 
    @Override
    public void onConnectionReady(TCPConnection tcpConnection) {
        printMessage("Connection ready! Address: " + host + ", Port: " + port);
        printMessage("Please enter a expression in style like this: 18*(20-12)+40/2*(2+6)");
    }
 
    @Override
    public void onReceiveString(TCPConnection tcpConnection, String value) {
        printMessage(value);
    }
 
    @Override
    public void onException(TCPConnection connection, Exception ex) {
        printMessage("Connection exception: " + ex);
    }
 
    private synchronized void printMessage(String msg) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                log.append(msg + "\r\n");
                log.setCaretPosition(log.getDocument().getLength());
            }
        });
    }
}
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class Server implements TCPConnectionListener {
 
    private final static int PORT = 8189;
    private final static String IP_ADDRESS = "localhost";
 
 
    public static void main(String[] args) {
        String address = args.length <= 0 ? IP_ADDRESS : args[0];
        int port = args.length <= 0 ? PORT : Integer.parseInt(args[1]);
        new Server(address,port);
    }
 
    private TCPConnection tcpConnection;
 
    public Server(String address, int port) {
        System.out.println("Server runner");
 
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            while (true) {
                try {
                    tcpConnection = new TCPConnection(this, serverSocket.accept());
                } catch (IOException e){
                    System.out.println("TCPConnection exception: " + e);
                }
            }
        } catch (IOException ex) {
            throw new RuntimeException();
        }
 
    }
 
    @Override
    public synchronized void onConnectionReady(TCPConnection tcpConnection) {
        tcpConnection.sendString("Client connected: "+ tcpConnection);
    }
 
    @Override
    public synchronized void onReceiveString(TCPConnection tcpConnection, String value) {
        tcpConnection.sendString(value);
    }
 
    @Override
    public synchronized void onException(TCPConnection connection, Exception ex) {
        System.out.println("TCPConnection exception: " + ex);
    }
 
}
XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?xml version="1.0" encoding="UTF-8"?>
<project name="Calculator" basedir="." default="run">
 
    <property name="src.dir"  value="./src"/>
    <property name="build.dir" value="./classes"/>
    <property name="classes.dir" value="./classes"/>
    <property name="jar.dir"   value="${build.dir}/jar"/>
    <property name="client-class"  value="com.test.calc.Client"/>
    <property name="server-class" value="com.test.calc.Server"/>
    <property name="junit" value="lib/junit-4.12.jar"/>
 
    <property name="lib.dir"  value="${basedir}/lib"/>
 
    <path id="classpath">
        <fileset dir="${lib.dir}">
            <include name="**/*.jar" />
        </fileset>
    </path>
 
    <path id = "classpath.test">
        <pathelement location = "${junit}" />
        <pathelement location = "${src.dir}" />
        <path refid = "classpath" />
    </path>
 
    <target name="clean">
        <delete dir="${build.dir}"/>
    </target>
 
    <target name="compile" depends="clean">
        <mkdir dir="${classes.dir}"/>
        <javac srcdir="${src.dir}" destdir="${classes.dir}" classpathref="classpath" includeantruntime="false"/>
        <mkdir dir="${classes.dir}/lib"/>
        <copy todir="${classes.dir}/lib">
            <fileset dir="${lib.dir}">
                <include name="**/*.jar"/>
            </fileset>
        </copy>
    </target>
 
    <target name="build" depends="compile">
        <mkdir dir="${jar.dir}"/>
        <jar destfile="${jar.dir}/Client.jar" basedir="${classes.dir}">
            <manifest>
            <attribute name="Main-Class" value="${client-class}"/>
        </manifest>
        </jar>
        <jar destfile="${jar.dir}/Server.jar" basedir="${classes.dir}">
            <manifest>
                <attribute name="Main-Class" value="${server-class}"/>
            </manifest>
        </jar>
    </target>
 
    <target name="run" depends="build">
        <parallel>
        <java jar="${jar.dir}/Server.jar" fork="true"/>
        <java jar="${jar.dir}/Client.jar" fork="true"/>
    </parallel>
    </target>
 
 
    <target name="test" depends="compile">
        <junit printsummary="on" fork="true" showoutput="true">
            <classpath path="${classes.dir}">
                <path refid="classpath" />
            </classpath>
            <formatter type="brief" usefile="false"/>
            <test name="test_class.CalculatorTest"/>
        </junit>
    </target>
 
</project>
Парсинг делаю через стороннюю либу. В анте её подкачиваю в jar файл клиента.
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
26.09.2017, 18:33
Ответы с готовыми решениями:

Не выводит результат в jTextArea
Здравствуйте, нужна помощь. Не могу вывести результат в интерфейс. Код класса откуда я хочу вывести результат public class...

Текст в JTextArea
Вот мой класс. Обычный фрейм в который должен выводится текст. import java.awt.*; import javax.swing.*; import...

Как в (JTextArea,TextArea) красить текст?
Ne poskajete, kak na Java, a imenno (JTextArea,TextArea) krasit' text. naprimer zagolovki -&gt; krasnim cvetom komentarii serim cvetom...

1
Эксперт Java
3639 / 2971 / 918
Регистрация: 05.07.2013
Сообщений: 14,220
26.09.2017, 19:46
Цитата Сообщение от twikk Посмотреть сообщение
Сборку делаю через ant
зачем?
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
26.09.2017, 19:46
Помогаю со студенческими работами здесь

Подсвечивать другим цветом текст в JTextArea
Ребята помогите пожалуйста реализовать программку.

Разъезжаются объекты swing когда пишу текст в JTextArea
Доброго времени суток. Когда пишу текст в форму JTextArea JPanel растягивается в ширину. В конечном итоге пропадает вся панель. В чем...

JPanel panel_south=new JPanel(); JTextArea textArea=new JTextArea(); Где ошибка?
JPanel panel_south=new JPanel(); JTextArea textArea=new JTextArea(); Label label=new JLabel(' '); ...

Прочитать письмо - программа выводит отправителя, но не выводит текст письма
получаю id письма IdMessage1.MsgId; считываю if pop.Connected then pop.Disconnect; pop.Host:= server; ...

Написать программу, которая считывает текст из файла и выводит на экран количество гласных букв в строке текст
Написать программу, которая считывает текст из файла и выводит на экран количество гласных букв в строке текста


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Синхронизация спрайтов SDL3 и тел Box2D
8Observer8 04.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-sync-physics-sprites-sdl3-c. zip На первой гифке отладочные линии отключены, а на второй включены:. . .
SDL3 для Web (WebAssembly): Идентификация объектов на Box2D v3 - использование userData и событий коллизий
8Observer8 02.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-collision-events-sdl3-c. zip https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11680&amp;d=1772460536 Одним из. . .
Реалии
Hrethgir 01.03.2026
Нет, я не закончил до сих пор симулятор. Эта задача сложнее. Не получилось уйти в плавсостав, но оно и к лучшему, возможно. Точнее получалось - но сварщиком в палубную команду, а это значит, в моём. . .
Ритм жизни
kumehtar 27.02.2026
Иногда приходится жить в ритме, где дел становится всё больше, а вовлечения в происходящее — всё меньше. Плотный график не даёт вниманию закрепиться ни на одном событии. Утро начинается с быстрых,. . .
SDL3 для Web (WebAssembly): Сборка библиотек: SDL3, Box2D, FreeType, SDL3_ttf, SDL3_mixer и SDL3_image из исходников с помощью CMake и Emscripten
8Observer8 27.02.2026
Недавно вышла версия 3. 4. 2 библиотеки SDL3. На странице официальной релиза доступны исходники, готовые DLL (для x86, x64, arm64), а также библиотеки для разработки под Android, MinGW и Visual Studio. . . .
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru