Posts from February 2008

Feb
15
2008

Java: Word Wrap for JLabels



Posted in Programming

Why couldn't Sun have made JLabels automatically wrap when they're too wide to fit the container they're in? I'd been trying to get a custom component to automatically wrap for hours, then someone suggested a JTextPane in IRC. You can style the pane to look like a JLabel, and it automatically wraps.

JTextPane txtMyTextPane= new JTextPane();
            txtMyTextPane.setText("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas aliquam sem et nunc vulputate aliquet. Duis sollicitudin. Vestibulum sit amet lacus a risus egestas nonummy. Donec eu odio id felis auctor lobortis. Cras id nisl vitae pede lacinia elementum. Suspendisse convallis leo. Donec elit. Quisque id mi tincidunt quam tristique posuere.");
            txtMyTextPane.setBackground(null);
            txtMyTextPane.setEditable(false);
            txtMyTextPane.setBorder(null);
Feb
8
2008

Java: Close a JFrame with Escape



Posted in Programming

This will close a JFrame when the escape key is pressed. The actionPerformed method can do be used to call another method or to close the frame which called it.

KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
Action escapeAction = new AbstractAction() {
    // close the frame when the user presses escape
    public void actionPerformed(ActionEvent e) {
        myFrame.dispose();
    }
}; 
myFrame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke, "ESCAPE");
myFrame.getRootPane().getActionMap().put("ESCAPE", escapeAction);