-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackConverterGUI.java
More file actions
398 lines (331 loc) · 15 KB
/
Copy pathStackConverterGUI.java
File metadata and controls
398 lines (331 loc) · 15 KB
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
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
/**
* Lab 5 – Infix Expression Converter GUI
*
* Connects to the C back-end via JNI (StackConverter).
* Features:
* • Convert infix → postfix and prefix
* • Handle + - * / ^ unary-minus parentheses
* • Variable substitution and numeric evaluation
* • History list (last 5 conversions, stack-based undo/redo)
*/
public class StackConverterGUI extends JFrame {
/* ── JNI bridge ── */
private final StackConverter conv = new StackConverter();
/* ── Input widgets ── */
private JTextField infixField;
private JTextArea postfixArea;
private JTextArea prefixArea;
private JTextArea resultArea;
/* ── Variable table ── */
private DefaultTableModel varModel;
/* ── History stack (max 5) ── */
private final Deque<String[]> history = new ArrayDeque<>(); // undo stack
private final Deque<String[]> redoStack = new ArrayDeque<>(); // redo stack
private static final int MAX_HISTORY = 5;
/* ── History display ── */
private DefaultListModel<String> historyListModel;
private JList<String> historyList;
/* ── Colour palette ── */
private static final Color COL_BG = new Color(245, 247, 252);
private static final Color COL_HEADER = new Color( 37, 99, 235);
private static final Color COL_ACCENT = new Color( 99, 102, 241);
private static final Color COL_BTN_FG = Color.WHITE;
private static final Color COL_AREA_BG = new Color(250, 251, 255);
private static final Font MONO = new Font("Monospaced", Font.PLAIN, 14);
private static final Font LABEL_FONT = new Font("SansSerif", Font.BOLD, 12);
/* ══════════════════════════════════════════════════════ */
public StackConverterGUI() {
super("Lab 5 – Infix Expression Converter (Java + C via JNI)");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(900, 700);
setMinimumSize(new Dimension(780, 580));
getContentPane().setBackground(COL_BG);
setLayout(new BorderLayout(10, 10));
add(buildHeader(), BorderLayout.NORTH);
add(buildCenter(), BorderLayout.CENTER);
add(buildSidePanel(), BorderLayout.EAST);
add(buildStatusBar(), BorderLayout.SOUTH);
setLocationRelativeTo(null);
setVisible(true);
}
/* ─────────────────── Header ─────────────────── */
private JPanel buildHeader() {
JPanel p = new JPanel(new BorderLayout(8, 8));
p.setBackground(COL_HEADER);
p.setBorder(new EmptyBorder(14, 18, 14, 18));
JLabel title = new JLabel("Infix Expression Converter | Stack Application");
title.setFont(new Font("SansSerif", Font.BOLD, 18));
title.setForeground(Color.WHITE);
p.add(title, BorderLayout.WEST);
JLabel subtitle = new JLabel("Data Structures Lab 5");
subtitle.setFont(new Font("SansSerif", Font.ITALIC, 13));
subtitle.setForeground(new Color(186, 230, 253));
p.add(subtitle, BorderLayout.EAST);
return p;
}
/* ─────────────────── Centre (input + output) ─────────────────── */
private JPanel buildCenter() {
JPanel p = new JPanel(new BorderLayout(8, 8));
p.setBackground(COL_BG);
p.setBorder(new EmptyBorder(8, 14, 8, 6));
p.add(buildInputPanel(), BorderLayout.NORTH);
p.add(buildOutputPanel(), BorderLayout.CENTER);
p.add(buildEvalPanel(), BorderLayout.SOUTH);
return p;
}
private JPanel buildInputPanel() {
JPanel p = new JPanel(new BorderLayout(8, 0));
p.setBackground(COL_BG);
p.setBorder(titled("Infix Expression"));
infixField = new JTextField("a+b*c");
infixField.setFont(MONO);
infixField.setPreferredSize(new Dimension(0, 36));
infixField.addActionListener(e -> doConvert());
JButton btnConvert = styledBtn("Convert", COL_HEADER);
btnConvert.addActionListener(e -> doConvert());
JButton btnClear = styledBtn("Clear", new Color(107, 114, 128));
btnClear.addActionListener(e -> {
infixField.setText("");
postfixArea.setText("");
prefixArea.setText("");
resultArea.setText("");
});
JPanel btnPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 0));
btnPanel.setBackground(COL_BG);
btnPanel.add(btnClear);
btnPanel.add(btnConvert);
p.add(new JLabel(" Enter expression: "), BorderLayout.WEST);
p.add(infixField, BorderLayout.CENTER);
p.add(btnPanel, BorderLayout.EAST);
return p;
}
private JPanel buildOutputPanel() {
JPanel p = new JPanel(new GridLayout(1, 2, 10, 0));
p.setBackground(COL_BG);
p.setBorder(new EmptyBorder(4, 0, 4, 0));
postfixArea = outputArea();
prefixArea = outputArea();
p.add(labelledArea("Postfix (~ = unary minus)", postfixArea));
p.add(labelledArea("Prefix", prefixArea));
return p;
}
private JPanel buildEvalPanel() {
JPanel outer = new JPanel(new BorderLayout(8, 4));
outer.setBackground(COL_BG);
outer.setBorder(titled("Evaluate (enter variable values below)"));
/* Variable table */
String[] cols = { "Variable", "Value" };
varModel = new DefaultTableModel(cols, 0) {
@Override public boolean isCellEditable(int r, int c) { return true; }
};
for (char v : "abcdefghij".toCharArray())
varModel.addRow(new Object[]{ String.valueOf(v), "" });
JTable varTable = new JTable(varModel);
varTable.setRowHeight(22);
varTable.setFont(MONO);
varTable.getTableHeader().setFont(LABEL_FONT);
varTable.setGridColor(new Color(220, 225, 235));
JScrollPane scroll = new JScrollPane(varTable);
scroll.setPreferredSize(new Dimension(0, 120));
outer.add(scroll, BorderLayout.CENTER);
/* Evaluate button + result */
JPanel bottom = new JPanel(new BorderLayout(8, 0));
bottom.setBackground(COL_BG);
JButton btnEval = styledBtn("Evaluate", COL_ACCENT);
btnEval.addActionListener(e -> doEvaluate());
resultArea = outputArea();
resultArea.setPreferredSize(new Dimension(0, 36));
bottom.add(btnEval, BorderLayout.WEST);
bottom.add(labelledArea("Result", resultArea), BorderLayout.CENTER);
outer.add(bottom, BorderLayout.SOUTH);
return outer;
}
/* ─────────────────── Side panel (history + undo/redo) ─────────────────── */
private JPanel buildSidePanel() {
JPanel p = new JPanel(new BorderLayout(4, 6));
p.setBackground(COL_BG);
p.setBorder(new CompoundBorder(
new EmptyBorder(8, 0, 8, 14),
titled("History (max 5)")));
p.setPreferredSize(new Dimension(220, 0));
historyListModel = new DefaultListModel<>();
historyList = new JList<>(historyListModel);
historyList.setFont(new Font("Monospaced", Font.PLAIN, 11));
historyList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
historyList.addMouseListener(new MouseAdapter() {
@Override public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) restoreFromHistory();
}
});
JScrollPane sp = new JScrollPane(historyList);
p.add(sp, BorderLayout.CENTER);
JPanel btnRow = new JPanel(new GridLayout(1, 2, 6, 0));
btnRow.setBackground(COL_BG);
JButton undo = styledBtn("Undo", new Color(202, 79, 79));
JButton redo = styledBtn("Redo", new Color( 59, 130, 246));
undo.addActionListener(e -> doUndo());
redo.addActionListener(e -> doRedo());
btnRow.add(undo);
btnRow.add(redo);
p.add(btnRow, BorderLayout.SOUTH);
return p;
}
/* ─────────────────── Status bar ─────────────────── */
private JLabel statusLabel;
private JPanel buildStatusBar() {
JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT, 14, 4));
p.setBackground(new Color(230, 234, 245));
statusLabel = new JLabel("Ready. Double-click a history entry to restore it.");
statusLabel.setFont(new Font("SansSerif", Font.PLAIN, 11));
p.add(statusLabel);
return p;
}
/* ══════════════════════════════════════════════════════ */
/* Actions */
/* ══════════════════════════════════════════════════════ */
private void doConvert() {
String infix = infixField.getText().trim();
if (infix.isEmpty()) { status("Please enter an expression."); return; }
String pf = conv.toPostfix(infix);
String pr = conv.toPrefix(infix);
postfixArea.setText(pf);
prefixArea.setText(pr);
resultArea.setText("");
if (!pf.startsWith("ERROR")) {
pushHistory(new String[]{ infix, pf, pr });
status("Converted: " + infix);
} else {
status("Conversion error – check your expression.");
}
}
private void doEvaluate() {
String infix = infixField.getText().trim();
if (infix.isEmpty()) { status("No expression to evaluate."); return; }
/* Build variable string "a=1,b=2,..." from table */
StringBuilder sb = new StringBuilder();
for (int r = 0; r < varModel.getRowCount(); r++) {
Object varObj = varModel.getValueAt(r, 0);
Object valObj = varModel.getValueAt(r, 1);
if (varObj == null || valObj == null) continue;
String val = valObj.toString().trim();
if (val.isEmpty()) continue;
if (sb.length() > 0) sb.append(',');
sb.append(varObj).append('=').append(val);
}
String result = conv.evaluate(infix, sb.toString());
resultArea.setText(result);
status(result.startsWith("ERROR") ? "Evaluation failed." :
"Result = " + result);
}
/* ── History ── */
private void pushHistory(String[] entry) {
/* Push current state to undo stack */
if (history.size() == MAX_HISTORY) history.pollFirst();
history.offerLast(entry);
redoStack.clear();
refreshHistoryList();
}
private void refreshHistoryList() {
historyListModel.clear();
for (String[] e : history)
historyListModel.addElement(e[0]);
if (!historyListModel.isEmpty())
historyList.setSelectedIndex(historyListModel.size() - 1);
}
private void restoreFromHistory() {
int idx = historyList.getSelectedIndex();
if (idx < 0) return;
String[] entry = (String[]) history.toArray()[idx];
infixField.setText(entry[0]);
postfixArea.setText(entry[1]);
prefixArea.setText(entry[2]);
status("Restored: " + entry[0]);
}
private void doUndo() {
if (history.isEmpty()) { status("Nothing to undo."); return; }
String[] last = history.pollLast();
redoStack.offerLast(last);
refreshHistoryList();
if (!history.isEmpty()) {
String[] prev = history.peekLast();
infixField.setText(prev[0]);
postfixArea.setText(prev[1]);
prefixArea.setText(prev[2]);
status("Undo → " + prev[0]);
} else {
infixField.setText("");
postfixArea.setText("");
prefixArea.setText("");
status("Undone all entries.");
}
}
private void doRedo() {
if (redoStack.isEmpty()) { status("Nothing to redo."); return; }
String[] entry = redoStack.pollLast();
if (history.size() == MAX_HISTORY) history.pollFirst();
history.offerLast(entry);
infixField.setText(entry[0]);
postfixArea.setText(entry[1]);
prefixArea.setText(entry[2]);
refreshHistoryList();
status("Redo → " + entry[0]);
}
/* ══════════════════════════════════════════════════════ */
/* UI helpers */
/* ══════════════════════════════════════════════════════ */
private JTextArea outputArea() {
JTextArea a = new JTextArea();
a.setFont(MONO);
a.setBackground(COL_AREA_BG);
a.setEditable(false);
a.setLineWrap(true);
a.setWrapStyleWord(true);
a.setBorder(new EmptyBorder(4, 6, 4, 6));
return a;
}
private JPanel labelledArea(String label, JTextArea area) {
JPanel p = new JPanel(new BorderLayout(0, 2));
p.setBackground(COL_BG);
JLabel l = new JLabel(label);
l.setFont(LABEL_FONT);
l.setForeground(new Color(75, 85, 99));
p.add(l, BorderLayout.NORTH);
p.add(new JScrollPane(area), BorderLayout.CENTER);
return p;
}
private JButton styledBtn(String text, Color bg) {
JButton b = new JButton(text);
b.setBackground(bg);
b.setForeground(COL_BTN_FG);
b.setFont(new Font("SansSerif", Font.BOLD, 12));
b.setFocusPainted(false);
b.setBorder(new EmptyBorder(7, 16, 7, 16));
b.setCursor(new Cursor(Cursor.HAND_CURSOR));
b.setOpaque(true); // ← add this
b.setContentAreaFilled(true); // ← add this
b.setUI(new javax.swing.plaf.basic.BasicButtonUI()); // ← add this
return b;
}
private TitledBorder titled(String t) {
TitledBorder tb = BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(new Color(209, 213, 219), 1), t);
tb.setTitleFont(LABEL_FONT);
tb.setTitleColor(COL_HEADER);
return tb;
}
private void status(String msg) {
statusLabel.setText(msg);
}
/* ══════════════════════════════════════════════════════ */
public static void main(String[] args) {
try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }
catch (Exception ignored) {}
SwingUtilities.invokeLater(StackConverterGUI::new);
}
}