AbstractAction and JCheckBox

Hello,
I'm using AbstractAction throughout my application, so that I can assign the same action to different components (menu, normal buttons etc.).
Now I want to create a customized AbstractAction which also handles the selected state of JCheckBox, JMenuItemCheckBox, so that if one CheckBox is selected all CheckBoxes using the same Action is also selected. I thought of using AbstractAction.firePropertyChange, but I am not sure what property to use, and if it will work at all. I want to avoid an infinite recursion.
Any suggestions?

Take a look at JGoodies Binding library. Don't reinvent the wheel!!

Similar Messages

  • AlphaComposite and JCheckBox problem

    Hello,
    my problems looks as follows:
    1. i got JPanel pX with displayed picture on it
    2. there's translucent JPanel pY (with alpha = 12%) on pX
    3. there're several components (JTextFileds, JButtons, JCheckBoxes) on pY
    All I want is that pY should be translucent (it is) and all of its components sholdn't be. It works great until I click on any of JCheckBoxes. It repaints very strange, on its background appear random fragments of pX, pY etc until it become totally opaque.
    Hiding and showing pY "repairs" it.
    My pYClass is defined as follows:
    class pyClass extends JPanel
      public pYClass(float _alpha)
        this.putClientProperty("alpha", AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
      public void painComponent(Graphics g)
        Graphics2D g2 = (Graphics2D) g;
        Composite oldc = g2.getComposite();
        AlphaComposite alc = (AlphaComposite) this.getClientProperty("alpha");
        if (alpha != null) g2.setComposite(alc);
        super.paintComponent(g);
        if (alpha != null) g2.setComposite(oldc);
    }Any help would be great
    Regards
    Marcin Zochowski
    sorry for my english

    Hi, it's me again.
    I got through java spurce codes and i think i got it. Problem is in doClick method in AbstractButton. It calls paintImmediately() methow which clears rectangle region "under" icon and text.
    So my question is:
    how to override AbstractButton.doClick() method in class that extends JCheckBox?
    I wrote in MyCheckBox class my own public void doClick(){return;} but it seems that it isn't called at all :-(
    Regards
    Marcin Zochowski

  • Save JTable and JCheckBox content

    I've made a JTable(working with DefaultTableModel). One of the columns contains JCheckBoxes. I would like to save the data into a file, but i don't know how to manage this.
    Is there somebody who knows a possible solution?!
    Thx

    I have code which can save the jtable, but i doesn't work with jcheckboxes in the jtable
    CODE:
    public void saveTable()
    if (table.getRowCount() == 0)
    System.out.println("Empty list");
    return;
    try
    FileOutputStream fos = new FileOutputStream("data.dat");
    Writer out = new OutputStreamWriter(fos,"UTF8");
    for (int i = 0; i < table.getRowCount(); i++)
    for(int j=0; j < table.getColumnCount(); j++)
    String value = (String)table.getValueAt(i,j) + "|";
    out.write(value);
    out.close();
    catch(IOException e)
    System.out.println("Error IOException " + e.getMessage());
    }

  • JMenu and JCheckBox

    Hi all,
    How to select/unselect more than one JCheckBoxMenuItem in a time in a JMenu ?
    (for instance i'm not able to select 3 item out of 10 in one time -need to do the manip 3 times ...)
    thanks in advance

    Ok, i give you an example to be more concrete:
    Lets say we have a JMenu with Checkbox giving different movie categories (action, thriller,comedy,western...) .
    -> i want to view in my jtable only the categories "action" and "western" by selecting them in the Menu.
    -> but as it's currently implemented, once you select one of the category, the JMenu directly auto-closes, so you have once again to open the menu to select the second.
    Suppose you have 10 checkbox (out of 20) to select...

  • AbstractAction and JRadioButtonMenuItem

    I can use the Action putValue(...) method to set the text, icon, mneumonic, accel., etc for my JRadioButtonMenuItem. I can also call setEnabled(...).
    Is there a way to use Action to control the state (selected or not-selected) of a JRadioButton or JRadioButtonMenuItem?

    No, Action doesn't support a "selected" property yet (it will be added, along with a "large-icon" property, in the 1.5 release). In the meantime, the source code for this article contains a workaround you might be able to use.

  • JRadioButton/JCheckBox and text alignement

    Hi all,
    It is possible only using JRadioButton and JCheckBox to have when using several
    of these elements to have text on the left aligned to left and the button right aligned
    with the gap in between being variable so that start of text and buttons are aligned.
    I would like to have that
    Text of my fist button    0
    2nd text                  0
    3rd text                  0                        
    ^--- text left aligned    ^---- here the radiobuttons/check boxes right alignedI know how to set text on the left side: myRadioButton.setHorizontalTextPosition(myRadioButton.LEADING).
    This is not a problem.
    Thanx,
    Xavier.

    Looking at this, I can't see an easy way. Using the
    components you specified, I guess I would set the font
    to a fixed size font, and pad the labels with spaces.
    If I was going it, I would make each label a JLabel,
    not assign a label to a checkbox, and put them
    together with a GridLayout. Hope this helpsWell this can be a solution but I would like two things:
    -1 be able to use any font
    -2 have the default behaviour of RadioButton or Checkbox
    that is text also selectable not only the button itself.
    I tried another solution: working the FontMetrics and
    defined gap between text and icon. But it must be buggy
    because it is look and feel (L&F) dependant. In my example,
    it only works as expected for motif L&F (i'm running under XP).
    And funny enough in my real application, it also works on XP.
    Metal that should be the most portable is the worse! :(
    I tried J2SE 1.4.3_02 and 1.5.0beta1: same result reagding
    alignement.
    Is it a bug or a mistake from my side?
    Here is my code:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class DoubleAligned extends JFrame {
      protected JMenu lookAndFeelMenu;
      protected Action metalAction;
      protected Action motifAction;
      protected Action windowsAction;
      public static final String METAL_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
      public static final String MOTIF_LOOK_AND_FEEL = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
      public static final String WINDOWS_LOOK_AND_FEEL = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
      protected JPanel singleAlignementPane;
      protected JPanel doubleAlignementPane;
      protected ButtonGroup singleBG;
      protected JRadioButton jRadioButton_s1;
      protected JRadioButton jRadioButton_s2;
      protected JRadioButton jRadioButton_s3;
      protected JRadioButton jRadioButton_s4;
      protected JCheckBox jCheckBox_s1;
      protected Set buttonSet;
      protected ButtonGroup doubleBG;
      protected JRadioButton jRadioButton_d1;
      protected JRadioButton jRadioButton_d2;
      protected JRadioButton jRadioButton_d3;
      protected JRadioButton jRadioButton_d4;
      protected JCheckBox jCheckBox_d1;
      /** Creates a new instance of JSCResultModePanel */
      public DoubleAligned(String title) {
        super(title);
        lookAndFeelMenu = createLookAndFeelMenu();
        JMenuBar mb = new JMenuBar();
        mb.add(lookAndFeelMenu);
        setJMenuBar(mb);
        JPanel jPanel = new JPanel();
        jPanel.setLayout(new BorderLayout());
        singleAlignementPane = createSingleAlignPane();
        doubleAlignementPane = createDoubleAlignPane();
        jPanel.add(singleAlignementPane,BorderLayout.WEST);
        jPanel.add(doubleAlignementPane,BorderLayout.EAST);
        setContentPane(jPanel);
      private JPanel createSingleAlignPane() {
        JPanel jPanel = new JPanel();
        jPanel.setBorder(BorderFactory.createTitledBorder("Single aligned (swing default)"));
        // Creation of the layout
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        c.weighty = 1.0;   //request any extra vertical space
        c.weightx = 1.0;   //request any extra horizontal space
        c.gridwidth = 1;
        c.insets = new Insets(2,2,2,2);
        c.anchor = GridBagConstraints.EAST;
        c.fill = GridBagConstraints.BOTH;
        jPanel.setLayout(gridbag);
        // Creation of sub elements
        singleBG = new ButtonGroup();
        jRadioButton_s1 = new JRadioButton("First radio button long text");
        jRadioButton_s1.setHorizontalTextPosition(JRadioButton.LEADING);
        jRadioButton_s1.setBackground(Color.PINK);
        jRadioButton_s2 = new JRadioButton("2nd is shorter");
        jRadioButton_s2.setHorizontalTextPosition(JRadioButton.LEADING);
        jRadioButton_s2.setBackground(Color.GREEN);
        jRadioButton_s3 = new JRadioButton("shortest");
        jRadioButton_s3.setHorizontalTextPosition(JRadioButton.LEADING);
        jRadioButton_s3.setBackground(Color.RED);
        jRadioButton_s4 = new JRadioButton("4th");
        jRadioButton_s4.setHorizontalTextPosition(JRadioButton.LEADING);
        jRadioButton_s4.setBackground(Color.MAGENTA);
        singleBG.add(jRadioButton_s1);
        singleBG.add(jRadioButton_s2);
        singleBG.add(jRadioButton_s3);
        singleBG.add(jRadioButton_s4);
        jCheckBox_s1 = new JCheckBox("Check box is also taken into account");
        jCheckBox_s1.setHorizontalTextPosition(JCheckBox.LEADING);
        jCheckBox_s1.setBackground(Color.YELLOW);
        // Layout of all the components (components added column by column)
        c.gridx = 0;
        c.gridy = 0;
        jPanel.add(jRadioButton_s1,c);
        c.gridy = 1;
        jPanel.add(jRadioButton_s2,c);
        c.gridy = 2;
        jPanel.add(jRadioButton_s3,c);
        c.gridy = 3;
        jPanel.add(jRadioButton_s4,c);
        c.gridy = 4;
        jPanel.add(jCheckBox_s1,c);
        return jPanel;
      private JPanel createDoubleAlignPane() {
        JPanel jPanel = new JPanel();
        jPanel.setBorder(BorderFactory.createTitledBorder("Double aligned"));
        // Creation of the layout
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        c.weighty = 1.0;   //request any extra vertical space
        c.weightx = 1.0;   //request any extra horizontal space
        c.gridwidth = 1;
        c.insets = new Insets(2,2,2,2);
        c.anchor = GridBagConstraints.EAST;
        c.fill = GridBagConstraints.BOTH;
        jPanel.setLayout(gridbag);
        // Creation of sub elements
        doubleBG = new ButtonGroup();
        buttonSet = new HashSet();
        int largerButtonSize = 0;
        jRadioButton_d1 = new JRadioButton("First radio button long text");
        jRadioButton_d1.setHorizontalTextPosition(JRadioButton.LEADING);
        jRadioButton_d1.setBackground(Color.PINK);
        buttonSet.add(jRadioButton_d1);
        jRadioButton_d2 = new JRadioButton("2nd is shorter");
        jRadioButton_d2.setHorizontalTextPosition(JRadioButton.LEADING);
        jRadioButton_d2.setBackground(Color.GREEN);
        buttonSet.add(jRadioButton_d2);
        jRadioButton_d3 = new JRadioButton("shortest");
        jRadioButton_d3.setHorizontalTextPosition(JRadioButton.LEADING);
        jRadioButton_d3.setBackground(Color.RED);
        buttonSet.add(jRadioButton_d3);
        jRadioButton_d4 = new JRadioButton("4th");
        jRadioButton_d4.setHorizontalTextPosition(JRadioButton.LEADING);
        jRadioButton_d4.setBackground(Color.MAGENTA);
        buttonSet.add(jRadioButton_d4);
        singleBG.add(jRadioButton_d1);
        singleBG.add(jRadioButton_d2);
        singleBG.add(jRadioButton_d3);
        singleBG.add(jRadioButton_d4);
        jCheckBox_d1 = new JCheckBox("Check box is also taken into account");
        jCheckBox_d1.setHorizontalTextPosition(jCheckBox_d1.LEADING);
        jCheckBox_d1.setBackground(Color.YELLOW);
        buttonSet.add(jCheckBox_d1);
        // Layout of all the components (components added column by column)
        c.gridx = 0;
        c.gridy = 0;
        jPanel.add(jRadioButton_d1,c);
        c.gridy = 1;
        jPanel.add(jRadioButton_d2,c);
        c.gridy = 2;
        jPanel.add(jRadioButton_d3,c);
        c.gridy = 3;
        jPanel.add(jRadioButton_d4,c);
        c.gridy = 4;
        jPanel.add(jCheckBox_d1,c);
        return jPanel;
      private JMenu createLookAndFeelMenu() {
        JMenuItem menuItem = null;
        JMenu jMenu = new JMenu("Look and feel");
        // *** Metal menu item ***
        metalAction = new AbstractAction("Metal", null) {
          public void actionPerformed(ActionEvent e) {
            updateLookAndFeel(METAL_LOOK_AND_FEEL);
        menuItem = jMenu.add(metalAction);
        // *** Motif menu item ***
        motifAction = new AbstractAction("Motif", null) {
          public void actionPerformed(ActionEvent e) {
            updateLookAndFeel(MOTIF_LOOK_AND_FEEL);
        menuItem = jMenu.add(motifAction);
        // *** Windows menu item ***
        windowsAction = new AbstractAction("Windows",null) {
          public void actionPerformed(ActionEvent e) {
            updateLookAndFeel(WINDOWS_LOOK_AND_FEEL);
        menuItem = jMenu.add(windowsAction);
        return jMenu;
      private int getMax(int item1, int item2) {
        return item1<item2 ? item2 : item1;
      public void paint(Graphics g) {
        FontMetrics fm = getFontMetrics( g.getFont( ) );
        String stringButton;
        AbstractButton myButton;
        int maxWidth;
        Iterator i;
        maxWidth = 0;
        i = buttonSet.iterator();
        // Hack to have text on the left and left aligned with the buttons themselves
        // on the right and right aligned to.
        // WARNING: Do not use HTML button because Button.getText will return the
        // HTML source not the result. Note also that it's not possible to use
        // Button.getSize().width because it returns the size after the layout process
        // it for display.
        while (i.hasNext()) {
          stringButton = ((AbstractButton)i.next()).getText();
          maxWidth = getMax(maxWidth, fm.stringWidth(stringButton));
        i = buttonSet.iterator();
        int currentWidth;
        int newGap;
        while (i.hasNext()) {
          AbstractButton currentButton = (AbstractButton)i.next();
          stringButton = currentButton.getText();
          currentWidth = fm.stringWidth(stringButton);
          newGap = maxWidth - currentWidth + 10;
          currentButton.setIconTextGap(newGap);
        super.paint(g);
      public void updateLookAndFeel(String lookAndFeel) {
        try {
          UIManager.setLookAndFeel(lookAndFeel);
          SwingUtilities.updateComponentTreeUI(this);
        } catch (Exception e) {
          // log an error
      public static void main(String []args) {
        DoubleAligned frame = new  DoubleAligned("A solution to have double alignemnt of several radio buttons/check boxes");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

  • JTable with JCheckbox problems

    Ok so I have a couple of questions. I have a JTable with a column represented as a checkbox.
    1. If I put the checkbox column as the first in the table, the rest of the cells are blank/null. Any idea what the reason is?
    2. What is the best workaround to having draggable columns, meaning icons/checkboxes don't render if you move the columns around?
    3. Does anyone have some links to good resources on JTables and things like custom components in them. I have googled but don't get many good links so would appreciate any help
    Code snippet as follows:
    public class ClobberTableCellRenderer implements TableCellRenderer
    private JPanel renderPanel = new JPanel(new BorderLayout());
    private JLabel renderLbl = new JLabel("");
    private JCheckBox checked = new JCheckBox();
    private Icon successIcon;
    private Icon errorIcon;
    public Component getTableCellRendererComponent(JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row,
    int column)
    String columnName = table.getModel().getColumnName(column);
    if (value == null)
    return null;
    else if ("Status".equals(columnName) && "ok".equals(value))
    renderLbl.setIcon(successIcon);
    renderLbl.setText("");
    renderPanel.remove(checked);
    else if ("Status".equals(columnName) && "error".equals(value))
    renderLbl.setIcon(errorIcon);
    renderLbl.setText("");
    renderPanel.remove(checked);
    else if ("Active".equals(columnName))
    renderLbl.setText("");
    renderPanel.add(checked);
    renderPanel.setBackground(Color.white);
    else
    renderLbl.setHorizontalAlignment(value instanceof Date || value instanceof Number ? JLabel.RIGHT : JLabel.LEFT);
    renderLbl.setIcon(null);
    renderLbl.setText(value instanceof Date ? df.format((Date)value) : value.toString());
    renderLbl.setToolTipText(null);
    renderPanel.setToolTipText(null);
    renderPanel.remove(checked);
    if (isSelected)
    renderPanel.setBackground((Color)UIManager.getDefaults().get("Table.selectionBackground"));
    else
    renderPanel.setBackground((Color)UIManager.getDefaults().get("Table.background"));
    return renderPanel;
    }

    Hi :) I have also worked on JTables and JCheckBoxes before. This article
    helped me a lot: http://www-128.ibm.com/developerworks/java/library/j-jtable/

  • Actions and mnemonic keys

    Hi all
    I have a JToolBar with some Actions (classes that extend AbstractAction) and I would like to associate shortcut keys to those Actions, something like ctrl + n to open a new window. How can I do that? Any pointers or ideas would be welcome.

    For selection guidelines see the section Mnemonics which is referenced from Java look and feel Graphics Repository.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ActionMnemonics
        private JToolBar getToolBar()
            JToolBar toolBar = new JToolBar(JToolBar.HORIZONTAL);
            toolBar.add(one);
            JButton button = toolBar.add(two);
            button.setMnemonic(KeyEvent.VK_T);
            return toolBar;
        private Action one = new AbstractAction("one")
                putValue(Action.MNEMONIC_KEY, KeyEvent.VK_O);
            public void actionPerformed(ActionEvent e)
                System.out.println(getValue(Action.NAME));
        private Action two = new AbstractAction("two")
            public void actionPerformed(ActionEvent e)
                System.out.println(getValue(Action.NAME));
        public static void main(String[] args)
            ActionMnemonics test = new ActionMnemonics();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test.getToolBar(), "North");
            f.setSize(300,200);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Give static size to Jcomponents

    Hi,
    I have problem to fix the size of my JLabel, JComboBox and JCheckBox.
    Those components are included in a JPanel which is included in a GridLayout component.
    However I used the following propertie :
    tabComboBox.setPreferredSize(new Dimension(80, 5));
    If I run my application, this size isn't set.
    It depends of the "JPanel", I think ?
    If somebody has an idea how to do that ?
    Thanks.

    And I saw that "GridBagLayout" doesn't offer the same possibility ?Sure it does. You just need to become familiar with the various constraints. Check out the tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use Layout Managers.
    Or, you can always mix and match LayoutManagers. Maybe something like:
    JPanel main = new JPanel( new GridLayout(0, 1) );
    for (each row)
    JPanel row = new JPanel();
    row.add(label);
    row.add(comboBox);
    row.add(checkBox);
    main.add(row);

  • Keybindings for undo/redo buttons.

    I thought I knew how to do this, and I do seem to have this working fine for cut/copy/paste/select all keybindings CTRL X/C/V/A respectively.
    However I tried to do this for CTRL X and Y undo/redo and it's not working as I intended. Can anyone see what I'm doing wrong?
    I created a SSCCE based off the original example I was following from: [http://www.java2s.com/Code/Java/Swing-JFC/Undoredotextarea.htm]
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.KeyStroke;
    import javax.swing.event.UndoableEditEvent;
    import javax.swing.event.UndoableEditListener;
    import javax.swing.undo.CannotRedoException;
    import javax.swing.undo.UndoManager;
    public class UndoRedoTextArea extends JFrame implements KeyListener{
        private static final long serialVersionUID = 1L;
        protected JTextArea textArea = new JTextArea();
        protected UndoManager undoManager = new UndoManager();
        protected JButton undoButton = new JButton("Undo");
        protected JButton redoButton = new JButton("Redo");
        public UndoRedoTextArea() {
            super("Undo/Redo Demo");
            undoButton.setEnabled(false);
            redoButton.setEnabled(false);
            JPanel buttonPanel = new JPanel(new GridLayout());
            buttonPanel.add(undoButton);
            buttonPanel.add(redoButton);
            JScrollPane scroller = new JScrollPane(textArea);
            getContentPane().add(buttonPanel, BorderLayout.NORTH);
            getContentPane().add(scroller, BorderLayout.CENTER);
            textArea.getDocument().addUndoableEditListener(
                new UndoableEditListener() {
                    public void undoableEditHappened(UndoableEditEvent e) {
                        undoManager.addEdit(e.getEdit());
                        updateButtons();
            undoButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    try {
                        undoManager.undo();
                    } catch (CannotRedoException cre) {
                        cre.printStackTrace();
                    updateButtons();
            undoButton.addKeyListener(this);
            redoButton.addKeyListener(this);
            redoButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    try {
                        undoManager.redo();
                    } catch (CannotRedoException cre)  {
                        cre.printStackTrace();
                    updateButtons();
            setSize(400, 300);
            setVisible(true);
        public void updateButtons() {
            undoButton.setText(undoManager.getUndoPresentationName());
            redoButton.setText(undoManager.getRedoPresentationName());
            undoButton.setEnabled(undoManager.canUndo());
            redoButton.setEnabled(undoManager.canRedo());
        public static void main(String argv[]) {
            new UndoRedoTextArea();
        public void keyPressed(KeyEvent e){
            if (e.equals(KeyStroke.getKeyStroke
                (KeyEvent.VK_Z, InputEvent.CTRL_DOWN_MASK))){
                // undo
                try {
                    undoManager.undo();
                } catch (CannotRedoException cre)  {
                    cre.printStackTrace();
                updateButtons();
            else if (e.equals(KeyStroke.getKeyStroke
                    (KeyEvent.VK_Y, InputEvent.CTRL_DOWN_MASK))){
                // redo
                try  {
                    undoManager.redo();
                } catch (CannotRedoException cre) {
                    cre.printStackTrace();
                updateButtons();
        public void keyTyped(KeyEvent e){}
        public void keyReleased(KeyEvent e){}
    }Edited by: G-Unit on Oct 24, 2010 5:30 AM

    camickr wrote:
    So the way I posted in the second lump of code OK (3rd post) or did you mean something different? Why did you set the key bindings? Did I not state they would be created automatically? I think you need to reread my suggestion (and the tutorial).Because I don't get it, it says only Menu items can contain accelerators and buttons only get mnemonics. I'm not using menu items here, I only have a text pane and 2 buttons. So I set the actions for the InputMap in TextPane. For the buttons, I pretty much used the small bit of code using undoManager.
    I tried to set KEYSTROKE constructor for the action and simply add them to the buttons that way, but this didn't seem to have any response.
    Also I don't get how this could happen anyway if the TextPane has the focus.
    Not like the example using MNEMONICS.
        Action leftAction = new LeftAction(); //LeftAction code is shown later
        button = new JButton(leftAction)
        menuItem = new JMenuItem(leftAction);
    To create an Action object, you generally create a subclass of AbstractAction and then instantiate it. In your subclass, you must implement the actionPerformed method to react appropriately when the action event occurs. Here's an example of creating and instantiating an AbstractAction subclass:
        leftAction = new LeftAction("Go left", anIcon,
                     "This is the left button.",
                     new Integer(KeyEvent.VK_L));
        class LeftAction extends AbstractAction {
            public LeftAction(String text, ImageIcon icon,
                              String desc, Integer mnemonic) {
                super(text, icon);
                putValue(SHORT_DESCRIPTION, desc);
                putValue(MNEMONIC_KEY, mnemonic);
            public void actionPerformed(ActionEvent e) {
                displayResult("Action for first button/menu item", e);
        }This is what I attempted. No errors... It just doesn't work.
    public JPanel p()
        undoButton.addActionListener(new UndoAction(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Event.CTRL_MASK)));
        panel.add(undoButton);
        return panel;
    private class UndoAction extends AbstractAction
         public UndoAction(KeyStroke keyStroke)
              putValue(ACCELERATOR_KEY, keyStroke);
         private static final long serialVersionUID = 1L;
         public void actionPerformed(ActionEvent e)
              try
                   if (undoManager.canUndo())
                        undoManager.undo();
              catch (CannotRedoException cre)
                   cre.printStackTrace();
              updateButtons();
    }Edited by: G-Unit on Oct 25, 2010 8:32 AM

  • Best way to initialize a GUI

    Let's say I want to construct a GUI that has over 120 components composed of JTextFields, JLabels and JCheckBoxes. Each component will have an event listener, aside from the JLabels. This GUI will be displaying and inserting data into a database. Should all of this code go into the same class, as opposed to whatever the alternative would be?
    Just seems like alot of code for one class. Is this how GUI's are usually initialized, in one class?
    Thanks everyone.

    Consider whether subsections of the GUI are reusable.
    If so, write separate classes for those. Otherwise put it all in the same class.
    For example, a widget for entering a date may have 3 components, one each for day, month, year. This widget is likely to be reusable. You may even want to use it several times on the same form. Therefore I would create a DateGUI class which would extend JPanel.

  • Components not showing in java 1.4

    I have a small program where some JLabels, JTextFields, JComboBoxes and JCheckBoxes are shown in a JFrame. It works fine in JBuilder 7 but when I tried to run it outside JBuilder, where I have java 1.4.1 installed, the components are not showing correctly. The JLabels are not shown att all and the rest of the components are not fully painted, if at all. If I run it from the bin directory in JBuilder, where java 1.3 is installed, the program works fine.
    Anybody have any idea what could be wrong?

    I have tried compiling both with javac and in JBuilder and in JBuilder and java 1.3 it works fine, but with java 1.4.1 it doesn't.
    I am not using any special JBuilder layout, I have written all the code by hand (haven't figured out the design function in jBuilder yet).

  • JTextField doesn't cause a validateTree()

    Hello,
    I've written a new layout manager. If I change the visible state of a component the layout manager should do a new layout. This works for
    JLabel, JButton, JRadioButton, JCombobox, JPanel and JCheckbox but not for JTextField.
    After debugging I noticed, that JTextField is the only Component witch ovewrites the method isValidateRoot() and so it returns true instead of false. This causes that the RepaintManager.addInvalidComponent() returns before it adds an event to the EventQueue if the JTextfield is changed to visible = false.
    Is this a bug, or how can I solv this problem?
    Thx
    Guido

    If somebody has an answer to this question I would still be very interested.
    I am also puzzled about the logic inside the method isValidateRoot() inside JTextField:
        public boolean isValidateRoot() {
         Component parent = getParent();
         if (parent instanceof JViewport) {
             return false;
            return true;
        }Meaning the JTextField is itself in charge for handling layout updates inside its own boundaries, but also when calling setVisible(true) on the JTextField. The documentation says that it is for handling calls to revalidate from within the component itself (unless it is contained inside a JViewport). I don't understand this. If anyone can explain this?
    At first sight overriding isValidateRoot() always returning true in a subclass of JTextField would also solve the problem. But that could lead to a much heavier revalidation of the internal JTextField mechanisms?
    Conclusion (without knowing answers to the questions above) is that when you call setVisible on a JTextField that you have to call revalidate() on its container again in order to see the new layout situation.

  • JDBC with Swing ?

    Hi,
    I want to build a Java application that accesses an Oracle database. I want the fields of that form (JTextField) to be somehow "assocated" to the database's table so that whenever I update the field all I have to do is a save (or commit).
    I know Borland has a bunch of tools like that (com.borland.dx.dataset), but I want to stay away from that Borland-specific stuff.
    Is that possible to do with the Rowset Implementation ? Do I need something else ?
    Thanks !

    Here is what I mean :
    Let say you have a JFrame with a few JTextFields and JCheckBox, and you want to have a simple query returning the results into those fields.
    Then, after modifying the value of those fields, you want to click on Save.
    Is there a way to show the query data in those fields and "post" the changes without saying : JTextField value goes to that table column, etc.
    Something like :
      jtextfield1.assignToTable("MYTABLE");
      jtextfield1.assignToColumn("PRODUCT_ID");And whenever I update or requery this database table, the associated fields would get populated automatically.
    Regards,
    Alexandre

  • What is an event handler..?

    I'm trying to learn how to make responsiveness UI. I've read that I can not use SwingUtilities.invokeLater() method if I am in a event handler. The question can seems stupid but I'm only a beginner: what is a event handler? From what I know it might be the actionPerformed method..is it right? Could somebody give me an example? thanks!

    Basically an event handler is a class that performs code.
    It can be any class (even the same that fires the event), but it has to implement the proper interface for the event you want to catch. If you want to perform special code when someone clicks on a button you want to catch an Action, therefor you need an ActionListener, a class that either implements the ActionListener interface (and therefor the method actionPerformed) or your class has to extend AbstractAction (and therefor has an actionPerformed, too).
    It you want to perform special code when someone chooses an element from a list, you want to be informed about a ListSelectionEvent and therefor need a class that implements the ListSelectionListener Interface (and provides the method selectionChanged).
    The class that should react on the event has to be declared as being a listener to the object that fires the events. So an actionListener on a Button would be added by
    button.addActionListener(listener);or
    button.setAction(action);(Note that all variables used are just for clarifiing the type you need and have to be exchanged by the names of your declared objects)
    There are many more events ... really, read the tutorial!

Maybe you are looking for

  • Ipad - Itunes Unknown Error Message 0xE800000A

    All..Apologies if this has turned up before but can't find anything on the internet/forum - Proud owner of a Ipad 64G purchased today 30/10/10 - can I get Itunes to recognise it...no! Get a very annoying error message 'Itunes could not connect to thi

  • How to you "publish" Bonjour Shared printers using Workgroup Manager?

    Dear Friends, Hello. We have just spend considerable time setting up Mac OS X 10.6.4 server to host some printers to our Mac clients (previously we had used a Windows print server but it was too slow and inflexible). We have the printers we need set-

  • Import extended IDOC to Integration Builder

    Hi All, I´m faced with the following situation using an Idoc with customer extension from a SAP R/3 40B System with my scenario: IDX2 - Import works fine, basistype and extension in place Integration Builder: Can ´t see the extension with or without

  • Build multi-product contest entry form with payment

    I have a client that wants to build a contest entry form that allows the user to enter multiple products with details and totals the amount for payment in one form. Each product that will be entered into the contest will have the same price of $60. F

  • Jsp & struts problem

    I have a jsp that display some data from database. I display it in textarea , so that i can edit them , once editing is completed then i have to store that data in database again . Rows of data that i will be getting is dynamic . so i can not write s