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

KeyListener. Не работает ввод с клавиатуры

05.04.2018, 13:22. Показов 2447. Ответов 9
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.KeyEventDispatcher;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
 
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
 
import com.sun.xml.internal.ws.api.Component;
 
public class C1 extends JFrame {
 
    JButton b0 = new JButton("0");
    JButton b1 = new JButton("1");
    JButton b2 = new JButton("2");
    JButton b3 = new JButton("3");
    JButton b4 = new JButton("4");
    JButton b5 = new JButton("5");
    JButton b6 = new JButton("6");
    JButton b7 = new JButton("7");
    JButton b8 = new JButton("8");
    JButton b9 = new JButton("9");
    JButton b10 = new JButton("+");
    JButton b11 = new JButton("-");
    JButton b12 = new JButton("*");
    JButton b13 = new JButton("/");
    JButton b14 = new JButton("=");
    JButton b15 = new JButton("CE");
    JButton b16 = new JButton("<-");
    JButton b17 = new JButton("CLOSE");
 
    JTextField t = new JTextField();
    boolean bb;
    
    
    public C1(String name) {
        super("Калькулятор");
        setLayout(null);
        setSize(300, 400);
        t.setBounds(10, 10, 260, 50);
        t.setEditable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
 
        setVisible(true);
 
        b0.setBounds(60, 220, 50, 50);
        b0.setBackground(Color.BLUE);
        b1.setBounds(10, 70, 50, 50);
        b2.setBounds(60, 70, 50, 50);
        b3.setBounds(110, 70, 50, 50);
        b4.setBounds(10, 120, 50, 50);
        b5.setBounds(60, 120, 50, 50);
        b6.setBounds(110, 120, 50, 50);
        b7.setBounds(10, 170, 50, 50);
        b8.setBounds(60, 170, 50, 50);
        b9.setBounds(110, 170, 50, 50);
        b10.setBounds(10, 220, 50, 50);
        b10.setBackground(Color.CYAN);
        b11.setBounds(110, 220, 50, 50);
 
        b12.setBounds(160, 70, 50, 50);
        b13.setBounds(160, 120, 50, 50);
        b14.setBounds(160, 170, 50, 50);
        b15.setBounds(160, 220, 50, 50);
        b16.setBounds(210, 70, 60, 200);
        b17.setBounds(10, 270, 100, 70);
        add(b0);
        add(b1);
        add(b2);
        add(b3);
        add(b4);
        add(b5);
        add(b6);
        add(b7);
        add(b8);
        add(b9);
        add(b10);
        add(b11);
        add(b12);
        add(b13);
        add(b14);
        add(b15);
        add(b16);
        add(b17);
        add(t);
        
        b17.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
 
                System.exit(0);
            }
        });
        
    b0.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_NUMPAD0) {
                t.setText(t.getText() + "0");
 
            }
        }
 
    });
    
    }
}
            
Так же мне надо создать возможность попеременного ввода с клавиатуры и по нажатию JButton
вот пример кода:
 
        b2.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "2");
 
            }
 
        });
        b2.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_NUMPAD2) {
                    t.setText(t.getText() + "2");
                }
            }
        });
KeyListener работает только после нажатия JButton с соответствующей цифрой.
Надо сделать через Runnable. Я не знаю как.
Прошу совета.
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
05.04.2018, 13:22
Ответы с готовыми решениями:

Не работает keylistener
package net.drmgc.PingPong; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import...

KeyListener не работает
События от кнопок клавиатуры (коды 37,38,39,40) не воспринимаются. Я убирал из кода программы Кнопку (Старт - Стоп), но оставлял Таймер...

Не работает KeyListener
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import...

9
13 / 11 / 10
Регистрация: 23.09.2017
Сообщений: 95
06.04.2018, 12:49
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package com.antoniointerprise;
 
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
 
public class C1 extends JFrame {
    JButton b0 = new JButton("0");
    JButton b1 = new JButton("1");
    JButton b2 = new JButton("2");
    JButton b3 = new JButton("3");
    JButton b4 = new JButton("4");
    JButton b5 = new JButton("5");
    JButton b6 = new JButton("6");
    JButton b7 = new JButton("7");
    JButton b8 = new JButton("8");
    JButton b9 = new JButton("9");
    JButton b10 = new JButton("+");
    JButton b11 = new JButton("-");
    JButton b12 = new JButton("*");
    JButton b13 = new JButton("/");
    JButton b14 = new JButton("=");
    JButton b15 = new JButton("CE");
    JButton b16 = new JButton("<-");
    JButton b17 = new JButton("CLOSE");
 
    JTextField t = new JTextField();
    boolean bb = false;
 
    public static void main(String[] args){
        C1 c = new C1();
        c.start();
    }
 
