Posts

Showing posts with the label Java

Tabbing In and Out of an Editable JComboBox

Tabbing in and out of an editable JComboBox seems to be really quirky. First we need to disable the default focus traversal keys for the JComboBox editor. editor.setFocusTraversalKeysEnabled(false); Then we add a KeyListener as below : editor.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_TAB: int n = e.getModifiers(); if (n > 0) { comboBox.transferFocusBackward(); } else { comboBox.getEditor().getEditorComponent().transferFocus(); } e.consume(); break; } } }); Notice that to tab forward, we are using the editor component and to tab backward we are using the combobox directly. Any...

How to Convert an ImageIcon to a Base64 encoded String in Java

To convert an ImageIcon to a Base64 encoded string, we first need to convert the ImageIcon to a BufferedImage. The BufferedImage then needs to be converted to a ByteArray using a ByteArrayOutputStream. Then using a Base64 encoder, we can convert the ByteArray to a Base64 String. Particularly useful when trying to save an image loaded into a JLabel  to the database. To get the image from the JLabel, we need to get the ImageIcon from the JLabel using getIcon(); import com.itextpdf.text.pdf.codec.Base64; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import javax.imageio.ImageIO; import java.awt.Graphics; private String ConvertImageIconToBase64String(ImageIcon ii) { // Create a buffered image of the size of the original image icon BufferedImage image = new BufferedImage(ii.getIconWidth(), ii.getIconHeight(), BufferedImage.TYPE_INT_RGB); // Create a graphics object to draw the image Graphics g = image.createGraphics(); // Paint the icon on ...