creazione del componente per leggere codice hex e trasformarlo in testo

This commit is contained in:
2026-03-01 11:31:27 +01:00
commit 2c4b58ef5b

View File

@@ -0,0 +1,250 @@
package hexeditorcomponent;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.beans.SimpleBeanInfo;
import java.util.ArrayList;
import java.util.List;
/**
* HexTextBoxPanel 2.0 - Bidirezionale
*
* Ogni textbox HEX aggiorna la casella ASCII
* Scrivendo nella casella ASCII si aggiornano automaticamente i campi HEX
*
* Proprietà per GUI Builder:
* - numBytes
* - hexFieldBackground
*/
public class HexTextBoxPanel extends JPanel {
private List<JTextField> hexFields = new ArrayList<>();
private JTextField asciiField;
private int numBytes = 8;
private Color hexFieldBackground = Color.WHITE;
private boolean updatingFromAscii = false; // evita loop
// ---------------- COSTRUTTORE ----------------
public HexTextBoxPanel() {
initComponent();
}
public HexTextBoxPanel(int numBytes) {
this.numBytes = numBytes;
initComponent();
}
// ---------------- INIZIALIZZAZIONE COMPONENTI ----------------
private void initComponent() {
removeAll();
hexFields.clear();
setLayout(new FlowLayout(FlowLayout.LEFT));
// Textbox per ogni byte
for (int i = 0; i < numBytes; i++) {
JTextField tf = new JTextField(2);
tf.setDocument(new HexDocument());
tf.setHorizontalAlignment(JTextField.CENTER);
tf.setBackground(hexFieldBackground);
tf.setText("00");
tf.addFocusListener(new java.awt.event.FocusAdapter() {
@Override
public void focusLost(java.awt.event.FocusEvent e) {
String text = tf.getText();
if (text.length() == 1) {
tf.setText("0" + text.toUpperCase());
}
if (text.length() < 1) {
tf.setText("00");
}
}
@Override
public void focusGained (java.awt.event.FocusEvent e) {
tf.selectAll();
}
});
tf.getDocument().addDocumentListener(new SimpleDocumentListener() {
@Override
public void update() {
if (!updatingFromAscii) {
updateAsciiField();
}
}
});
hexFields.add(tf);
add(tf);
}
// Textbox ASCII bidirezionale
asciiField = new JTextField(numBytes);
asciiField.setDocument(new FixedLengthDocument(numBytes));
asciiField.setFont(new Font("Monospaced", Font.PLAIN, 12));
asciiField.setEditable(true);
asciiField.getDocument().addDocumentListener(new SimpleDocumentListener() {
@Override
public void update() {
updateHexFieldsFromAscii();
}
});
add(asciiField);
updateAsciiField();
revalidate();
repaint();
}
// ---------------- AGGIORNA ASCII DAI BYTE ----------------
private void updateAsciiField() {
StringBuilder sb = new StringBuilder();
for (JTextField tf : hexFields) {
String hex = tf.getText();
if (hex.length() == 2) {
try {
int val = Integer.parseInt(hex, 16);
// ASCII stampabile
if (val >= 32 && val <= 126) {
sb.append((char) val);
} else {
sb.append('.');
}
} catch (NumberFormatException ignored) {
sb.append('.');
}
} else {
sb.append('.');
}
}
updatingFromAscii = true;
asciiField.setText(sb.toString());
updatingFromAscii = false;
}
public byte[] getBytes() {
byte[] data = new byte[hexFields.size()];
for (int i = 0; i < hexFields.size(); i++) {
JTextField tf = hexFields.get(i);
String hex = tf.getText();
try {
data[i] = (byte) Integer.parseInt(hex, 16);
} catch (NumberFormatException e) {
data[i] = 0; // se il campo non è valido, restituisci 0
}
}
return data;
}
public void setBytes(byte[] data) {
int len = Math.min(data.length, hexFields.size());
for (int i = 0; i < len; i++) {
hexFields.get(i).setText(String.format("%02X", data[i]));
}
}
public void clear(){
for (int i = 0; i < hexFields.size(); i++) {
hexFields.get(i).setText("00");
}
}
// ---------------- AGGIORNA BYTE DALL'ASCII ----------------
private void updateHexFieldsFromAscii() {
if (updatingFromAscii) return;
updatingFromAscii = true;
String text = asciiField.getText();
for (int i = 0; i < hexFields.size(); i++) {
JTextField tf = hexFields.get(i);
if (i < text.length()) {
int val = (int) text.charAt(i);
tf.setText(String.format("%02X", val));
} else {
tf.setText("00");
}
}
updatingFromAscii = false;
}
// ---------------- PROPRIETÀ GUI BUILDER ----------------
public int getNumBytes() {
return numBytes;
}
public void setNumBytes(int numBytes) {
if (numBytes <= 0) return;
this.numBytes = numBytes;
initComponent();
}
public Color getHexFieldBackground() {
return hexFieldBackground;
}
public void setHexFieldBackground(Color hexFieldBackground) {
this.hexFieldBackground = hexFieldBackground;
for (JTextField tf : hexFields) {
tf.setBackground(hexFieldBackground);
}
repaint();
}
private static class FixedLengthDocument extends PlainDocument {
private final int maxLength;
public FixedLengthDocument(int maxLength) {
this.maxLength = maxLength;
}
@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (str == null) return;
if ((getLength() + str.length()) <= maxLength) {
super.insertString(offs, str, a);
}
}
}
// ---------------- DOCUMENT PER VALIDAZIONE HEX ----------------
private static class HexDocument extends PlainDocument {
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if (str == null) return;
str = str.toUpperCase();
StringBuilder filtered = new StringBuilder();
for (char c : str.toCharArray()) {
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
filtered.append(c);
}
}
if ((getLength() + filtered.length()) <= 2) {
super.insertString(offs, filtered.toString(), a);
}
}
}
// ---------------- DOCUMENT LISTENER SEMPLIFICATO ----------------
private abstract static class SimpleDocumentListener implements javax.swing.event.DocumentListener {
public abstract void update();
@Override public void insertUpdate(javax.swing.event.DocumentEvent e) { update(); }
@Override public void removeUpdate(javax.swing.event.DocumentEvent e) { update(); }
@Override public void changedUpdate(javax.swing.event.DocumentEvent e) { update(); }
}
}