    public void start() {
        setTitle("Калькулятор");
        setLayout(null);
        setSize(300, 400);
        t.setBounds(10, 10, 260, 50);
        t.setEditable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
 
        setVisible(true);
 
        b0.setBounds(60, 220, 50, 50);
        b0.setBackground(Color.BLUE);
        b1.setBounds(10, 70, 50, 50);
        b2.setBounds(60, 70, 50, 50);
        b3.setBounds(110, 70, 50, 50);
        b4.setBounds(10, 120, 50, 50);
        b5.setBounds(60, 120, 50, 50);
        b6.setBounds(110, 120, 50, 50);
        b7.setBounds(10, 170, 50, 50);
        b8.setBounds(60, 170, 50, 50);
        b9.setBounds(110, 170, 50, 50);
        b10.setBounds(10, 220, 50, 50);
        b10.setBackground(Color.CYAN);
        b11.setBounds(110, 220, 50, 50);
 
        b12.setBounds(160, 70, 50, 50);
        b13.setBounds(160, 120, 50, 50);
        b14.setBounds(160, 170, 50, 50);
        b15.setBounds(160, 220, 50, 50);
        b16.setBounds(210, 70, 60, 200);
        b17.setBounds(10, 270, 100, 70);
 
        action();
 
        add(b0);
        add(b1);
        add(b2);
        add(b3);
        add(b4);
        add(b5);
        add(b6);
        add(b7);
        add(b8);
        add(b9);
        add(b10);
        add(b11);
        add(b12);
        add(b13);
        add(b14);
        add(b15);
        add(b16);
        add(b17);
        add(t);
    }
 
    public void action() {
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                bb = true;
                for(int i = 0; i < 9; i++) {
                    if (e.getKeyCode() == 96+i) {
                        t.setText(t.getText() + i);
                    }
                }
            }
        });
 
        b17.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.exit(0);
            }
        });
    }
}
нажатие кнопок делай по примеру с b17
Java
1
2
3
4
5
6
 b17.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.exit(0);
            }
        });
0
0 / 0 / 0
Регистрация: 01.04.2018
Сообщений: 29
07.04.2018, 01:04  [ТС]
Добавлено через 10 минут
У меня остался только 1 вопрос. Что такое 96?

molodoyparen ОГРОМНОЕ ВАМ СПАСИБО ЗА ПОМОЩЬ

Добавлено через 41 минуту
molodoyparen вы знаете, всё -равно после добавления слушателя мыши на JButton и, при нажатии на JButton перестаёт работать ввод с клавиатуры.
При добавлении по примеру с b17 и нажатии на JButton перестаёт работать ввод с клавиатуры.
Походы надо делать через Runnable, если есть возможность напишите как сделать через Runnable
0
13 / 11 / 10
Регистрация: 23.09.2017
Сообщений: 95
07.04.2018, 14:22
DDD7555, Прошу прощения, нужно было через ActionListener а не MouseListener, теперь все работает
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import org.w3c.dom.events.Event;
 
import java.awt.Color;
import java.awt.event.*;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.*;
 
public class C1 extends JFrame implements Runnable {
    JPanel panel = new JPanel();
    JButton b[] = new JButton[18]; // Массив кнопок от [0]-[9] будут цифры, остальное - другие функции
    JTextField t = new JTextField();
 
    public static void main(String[] args){
        C1 c = new C1();
        c.run();
    }
 
    @Override
    public void run() {
        setTitle("Калькулятор");
        panel.setLayout(null);
        setSize(300, 400);
        t.setBounds(10, 10, 260, 50);
        t.setEditable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        for(int i = 0; i < b.length; i++){
            if(i<10) {
                b[i] = new JButton(String.valueOf(i)); // Инициализируем кнопки и добавляем текст
                actionNumb(b[i]); // Для клавиш от 0 к 9
            }
            else
                b[i] = new JButton();
        }
 
        b[10] = new JButton("+");
        b[11] = new JButton("-");
        b[12] = new JButton("*");
        b[13] = new JButton("/");
        b[14] = new JButton("=");
        b[15] = new JButton("CE");
        b[16] = new JButton("<-");
        b[17] = new JButton("CLOSE");
 
 
        b[0].setBounds(60, 220, 50, 50);
        b[0].setBackground(Color.BLUE);
        b[1].setBounds(10, 70, 50, 50);
        b[2].setBounds(60, 70, 50, 50);
        b[3].setBounds(110, 70, 50, 50);
        b[4].setBounds(10, 120, 50, 50);
        b[5].setBounds(60, 120, 50, 50);
        b[6].setBounds(110, 120, 50, 50);
        b[7].setBounds(10, 170, 50, 50);
        b[8].setBounds(60, 170, 50, 50);
        b[9].setBounds(110, 170, 50, 50);
        b[10].setBounds(10, 220, 50, 50);
        b[10].setBackground(Color.CYAN);
        b[11].setBounds(110, 220, 50, 50);
        b[12].setBounds(160, 70, 50, 50);
        b[13].setBounds(160, 120, 50, 50);
        b[14].setBounds(160, 170, 50, 50);
        b[15].setBounds(160, 220, 50, 50);
        b[16].setBounds(210, 70, 60, 200);
        b[17].setBounds(10, 270, 100, 70);
 
        for(int i = 0; i < b.length; i++) {
            b[i].setFocusable(false); // Что-бы не было проблем с фокусом
        }
 
        action(); // Добавляем слушателя и прочее для всего остального
 
        for(int i = 0; i < b.length; i++){
            panel.add(b[i]);
        }
        panel.add(t);
 
        panel.setBackground(Color.WHITE);
        this.add(panel);
        setVisible(true);
    }
 
    public void actionNumb(JButton butt){ // Для чисел от 0 к 9
        butt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + butt.getText());
            }
        });
    }
 
    public void action() {
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) { // Если мышь весит на JFrame
                requestFocusInWindow(); // тогда фокус всеравно будет на форме для Нумпада
            }
 
            @Override
            public void mouseExited(MouseEvent e) { // И если выйдет с формы на любой другой компонент
                requestFocusInWindow();
            }
        });
 
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                for(int i = 0; i < 9; i++) {
                    if (e.getKeyCode() == 96 + i) { // от 96 к 105 - Номер кнопок на нумпаде от 0 к 9
                        t.setText(t.getText() + i);
                    }
                }
            }
        });
 
        b[17].addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
 
        b[16].addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) { // Для <-
                String str = t.getText();
                String newStr = "";
                char[] chrStr = str.toCharArray();
 
                for(int i = 0; i < chrStr.length - 1; i++){
                    newStr += chrStr[i];
                }
                t.setText(newStr);
            }
        });
 
        b[14].addActionListener(new ActionListener() { // Это для = , пиши любое уровнение с множеством + - *... , оно все решит :)
            @Override
            public void actionPerformed(ActionEvent e) {
                ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
                String expression = t.getText();
 
                float result = 0;
                try {
                    result = Float.valueOf(engine.eval(expression).toString());
                    t.setText(String.valueOf(result));
                } catch (ScriptException e1) {
                    e1.printStackTrace();
                }
            }
        });
 
        b[10].addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + " + ");
            }
        });
 
        //   Для -, *, /, CE сам допишешь
 
    }
}
от 96 к 105 это цифры нумпада

Добавлено через 15 минут
И кнопки на нумпаде не работали через смену фокуса(исправил, читайте комментарии к коду)
1
0 / 0 / 0
Регистрация: 01.04.2018
Сообщений: 29
07.04.2018, 22:50  [ТС]
Большое спасибо. Завтра всё буду смотреть и догонять.
0
0 / 0 / 0
Регистрация: 01.04.2018
Сообщений: 29
17.04.2018, 23:27  [ТС]
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.KeyEventDispatcher;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
 
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
 
import com.sun.xml.internal.ws.api.Component;
 
public class C1 extends JFrame {
     
    JButton b0 = new JButton("0");
    JButton b1 = new JButton("1");
    JButton b2 = new JButton("2");
    JButton b3 = new JButton("3");
    JButton b4 = new JButton("4");
    JButton b5 = new JButton("5");
    JButton b6 = new JButton("6");
    JButton b7 = new JButton("7");
    JButton b8 = new JButton("8");
    JButton b9 = new JButton("9");
    JButton b10 = new JButton("+");
    JButton b11 = new JButton("-");
    JButton b12 = new JButton("*");
    JButton b13 = new JButton("/");
    JButton b14 = new JButton("=");
    JButton b15 = new JButton("CE");
    JButton b16 = new JButton("<-");
    JButton b17 = new JButton("CLOSE");
 
