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

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

26.09.2017, 18:33. Показов 1308. Ответов 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
Ответ Создать тему
Новые блоги и статьи
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост.
Programma_Boinc 28.12.2025
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост. Налог на собак: https:/ / **********/ gallery/ V06K53e Финансовый отчет в Excel: https:/ / **********/ gallery/ bKBkQFf Пост отсюда. . .
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США.
Programma_Boinc 26.12.2025
Нашел на реддите интересную статью под названием Anyone know where to get a free Desktop or Laptop? Ниже её машинный перевод. После долгих разбирательств я наконец-то вернула себе. . .
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Рецензия / Мнение/ Перевод Нашел на реддите интересную статью под названием The Thinkpad X220 Tablet is the best budget school laptop period . Ниже её машинный перевод. Thinkpad X220 Tablet —. . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru