Scrolling a JPanel

Hi, I'm relatively new to Java and I'm having trouble grasping what I think is a simple concept. I am writing an app which uses a JScrollPane to scroll over a JPanel with about 600 vertically stacked JTextFields and labels on it (its a big multiple choice test). Scrolling works fine with the mouse and pgup/down keys. The problem is that when I traverse the text fields with the tab key, the JPanel doesn't scroll. So, ok, that's kind of expected. But I'm really not sure how to implement this behavior. I read the ScrollPanel tutorial and looked at some of the demo code.
So as far as I can tell, each textfield needs an event listener which will tell me what keys were pressed: I need to determine if I am scrolling up or down (i.e. shift+tab or just tab is pressed). So I wait for that event and then I need to somehow calculate the proper visible Rectangle and call the scrollRectToVisible method on my JPanel, which will send a message to its parent- the scroll panel which will move the visible rectangle for me.
I would really appreciate some sample code snippets to help me along, or maybe I am barking up the wrong tree completely?
Thanks very much,
-Jonathan

So as far as I can tell, each textfield needs an
event listener which will tell me what keys were
pressed: I need to determine if I am scrolling up orNo. Use a FocusListener. And btw you can just use 1 focus listener for all your elements if you are clever about it
calculate the proper visible Rectangle and call thesee Component.getBounds()
scrollRectToVisible method on my JPanel, which will
send a message to its parent- the scroll panel which
will move the visible rectangle for me.Yes