    JTextField t = new JTextField();
    boolean bb;
    
    
    public C1(String name) {
        super("Калькулятор");
        setLayout(null);
        setSize(300, 400);
        t.setBounds(10, 10, 260, 50);
        t.setEditable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
 
        setVisible(true);
 
        b0.setBounds(60, 220, 50, 50);
        b0.setBackground(Color.BLUE);
        b1.setBounds(10, 70, 50, 50);
        b2.setBounds(60, 70, 50, 50);
        b3.setBounds(110, 70, 50, 50);
        b4.setBounds(10, 120, 50, 50);
        b5.setBounds(60, 120, 50, 50);
        b6.setBounds(110, 120, 50, 50);
        b7.setBounds(10, 170, 50, 50);
        b8.setBounds(60, 170, 50, 50);
        b9.setBounds(110, 170, 50, 50);
        b10.setBounds(10, 220, 50, 50);
        b10.setBackground(Color.CYAN);
        b11.setBounds(110, 220, 50, 50);
 
        b12.setBounds(160, 70, 50, 50);
        b13.setBounds(160, 120, 50, 50);
        b14.setBounds(160, 170, 50, 50);
        b15.setBounds(160, 220, 50, 50);
        b16.setBounds(210, 70, 60, 200);
        b17.setBounds(10, 270, 100, 70);
        add(b0);
        add(b1);
        add(b2);
        add(b3);
        add(b4);
        add(b5);
        add(b6);
        add(b7);
        add(b8);
        add(b9);
        add(b10);
        add(b11);
        add(b12);
        add(b13);
        add(b14);
        add(b15);
        add(b16);
        add(b17);
        add(t);
        
 
 
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_F11) {
                System.exit(0);
            }
            }
        });
        
        b17.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                 System.exit(0);
 
            }
 
        });
 
 
 
            
        b0.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "0");
 
            }
 
        });
 
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                   for(int i = 0; i <= 9; i++) {
                        if (e.getKeyCode() == 96 + i || e.getKeyCode() == 48 + i) {
                             t.setText(t.getText() + i);
                            
                        }
                     
                    }
                }
                    });
        
        
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
            if(e.getKeyCode()==KeyEvent.VK_DIVIDE) {
                 t.setText(t.getText()+"/");
            }
            }
                
            });
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
            if(e.getKeyCode()==KeyEvent.VK_SUBTRACT || e.getKeyCode()==45) {
                 t.setText(t.getText()+"-");
            }
            }
                
            });
    
        
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
            if(e.getKeyCode()==KeyEvent.VK_ADD || e.getKeyCode()==16 && e.getKeyCode()==61) {
                 t.setText(t.getText()+"+");
            }
            }
            @Override
            public void keyTyped(KeyEvent e) {
                if(e.getKeyCode()==16+61) {
                     t.setText(t.getText()+"+");
                    
                }
            }
                
            });
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
            if(e.getKeyCode()==KeyEvent.VK_MULTIPLY) {
                 t.setText(t.getText()+"*");
            }
            }
                
            });
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
            if(e.getKeyCode()==KeyEvent.VK_DECIMAL) {
                 t.setText(t.getText()+".");
            }
            }
                
            });
        
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
            if(e.getKeyCode()==KeyEvent.VK_BACK_SPACE) {
                String temp= t.getText();
                 t.setText(temp.substring(0, temp.length()-1));
            }
            }
                
            });
        
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
            if(e.getKeyCode()==KeyEvent.VK_DELETE) {
                String temp= t.getText();
                 t.setText(temp.substring(0, temp.length()-temp.length()));
            }
            }
                
            });
        b14.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                ScriptEngine sm= new ScriptEngineManager().getEngineByName("JavaScript");       
                String totals=t.getText();
                float result=0;
                try {
                    result=Float.valueOf(sm.eval(totals).toString());
                    t.setText(String.valueOf(result));
                }
                catch (ScriptException e1) {
                    e1.printStackTrace();
                            }
            }
            
        });
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
            if(e.getKeyCode()==KeyEvent.VK_ENTER) {
                 ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
                    String expression = t.getText();
     
                    float result = 0;
                    try {
                        result = Float.valueOf(engine.eval(expression).toString());
                    t.setText(String.valueOf(result));
                    } catch (ScriptException e1) {
                        e1.printStackTrace();
                    }
                }
            }
            });
     
            
        b2.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "2");
 
            }
 
        });
    
        
        b3.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "3");
 
            }
 
        });
        
        b4.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "4");
 
            }
 
        });
    
        b5.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "5");
 
            }
 
        });
    
        b6.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "6");
 
            }
 
        });
        
 
        b7.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "7");
 
            }
 
        });
        
        b8.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "8");
 
            }
 
        });
    
        b9.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "9");
 
            }
 
        });
        
        b10.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "+");
 
            }
 
        });
        
        b11.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "-");
 
            }
 
        });
        
        b12.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "*");
 
            }
 
        });
        b13.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "/");
 
            }
 
        });
        
           
        b15.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "");
 
            }
 
        });
        b16.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "");
 
            }
 
        });
 
        b16.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String temp = t.getText();
                t.setText(temp.substring(0, temp.length() - 1));
            }
        });
        b15.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String temp = t.getText();
                t.setText(temp.substring(0, temp.length() - temp.length()));
            }
        });
        int fv = 0;
        String op = "+";
 
        b10.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int fv = Integer.valueOf(t.getText());
                t.setText(t.getText());
                String op = "+";
            }
        });
        b11.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int fv = Integer.valueOf(t.getText());
                t.setText(t.getText());
                String op = "-";
            }
        });
        b12.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int fv = Integer.valueOf(t.getText());
                t.setText(t.getText());
                String op = "*";
            }
        });
 
        b13.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int fv = Integer.valueOf(t.getText());
                t.setText(t.getText());
                String op = "/";
 
            }
        });
 
    
 
    }
 
}
public class Main {
 
