/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
/**
* @author Ing. František Kučera (frantovo.cz)
*/
public class Caesar extends JFrame {
private JTextField prostýText = new JTextField();
private JTextField šifrovanýText = new JTextField();
private JButton šifruj = new JButton("Šifruj");
private JButton dešifruj = new JButton("Dešifruj");
private static final char[] ABECEDA_ZNAKY = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
private static final List ABECEDA;
private static final int SKOK = 3;
static {
List abeceda = new ArrayList<>();
for (char z : ABECEDA_ZNAKY) {
abeceda.add(z);
}
ABECEDA = Collections.unmodifiableList(abeceda);
}
public static void main(String[] args) {
Caesar c = new Caesar();
c.setVisible(true);
}
public Caesar() throws HeadlessException {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Caesarova šifra");
setLocationRelativeTo(null);
setLayout(new GridLayout(3, 2));
add(new JLabel("Prostý text"));
add(prostýText);
add(new JLabel("Šifrovaný text"));
add(šifrovanýText);
add(šifruj);
add(dešifruj);
šifruj.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
šifrovanýText.setText(posuň(prostýText.getText(), SKOK));
}
});
dešifruj.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
prostýText.setText(posuň(šifrovanýText.getText(), -SKOK));
}
});
pack();
}
private static String posuň(String text, int oKolik) {
StringBuilder posunutý = new StringBuilder(text.length());
for (char z : text.toCharArray()) {
posunutý.append(posuň(z, oKolik));
}
return posunutý.toString();
}
private static char posuň(char znak, int oKolik) {
int původníPozice = ABECEDA.indexOf(znak);
if (původníPozice < 0) {
return znak;
} else {
int nováPozice = (původníPozice + oKolik) % ABECEDA_ZNAKY.length;
nováPozice = nováPozice < 0 ? ABECEDA_ZNAKY.length + nováPozice : nováPozice;
return ABECEDA.get(nováPozice);
}
}
}