Resizing JButtons in a BorderLayout

Hi, I've been working with a BorderLayout and whenever I try and set a JButton's size or preferredSize, it always ignores what I set it at and puts it's size as filling the entire BorderLayout.CENTER. Any ideas?

{color:#507C9A}1. In future, post Swing questions in the Swing forum: http://forum.java.sun.com/forum.jspa?forumID=57
2. The behaviour of a Borderlayout is to ignore a component's preferredSize and stretch it to fill the centre.
Solution: nest.
JPanel withBorderLayout = ...
JButton btn = ...
//withBorderLayout .add(btn, BorderLayout.CENTER);
JPanel centrePanel = new JPanel(); //FlowLayout by default, you may want to change this
centrePanel .add(btn);
withBorderLayout .add(centrePanel , BorderLayout.CENTER);{color}

Similar Messages

  • Resizing JButtons

    Here's the dilema- I'm trying to make an applet with a lot of buttons in each row, but I don't want the applet to stretch the width of the screen. Some of the buttons don't have anything on them but a "-" or a single digit number. How can I properly size these buttons down so that they don't take up as much space as the larger buttons?
    Here's what I'm dealing with:
    public class inputscreen extends JApplet {
      upstat x;
      String fname;
      String lname;
      String ppg, xft, xfta, home, pos, cl, ht, wt;
      Connection con = null;
      Statement st = null;
      ResultSet rs = null;
      int vfg, vfga, vt3, vt3a, vft, vfta, vrb, vas, vf, vtot;
      String updateString;
      Container cp = getContentPane();
      JTextField ply = new JTextField(3);
      JButton upd = new JButton("UD");
      String sfg;
      JButton fg = new JButton(sfg);
      JButton fgm = new JButton("-");
      String sfga;
      JButton fga = new JButton(sfga);
      JButton fgam = new JButton("-");
      String st3;
      JButton t3 = new JButton(st3);
      JButton t3m = new JButton("-");
      String st3a;
      JButton t3a = new JButton(st3a);
      JButton t3am = new JButton("-");
      String sft;
      JButton ft = new JButton(sft);
      JButton ftm = new JButton("-");
      String sfta;
      JButton fta = new JButton(sfta);
      JButton ftam = new JButton("-");
      String srb;
      JButton rb = new JButton(srb);
      JButton rbm = new JButton("-");
      String sas;
      JButton as = new JButton(sas);
      JButton asm = new JButton("-");
      String sf;
      JButton f = new JButton(sf);
      JButton fm = new JButton("-");
      String stot;
      JTextField tot = new JTextField(4);
      JButton player = new JButton("Player");
      JButton season = new JButton("Season");
      JButton tonight = new JButton("Tonight");
      public void init() {
        JPanel line = new JPanel();
        line.add(ply);
        line.add(upd);
        line.add(fg);
        line.add(fgm);
        line.add(fga);
        line.add(fgam);
        line.add(t3);
        line.add(t3m);
        line.add(t3a);
        line.add(t3am);
        line.add(ft);
        line.add(ftm);
        line.add(fta);
        line.add(ftam);
        line.add(rb);
        line.add(rbm);
        line.add(as);
        line.add(asm);
        line.add(f);
        line.add(fm);
        line.add(tot);
        JPanel lower = new JPanel();
        lower.add(player);
        lower.add(season);
        lower.add(tonight);
        line.setLayout(new GridLayout(2, 21));
        lower.setLayout(new FlowLayout());
        cp.setLayout(new BorderLayout());
        cp.add(line, BorderLayout.NORTH);
        cp.add(lower, BorderLayout.CENTER);
        upd.addActionListener(new ButtonListener());
        fg.addActionListener(new ButtonListener());
        fgm.addActionListener(new ButtonListener());
        fga.addActionListener(new ButtonListener());
        fgam.addActionListener(new ButtonListener());
        t3.addActionListener(new ButtonListener());
        t3m.addActionListener(new ButtonListener());
        t3a.addActionListener(new ButtonListener());
        t3am.addActionListener(new ButtonListener());
        ft.addActionListener(new ButtonListener());
        ftm.addActionListener(new ButtonListener());
        fta.addActionListener(new ButtonListener());
        ftam.addActionListener(new ButtonListener());
        rb.addActionListener(new ButtonListener());
        rbm.addActionListener(new ButtonListener());
        as.addActionListener(new ButtonListener());
        asm.addActionListener(new ButtonListener());
        f.addActionListener(new ButtonListener());
        fm.addActionListener(new ButtonListener());
        player.addActionListener(new ButtonListener());
        season.addActionListener(new ButtonListener());
        tonight.addActionListener(new ButtonListener());
      }I'm trying to figure out JButton.setPreferredSize(new Dimension(x,y)); with no success. If someone could give me an example of how to implement that or another technique of resizing individual buttons, I'd really appreciate it.

    The post by camickr is correct: Java components are sized by the layout manager managing the container in which they reside. Simply, GridLayout attempts to size every component the same -- your precise problem. If you use a GridBagLayout instead, the buttons will all respect their preferred size. See the given link.
    - Steev.

  • How to Resize JButton,JTextArea and JTextFields on Mouse Over....

    Hi All...
    Hi friends.. I want to be implement my java swing application Resize the Width and Height wise of JButton,JLabel,JTextFields on mouse over etc.
    ============================
    Arjun Palanichamy.
    Senior Programmer.
    Chennai-India.

    Hi All...
    I am herewith enclosed my sample code for resize the JButton(),But This one resize the when will be extend the Button Caption letters,But i want mouse click resize the without button caption or with caption.
    sample code :
    package Resize;
    import java.awt.Container;
    import java.awt.FlowLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import java.awt.Dimension;
    import java.awt.ComponentOrientation;
    public class ReButton{
    public static boolean RIGHT_TO_LEFT = false;
    public static void addComponents(Container contentPane) {
    if (RIGHT_TO_LEFT) {
    contentPane.setComponentOrientation(
    ComponentOrientation.RIGHT_TO_LEFT);
    contentPane.setLayout(new FlowLayout());
    contentPane.add(new JButton("1"));
    contentPane.add(new JButton("100"));
    contentPane.add(new JButton("100 100"));
    contentPane.add(new JButton("100 100 100"));
    contentPane.add(new JButton("100 100 100 100"));
    contentPane.add(new JButton("5"));
    private static void createAndShowGUI() {
    JFrame frame = new JFrame("FlowLayoutDemo") {
    public Dimension getMinimumSize() {
    Dimension prefSize = getPreferredSize();
    return new Dimension(100, prefSize.height);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Set up the content pane.
    addComponents(frame.getContentPane());
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    for example can you Click this.....
    http://www.eclipse.org/vep/WebContent/docs/testcases/null-layout/null-layout.htm
    Thanks for your time.
    Arjun Palanichamy.
    Chennai-India.

  • Problems resizing JButtons

    Hi. I have a GUI with a JPanel to which I have added 43 JButtons. I use a for loop to add the buttons but I cannot set the size of individual buttons. I want two of the buttons to be bigger than the rest. Can anyone please help me

    Hi. I have a GUI with a JPanel to which I have added
    43 JButtons. I use a for loop to add the buttons but I
    cannot set the size of individual buttons. I want two
    of the buttons to be bigger than the rest. Can anyone
    please help meAs some else has mentioned, much depends on your
    layout manager. You be able to do the job with
    GridBagLayout, but if that's too much like hard
    work, you can always turn the panel's layout manager off
    and manually place & size each of your buttons.
    setLayout( null );
    and for each button:
    button.setBounds( x, y, width, height );
    If you do this, the buttons won't move or expand
    when the panel is resized. I reckon that's not
    a bad thing for buttons anyway.

  • Resize JButtons Using FlowLayout ?

    I'm using some images for my Jbuttons and when I use FlowLayout, it sets the buttons dimensions bigger than the images and I can't figure out how to set the dimensions while having FlowLayout set too. They look fine when I use absolute positioning, but I need the flexibility of FlowLayout for different resolutions, etc. Anyonw know how to set the dimensions of a JButton while having FlowLayout set too? Thanks so much!

    As far as I know, FlowLayout doesn't adjust the size of
    components at all. Can you post a short, self-contained,
    compileable example that shows the offending behavour?
    You should be able to do new JButton(myIcon); or
    myButton.setIcon(myIcon); and have it Just Work. The button
    should resize itself to contain the icon.

  • Resizing JButton on JPanel?

    Hi all,
    I just started to learn to use swing and I ran into problem when I try to change the size of a JButton on JPanel. The following code make sense to me, but it just doesn't work. Am I missing something? Can anyone give me some directions?
    import javax.swing.*;
    public class TestFrame extends JFrame
         public static void main(String[] args)
              TestFrame myFrame = new TestFrame();
              myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              myFrame.setVisible(true);
         private JPanel myPanel = new JPanel();
         private JButton myBtn = new JButton("Test");
         public TestFrame()
              setSize(300, 300);
              myBtn.setSize(200, 200); // the button size still does not change
              myPanel.add(myBtn);     
              getContentPane().add(myPanel);          
    }

    use setPreferredSize instead of setSize
    import javax.swing.*;
    import java.awt.Dimension;
    public class TestFrame extends JFrame
         public static void main(String[] args)
              TestFrame myFrame = new TestFrame();
              myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              myFrame.setVisible(true);
         private JPanel myPanel = new JPanel();
         private JButton myBtn = new JButton("Test");
         public TestFrame()
              setSize(300, 300);
              //myBtn.setSize(200, 200); // the button size still does not change
              myBtn.setPreferredSize(new Dimension(200, 200));
              myPanel.add(myBtn);     
              getContentPane().add(myPanel);          
    }

  • How to resize data in JTable?

    Hi all,
    I wish to provide a resize button on an application which will resize the data in a table (in most cases just text) as well as the table containing it. Is it possible to directly resize the table or must I change the renderer to draw all of the data bigger? I'm also not sure how to increase the width of the table. Any help would be much appreciated.
    package gui;
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.SwingUtilities;
    import javax.swing.table.DefaultTableModel;
    public class Resizer extends JFrame
         * @see java.io.Serializable
        public static final long serialVersionUID = 0;
         * Table containing data
        private JTable table = null;
         * Scroll pane containing table
        private JScrollPane scroller = null;
         * Name of button to increase text size
        private static final String INCREASE = "Increase";
         * Name of button to decrease text size
        private static final String DECREASE = "Decrease";
         * An increment to use when resizing
        private static final int INCREMENT = 5;
        public Resizer()
            setTitle("Resizer");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(300,200);
            getContentPane().setLayout(new BorderLayout());
            // Add the table and its contents
            table = createTable();
            scroller = new JScrollPane(table);
            getContentPane().add(scroller, BorderLayout.CENTER);
            // Add buttons to resize
            JButton increase = new JButton(INCREASE);
            increase.addActionListener(new ButtonListener());
            JButton decrease = new JButton(DECREASE);
            decrease.addActionListener(new ButtonListener());
            JPanel panel = new JPanel();
            panel.add(increase);
            panel.add(decrease);
            getContentPane().add(panel, BorderLayout.SOUTH);
            // Show this window
            setLocationRelativeTo(null);
            setVisible(true);
        private JTable createTable()
            JTable t = new JTable();
            t.setModel(new MyModel());
            // Row 1
            t.getModel().setValueAt("John", 0, 0);
            t.getModel().setValueAt(new Integer(1), 0, 1);
            // Row 2
            t.getModel().setValueAt("Chris", 1, 0);
            t.getModel().setValueAt(new Integer(2), 1, 1);
            // Row 3
            t.getModel().setValueAt("Susan", 2, 0);
            t.getModel().setValueAt(new Integer(3), 2, 1);
            return t;
        private class MyModel extends DefaultTableModel
            private static final long serialVersionUID = 2;
            public MyModel()
                this.setColumnCount(2);
                this.setRowCount(3);
            public String getColumnName(int col)
                switch(col)
                case 0:
                    return "Name";
                case 1:
                    return "Number";
                default:
                    return "Oops";
        private class ButtonListener implements ActionListener
            public void actionPerformed(ActionEvent ae)
                    if (((JButton)ae.getSource()).getText().equals(INCREASE))
                        increaseTable();  
                    else if (((JButton)ae.getSource()).getText().equals(DECREASE))
                        decreaseTable();
        private void increaseTable()
            this.setSize(this.getWidth()+INCREMENT, this.getHeight()+INCREMENT);
            table.setRowHeight(table.getRowHeight()+INCREMENT);
            table.setSize(table.getWidth()+INCREMENT, table.getHeight()+INCREMENT);
        private void decreaseTable()
            this.setSize(this.getWidth()-INCREMENT, this.getHeight()-INCREMENT);
            table.setRowHeight(table.getRowHeight()-INCREMENT);
            table.setSize(table.getWidth()-INCREMENT, table.getHeight()-INCREMENT);
        public static void main(String[] args)
            SwingUtilities.invokeLater(new Runnable()
                public void run()
                    new Resizer();
    }Using JDK 1.4.2

    Thanks all.
    The solution was to use setFont() on the table and its headers. Here's what I put in to increase and descrease the table size (for future reference).
         * Increases the size of everything in the table
        private void increaseTable()
            table.setRowHeight(table.getRowHeight() + INCREMENT);
            table.setSize(table.getWidth() + INCREMENT, table.getHeight() + INCREMENT);
            for (int i = 0; i < table.getColumnCount(); i++)
                TableColumn col = table.getColumnModel().getColumn(i);
                col.setWidth(col.getWidth() + INCREMENT / table.getColumnCount());
            Font headerFont = table.getTableHeader().getFont();
            table.getTableHeader().setFont(headerFont.deriveFont(headerFont.getSize2D()+INCREMENT));
            Font dataFont = table.getFont();
            table.setFont(dataFont.deriveFont(dataFont.getSize2D() + INCREMENT));
         * Decreases the size of everything in the table
        private void decreaseTable()
            if (table.getRowHeight() > INCREMENT)
                table.setRowHeight(table.getRowHeight() - INCREMENT);
                table.setSize(table.getWidth() - INCREMENT, table.getHeight() - INCREMENT);
                for (int i = 0; i < table.getColumnCount(); i++)
                    TableColumn col = table.getColumnModel().getColumn(i);
                    col.setWidth(col.getWidth() - INCREMENT / table.getColumnCount());
                Font headerFont = table.getTableHeader().getFont();
                table.getTableHeader().setFont(headerFont.deriveFont(headerFont.getSize2D()-INCREMENT));
                Font dataFont = table.getFont();
                table.setFont(dataFont.deriveFont(dataFont.getSize2D() - INCREMENT));
        }

  • BorderLayout theoretical question

    Hello, i am trying to code an application GUI using BorderLayout. At the top of the GUI i.e. borderlayout.NORTH, i will like to have a group of JLabels and JTextFields.
    e.g.
    Man: Beard
    Tree: Mango
    etc..
    where man is the Label name and beard is the associated JTextField contents. I will have five such labels and textfields in the application GUI.
    My problem is that how do i add the group of labels and Textfields as a group to the top of frame using e.g. getContentPane.add( group of labels and textfields , borderlayout.NORTH). where " group of labels and textfields " will be the group of labels and textfields as indicated above.
    Your input will be very much appreciated.

    for example:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class LayoutExample extends JPanel
        public LayoutExample()
            setLayout(new BorderLayout());
            setPreferredSize(new Dimension( 450, 300));
            int eb = 15;
            setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
            JPanel northPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 5));
            JTextField manTField = new JTextField(12);
            JTextField treeTField = new JTextField(12);
            manTField.setText("Beard");
            treeTField.setText("Mango");
            northPanel.add(new JLabel("Man:"));
            northPanel.add(new JLabel("  "));
            northPanel.add(manTField);
            northPanel.add(new JLabel("     "));
            northPanel.add(new JLabel("Tree:"));
            northPanel.add(new JLabel("  "));
            northPanel.add(treeTField);
            add(northPanel, BorderLayout.NORTH);
            add(new JButton("Center Button"), BorderLayout.CENTER);
        private static void createAndShowGUI()
            JFrame frame = new JFrame("LayoutExample Application");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new LayoutExample());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }

  • JButton problem in MVC Using DefaultTableModel

    View:
    I have a JDialog that contains a JTable.
    Model:
    I extend DefaultTableModel
    Problem:
    I want a button at the bottom of the JDialog, that is not in the JTable.
    The button is supposed to change a value in the model, when clicked
    I want the button's text to change when the value in the model changes, so it displays the new value.
    But it seems to me the real view is the JTable, not the enclosing JDialog, so if I try to create the JButton in the Model, I can not access it outside the JTable So how do work around this?
    Any advice??

    Create a panel containing the JTable, say BorderLayout.Center and JButton at say, BorderLayout.south. Add the panel to the JDialog. The button can have actionListener with actionPeformed method to change the value in the table. You should be able to access the button outside of the Table that way.

  • Set minimum size for GridBagLayout

    Hi all,
    I have a dialog which using GridBagLayout. I spent quite a lot of time to test, but still got the following problems. Could anyone give me some solutions?
    1. How do I set the dialog to have a minimum size ?
    Since the dialog is sizeable, so I have to make this limitation to prevent the dialog being too small .
    I tried the following code:
            this.getContentPane().setMinimumSize(new Dimension(686,520));
            this.setMinimumSize(new Dimension(686,520));but it's still not work... , I can still resize it too small.. any other way ?
    2. How do I set its default size when dialog pop up?
    I don't know why the dialog always auto popup in maximum size.
    I have tried to use this.setSize(new Dimension(686, 536)); inside jbInit() function, but still not work...
    Please help ... Thanks a lot.

    Why dont you try this.setResizable(false);?
    Anyway I have given a sample program here using Gridbag layout and this dialog cannot be resized.
    import java.awt.BorderLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class SunExample28 extends JDialog {
         public SunExample28() {
              setTitle("JDialog with Fixed size");
              JLabel nameLbl = new JLabel("Name:");
              JLabel ageLbl = new JLabel("Age:");
              JTextField nameFld = new JTextField(10);
              JTextField ageFld = new JTextField(10);
              GridBagConstraints gbc = new GridBagConstraints();
              Insets in = new Insets(5,5,5,5);
              JPanel compPanel = new JPanel(new GridBagLayout());
              gbc.gridx = 0;
              gbc.gridy = 0;
              compPanel.add(nameLbl,gbc);
              gbc.insets = in;
              gbc.gridx = 1;
              gbc.gridy = 0;
              compPanel.add(nameFld, gbc);
              gbc.insets = in;
              gbc.gridx = 0;
              gbc.gridy = 1;
              compPanel.add(ageLbl, gbc);
              gbc.insets = in;
              gbc.gridx = 1;
              gbc.gridy = 1;
              compPanel.add(ageFld, gbc);
              JButton okBtn = new JButton("OK");
              JButton cancelBtn = new JButton("Cancel");
              JPanel btnPanel = new JPanel();
              btnPanel.add(okBtn);
              btnPanel.add(cancelBtn);
              getContentPane().add(compPanel, BorderLayout.CENTER);
              getContentPane().add(btnPanel, BorderLayout.PAGE_END);
              setDefaultCloseOperation(DISPOSE_ON_CLOSE);
              setSize(500,300);
              setResizable(false);
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              new SunExample28().setVisible(true);
    }

  • I need help with repaint() and validate() or something else im not aware of

    Im a teacher and im trying to make educational games for my students. This is a simplified code of something i want the applet to do. When the JButton is pressed i want the interior panels to change. In this case JPanel pan3 is my main panel and i want to be able to switch between JPanel pan1 and JPanel pan2 by pressing either [ JButton 1 ] or [ JButton 2 ].
    What is happening in my code here when i press one of the buttons is that the interior panel will change the first time but not the second time, plus it will freeze up.
    Here is the code if someone can help me.
    import java.awt.*;
    import javax.swing.*;
    public class PanelApplet extends JApplet
         public void init()
              Panelswitch ps=new Panelswitch();
              ps.pan3.add(ps);
              ps.paneBuilder();
              getContentPane().add(ps.pan3);
              resize(500,500);
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    public class Panelswitch extends JPanel implements ActionListener
         public static Panelswitch pan1=new Panelswitch();
         public static Panelswitch pan2=new Panelswitch();
         public JPanel pan3;
         public Panelswitch()
              pan3=new JPanel();
              pan3.setLayout(new GridLayout(1,1,5,5));
         public static final String ONE="ONE";
         public static final String TWO="TWO";
         JButton one=new JButton("one");
         JButton two=new JButton("two");
         JLabel oneLabel=new JLabel("One Label");
         JLabel twoLabel=new JLabel("Two Label");
         public void paneBuilder()
              setLayout(new GridLayout(3,1,5,5));
              add(one);
              one.setActionCommand(ONE);
              one.addActionListener(this);
              add(two);
              add(oneLabel);
              two.setActionCommand(TWO);
              two.addActionListener(this);
         public void paneBuilder2()
              setLayout(new GridLayout(1,3,5,5));
              add(twoLabel);
              add(one);
              one.setActionCommand(ONE);
              one.addActionListener(this);
              add(two);
              two.setActionCommand(TWO);
              two.addActionListener(this);
         public void actionPerformed(ActionEvent e)
              // Im trying to make this take down panel 2 and replace it with panel 1
              if(e.getActionCommand().equals(ONE))
                   pan2.setVisible(false);
                   pan3.removeAll();
                   pan3.setLayout(new GridLayout(1,1,5,5));
                   pan1.paneBuilder();
                   pan1.setVisible(true);
                   pan3.add(pan1);
                   pan3.validate();
                   pan3.repaint();
                   System.out.println("one");
              // Im trying to make this take down panel 1 and replace it with panel 2
              if(e.getActionCommand().equals(TWO))
                   pan1.setVisible(false);
                   pan3.removeAll();
                   pan3.setLayout(new GridLayout(1,1,5,5));
                   pan2.paneBuilder2();
                   pan2.setVisible(true);
                   pan3.add(pan2);
                   pan3.validate();
                   pan3.repaint();
                   System.out.println("two");
    Thanks for looking

    Here's some sample code:
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JFrame;
    import javax.swing.JButton;
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    public class SwapFrame extends JFrame implements ActionListener {
      private JPanel firstPanel = new JPanel ();
      private JPanel secondPanel = new JPanel ();
      private JPanel buttonPanel = new JPanel ();
      private JButton addFirstJButton = new JButton("Foo");
      private JButton addSecondJButton = new JButton("Bar!");
      private Container frameContainer = null;
      public SwapFrame() {  // With JApplet, put this in your 'init()' method.
        // Frame specific.
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(new Dimension (400, 400));
        firstPanel.setLayout(new BorderLayout());
        firstPanel.add(new JButton ("Foo"), BorderLayout.CENTER);
        secondPanel.setLayout(new BorderLayout());
        secondPanel.add(new JButton ("Bar!"), BorderLayout.CENTER);
        buttonPanel.setLayout(new GridLayout(1, 2));
        buttonPanel.add(addFirstJButton);
        buttonPanel.add(addSecondJButton);
        addFirstJButton.addActionListener(this);
        addFirstJButton.setPreferredSize(new Dimension (100, 48));
        addSecondJButton.addActionListener(this);
        addSecondJButton.setPreferredSize(new Dimension (100, 48));
        frameContainer = getContentPane();
        frameContainer.setLayout(new BorderLayout());
        frameContainer.add(firstPanel, BorderLayout.CENTER);
        frameContainer.add(buttonPanel, BorderLayout.SOUTH);
        // Show application.
        this.validate();
        this.setVisible(true);
      public void actionPerformed (ActionEvent e) {
        if (e.getSource() instanceof JButton && ((JButton)e.getSource()) == addFirstJButton) {
          frameContainer.remove(secondPanel);
          frameContainer.add(firstPanel, BorderLayout.CENTER);
          this.validate();
          this.repaint();
        } else {  // There can only be two buttons...
          frameContainer.remove(firstPanel);
          frameContainer.add(secondPanel, BorderLayout.CENTER);
          this.validate();
          this.repaint();
      public static void main (String []args) {
        new SwapFrame();
    }Regards,
    Devyn

  • Exception occurred during event dispatching: ArrayIndexOutOfBoundsException

    Java GUI app that runs fine in NT, ported over to Linux (sparc), recompiled and I get the following traceback when I run it, happens whenever I generate a SWING event. JDK 1.3.0. I have the same problem with the swingset sample app as well:
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException: -1017
         at java.awt.Toolkit$SelectiveAWTEventListener.eventDispatched(Toolkit.java:1485)
         at java.awt.Toolkit.notifyAWTEventListeners(Toolkit.java:1355)
         at java.awt.Component.dispatchEventImpl(Component.java:2509)
         at java.awt.Container.dispatchEventToSelf(Container.java:1233)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:2449)
         at java.awt.LightweightDispatcher.trackMouseEnterExit(Container.java:2314)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:2189)     at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2125)
         at java.awt.Container.dispatchEventImpl(Container.java:1200)
         at java.awt.Window.dispatchEventImpl(Window.java:912)
         at java.awt.Component.dispatchEvent(Component.java:2499)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:333)
         at java.awt.EventDispatchThread.pumpOneEvent(EventDispatchThread.java:103)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:84)
    Here is also a small sample piece of code that makes it happen too. Whever I "hover" over the button this occurs.
    public class Test
    public static void
    main(String[] argv)
    throws Exception
    // set up GUI
    JFrame frame = new JFrame();
    frame.setBounds(0, 0, 100, 100);
    JPanel panel = new JPanel();
    frame.getContentPane().add(panel);
    panel.setLayout(new BorderLayout());
    panel.add(new JButton("Push me"), BorderLayout.NORTH);
    panel.add(new JLabel("Hello world"), BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    return;

    In the case of this problem, it happens EVERY TIME I run the application (and happens with Swingset too) and it DOES affect the application. I can't click on buttons, etc. All swing events seem to generate this trace back. I tried recompiling all the code thinking I might have a bad class file or something, but to no avail. Could this be a version mis-match? I'm running Linux 6.2.

  • Mouse wheel events aren't caught in browser

    Hello.
    I developed an applet with NetBeans 6.5 with mouse wheel zooming. In applet viewer everything works fine, but when I start applet in page in browser (I tried Firefox 3.0.6, MS IE 6.0, MS IE 7.0), no mouse wheel events (neither scrolling) are caught by applet.
    Any ideas?
    Thanks.

    The reason behind this is: When applet is run on web browser, the applet window does not get focus. If you can grab the focus somehow, mouse wheel events will work fine. However, this works fine in applet viewer and in older versions of JDK. This is broken in JDK 1.6 and already fixed in JDK 1.7. Please have a look into this bug:
    [http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6516675|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6516675]
    If you run following applet in your browser you will see mouse wheel events in action with JDK1.6:
    [In case it does not work, click on 'Click Me' button and try]
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    * @author mrityunjoy_saha
    public class TestApplet extends JApplet {
        public void init() {
             setLayout(new BorderLayout());
            XPane xPane = new XPane();
            //xPane.requestFocus();
            JScrollPane pane = new JScrollPane(xPane);
            //add(new JButton("Click Me"), BorderLayout.NORTH);
            add(pane, BorderLayout.CENTER);
        class XPane extends JPanel {
         private JLabel jLabel1;
            public XPane() {
                jLabel1 = new javax.swing.JLabel();
                addMouseWheelListener(new java.awt.event.MouseWheelListener() {
                    public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
                        formMouseWheelMoved(evt);
                jLabel1.setText("Mouse Wheel Info...");
                   add(jLabel1);
            private void formMouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
                jLabel1.setText(String.valueOf(evt.paramString()));
    }Thanks,
    Mrityunjoy

  • JFileChooser and links .lnk

    Hi. I'm having a problem with JFileChooser. When I try to click on a shortcut I get the file .lnk selected instead of the directory to it associated.
    Do you know how can I do this task?
    Alternatively I could use FileDialog..but, does it support Multiple Selection?
    Thanks very very much,
    Albert

    Hi ,
    use the class sun.awt.shell.ShellFolder
    the files are selected by the JFileChooser is a sun.awt.shell.ShellFolder
    sun.awt.shell.ShellFolder is a sub class of File
    This class contains a method isLink() , getLinkLocation() it will helps to
    get the link associated. I give the sample code and listen the actionPerformed
    method
    import java.awt.* ;
    import java.awt.event.* ;
    import java.io.* ;
    import javax.swing.*;
    import sun.awt.shell.ShellFolder;
    public class FCTest extends JFrame {
        public FCTest() {
            setTitle( "File Chooser Test" ) ;
            setDefaultCloseOperation( EXIT_ON_CLOSE ) ;
            init() ;
            setSize( 400 , 300 ) ;
            setVisible( true ) ;
        private JFileChooser fc ;
        private void init() {
            fc = new JFileChooser() ;
            fc.setMultiSelectionEnabled( true ) ;
            getContentPane().add( new JButton( new ButAct() ) , BorderLayout.SOUTH ) ;
        public class ButAct extends AbstractAction {
            public ButAct() {
                super( "My Button" ) ;
            public void actionPerformed( ActionEvent actEvt ) {
                int r = fc.showOpenDialog( FCTest.this ) ;
                if( r != JFileChooser.APPROVE_OPTION )
                    return ;
                File[] files = fc.getSelectedFiles() ;
                for( int i = 0 ; i < files.length ; i++ ) {
                    if( files[i] instanceof ShellFolder ) {
                        ShellFolder sf = ( ShellFolder ) files[i] ;
                        if( sf.isLink() ) {
                            try {
                                System.out.println( sf.getLinkLocation().getPath() );
                            } catch ( FileNotFoundException fnfe ) {
                                System.out.println( "Invalid Link : " + files.getPath() );
    } else {
    System.out.println( files[i].getPath() );
    } else {
    System.out.println( files[i].getPath() );
    public static void main(String[] args) {
    SwingUtilities.invokeLater( new Runnable() {
    public void run() {
    new FCTest() ;

  • Tree cell disapearing

    Hi
    I'm using Java 1.5.0.11
    I'm trying to make my own tree cell renderer and editor : the goal is to add to the standard tree cell (icon + uneditable text) an icon to the left, to indicate a certain "state". The state can be change by clicking on it, showxing a JPopupMenu to select a new one.
    In my proto, it works well, except that when I change one row, it is redrawn completely blank. I need to click on it again to have it appear.
    Any idea on why?
    Best regards

    TreeSelector. java
    package treeselectproto;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import javax.swing.AbstractAction;
    import javax.swing.AbstractCellEditor;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.tree.TreeCellEditor;
    import javax.swing.tree.TreeCellRenderer;
    import javax.swing.tree.TreePath;
    public class TreeSelector {
         protected JTree itsTree;
         protected JScrollPane itsScrollPane;
         protected Map<Object, State> itsStates=new HashMap<Object, State>();
         protected CellRenderer itsRenderer;
         protected JPopupMenu itsPopupMenu = new JPopupMenu();
         public TreeSelector()
              itsTree=new JTree();
              itsRenderer=new CellRenderer();
              itsTree.setCellRenderer(itsRenderer);
              itsTree.setCellEditor(itsRenderer);
              itsTree.setEditable(true);
              buildScrollPane();
              List<State> theStates=State.getPopupStates();
              for(State s:theStates)
                   PopupAction a=new PopupAction(s);
                   JMenuItem mi=new JMenuItem(a);
                   itsPopupMenu.add(mi);
         private void buildScrollPane() {
              itsScrollPane= new JScrollPane(itsTree,
                        ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
         public JScrollPane getScrollPane() {
              return itsScrollPane;
         @SuppressWarnings("serial")
         private  class CellRenderer extends AbstractCellEditor implements TreeCellRenderer, TreeCellEditor
              private JPanel itsPanel;
              private JLabel itsLabel;
              private JButton itsStateBtn;
              private BorderLayout itsLayout;
              public  CellRenderer()
                   itsPanel=new JPanel();
                   itsPanel.setLayout(itsLayout=new BorderLayout());
                   itsPanel.setDoubleBuffered(false);
                   itsLayout.setVgap(1);
                   itsLayout.setHgap(1);
                   itsLabel=new JLabel();
                   itsLabel.setDoubleBuffered(false);
                   itsPanel.add(itsLabel,BorderLayout.CENTER);
                   itsStateBtn=new JButton(new AbstractAction(){
                        public void actionPerformed(ActionEvent aE) {
                             showPopup();
                   itsStateBtn.setBorderPainted(true);
                   itsStateBtn.setContentAreaFilled(false);
                   itsStateBtn.setDoubleBuffered(false);
                   itsPanel.add(itsStateBtn,BorderLayout.WEST);
              protected void showPopup() {
                   itsPopupMenu.show(itsStateBtn, 0, 0);
              public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus)
                   TreePath thePath=tree.getPathForRow(row);
                   itsPanel.setBackground(tree.getBackground());
                   if(thePath != null)
                        State theState=getStateForTreePath(thePath);
                        String ic=theState.getSign();
                        itsStateBtn.setText(ic);
                   itsLabel.setText(value.toString());
                   itsStateBtn.setPreferredSize(null);
                   itsLabel.setPreferredSize(null);
                   itsPanel.setBackground( selected? Color.lightGray:tree.getBackground());
                   itsLayout.invalidateLayout(itsPanel);
                   return itsPanel;
              private Object itsValue;
              public Component getTreeCellEditorComponent(JTree aTree, Object aValue, boolean aIsSelected, boolean aExpanded, boolean aLeaf, int aRow) {
                   // if edting, it has the focus
                   itsValue=aValue;
                   return getTreeCellRendererComponent(aTree,aValue,aIsSelected,aExpanded,aLeaf,aRow,true);
              public Object getCellEditorValue() {
                   return itsValue;
         public State getStateForTreePath(TreePath thePath) {
              State ret=itsStates.get(thePath.getLastPathComponent());
              if(ret==null)
                   ret=State.defaultState();
              return ret;
         @SuppressWarnings("serial")
         private class PopupAction extends AbstractAction
              protected State itsState;
              public PopupAction(State aState) {
                   super(aState.getLabel());
                   itsState = aState;
              public void actionPerformed(ActionEvent aE) {
                   TreePath thePath=itsTree.getEditingPath();
                   Object theObj=thePath.getLastPathComponent();
                   itsStates.put(theObj, itsState);
    }

Maybe you are looking for

  • .mac Family pack:: questions about editing on two computers

    Hey I'm new and would love some advice. I'm a college student with some web experience. I'm helping out my folks' business by making them a website. I'd also like to have a website of my own. 1. It would be great if I could edit their business websit

  • VBOF - Not updating with Maximum no of items in FI reached.

    Hi All, When updating the billing documents in VBOF, iam getting error (not updating) due to  Maximum no of items in FI reached message. Did you face this kind of issue, what would be the best possible solution? Is there any SAP note for this. Regard

  • WRT54GS and wireless xbox

    Maybe stupid question but I'll ask anyway.  Just bought XBox 360.  Have a Linksys WRT54GS Wireless Router.  Do I need to purchase a wireless adapter for the Xbox 360 or is one built in and all I need to do is set it up? Solved! Go to Solution.

  • Access to PA20 - conflicts

    Hi I have just created a new role that gives display access to PA20, only for Infotypes 0001, 0002, 0024 and 0041 the role works fine for a user who has only ESS access This role gives access to all Empl Groups (e.g. EE) Another user needs this role

  • Light Weight JCE Provider with RSA implementation

    Hi all, I'm working on an applet that requires RSA encryption, but I have size constraints so I canno tuse the BouncyCastle provider (891 KBs) Does anyone know where to find a light weight JCE provider with an implementation of RSA, I've been searchi