    public static void main(String[] args) {
        C1 c=new C1("");
        
        c.setVisible(true);
    
    }
 
}
Может кому пригодится. Рабочая программа.
Только теряется слушатель нажатия клавиатуры после нажатия на JButton.
Буду благодарен за совет как это исправить.
Плюс сейчас доделываю слушателя реагирующего на нажатие сочетания клавиш (shift плюс =), чтобы вводился минус с клавиатуры

Добавлено через 1 минуту
Написано при участии пользователя 'molodoyparen'
0
Эксперт PythonЭксперт Java
19530 / 11067 / 2931
Регистрация: 21.10.2017
Сообщений: 23,294
18.04.2018, 20:34
Цитата Сообщение от DDD7555 Посмотреть сообщение
при участии пользователя 'molodoyparen'
...
Изображения
 
1
0 / 0 / 0
Регистрация: 01.04.2018
Сообщений: 29
18.04.2018, 23:46  [ТС]
Java
1
2
3
4
5
6
7
8
9
10
11
12
addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if(e.isShiftDown()&&e.getKeyCode()==61) {
                    t.setText(t.getText()+"+");
                }
                
            }
        
        
    });
Это для одновременного нажатия двух клавиш
0
0 / 0 / 0
Регистрация: 01.04.2018
Сообщений: 29
20.04.2018, 14:43  [ТС]
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
public class Main {
 
    public static void main(String[] args) {
        C1 c=new C1("");
        
        c.setVisible(true);
    
    }
 
}
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.KeyEventDispatcher;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
 
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
 
import com.sun.xml.internal.ws.api.Component;
 
public class C1 extends JFrame {
 
    JButton b0 = new JButton("0");
    JButton b1 = new JButton("1");
    JButton b2 = new JButton("2");
    JButton b3 = new JButton("3");
    JButton b4 = new JButton("4");
    JButton b5 = new JButton("5");
    JButton b6 = new JButton("6");
    JButton b7 = new JButton("7");
    JButton b8 = new JButton("8");
    JButton b9 = new JButton("9");
    JButton b10 = new JButton("+");
    JButton b11 = new JButton("-");
    JButton b12 = new JButton("*");
    JButton b13 = new JButton("/");
    JButton b14 = new JButton("=");
    JButton b15 = new JButton("CE");
    JButton b16 = new JButton("<-");
    JButton b17 = new JButton("CLOSE");
 
    JTextField t = new JTextField();
    boolean bb;
 