Similar Messages

  • How to scroll a JPanel?

    I have class, which extends JPanel, in which I override
    the paintComponent(Graphics g) method
    I am drawing a graph and, depending on the input values, the graph can be wider than the JPanel. I would like to be able to add a scroll bar so the whole of the graph can be viewed.
    I have tried to make the JPanel implement scrollable
    and I have tried putting the JPanel within a JScrollpane
    but neithor work.
    please help!
    Simon

    You should be able to add the JPanel to the JScrollPane by doing the following (setting the scrollbars as required)
    // create a panel to hols the scrollpane
    JPanel aPanel = new JPanel();
    // create the scrollpane with your graph in it = yourPanel
    // disable the vertical scrollbar and enable the hoziontal
    JScrollPane aScrollPane = new JScrollPane(yourGraph, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    // set the scrollpane to the same size as the panel
    aScrollPane.setSize(aPanel.getSize());
    // add the scrollpane to the panel
    aPanel.add(aScrollPane);
    // refresh the layout
    aScrollPane.doLayout();
    Hope this helps - I had the same problem a couple of days ago!

  • How does one scroll a JPanel?

    I have a drawing area in my GUI which is a JPanel on which I draw graphics. I have added scrollbars but I cannot get the JPanel to scroll. I tried setting the size (setSize) of this JPanel much larger than it appears within its JFrame but no go.
    Any suggestions?

    You have to put your JPanel inside of a JScollPane. For example...
    JPanel jp = new JPanel();
    // add your stuff to the JPanel
    JScrollPane sp = new JScrollPane(jp);
    Alternatively you can call setViewportView on the JScrollPane...
    sp.setViewportView(jp);
    Hope this helps.

  • Line wrapping and scrolling in JPanel

    Hello,
    I've got an empty JPanel to which I want to add an (unknown) number of JLabels. Each JLabel has a text which is just one word. When my program is adding JLabels to the JPanel, I want it to have the same behaviour as a normal text editor: when a line is full, the next line gets filled (line wrapping).
    If I just keep adding JLabels to a JPanel of a fixed size with .add(), there's no line wrapping. I tried it by giving the JPanel a fixed size, flowLayout and nesting it within a JScrollPane, but it keeps filling one long line, instead of jumping to the next one.
    Any obvious solutions??
    Thanks
    Mark

    well this depends on how your layout is build, you should post some code so we can see what your trying to do.
    For example if your JPanel is the Frame's main panel, fixing a MaximumSize or PreferredSize wont have any effect, it will grow as big as you defined the JFrame size.
    If you have only a JPanel with a max size of 200,300 in a JFrame with a size of 800,600, it will grow to 800,600.
    You could create a BoxLayout with X axis, then insert an HorizontalStruts, insert your JPanel and another Horizontal Struts(Box.createHorizontalStrut(int width) ) to force the JPanel to be smaller than the JFrame.
    I did not test this a lot, but it seams to work
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test {
      public static MyFrame frame ;
      public static void main(String[] args) {
        frame = new MyFrame();
        frame.show(true);
        frame.pack();
      public static class MyFrame extends JFrame {
        JLabel a, b, c, d, e, f, g, h, i, j, k ;
        public MyFrame(){
          super();
          JPanel sizeLimiter = (JPanel)this.getContentPane();
          sizeLimiter.setLayout(new BoxLayout(sizeLimiter, BoxLayout.X_AXIS));
         // sizeLimiter.setPreferredSize(new Dimension(800,600));
          JPanel mainPanel = new JPanel();
          mainPanel.setLayout(new FlowLayout());
          mainPanel.setPreferredSize(new Dimension(400,300));
          mainPanel.setMinimumSize(new Dimension(400,300));
          a = new JLabel("this is sample test ");
          b = new JLabel("to demonstrate an example ");
          c = new JLabel("of simple a flow layout ");
          d = new JLabel("which is wrapping ");
          e = new JLabel("when it reaches the end ");
          f = new JLabel("of a line. ");
          g = new JLabel("Set the maximum size of the panel ");
          h = new JLabel("And it should work ");
          i = new JLabel("If it doesnt post your code so we can");
          j = new JLabel("check it out to see whats wrong ");
          k = new JLabel("sincerly yours, Jf Beaulac ");
          mainPanel.add(a);
          mainPanel.add(b);
          mainPanel.add(c);
          mainPanel.add(d);
          mainPanel.add(e);
          mainPanel.add(f);
          mainPanel.add(g);
          mainPanel.add(h);
          mainPanel.add(i);
          mainPanel.add(j);
          mainPanel.add(k);
          // Fix some "margins"
          sizeLimiter.add(Box.createHorizontalStrut(200));
          // Squeeze the panel
          sizeLimiter.add(mainPanel);
          sizeLimiter.add(Box.createHorizontalStrut(200));
        protected void processWindowEvent(WindowEvent e) {
          super.processWindowEvent(e);
          if (e.getID() == WindowEvent.WINDOW_CLOSING) {
            this.dispose();
    }Regards,
    Jf Beaulac

  • Having trouble with scrolling my  JPanel

    hello there,
    I'm building a simple GUI that consists of a JPanel containing JLabel objects that are added dynamically, during the execution of the program. I want the panel to be scrollable (if needed) and that's the instruction I've written for it :
    public class GUI extends JPanel
    JPanel jpanel = new JPanel( );
    JScrollPane sp = new JScrollPane( );
    sp.setViewportView( jpanel );
    add( sp , BorderLayout.CENTER );
    This code isn't complicated and should not be... so why isn't my panel scrollable when I'm adding JLabels to it???
    regars
    Peter

    You have to explicitly set the size of the panel. You are adding the labels on Panel but set the PreferredSize and SetSize explicitly.
    Cheers

  • Scrolling of text

    i want to scroll text in three lines at the same speed using
    any swing component,also without flickering,can anyone give me
    some sample codings regarding this
    thanks
    yas

    ok I got it to work correctly. Here you go:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    /* This is the component that scrolls.
    * It would actually be wiser to make
    * an AWT component, because AWT is thread-safe.
    * This component is slow because it has to use Timer. :(
    class Scroll extends JPanel implements ActionListener {
         Image buffer;
         int w,h,len,spd,x[],y[];
         String[] s;
         Dimension d;
         Font font;
         boolean first;
         Timer t;
         public Scroll() {
              font = new Font("SansSerif",Font.PLAIN,15);
              s = new String[] {"First string","Second string","Third string"};
              x = new int[s.length];
              this.y = new int[s.length];
              spd = 2;
              first = true;
              t = new Timer(1,this);
              t.start();
         public void actionPerformed(ActionEvent e) {
              if (e.getSource() instanceof Timer) {
                   for (int j = 0;j < y.length;j++) {
                        x[j] -= spd;
              repaint();
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              if (first) {
                   first = false;
                   d = getSize();
                   w = d.width;
                   h = d.height;
                   buffer = createImage(w,h);
                   FontMetrics f = getFontMetrics(font);
                   len = 0;
                   for (int y = 1;y <= this.y.length;y++) {
                        len = Math.max(len,f.stringWidth(s[y-1]));
                        this.y[y-1] = y*(f.getAscent()+(f.getAscent()/2));
                        x[y-1] = w;
              Graphics gfx = buffer.getGraphics();
              gfx.setColor(getBackground());
              gfx.fillRect(0,0,w,h);
              gfx.setColor(Color.black);
              for (int j = 0;j < y.length;j++) {
                   x[j]--;
                   if (x[j] < -len) {
                        x[j] = w;
                   gfx.drawString(s[j],x[j],y[j]);
              g.drawImage(buffer,0,0,null);
    /* This is an example container
    * that will hold the scroll component.
    * <applet code="ScrollApplet.class" width=400 height=400></applet>
    public class ScrollApplet extends JApplet {
         public void init() {
              getContentPane().add(new Scroll());
    }It should be able to scroll more than 3 lines... just add to the String array. :)

  • Scroll a Message

    I am building an application and I am interested in scrolling a message at the bottom of my application frame. Does anyone know of a Swing object I can use to do this.... Or any code I can't find to do this.

    Here is another example I found by searching the forum:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    /* This is the component that scrolls.
    * It would actually be wiser to make
    * an AWT component, because AWT is thread-safe.
    * This component is slow because it has to use Timer. :(
    class Scroll extends JPanel implements ActionListener
        Image buffer;
        int w,h,len,spd,x[],y[];
        String[] s;
        Dimension d;
        Font font;
        boolean first;
        Timer t;
        public Scroll()
            font = new Font("SansSerif",Font.PLAIN,15);
            s = new String[] {"First string","Second string","Third string"};
            x = new int[s.length];
            this.y = new int[s.length];
            spd = 2;
            first = true;
            t = new Timer(100,this);
            t.start();
        public void actionPerformed(ActionEvent e)
            if (e.getSource() instanceof Timer)
                for (int j = 0;j < y.length;j++)
                    x[j] -= spd;
            repaint();
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            if (first)
                first = false;
                d = getSize();
                w = d.width;
                h = d.height;
                buffer = createImage(w,h);
                FontMetrics f = getFontMetrics(font);
                len = 0;
                for (int i = 1; i <= y.length; i++)
                    len = Math.max(len,f.stringWidth(s[i-1]));
                    y[i-1] = i*(f.getAscent()+(f.getAscent()/2));
                    x[i-1] = w;
            Graphics gfx = buffer.getGraphics();
            gfx.setColor(getBackground());
            gfx.fillRect(0,0,w,h);
            gfx.setColor(Color.black);
            for (int j = 0; j < y.length; j++)
                x[j]--;
                if (x[j] < -len)
                    x[j] = w;
                gfx.drawString(s[j],x[j],y[j]);
            g.drawImage(buffer,0,0,null);
        public static void main(String[] args)
            JFrame frame = new JFrame();
            frame.getContentPane().add( new Scroll() );
            frame.setSize(200, 200);
            frame.setVisible( true );
    }I'm sure there are others but you can do your own searching.

  • Implementing a Scrollable JPanel

    Does anyone have any suggestions for making a JPanel scrollable? Apparently, simply placing the JPanel inside a JScrollPane doesn't work, since JPanel does not implement Scrollable. I guess the solution would be to implement a custom JScrollablePanel. Has anyone else come across this problem?
    Thanks.

    Ok - I figured it out - It's the FlowLayout that I'm
    using for the JPanel. It doesn't support wrapping.hmm, no, that's not it. FlowLayout is actually a simple/limited layout manager - it's preferred size is always calculated as though it should be on one line, but it will wrap if the panel's actual width is too small and it's height can accomodate more than 1 row. When you put a JPanel in a JScrollPane, the panel's preferred-size is used to size the panel, hence, a single line that goes on forever. The best solution is to subclass your JPanel and implement Scrollable - that is the whole reason that Scrollable exists, so that you can tell the JScrollPane how to scroll. Here's a sample that obviously only works with FlowLayout: import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ScrollablePanel extends JPanel implements Scrollable {
         public ScrollablePanel() {
              this(FlowLayout.LEFT);
         public ScrollablePanel(int flowLayoutType) {
              super(new FlowLayout(flowLayoutType));
         public ScrollablePanel(int flowLayoutType, int hgap, int vgap) {
              super(new FlowLayout(flowLayoutType, hgap, vgap));
         public Dimension getPreferredSize() {
              if (getParent() == null)
                   return getPreferredSize();
                    // calculate the preferred size based on the flow of components
              FlowLayout flow = (FlowLayout)getLayout();
              int w = getParent().getWidth();
              int h = flow.getVgap();
              int x = flow.getHgap();
              int rowH = 0;
              Dimension d;
              Component[] comps = getComponents();
              for (int i = 0; i < comps.length; i++) {
                   if (comps.isVisible()) {
                        d = comps[i].getPreferredSize();
                        if (x + d.width > w && x > flow.getHgap()) {
                             x = flow.getHgap();
                             h += rowH;
                             rowH = 0;
                             h += flow.getVgap();
                        rowH = Math.max(d.height, rowH);
                        x += d.width + flow.getHgap();
              h += rowH;
              return new Dimension(w, h);
         public Dimension getPreferredScrollableViewportSize() {
              return getPreferredSize();
         public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
              // shift the view so that you see the next logical page
              if (orientation == SwingConstants.HORIZONTAL) {
                   // this won't happen in this case since we never scroll horizontally
                   return visibleRect.width;
              return visibleRect.height;
         public boolean getScrollableTracksViewportHeight() {
              // only force the height if the preferred size is too short to fill the viewport
              return getPreferredSize().height < getParent().getHeight();
         public boolean getScrollableTracksViewportWidth() {
              // always force this panel's width to the viewport's width
    // this effectively disables horizontal scrolling
              return true;
         public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
              return 10;
         private static JScrollPane scroller;
         private static ScrollablePanel sp;
         public static void main(String[] args) {
              try {
                   SwingUtilities.invokeAndWait(new Runnable() {
                        public void run() {
                             sp = new ScrollablePanel(FlowLayout.LEFT, 20, 20);
                             scroller = new JScrollPane(sp);
                             final JButton button = new JButton("Add Label");
                             button.addActionListener(new ActionListener() {
                                  public void actionPerformed(ActionEvent e) {
                                       sp.add(new JLabel("HELLO"));
                                       scroller.validate();
                             JPanel content = new JPanel(new BorderLayout());
                             content.add(button, BorderLayout.NORTH);
                             content.add(scroller);
                             JFrame f = new JFrame("Test");
                             f.setContentPane(content);
                             f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                             f.setSize(600, 400);
                             f.setLocationRelativeTo(null);
                             f.setVisible(true);
              catch (Exception e) { e.printStackTrace(); }

  • How to fire mouse wheel events to parent container?

    Hi,
    When I create a JPanel (let's say jParent) inside a JScrollPane and this JPanel is larger than the current viewport I can use my mouse wheel to scroll the JPanel's containt without coding anything about that.
    But if I add another JPanel-derived component (let's say jChild) to the first JPanel, mouse wheel events are not received by the first JPanel when the mouse is over the new added child JPanel.
    How can I forward child's mouse wheel events to the first JPanel?
    If I use:
    jChild.addMouseWheelListener(jParent)I must implement a mouseWheelMoved() method in jParent that requires some code to work while it was doing it byitself before...
    Thanks in advance for any help :-)
    Regards,
    Lara.

    you have a mouseWheelListener added to jChild?
    if so, in the mouseWheelMoved code include this line
    jParent.dispatchEvent(mouseWheelEvent);//or to the scrollpane

  • Delete records from a Table. Please help

    Hello Folks,
    I have a table that contains 7 records with a Button to delete each record.
    I am unable to delete any records from the table.
    Please can some one just have a look into my class and tell me how
    to delete a record from the table when the button is clicked.
    You can also run this class from the your command Prompt
    Just cut this and create a new java file.
    Please assist.
    Code Attached :
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    public class ButtonTableFactory {
    public static JTable createTable(Vector data, String buttonLabel, ActionListener action) {
    return createTable(data.iterator(), buttonLabel, action);
    public static JTable createTable(
    Iterator dataIterator,
    String buttonLabel,
    ActionListener action) {
    DefaultTableModel model = new DefaultTableModel() {
    public boolean isCellEditable(int row, int col) {
    return col == 1;
    model.setColumnCount(2);
    while (dataIterator.hasNext()) {
    Object[] row = { dataIterator.next().toString(), null };
    model.addRow(row);
    DefaultTableColumnModel columnModel = new DefaultTableColumnModel();
    columnModel.addColumn(new TableColumn(0, 100));
    columnModel.addColumn(new TableColumn(1, 80,
    new TableButtonCellRenderer(buttonLabel),
    new TableButtonCellEditor(buttonLabel, action)
    JTable table = new JTable(model, columnModel) {
    public void valueChanged(ListSelectionEvent e) {
    super.valueChanged(e);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    return table;
    private static class TableButtonCellRenderer implements TableCellRenderer {
    final JButton button;
    TableButtonCellRenderer(String buttonLabel) {
    button = new JButton(buttonLabel);
    public Component getTableCellRendererComponent(
    JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus, int row, int column) {
    return button;
    private static class TableButtonCellEditor
    extends AbstractCellEditor
    implements TableCellEditor, ActionListener {
    final JButton button;
    final ActionListener callback;
    TableButtonCellEditor(String buttonLabel, ActionListener callback) {
    button = new JButton(buttonLabel);
    this.callback = callback;
    button.addActionListener(this);
    public Component getTableCellEditorComponent(
    JTable table,
    Object value,
    boolean isSelected,
    int row, int column) {
    return button;
    public Object getCellEditorValue() {
    return null;
    public void actionPerformed(ActionEvent e) {
    button.getParent().requestFocus();
    callback.actionPerformed(e);
    static JTable table;
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Vector items = new Vector();
    for (int i = 0; i < 7; i++) {
    items.add(Integer.toString(i));
    ActionListener al = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.out.println("You clicked row: " + table.getSelectedRow());
    table = ButtonTableFactory.createTable(items, "More:", al);
    frame.getContentPane().add(new JScrollPane(table));
    frame.pack();
    frame.show();

    This will get you closer:
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    public class ButtonTableFactory {
        private JTable table;
        private Vector items = new Vector();
        private JScrollPane scroll;
        private JPanel main;
        private ActionListener al;
        public static JTable createTable(Vector data, String buttonLabel, ActionListener action) {
            return createTable(data.iterator(), buttonLabel, action);
        public static JTable createTable(
                Iterator dataIterator,
                String buttonLabel,
                ActionListener action) {
            DefaultTableModel model = new DefaultTableModel() {
                public boolean isCellEditable(int row, int col) {
                    return col == 1;
            model.setColumnCount(2);
            while (dataIterator.hasNext()) {
                Object[] row = { dataIterator.next().toString(), null };
                model.addRow(row);
            DefaultTableColumnModel columnModel = new DefaultTableColumnModel();
            columnModel.addColumn(new TableColumn(0, 100));
            columnModel.addColumn(new TableColumn(1, 80,
                    new TableButtonCellRenderer(buttonLabel),
                    new TableButtonCellEditor(buttonLabel, action)
            JTable table = new JTable(model, columnModel) {
                public void valueChanged(ListSelectionEvent e) {
                    super.valueChanged(e);
            table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            return table;
        private static class TableButtonCellRenderer implements TableCellRenderer {
            final JButton button;
            TableButtonCellRenderer(String buttonLabel) {
                button = new JButton(buttonLabel);
            public Component getTableCellRendererComponent(
                    JTable table,
                    Object value,
                    boolean isSelected,
                    boolean hasFocus, int row, int column) {
                return button;
        private static class TableButtonCellEditor
                extends AbstractCellEditor
                implements TableCellEditor, ActionListener {
            final JButton button;
            final ActionListener callback;
            TableButtonCellEditor(String buttonLabel, ActionListener callback) {
                button = new JButton(buttonLabel);
                this.callback = callback;
                button.addActionListener(this);
            public Component getTableCellEditorComponent(
                    JTable table,
                    Object value,
                    boolean isSelected,
                    int row, int column) {
                return button;
            public Object getCellEditorValue() {
                return null;
            public void actionPerformed(ActionEvent e) {
                button.getParent().requestFocus();
                callback.actionPerformed(e);
        public void init() {
            main = new JPanel();
            main.setLayout(new BorderLayout());
            for (int i = 0; i < 7; i++) {
                items.add(Integer.toString(i));
            al = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println("You clicked row: " + table.getSelectedRow());
                    items.remove(table.getSelectedRow());
                    buildTable(items);
            buildTable(items);
        public void buildTable(Vector items) {
            table = ButtonTableFactory.createTable(items, "More:", al);
            scroll = new JScrollPane(table);
            main.removeAll();
            main.add(scroll);
            main.revalidate();
            main.repaint();
        public JPanel getContent() {
            return main;
        public static void main(String[] args) {
            ButtonTableFactory factory = new ButtonTableFactory();
            factory.init();
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(factory.getContent());
            frame.setSize(300, 300);
            frame.setVisible(true);
    //        frame.pack();
    //        frame.show();
    }

  • Table header disappearing

    I've been scratching my heads for hours and still can't understand why this is happening. I have two JDialog. One to display the table, let's call it Dialog 1, and the other to display the row details, Dialog 2. When Dialog 2 displays on top of the table headers and you close the dialog, the column headers seems to disappear. I've checked and rechecked the code to see if there's anything funky but I can't see any problems with this. The code is displayed below.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dialog;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import javax.swing.BorderFactory;
    import javax.swing.ButtonGroup;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComboBox;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JScrollPane;
    import javax.swing.JSeparator;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.JToolBar;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    * Created on Mar 2, 2004
    * To change the template for this generated file go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    * @author Administrator
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    class PaymentTypeSetupDialog extends JDialog {
         private JTable paymentTable;
         private PaymentTypeListTableModel paymentModel;
         private JTextField lookup;
         private JRadioButton byCode, byAcctCode, byPaymentType;
         private ButtonGroup group;
         private JButton add, edit, delete;
         public PaymentTypeSetupDialog(JFrame parent) {
              super(parent, "Payment Setup", true);
              initialize();
              setSize(new Dimension(600, 400));
              setResizable(false);
              setVisible(true);
         public PaymentTypeSetupDialog(Dialog parent) {
              super(parent, "Payment Setup", true);
              initialize();
              setSize(new Dimension(600, 400));
              setResizable(false);
              setVisible(true);
         private void initialize() {
              Container pane = getContentPane();
              pane.add(paymentCtrls(), BorderLayout.NORTH);
              pane.add(paymentList(), BorderLayout.CENTER);
              pane.add(paymentLookup(), BorderLayout.SOUTH);
         private JToolBar paymentCtrls() {
              final JSeparator sep = new JSeparator(JSeparator.VERTICAL);
              sep.setPreferredSize(new Dimension(20, 20));
              JToolBar bar = new JToolBar();
              bar.setLayout(new FlowLayout(FlowLayout.LEFT, 4, 4));
              bar.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY));
              bar.setFloatable(false);          
              bar.setRollover(true);
              add = new JButton("Add", new ImageIcon("images/Add16.gif"));
              add.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        PaymentType payment = new PaymentType();
                        PaymentDetails dialog = new PaymentDetails(PaymentTypeSetupDialog.this, payment, true);
                        if (!payment.getPaymentID().equals("")) {
                             insertTableRow(payment);
                   private void insertTableRow(PaymentType payment) {
                        int index = paymentTable.getSelectedRow();
                        int size = paymentTable.getRowCount();
                        ArrayList data = new ArrayList();
                        data.add(new Boolean(payment.isEnabled()));
                        data.add(payment.getPaymentID());
                        data.add(payment.getAccountID());
                        data.add(payment.getPaymentType());
                        // if no selection or if item in last position is selected.
                        // add the new one to the end of the list, and select new one.
                        if (index == -1 || index+1 == size) {
                             paymentModel.addNewRow(size, data);
                             paymentTable.getSelectionModel().setSelectionInterval(size, size);
                        } else {
                             paymentModel.addNewRow(index, data);
                             paymentTable.getSelectionModel().setSelectionInterval(index+1, index+1);
              add.setEnabled(true);          
              add.setFocusable(false);
              bar.add(add);
              edit = new JButton("Edit", new ImageIcon("images/Edit16.gif"));
              edit.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        int row = paymentTable.getSelectedRow();
                        final PaymentType payment = new PaymentType();
                        payment.setPaymentID(paymentTable.getValueAt(row, 1).toString());
                        try {
                             DBPaymentType.getPaymentType(payment);
                        } catch (SQLException sqle) {
                             // TODO Auto-generated catch block
                             sqle.printStackTrace();
                        PaymentDetails dialog = new PaymentDetails(PaymentTypeSetupDialog.this, payment, false);
                        if (!payment.getPaymentID().equals("")) {
                             ArrayList data = new ArrayList();
                             data.add(new Boolean(payment.isEnabled()));
                             data.add(payment.getPaymentID());
                             data.add(payment.getAccountID());
                             data.add(payment.getPaymentType());
                             paymentModel.updateRow(row, data);
              edit.setEnabled(false);          
              add.setFocusable(false);
              bar.add(edit);
              delete = new JButton("Delete", new ImageIcon("images/Delete16.gif"));
              delete.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        int selection = JOptionPane.showConfirmDialog(PaymentTypeSetupDialog.this, "Are you sure you want to remove this payment type?");
                        if (selection == 0) {
                             int row = paymentTable.getSelectedRow();
                             int size = paymentTable.getRowCount();     
                             if (size == 0) { // Nobody left
                                  edit.setEnabled(false);
                                  delete.setEnabled(false);
                             } else {
                                  PaymentType payment = new PaymentType();
                                  payment.setPaymentID(paymentTable.getValueAt(row, 1).toString());
                                  try {
                                       DBPaymentType.removePaymentType(payment);
                                       paymentModel.removeRow(row);
                                       if (row+1 == size) {                              
                                            row--;
                                       paymentTable.getSelectionModel().setSelectionInterval(row, row);
                                  } catch (SQLException e1) {
                                       // TODO Auto-generated catch block
                                       e1.printStackTrace();
              delete.setEnabled(false);
              delete.setFocusable(false);
              bar.add(delete);
              bar.add(sep);
              JButton btn = new JButton("Exit", new ImageIcon("images/Stop16.gif"));
              btn.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        dispose();
              btn.setFocusable(false);
              bar.add(btn);
              return bar;
         private JScrollPane paymentList() {
              paymentModel = new PaymentTypeListTableModel();
              paymentTable = new JTable(paymentModel);
              paymentTable.setFocusable(false);
              paymentTable.setCellSelectionEnabled(false);
              paymentTable.setRowHeight(20);
              paymentTable.setSelectionBackground(Color.yellow);
              paymentTable.setSelectionForeground(Color.black);
              paymentTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              paymentTable.getTableHeader().setReorderingAllowed(false);
              paymentTable.getTableHeader().setResizingAllowed(false);
              paymentTable.getColumnModel().getColumn(0).setPreferredWidth(50);     
              paymentTable.getColumnModel().getColumn(1).setPreferredWidth(50);
              paymentTable.getColumnModel().getColumn(2).setPreferredWidth(50);
              paymentTable.getColumnModel().getColumn(3).setPreferredWidth(200);
              paymentTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
                   public void valueChanged(ListSelectionEvent e) {
                        if (paymentTable.getRowCount() > 0) {
                             if (!edit.isEnabled())
                                  edit.setEnabled(true);
                             if (!delete.isEnabled())
                                  delete.setEnabled(true);
                        } else {
                             edit.setEnabled(false);
                             delete.setEnabled(false);
              paymentTable.addMouseListener(new MouseAdapter() {
                   public void mouseClicked(MouseEvent e) {
                        if (e.getClickCount() == 2 && e.getButton() == 1) {
                             int row = paymentTable.getSelectedRow();
                             final PaymentType payment = new PaymentType();
                             payment.setPaymentID(paymentTable.getValueAt(row, 1).toString());
                             try {
                                  DBPaymentType.getPaymentType(payment);
                             } catch (SQLException sqle) {
                                  // TODO Auto-generated catch block
                                  sqle.printStackTrace();
                             PaymentDetails dialog = new PaymentDetails(PaymentTypeSetupDialog.this, payment, false);
                             if (!payment.getPaymentID().equals("")) {
                                  ArrayList data = new ArrayList();
                                  data.add(new Boolean(payment.isEnabled()));
                                  data.add(payment.getPaymentID());
                                  data.add(payment.getAccountID());
                                  data.add(payment.getPaymentType());
                                  paymentModel.updateRow(row, data);
              JScrollPane scroll = new JScrollPane(paymentTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,       
                   JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              scroll.setCorner(JScrollPane.UPPER_RIGHT_CORNER,paymentTable.getTableHeader());
              scroll.getViewport().setBackground(Color.white);
              return scroll;
         private JPanel paymentLookup() {
              JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 2));
              panel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
              group = new ButtonGroup();
              panel.add(new JLabel("Search"));
              lookup = new JTextField(20);
              lookup.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if (lookup.getText().equals("")) {
                             JOptionPane.showMessageDialog(PaymentTypeSetupDialog.this, "Look up value is empty.");
                        } else {
                             int col;
                             if (byCode.isSelected()) {
                                  col = 1;
                             } else if (byAcctCode.isSelected()) {
                                  col = 2;
                             } else {
                                  col = 3;
                             int index = paymentModel.getIndexFor(col, lookup.getText());
                             if (index != -1) {
                                  paymentTable.getSelectionModel().setSelectionInterval(index, index);
              panel.add(lookup);
              byCode = new JRadioButton("Code");
              byCode.setSelected(true);
              byCode.setFocusable(false);
              group.add(byCode);
              panel.add(byCode);
              byAcctCode = new JRadioButton("Account code");
              byAcctCode.setSelected(true);
              byAcctCode.setFocusable(false);
              group.add(byAcctCode);
              panel.add(byAcctCode);
              byPaymentType = new JRadioButton("Payment type");
              byPaymentType.setFocusable(false);
              group.add(byPaymentType);
              panel.add(byPaymentType);
              return panel;
         public void setVisible(boolean visible) {
              if (visible) {
                   Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                   Dimension size = getSize();
                   int x;
                   int y;
                   x = screenSize.width / 2 - size.width / 2;
                   y = screenSize.height / 2 - size.height / 2;
                   setBounds(x, y, size.width, size.height);               
              super.setVisible(visible);
         class PaymentDetails extends JDialog {
              private PaymentType payment;
              private boolean newPayment;
              private JTextField code, type, image, imageUrl;
              private JComboBox accountList;
              private JCheckBox isEnabled;
              private JLabel paymentImage;
              public PaymentDetails(Dialog parent, PaymentType payment, boolean newPayment) {
                   super(parent, "Payment Details", false);
                   this.payment = payment;
                   this.newPayment = newPayment;
                   initialize();
                   pack();
                   setVisible(true);
              private void initialize() {
                   Container pane = getContentPane();
                   pane.add(paymentDetails(), BorderLayout.CENTER);
                   pane.add(detailCtrls(), BorderLayout.SOUTH);
              private JPanel paymentDetails() {
                   JPanel panel = new JPanel(new GridBagLayout());
                   panel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
                   GridBagConstraints gbc = new GridBagConstraints();
                   gbc.anchor = GridBagConstraints.WEST;
                   gbc.fill = GridBagConstraints.NONE;
                   gbc.insets = new Insets(4, 2, 4, 2);
                   JLabel label;
                   gbc.gridx = 0;
                   gbc.gridy = 0;
                   gbc.weightx = 0;
                   label = new JLabel("Code");
                   panel.add(label, gbc);
                   gbc.gridx++;
                   gbc.weightx = 1;
                   code = new JTextField(payment.getPaymentID(), 10);
                   code.setEditable(newPayment);
                   panel.add(code, gbc);
                   gbc.gridx++;
                   isEnabled = new JCheckBox("Activate", payment.isEnabled());
                   panel.add(isEnabled, gbc);
                   gbc.gridx = 0;
                   gbc.gridy++;
                   gbc.fill = GridBagConstraints.HORIZONTAL;
                   label = new JLabel("Account code");
                   panel.add(label, gbc);
                   gbc.gridx++;
                   gbc.weightx = 1;
                   gbc.gridwidth = 2;
                   accountList = new JComboBox(new AccountTypeListModel(payment.getAccountID()));
                   panel.add(accountList, gbc);
                   gbc.gridx = 0;
                   gbc.gridy++;
                   gbc.gridwidth = 1;
                   label = new JLabel("Payment Type");
                   panel.add(label, gbc);
                   gbc.gridx++;
                   gbc.weightx = 1;
                   gbc.gridwidth = 2;
                   type = new JTextField(payment.getPaymentType(), 20);
                   panel.add(type, gbc);
                   gbc.gridx = 0;
                   gbc.gridy++;
                   gbc.gridwidth = 1;
                   label = new JLabel("Image");
                   panel.add(label, gbc);
                   gbc.gridx++;
                   gbc.weightx = 1;
                   gbc.gridwidth = 2;
                   panel.add(paymentImage(), gbc);
                   gbc.gridx = 0;
                   gbc.gridy++;
                   gbc.gridwidth = 1;
                   label = new JLabel("Image URL");
                   panel.add(label, gbc);
                   gbc.gridx++;
                   gbc.fill = GridBagConstraints.NONE;
                   imageUrl = new JTextField(payment.getImage(), 10);
                   panel.add(imageUrl, gbc);
                   gbc.gridx++;
                   JButton btn = new JButton("Browse");
                   btn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             System.out.println("Browse image directory");
                   panel.add(btn, gbc);
                   return panel;
              private JScrollPane paymentImage() {
                   paymentImage = new JLabel(new ImageIcon("images/Category48.gif"));
                   JScrollPane scroll = new JScrollPane(paymentImage, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,       
                        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                   scroll.setCorner(JScrollPane.UPPER_RIGHT_CORNER,paymentTable.getTableHeader());
                   scroll.getViewport().setBackground(Color.white);
                   scroll.setPreferredSize(new Dimension(200, 200));
                   return scroll;
              private JPanel detailCtrls() {
                   JPanel panel = new JPanel();
                   JButton btn = new JButton("Save");
                   btn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             if (code.getText().equals("")) {
                                  JOptionPane.showMessageDialog(PaymentDetails.this, "Code cannot be empty.");
                             } else {
                                  payment.setPaymentID(code.getText());
                                  payment.setAccountID(((AccountType) accountList.getSelectedItem()).getAccountID());
                                  payment.setPaymentType(type.getText());
                                  payment.setImage(imageUrl.getText());
                                  payment.setEnabled(isEnabled.isSelected());
                                  if (newPayment) {
                                       try {
                                            DBPaymentType.addPaymentType(payment);
                                            dispose();
                                       } catch (SQLException e1) {
                                            // TODO Auto-generated catch block
                                            e1.printStackTrace();
                                  } else {
                                       try {
                                            DBPaymentType.updatePaymentType(payment);
                                            dispose();
                                       } catch (SQLException e1) {
                                            // TODO Auto-generated catch block
                                            e1.printStackTrace();
                   panel.add(btn);
                   btn = new JButton("Cancel");
                   btn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             payment.setPaymentID("");
                             dispose();
                   panel.add(btn);
                   return panel;
              public void setVisible(boolean visible) {
                   if (visible) {
                        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                        Dimension size = getSize();
                        int x;
                        int y;
                        x = screenSize.width / 2 - size.width / 2;
                        y = screenSize.height / 2 - size.height / 2;
                        setBounds(x, y, size.width, size.height);               
                   super.setVisible(visible);
    }Please help!
    Thx.

    Hmmm...Interesting. If you add paymentTable.updateUI(); after any edits or adds, the whole column headers disappear. It only seems to happen when the 2nd modal dialog is on top of the column header. If it is not, the application works fine. I've tested this against 1.4.2 and 1.5 beta and it i get the same result.

  • Problem facing in netbeans

    Hi,
    I am in need to scroll my JPanel. I created some sample code and test it. It is working properly if i am not using groupLayout. If i use groupLayout then i am facing the error.
    Please help me to resolve this issue.
    Thanks in advance.

    [http://www.netbeans.org]

  • Update JScrollPane at runtime

    Hi, well my problem is that I have a few JTextFields and an empty JScrollPane, but when something happens (e.i. a JButton is pressed) the text in the JTextFields should be added to the JScrollPane, but instead of that only the text from the last JTextField (in the example JTextField2) is added one time, no matters how many times the button is pressed, so the problem is:
    How to add all the elements (in this case JLabels with the text from the JTextFields)?
    I guess that all the elements are added but the last one overlaps the others.
    Example:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ScrollUpdate extends JFrame{
         JTextField text1;
         JTextField text2;
         JScrollPane scroll;
         public ScrollUpdate(){
              text1 = new JTextField("Text 1");
              text1.setPreferredSize(new Dimension(100,22));
              text2 = new JTextField("Text 2");
              text2.setPreferredSize(new Dimension(100,22));
              JPanel panel = (JPanel)getContentPane();
              panel.add(text1, BorderLayout.LINE_START);
              scroll = new JScrollPane();
              scroll.setPreferredSize(new Dimension(100,100));
              panel.add(scroll, BorderLayout.LINE_END);
              panel.add(text2, BorderLayout.CENTER);
              JButton update = new JButton("Update");
              update.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        JLabel texto1 = new JLabel(text1.getText());
                        texto1.setAlignmentX(CENTER_ALIGNMENT);
                        scroll.getViewport().add(texto1);
                        JLabel texto2 = new JLabel(text2.getText());
                        texto2.setAlignmentX(CENTER_ALIGNMENT);
                        scroll.getViewport().add(texto2);
                        scroll.getViewport().revalidate();
                        scroll.repaint();
              panel.add(update, BorderLayout.PAGE_END);
              pack();
              setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
              setLocationRelativeTo(null);
         public static void main(String args[]){
              java.awt.EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        try {
                             // Set System L&F
                             JFrame.setDefaultLookAndFeelDecorated(true);
                             JDialog.setDefaultLookAndFeelDecorated(true);
                             UIManager.setLookAndFeel(UIManager
                                       .getSystemLookAndFeelClassName());
                        } catch (ClassNotFoundException e) {
                              //handle exception
                        } catch (Exception e) {
                             try {
                                  UIManager
                                            .setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
                             } catch (Exception f) {
                        ScrollUpdate fenster = new ScrollUpdate();
                        fenster.setVisible(true);
    }

    I think that your problem is that you're adding things directly to the viewport rather than to a JPanel that is viewed in the viewport, say one that uses a GridLayout(0, 1). For e.g.,
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ScrollUpdate extends JFrame {
      JTextField text1;
      JTextField text2;
      JScrollPane scroll;
      private JPanel innerScrolledPanel = new JPanel(new GridLayout(0, 1));
      public ScrollUpdate() {
        text1 = new JTextField("Text 1");
        text1.setPreferredSize(new Dimension(100, 22));
        text2 = new JTextField("Text 2");
        text2.setPreferredSize(new Dimension(100, 22));
        JPanel panel = (JPanel) getContentPane();
        panel.add(text1, BorderLayout.LINE_START);
        scroll = new JScrollPane(innerScrolledPanel);
        scroll.setPreferredSize(new Dimension(100, 100));
        panel.add(scroll, BorderLayout.LINE_END);
        panel.add(text2, BorderLayout.CENTER);
        JButton update = new JButton("Update");
        update.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            JLabel texto1 = new JLabel(text1.getText());
            texto1.setAlignmentX(CENTER_ALIGNMENT);
            innerScrolledPanel.add(texto1);
            JLabel texto2 = new JLabel(text2.getText());
            texto2.setAlignmentX(CENTER_ALIGNMENT);
            innerScrolledPanel.add(texto2);
            innerScrolledPanel.revalidate();
            scroll.repaint();
        panel.add(update, BorderLayout.PAGE_END);
        pack();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
      public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            ScrollUpdate fenster = new ScrollUpdate();
            fenster.setVisible(true);
    }

  • GridBagLayout() hell

    Hello,
    I have almost completed the GUI for my RAT client although there are layout problems i.e. some elements are not where they should be.
    This is what the layout should be like:
    / label / /
    /textField / JEditorPane /
    / textField / /
    /textField / /
    Obviously there are more labels and textFields as shown in the code below. I have tried to edit the properties for each label, textField etc, I have also tried to relate it to the tutorials on Java swing but with no luck. Please help.
    import java.net.*;
    import javax.swing.text.html.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.applet.Applet;
    * Requires RatServer to be running
    * set path="C:\Program Files\Java\jdk1.5.0_08\bin"
    public class RatClient implements ActionListener
         JTextField host = null;
         JTextField port = null;
         JTextField cmd = null;
         JTextField file = null;
         JEditorPane jep = null;
         BufferedReader in = null;
         JScrollPane scroll = null;
         public Component createComponents()
              JPanel pane = new JPanel(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
              jep = new JEditorPane();
              c.gridx = 2;
              c.gridy = 0;
              c.ipadx = 40;
              c.ipady = 40;
              c.weightx = 0.0;
              c.gridwidth = 3;
              c.gridheight = -14;
            pane.add(jep, c);
              scroll = new JScrollPane(jep);
              c.gridx = 2;
              c.gridy = 0;
              c.ipadx = 40;
              c.ipady = 40;
              c.weightx = 0.0;
              c.gridwidth = 3;
              pane.add(scroll, c);
              JLabel hostLabel = new JLabel("Enter host: ");
              c.ipadx = 10;
              c.ipady = 10;
              c.gridx = 0;
              c.gridy = 0;
              pane.add(hostLabel, c);
              host = new JTextField("192.168.0.4");
              c.gridx = 0;
              c.gridy = 1;
              pane.add(host, c);
              JLabel portLabel = new JLabel("Enter port: ");
              c.gridx = 0;
              c.gridy = 2;
              pane.add(portLabel, c);
              port = new JTextField("80");
              c.gridx = 0;
              c.gridy = 3;
              pane.add(port, c);
              JLabel cmdLabel = new JLabel("Send a command: ");
              c.gridx = 0;
              c.gridy = 4;
              pane.add(cmdLabel, c);
              cmd = new JTextField("GetInfo");
              c.gridx = 0;
              c.gridy = 5;
              pane.add(cmd, c);
              JLabel fileLabel = new JLabel("Send a file: ");
              c.gridx = 0;
              c.gridy = 6;
              pane.add(fileLabel, c);
              file = new JTextField("C:\\misc.txt");
              c.gridx = 0;
              c.gridy = 7;
              pane.add(file, c);
              JButton button = new JButton("Connect");
              c.gridx = 0;
              c.gridy = 8;
              button.addActionListener(this);
            pane.add(button, c);
            return pane;
    private static void Gui()
              //Create and set up the window.
              JFrame frame = new JFrame("RatClient");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              RatClient app = new RatClient();
              Component contents = app.createComponents();
              frame.getContentPane().add(contents);
              //Display the window.
              frame.pack();
              frame.setVisible(true);
        }

    Ok heres an SSCCE that shows the incorrect layout.
    Ive tried using another panel also but to no avail.
    At the moment its not showing the JEditorPane at all.
    Please help again.
    Cheers
    import java.net.*;
    import javax.swing.text.html.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.applet.Applet;
    * Requires RatServer to be running
    * set path="C:\Program Files\Java\jdk1.5.0_08\bin"
    public class RatClient2 implements ActionListener
         JTextField host = null;
         JTextField port = null;
         JTextField cmd = null;
         JTextField file = null;
         JEditorPane jep = null;
         BufferedReader in = null;
         JScrollPane scroll = null;
         public Component createComponents()
              JPanel paneForJep = new JPanel(new GridBagLayout());
              GridBagConstraints gbc = new GridBagConstraints();
              jep = new JEditorPane();
              gbc.gridx = 2;
              gbc.gridy = 0;
              gbc.ipadx = 40;
              gbc.ipady = 40;
            paneForJep.add(jep, gbc);
              scroll = new JScrollPane(jep);
              gbc.gridx = 2;
              gbc.gridy = 0;
              gbc.ipadx = 40;
              gbc.ipady = 40;
              paneForJep.add(scroll, gbc);
              JPanel pane = new JPanel(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
              JLabel hostLabel = new JLabel("Enter host: ");
              c.ipadx = 10;
              c.ipady = 10;
              c.gridx = 0;
              c.gridy = 0;
              pane.add(hostLabel, c);
              host = new JTextField("192.168.0.4");
              c.gridx = 0;
              c.gridy = 1;
              pane.add(host, c);
              JLabel portLabel = new JLabel("Enter port: ");
              c.gridx = 0;
              c.gridy = 2;
              pane.add(portLabel, c);
              port = new JTextField("80");
              c.gridx = 0;
              c.gridy = 3;
              pane.add(port, c);
              JLabel cmdLabel = new JLabel("Send a command: ");
              c.gridx = 0;
              c.gridy = 4;
              pane.add(cmdLabel, c);
              cmd = new JTextField("GetInfo");
              c.gridx = 0;
              c.gridy = 5;
              pane.add(cmd, c);
              JLabel fileLabel = new JLabel("Send a file: ");
              c.gridx = 0;
              c.gridy = 6;
              pane.add(fileLabel, c);
              file = new JTextField("C:\\a.jpg");
              c.gridx = 0;
              c.gridy = 7;
              pane.add(file, c);
              JButton button = new JButton("Connect");
              c.gridx = 0;
              c.gridy = 8;
              button.addActionListener(this);
            pane.add(button, c);
            return pane;
        public void actionPerformed(ActionEvent e)
              String host2 = host.getText();
              String port2 = port.getText();
              String command = cmd.getText();
              String file2 = file.getText();
         private static void Gui()
              //Create and set up the window.
              JFrame frame = new JFrame("RatClient2");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              RatClient2 app = new RatClient2();
              Component contents = app.createComponents();
              frame.getContentPane().add(contents);
              //Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args)
                   javax.swing.SwingUtilities.invokeLater(new Runnable()
                        public void run()
                             Gui();
         }I hope this is okay i.e. I have tried my best to conform to the forum rules.

  • JDialog sizing problems

    First of all, just let me say I have read everything there is available on layout managers and how pack() and validate() work.
    My problem is simply that my JDialog appears far longer than its components, and I can't see why.
    I've created screenshots of the desired appearance and the actual appearance:
    http://www.komododave.co.uk/gallery/main.php?g2_itemId=167
    The first 'undesired' screenshot shows what the JDialog looks like upon instantiation. The second shows what it looks like once you manually shrink it in the Y direction by more than about 10 pixels.
    I don't understand how the maximum size can exceed the Dimension I set with 'dialog.setMaximumSize(...', since I'm using BoxLayout for the JDialog and that respects a given maximum size.
    The constructor creating the JDialog is shown here:
              public AbstractSelectionDialog(Vector<String> argVector, String title,
                        String message) {
                   Vector<String> vector = argVector;
                   // create new modal JDialog
                   final JDialog dialog = new JDialog(Silk.getFrame(), title, true);
                   // set boxlayout for dialog frame
                   dialog.getContentPane().setLayout(new BoxLayout(dialog.getContentPane(),
                             BoxLayout.Y_AXIS));
                   // set default close operation
                   dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                   // create ButtonGroup to enforce exclusive collection choice
                   final ButtonGroup buttonGroup = new ButtonGroup();
                   // initialise other components
                   // use fake space for label rather than use another HorizontalGlue
                   JLabel label = new JLabel("   " + message);
                   // panel containing collection selection
                   JPanel selectionPanel = new JPanel();
                   // run initialiser methods
                   JPanel buttonPanel = (JPanel) createButtons(buttonGroup, dialog);
                   AbstractButton selection[] = createSelection(vector, buttonGroup,
                             selectionPanel);
                   // scrollPane containing collection panel
                   JScrollPane scrollPane = new JScrollPane(selectionPanel,
                             JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                             JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                   // panel containing scroll pane
                   JPanel scrollPanel = new JPanel();
                   scrollPanel.setLayout(new BoxLayout(scrollPanel, BoxLayout.X_AXIS));
                   selectionPanel.setLayout(new GridLayout(vector.size(), 1));
                   // assemble component structure
                   scrollPanel.add(Box.createHorizontalGlue());
                   scrollPanel.add(scrollPane);
                   scrollPanel.add(Box.createHorizontalGlue());
                   dialog.add(label);
                   dialog.add(scrollPanel);
                   dialog.add(buttonPanel);
                   // set all components to be left-justified
                   label.setAlignmentX(0.0F);
                   scrollPanel.setAlignmentX(0.0F);
                   selectionPanel.setAlignmentX(0.0F);
                   buttonPanel.setAlignmentX(0.0F);
                   // set higher-level component sizes
                   Silk.setSizeAttributes(label, 300, 30, true);
                   selectionPanel.setMaximumSize(new Dimension(250, 400));
                   scrollPane.setMinimumSize(new Dimension(250, 50));
                   scrollPane.setMaximumSize(new Dimension(250, 400));
                   dialog.setMinimumSize(new Dimension(300, 200));
                   dialog.setMaximumSize(new Dimension(300, 500));
                   dialog.pack();
                   // set components to be opaque
                   label.setOpaque(true);
                   scrollPane.setOpaque(true);
                   selectionPanel.setOpaque(true);
                   // display dialog frame
                   //dialog.setResizable(false);
                   dialog.setVisible(true);
              }The 'createButtons' method it uses is here:
         public JPanel createButtons(ButtonGroup bg, JDialog jd) {
                   final ButtonGroup buttonGroup = bg;
                   final JDialog dialog = jd;
                   // confirmation buttons
                   JButton okBtn = new JButton();
                   JButton cancelBtn = new JButton();
                   JButton newBtn = new JButton();
                   // panel containing OK and CANCEL buttons
                   JPanel bothPanel = new JPanel();
                   // panel containing NEW COLLECTION button
                   JPanel newPanel = new JPanel();
                   // panel to contain all other button panels
                   JPanel confPanel = new JPanel();
                   confPanel.setLayout(new BoxLayout(confPanel, BoxLayout.X_AXIS));
                   newPanel.setLayout(new BoxLayout(newPanel, BoxLayout.X_AXIS));
                   bothPanel.setLayout(new BoxLayout(bothPanel, BoxLayout.Y_AXIS));
                   // definition of button Actions
                   okBtn.setAction(new AbstractAction() {
                        public void actionPerformed(ActionEvent ae) {
                             Actions.addScript(buttonGroup.getSelection()
                                       .getActionCommand(), null);
                             dialog.dispose();
                   cancelBtn.setAction(new AbstractAction() {
                        public void actionPerformed(ActionEvent ae) {
                             dialog.dispose();
                   newBtn.setAction(new AbstractAction() {
                        public void actionPerformed(ActionEvent ae) {
                             dialog.dispose();
                             new Actions.NewCollectionAction().actionPerformed(ae);
                             new Actions.NewScriptAction().actionPerformed(ae);
                   // override action-set button text
                   okBtn.setText("Ok");
                   cancelBtn.setText("Cancel");
                   newBtn.setText("Add New Collection");
                   // set button sizes
                   Silk.setSizeAttributes(okBtn, 115, 30, true);
                   Silk.setSizeAttributes(cancelBtn, 115, 30, true);
                   Silk.setSizeAttributes(newBtn, 250, 35, true);
                   // set opaque buttons
                   confPanel.setOpaque(true);
                   okBtn.setOpaque(true);
                   cancelBtn.setOpaque(true);
                   // assemble components
                   confPanel.add(Box.createHorizontalGlue());
                   confPanel.add(okBtn);
                   confPanel.add(Box.createRigidArea(new Dimension(20, 0)));
                   confPanel.add(cancelBtn);
                   confPanel.add(Box.createHorizontalGlue());
                   newPanel.add(Box.createHorizontalGlue());
                   newPanel.add(newBtn);
                   newPanel.add(Box.createHorizontalGlue());
                   bothPanel.add(Box.createRigidArea(new Dimension(0, 10)));
                   bothPanel.add(confPanel);
                   bothPanel.add(Box.createRigidArea(new Dimension(0, 5)));
                   bothPanel.add(newPanel);
                   bothPanel.add(Box.createRigidArea(new Dimension(0, 10)));
                   bothPanel.setMaximumSize(new Dimension(300, 100));
                   return bothPanel;
              }And the createSelection() method it uses is defined here:
         public AbstractButton[] createSelection(Vector<String> argVector,
                        ButtonGroup buttonGroup, JPanel selectionPanel) {
                   Vector<String> vector = argVector;
                   JRadioButton selection[] = new JRadioButton[vector.size()];
                   for (int i = 0; i < vector.size(); i++)
                        selection[i] = new JRadioButton(vector.get(i));
                   AbstractButton current;
                   for (byte i = 0; i < selection.length; i++) {
                        current = selection;
                        // set action command string to later identify button that's
                        // selected
                        current.setActionCommand(vector.get(i));
                        // fix button's size
                        Silk.setSizeAttributes(current, 250, 30, true);
                        // set button's colour
                        current.setBackground(Color.WHITE);
                        // add button to buttongroup
                        buttonGroup.add(current);
                        // add button to appropriate JPanel
                        selectionPanel.add(current);
                   // ensure one button is selected to prevent pressing OK with no
                   // selection
                   selection[0].setSelected(true);
                   return selection;
    Please help if you can.
    Thank you.
    - Dave

    Yeah sorry camickr, I need to get into the habit of posting SSCCEs.
    Here it is in SSCCE form:
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import javax.swing.AbstractAction;
    import javax.swing.AbstractButton;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.ButtonGroup;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JScrollPane;
    import java.util.Vector;
    public class Testing {
         // prevent instantiation
         private Testing() {
         public interface SelectionDialog {
              // produces a component containing all dialog buttons
              public Component createButtons(ButtonGroup bg, JDialog jd);
              // produces an array of the selection buttons to be used
              public abstract AbstractButton[] createSelection(
                        Vector<String> selectionVector, ButtonGroup buttonGroup,
                        JPanel selectionPanel);
         abstract static class AbstractSelectionDialog implements SelectionDialog {
              public AbstractSelectionDialog() {
                   Vector<String> vector = new Vector<String>();
                   String title = "Broken dialog box";
                   String message = "Why is the maximum size exceedable, hmm?";
                   /* for sscce */
                   vector.add("choice 1");
                   vector.add("choice 2");
                   vector.add("choice 3");
                   vector.add("choice 4");
                   vector.add("choice 5");
                   vector.add("choice 6");
                   vector.add("choice 7");
                   vector.add("choice 8");
                   vector.add("choice 9");
                   vector.add("choice 10");
                   vector.add("choice 11");
                   vector.add("choice 12");
                   vector.add("choice 13");
                   vector.add("choice 14");
                   vector.add("choice 15");
                   vector.add("choice 16");
                   vector.add("choice 17");
                   vector.add("choice 18");
                   // create new modal JDialog
                   final JDialog dialog = new JDialog(Silk.getFrame(), title, true);
                   // set boxlayout for dialog frame
                   dialog.getContentPane().setLayout(new BoxLayout(dialog.getContentPane(),
                             BoxLayout.Y_AXIS));
                   // set default close operation
                   dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                   // create ButtonGroup to enforce exclusive collection choice
                   final ButtonGroup buttonGroup = new ButtonGroup();
                   // initialise other components
                   // use fake space for label rather than use another HorizontalGlue
                   JLabel label = new JLabel("   " + message);
                   // panel containing collection selection
                   JPanel selectionPanel = new JPanel();
                   // run initialiser methods
                   JPanel buttonPanel = (JPanel) createButtons(buttonGroup, dialog);
                   AbstractButton selection[] = createSelection(vector, buttonGroup,
                             selectionPanel);
                   // scrollPane containing collection panel
                   JScrollPane scrollPane = new JScrollPane(selectionPanel,
                             JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                             JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                   // panel containing scroll pane
                   JPanel scrollPanel = new JPanel();
                   scrollPanel.setLayout(new BoxLayout(scrollPanel, BoxLayout.X_AXIS));
                   selectionPanel.setLayout(new GridLayout(vector.size(), 1));
                   // assemble component structure
                   scrollPanel.add(Box.createHorizontalGlue());
                   scrollPanel.add(scrollPane);
                   scrollPanel.add(Box.createHorizontalGlue());
                   dialog.add(label);
                   dialog.add(scrollPanel);
                   dialog.add(buttonPanel);
                   // set all components to be left-justified
                   label.setAlignmentX(0.0F);
                   scrollPanel.setAlignmentX(0.0F);
                   selectionPanel.setAlignmentX(0.0F);
                   buttonPanel.setAlignmentX(0.0F);
                   // set higher-level component sizes
                   Silk.setSizeAttributes(label, 300, 30, true);
                   selectionPanel.setMaximumSize(new Dimension(250, 400));
                   scrollPane.setMinimumSize(new Dimension(250, 50));
                   scrollPane.setMaximumSize(new Dimension(250, 400));
                   dialog.setMinimumSize(new Dimension(300, 200));
                   dialog.setMaximumSize(new Dimension(300, 500));
                   dialog.pack();
                   // set components to be opaque
                   label.setOpaque(true);
                   scrollPane.setOpaque(true);
                   selectionPanel.setOpaque(true);
                   // display dialog frame
                   // dialog.setResizable(false);
                   dialog.setVisible(true);
         protected static class ChooseCollectionDialog extends
                   AbstractSelectionDialog implements SelectionDialog {
              public ChooseCollectionDialog() {
                   super();
              public JPanel createButtons(ButtonGroup bg, JDialog jd) {
                   final ButtonGroup buttonGroup = bg;
                   final JDialog dialog = jd;
                   // confirmation buttons
                   JButton okBtn = new JButton();
                   JButton cancelBtn = new JButton();
                   JButton newBtn = new JButton();
                   // panel containing OK and CANCEL buttons
                   JPanel bothPanel = new JPanel();
                   // panel containing NEW COLLECTION button
                   JPanel newPanel = new JPanel();
                   // panel to contain all other button panels
                   JPanel confPanel = new JPanel();
                   confPanel.setLayout(new BoxLayout(confPanel, BoxLayout.X_AXIS));
                   newPanel.setLayout(new BoxLayout(newPanel, BoxLayout.X_AXIS));
                   bothPanel.setLayout(new BoxLayout(bothPanel, BoxLayout.Y_AXIS));
                   // definition of button Actions
                   okBtn.setAction(new AbstractAction() {
                        public void actionPerformed(ActionEvent ae) {
                             dialog.dispose();
                   cancelBtn.setAction(new AbstractAction() {
                        public void actionPerformed(ActionEvent ae) {
                             dialog.dispose();
                   newBtn.setAction(new AbstractAction() {
                        public void actionPerformed(ActionEvent ae) {
                   // override action-set button text
                   okBtn.setText("Ok");
                   cancelBtn.setText("Cancel");
                   newBtn.setText("Add New Collection");
                   // set button sizes
                   Silk.setSizeAttributes(okBtn, 115, 30, true);
                   Silk.setSizeAttributes(cancelBtn, 115, 30, true);
                   Silk.setSizeAttributes(newBtn, 250, 30, true);
                   // set opaque buttons
                   confPanel.setOpaque(true);
                   okBtn.setOpaque(true);
                   cancelBtn.setOpaque(true);
                   // assemble components
                   confPanel.add(Box.createHorizontalGlue());
                   confPanel.add(okBtn);
                   confPanel.add(Box.createRigidArea(new Dimension(20, 0)));
                   confPanel.add(cancelBtn);
                   confPanel.add(Box.createHorizontalGlue());
                   newPanel.add(Box.createHorizontalGlue());
                   newPanel.add(newBtn);
                   newPanel.add(Box.createHorizontalGlue());
                   bothPanel.add(Box.createRigidArea(new Dimension(0, 10)));
                   bothPanel.add(confPanel);
                   bothPanel.add(Box.createRigidArea(new Dimension(0, 5)));
                   bothPanel.add(newPanel);
                   bothPanel.add(Box.createRigidArea(new Dimension(0, 10)));
                   bothPanel.setMaximumSize(new Dimension(300, 100));
                   return bothPanel;
              public AbstractButton[] createSelection(Vector<String> argVector,
                        ButtonGroup buttonGroup, JPanel selectionPanel) {
                   Vector<String> vector = argVector;
                   JRadioButton selection[] = new JRadioButton[vector.size()];
                   for (int i = 0; i < vector.size(); i++)
                        selection[i] = new JRadioButton(vector.get(i));
                   AbstractButton current;
                   for (byte i = 0; i < selection.length; i++) {
                        current = selection;
                        // set action command string to later identify button that's
                        // selected
                        current.setActionCommand(vector.get(i));
                        // fix button's size
                        Silk.setSizeAttributes(current, 250, 30, true);
                        // set button's colour
                        current.setBackground(Color.WHITE);
                        // add button to buttongroup
                        buttonGroup.add(current);
                        // add button to appropriate JPanel
                        selectionPanel.add(current);
                   // ensure one button is selected to prevent pressing OK with no
                   // selection
                   selection[0].setSelected(true);
                   return selection;
         public static void main(String args[]) {
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        new ChooseCollectionDialog();
    I considered that the GridLayout might be a problem, but surely the fact that it's ultimately contained in a BoxLayout (which [i]does respect maximum size) means the maximum size still shouldn't be exceedable?
    Thanks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for

  • Front End servers within same Pool on different subnets

    The customer is looking to have Amazon AWS host Lync 2013, and despite Lync 2013 having built in HA via Pools, Amazon wants to split the Pools across two of their availability zones (AZ ). An AZ is nothing more than a metropolitan area network, or si

  • Error while creating virtual server in sunone web server 6.1

    I created virtual server class called vs1 and virtual server called vsr1 under it. I deleted them . now while i am trying to create another virtual server class by setting lisener socket and giving it a name. when i create virtual server class and cl

  • How do I change my search engine and home page to google?

    Hello the search engine drop down arrow has no search engines attached to it so i can't pick a default engine from there and when i go to "Manage Search Engines" the restore default button if shaded and inaccessible. Google also isn't an option when

  • Several BizTalk applications consuming the same web service

    When consuming a web service in Biztalk i use the generated items feature, using the service endpoint address. This creates binding files and service schema files. When trying to deploy the web service artifacts to BizTalk Server, and the files alrea

  • Regarding Business Rule Framework

    Hi, Could u please explain the process of Business Rule Framework(BRF) and how to create this Business Rule Framework(BRF) explain with step by step process.