    public C1(String name) {
        super("Калькулятор");
        setLayout(null);
        setSize(300, 400);
        t.setBounds(10, 10, 260, 50);
        t.setEditable(false);
        t.setSelectedTextColor(Color.RED);
        t.setBackground(Color.blue);
        t.setForeground(Color.white);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        setVisible(true);
 
        b0.setBounds(60, 220, 50, 50);
        b0.setBackground(Color.BLUE);
        b1.setBounds(10, 70, 50, 50);
        b2.setBounds(60, 70, 50, 50);
        b3.setBounds(110, 70, 50, 50);
        b4.setBounds(10, 120, 50, 50);
        b5.setBounds(60, 120, 50, 50);
        b6.setBounds(110, 120, 50, 50);
        b7.setBounds(10, 170, 50, 50);
        b8.setBounds(60, 170, 50, 50);
        b9.setBounds(110, 170, 50, 50);
        b10.setBounds(10, 220, 50, 50);
        b10.setBackground(Color.CYAN);
        b11.setBounds(110, 220, 50, 50);
 
        b12.setBounds(160, 70, 50, 50);
        b13.setBounds(160, 120, 50, 50);
        b14.setBounds(160, 170, 50, 50);
        b15.setBounds(160, 220, 50, 50);
        b16.setBounds(210, 70, 60, 200);
        b17.setBounds(10, 270, 100, 70);
        add(b0);
        add(b1);
        add(b2);
        add(b3);
        add(b4);
        add(b5);
        add(b6);
        add(b7);
        add(b8);
        add(b9);
        add(b10);
        add(b11);
        add(b12);
        add(b13);
        add(b14);
        add(b15);
        add(b16);
        add(b17);
        add(t);
 
            addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_F11) {
                    System.exit(0);
                }
            }
        });
 
        b17.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
 
            }
 
        });
 
        b0.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "0");
            }
 
        });
 
 
        b1.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "1");
            }
 
        });
 
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                for (int i = 0; i <= 9; i++) {
                    if (e.getKeyCode() == 96 + i || e.getKeyCode() == 48 + i) {
                        t.setText(t.getText() + i);
 
                    }
 
                }
            }
        });
 
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_DIVIDE) {
                    t.setText(t.getText() + "/");
                }
            }
 
        });
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_SUBTRACT || e.getKeyCode() == 45) {
                    t.setText(t.getText() + "-");
                }
            }
 
        });
 
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ADD || e.getKeyCode() == 16 && e.getKeyCode() == 61) {
                    t.setText(t.getText() + "+");
                }
            }
 
            @Override
            public void keyTyped(KeyEvent e) {
                if (e.getKeyCode() == 16 + 61) {
                    t.setText(t.getText() + "+");
 
                }
            }
 
        });
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_MULTIPLY) {
                    t.setText(t.getText() + "*");
                }
            }
 
        });
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_DECIMAL) {
                    t.setText(t.getText() + ".");
                }
            }
 
        });
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.isShiftDown() && e.getKeyCode() == 61) {
                    t.setText(t.getText() + "+");
                }
 
            }
 
        });
 
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
                    String temp = t.getText();
                    t.setText(temp.substring(0, temp.length() - 1));
                }
            }
 
        });
 
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_DELETE) {
                    String temp = t.getText();
                    t.setText(temp.substring(0, temp.length() - temp.length()));
                }
            }
 
        });
        b14.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                ScriptEngine sm = new ScriptEngineManager().getEngineByName("JavaScript");
                String totals = t.getText();
                float result = 0;
                try {
                    result = Float.valueOf(sm.eval(totals).toString());
                    t.setText(String.valueOf(result));
                } catch (ScriptException e1) {
                    e1.printStackTrace();
                }
            }
 
        });
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
                    String expression = t.getText();
 
                    float result = 0;
                    try {
                        result = Float.valueOf(engine.eval(expression).toString());
                        t.setText(String.valueOf(result));
                    } catch (ScriptException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        });
 
        b2.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "2");
 
            }
 
        });
 
        b3.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "3");
 
            }
 
        });
 
        b4.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "4");
 
            }
 
        });
 
        b5.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "5");
 
            }
 
        });
 
        b6.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "6");
 
            }
 
        });
 
        b7.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "7");
 
            }
 
        });
 
        b8.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "8");
 
            }
 
        });
 
        b9.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "9");
 
            }
 
        });
 
        b10.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "+");
 
            }
 
        });
 
        b11.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "-");
 
            }
 
        });
 
        b12.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "*");
 
            }
 
        });
        b13.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "/");
 
            }
 
        });
 
        b15.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "");
 
            }
 
        });
        b16.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "");
 
            }
 
        });
 
        b16.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String temp = t.getText();
                t.setText(temp.substring(0, temp.length() - 1));
            }
        });
        b15.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String temp = t.getText();
                t.setText(temp.substring(0, temp.length() - temp.length()));
            }
        });
        int fv = 0;
        String op = "+";
 
        b10.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int fv = Integer.valueOf(t.getText());
                t.setText(t.getText());
                String op = "+";
            }
        });
        b11.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int fv = Integer.valueOf(t.getText());
                t.setText(t.getText());
                String op = "-";
            }
        });
        b12.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int fv = Integer.valueOf(t.getText());
                t.setText(t.getText());
                String op = "*";
            }
        });
 
        b13.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int fv = Integer.valueOf(t.getText());
                t.setText(t.getText());
                String op = "/";
 
            }
        });
 
    }
 
}
0
13 / 11 / 10
Регистрация: 23.09.2017
Сообщений: 95
20.04.2018, 15:56
DDD7555, пропиши
Java
1
requestFocusInWindow();
Для каждого addKeyListener что-бы фокус не слетал, вот пример:
Java
1
2
3
4
5
6
7
8
9
10
11
 addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_DIVIDE) {
                    t.setText(t.getText() + "/");
                }
                requestFocusInWindow();
            }
 
        });
Добавлено через 55 минут
Если и это не сработает тогда у тебя не включен NumPad
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.KeyEventDispatcher;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
 
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
 
 
public class C1 extends JFrame {
    public static void main(String[] args){
        C1 c1 = new C1("");
        c1.setVisible(true);
    }
 
    JButton b0 = new JButton("0");
    JButton b1 = new JButton("1");
    JButton b2 = new JButton("2");
    JButton b3 = new JButton("3");
    JButton b4 = new JButton("4");
    JButton b5 = new JButton("5");
    JButton b6 = new JButton("6");
    JButton b7 = new JButton("7");
    JButton b8 = new JButton("8");
    JButton b9 = new JButton("9");
    JButton b10 = new JButton("+");
    JButton b11 = new JButton("-");
    JButton b12 = new JButton("*");
    JButton b13 = new JButton("/");
    JButton b14 = new JButton("=");
    JButton b15 = new JButton("CE");
    JButton b16 = new JButton("<-");
    JButton b17 = new JButton("CLOSE");
 
    JTextField t = new JTextField();
    boolean bb;
 
    public C1(String name) {
        super("Калькулятор");
        setLayout(null);
        setSize(300, 400);
        t.setBounds(10, 10, 260, 50);
        t.setEditable(false);
        t.setSelectedTextColor(Color.RED);
        t.setBackground(Color.blue);
        t.setForeground(Color.white);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        setVisible(true);
 
        b0.setBounds(60, 220, 50, 50);
        b0.setBackground(Color.BLUE);
        b1.setBounds(10, 70, 50, 50);
        b2.setBounds(60, 70, 50, 50);
        b3.setBounds(110, 70, 50, 50);
        b4.setBounds(10, 120, 50, 50);
        b5.setBounds(60, 120, 50, 50);
        b6.setBounds(110, 120, 50, 50);
        b7.setBounds(10, 170, 50, 50);
        b8.setBounds(60, 170, 50, 50);
        b9.setBounds(110, 170, 50, 50);
        b10.setBounds(10, 220, 50, 50);
        b10.setBackground(Color.CYAN);
        b11.setBounds(110, 220, 50, 50);
 
        b12.setBounds(160, 70, 50, 50);
        b13.setBounds(160, 120, 50, 50);
        b14.setBounds(160, 170, 50, 50);
        b15.setBounds(160, 220, 50, 50);
        b16.setBounds(210, 70, 60, 200);
        b17.setBounds(10, 270, 100, 70);
        add(b0);
        add(b1);
        add(b2);
        add(b3);
        add(b4);
        add(b5);
        add(b6);
        add(b7);
        add(b8);
        add(b9);
        add(b10);
        add(b11);
        add(b12);
        add(b13);
        add(b14);
        add(b15);
        add(b16);
        add(b17);
        add(t);
 
        requestFocusInWindow();
 
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_F11) {
                    System.exit(0);
                }
                requestFocusInWindow();
            }
        });
 
        b17.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
 
            }
 
 
        });
 
        b0.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "0");
            }
 
        });
 
 
        b1.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "1");
                requestFocusInWindow();
            }
 
        });
 
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                for (int i = 0; i <= 9; i++) {
                    if (e.getKeyCode() == 96 + i || e.getKeyCode() == 48 + i) {
                        t.setText(t.getText() + i);
                        requestFocusInWindow();
                    }
 
                }
            }
        });
 
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_DIVIDE) {
                    t.setText(t.getText() + "/");
                }
                requestFocusInWindow();
            }
 
        });
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_SUBTRACT || e.getKeyCode() == 45) {
                    t.setText(t.getText() + "-");
                }
                requestFocusInWindow();
            }
 
        });
 
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ADD || e.getKeyCode() == 16 && e.getKeyCode() == 61) {
                    t.setText(t.getText() + "+");
                    requestFocusInWindow();
                }
            }
 
            @Override
            public void keyTyped(KeyEvent e) {
                if (e.getKeyCode() == 16 + 61) {
                    t.setText(t.getText() + "+");
                    requestFocusInWindow();
                }
            }
 
        });
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_MULTIPLY) {
                    t.setText(t.getText() + "*");
                    requestFocusInWindow();
                }
            }
 
        });
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_DECIMAL) {
                    t.setText(t.getText() + ".");
                    requestFocusInWindow();
                }
            }
 
        });
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.isShiftDown() && e.getKeyCode() == 61) {
                    t.setText(t.getText() + "+");
                    requestFocusInWindow();
                }
 
            }
 
        });
 
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
                    String temp = t.getText();
                    t.setText(temp.substring(0, temp.length() - 1));
                    requestFocusInWindow();
                }
            }
 
        });
 
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_DELETE) {
                    String temp = t.getText();
                    t.setText(temp.substring(0, temp.length() - temp.length()));
                    requestFocusInWindow();
                }
            }
 
        });
        b14.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                ScriptEngine sm = new ScriptEngineManager().getEngineByName("JavaScript");
                String totals = t.getText();
                float result = 0;
                try {
                    result = Float.valueOf(sm.eval(totals).toString());
                    t.setText(String.valueOf(result));
                    requestFocusInWindow();
                } catch (ScriptException e1) {
                    e1.printStackTrace();
                }
            }
 
        });
        addKeyListener(new KeyAdapter() {
 
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
                    String expression = t.getText();
 
                    float result = 0;
                    try {
                        result = Float.valueOf(engine.eval(expression).toString());
                        t.setText(String.valueOf(result));
                        requestFocusInWindow();
                    } catch (ScriptException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        });
 
        b2.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "2");
                requestFocusInWindow();
            }
 
        });
 
        b3.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "3");
                requestFocusInWindow();
            }
 
        });
 
        b4.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "4");
                requestFocusInWindow();
            }
 
        });
 
        b5.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "5");
                requestFocusInWindow();
            }
 
        });
 
        b6.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "6");
                requestFocusInWindow();
            }
 
        });
 
        b7.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "7");
                requestFocusInWindow();
            }
 
        });
 
        b8.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "8");
                requestFocusInWindow();
            }
 
        });
 
        b9.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "9");
                requestFocusInWindow();
            }
 
        });
 
        b10.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "+");
                requestFocusInWindow();
            }
 
        });
 
        b11.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "-");
                requestFocusInWindow();
            }
 
        });
 
        b12.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "*");
                requestFocusInWindow();
            }
 
        });
        b13.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "/");
                requestFocusInWindow();
            }
 
        });
 
        b15.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "");
                requestFocusInWindow();
            }
 
        });
        b16.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText(t.getText() + "");
                requestFocusInWindow();
            }
 
        });
 
        b16.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String temp = t.getText();
                t.setText(temp.substring(0, temp.length() - 1));
                requestFocusInWindow();
            }
        });
        b15.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String temp = t.getText();
                t.setText(temp.substring(0, temp.length() - temp.length()));
                requestFocusInWindow();
            }
        });
        int fv = 0;
        String op = "+";
 
        b10.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int fv = Integer.valueOf(t.getText());
                t.setText(t.getText());
                String op = "+";
                requestFocusInWindow();
            }
        });
        b11.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int fv = Integer.valueOf(t.getText());
                t.setText(t.getText());
                String op = "-";
                requestFocusInWindow();
            }
        });
        b12.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int fv = Integer.valueOf(t.getText());
                t.setText(t.getText());
                String op = "*";
                requestFocusInWindow();
            }
        });
 
        b13.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int fv = Integer.valueOf(t.getText());
                t.setText(t.getText());
                String op = "/";
                requestFocusInWindow();
            }
        });
 
    }
 
}
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
20.04.2018, 15:56
Помогаю со студенческими работами здесь

Не работает ввод с клавиатуры
Добрый день, Помогите пожалуйсто исправить ошибку в коде org 100h jmp start array db 254 ;максимально допустимая len...

Не работает ввод с клавиатуры
Любая, абсолютно любая программа у меня не считывает ничего. Я ввожу, ввожу, а он не отвечает. Во вложении есть скрин проги A+B, где...

Не работает ввод с клавиатуры
В последнее время иногда не работает ввод с клавиатуры, ни в адресной строке, ни в поле сообщения, это касается только браузера. Браузер...

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

Не работает ввод строки с клавиатуры
Здравствуйте. Пишу програамку. Вот клочек который должен выполнять ввод строки с клавиатуры и счтать сколько символов ввели. почемут не...


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

Или воспользуйтесь поиском по форуму:
10
Ответ Создать тему
Новые блоги и статьи
Философия технологии
iceja 01.02.2026
На мой взгляд у человека в технических проектах остается роль генерального директора. Все остальное нейронки делают уже лучше человека. Они не могут нести предпринимательские риски, не могут. . .
SDL3 для Web (WebAssembly): Вывод текста со шрифтом TTF с помощью SDL3_ttf
8Observer8 01.02.2026
Содержание блога В этой пошаговой инструкции создадим с нуля веб-приложение, которое выводит текст в окне браузера. Запустим на Android на локальном сервере. Загрузим Release на бесплатный. . .
SDL3 для Web (WebAssembly): Сборка C/C++ проекта из консоли
8Observer8 30.01.2026
Содержание блога Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
SDL3 для Web (WebAssembly): Установка Emscripten SDK (emsdk) и CMake для сборки C и C++ приложений в Wasm
8Observer8 30.01.2026
Содержание блога Для того чтобы скачать Emscripten SDK (emsdk) необходимо сначало скачать и уставить Git: Install for Windows. Следуйте стандартной процедуре установки Git через установщик. . . .
SDL3 для Android: Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 29.01.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами. Версия v3 была полностью переписана на Си, в. . .
Инструменты COM: Сохранение данный из VARIANT в файл и загрузка из файла в VARIANT
bedvit 28.01.2026
Сохранение базовых типов COM и массивов (одномерных или двухмерных) любой вложенности (деревья) в файл, с возможностью выбора алгоритмов сжатия и шифрования. Часть библиотеки BedvitCOM Использованы. . .
SDL3 для Android: Загрузка PNG с альфа-каналом с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 28.01.2026
Содержание блога SDL3 имеет собственные средства для загрузки и отображения PNG-файлов с альфа-каналом и базовой работы с ними. В этой инструкции используется функция SDL_LoadPNG(), которая. . .
SDL3 для Android: Загрузка PNG с альфа-каналом с помощью SDL3_image
8Observer8 27.01.2026
Содержание блога SDL3_image - это библиотека для загрузки и работы с изображениями. Эта пошаговая инструкция покажет, как загрузить и вывести на экран смартфона картинку с альфа-каналом, то есть с. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru