SetEnable of scrollPane

i have added scrollpane to list and doing disable. list become diable but scroll bar is moving.
what is the solution to stop moving of scroll bar when scrollpane is disable.

thnks a lot
this is working
ScrollPane.getVerticalScrollBar().setEnabled(false);

Similar Messages

  • Problem with ScrollPane and JFrame Size

    Hi,
    The code is workin but after change the size of frame it works CORRECTLY.Please help me why this frame is small an scrollpane doesn't show at the beginning.
    Here is the code:
    import java.awt.*;
    public class canvasExp extends Canvas
         private static final long serialVersionUID = 1L;
         ImageLoader map=new ImageLoader();
        Image img = map.GetImg();
        int h, w;               // the height and width of this canvas
         public void update(Graphics g)
            paint(g);
        public void paint(Graphics g)
                if(img != null)
                     h = getSize().height;
                     System.out.println("h:"+h);
                      w = getSize().width;
                      System.out.println("w:"+w);
                      g.drawRect(0,0, w-1, h-1);     // Draw border
                  //  System.out.println("Size= "+this.getSize());
                     g.drawImage(img, 0,0,this.getWidth(),this.getHeight(), this);
                    int width = img.getWidth(this);
                    //System.out.println("W: "+width);
                    int height = img.getHeight(this);
                    //System.out.println("H: "+height);
                    if(width != -1 && width != getWidth())
                        setSize(width, getHeight());
                    if(height != -1 && height != getHeight())
                        setSize(getWidth(), height);
    }I create frame here...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    public class frame extends JFrame implements MouseMotionListener,MouseListener
         private static final long serialVersionUID = 1L;
        private ScrollPane scrollPane;
        private int dragStartX;
        private int dragStartY;
        private int lastX;
        private int lastY;
        int cordX;
        int cordY;
        canvasExp canvas;
        public frame()
            super("test");
            canvas = new canvasExp();
            canvas.addMouseListener(this);
            canvas.addMouseMotionListener(this);
            scrollPane = new ScrollPane();
            scrollPane.setEnabled(true);
            scrollPane.add(canvas);
            add(scrollPane);
            setSize(300,300);
            pack();
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public void mousePressed(MouseEvent e)
            dragStartX = e.getX();
            dragStartY = e.getY();
            lastX = getX();
            lastY = getY();
        public void mouseReleased(MouseEvent mouseevent)
        public void mouseClicked(MouseEvent e)
            cordX = e.getX();
            cordY = e.getY();
            System.out.println((new StringBuilder()).append(cordX).append(",").append(cordY).toString());
        public void mouseEntered(MouseEvent mouseevent)
        public void mouseExited(MouseEvent mouseevent)
        public void mouseMoved(MouseEvent mouseevent)
        public void mouseDragged(MouseEvent e)
            if(e.getX() != lastX || e.getY() != lastY)
                Point p = scrollPane.getScrollPosition();
                p.translate(dragStartX - e.getX(), dragStartY - e.getY());
                scrollPane.setScrollPosition(p);
    }...and call here
    public class main {
         public main(){}
         public static void main (String args[])
             frame f = new frame();
    }There is something I couldn't see here.By the way ImageLoader is workin I get the image.
    Thank you for your help,please answer me....

    I'm not going to even attempt to resolve the problem posted. There are other problems with your code that should take priority.
    -- class names by convention start with a capital letter.
    -- don't use the name of a common class from the standard API for your custom class, not even with a difference of case. It'll come back to bite you.
    -- don't mix awt and Swing components in the same GUI. Change your class that extends Canvas to extend JPanel instead, and override paintComponent(...) instead of paint(...).
    -- launch your GUI on the EDT by wrapping it in a SwingUtilities.invokeLater or EventQueue.invokeLater.
    -- calling setSize(...) followed by pack() is meaningless. Use one or the other.
    -- That's not the correct way to display a component in a scroll pane.
    Ah, well, and the problem is that when you call pack(), it retrieves the preferredSize of the components in the JFrame, and you haven't set a preferredSize for the scroll pane.
    Please, for your own good, take a break from whatever it is you're working on and go through The Java™ Tutorials: [Creating a GUI with JFC/Swing|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html]
    db

  • GridBagLayout Issues

    Hello All.
    I'm having problems with this panel. I added a new instance of the
    panel to three different Custom JDialogs that also contain another panel.
    I have tested this panel in a JFrame, and it works there. However, in
    my custom JDialogs, it seems like all of the componenets are rendered
    to two differenet places at the same time and the components 'flicker'.
    Also, the commented setLayout call ( BoxLayout) does not cause any
    problem. Is there anything that I am missing here that someone
    can help me with?
    public static class ChromSelectionPanel extends JPanel implements
                   ActionListener {
              private JList chromList;
              private JCheckBox selectAllCB;
              private JScrollPane scrollPane;
              private GridBagConstraints c = new GridBagConstraints();
              public ChromSelectionPanel(Dimension size) {
                   super();
                   this.setSize(size);
                   this.setBorder(BorderFactory
                             .createTitledBorder("Chromosome Selection:"));
                   this.setLayout(new GridBagLayout());
                   //this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
                   c.insets = new Insets(2, 2, 2, 2);
                   c.fill = GridBagConstraints.BOTH;
                   selectAllCB = new JCheckBox("Select All");
                   selectAllCB.addActionListener(this);
                   c.gridx = 0;
                   c.gridy = 0;
                   c.anchor = GridBagConstraints.LINE_END;
                   this.add(selectAllCB, c);
                   JLabel or = new JLabel(" Or ");
                   c.gridx = 1;
                   c.gridy = 0;
                   c.anchor = GridBagConstraints.LINE_START;
                   this.add(or, c);
                   String[] chromOptions = { "1", "2", "3", "4", "5", "6", "7", "8",
                             "9", "10", "11", "12", "13", "14", "15", "16", "17", "18",
                             "19", "20", "21", "22", "X", "Y" };
                   chromList = new JList(chromOptions);
                   chromList.setSize(10, 10);
                   scrollPane = new JScrollPane(chromList);
                   scrollPane.setSize(new Dimension(50, 50));
                   JPanel scrollPaneHolder = new JPanel();
                   scrollPaneHolder.add(scrollPane);
                   c.gridx = 2;
                   c.anchor = GridBagConstraints.LINE_START;
                   this.add(scrollPaneHolder, c);
                   JLabel tutorialLabel = new JLabel(
                             "<html><i>Use the SHIFT key to select multiple <br>"
                                       + " entries.  Use the CTRL key to toggle <br> selections on and off.</i></html>");
                   c.gridx = 3;
                   this.add(tutorialLabel, c);
              public List<Integer> getSelectedChroms() {
                   ArrayList<Integer> list = null;
                   if (selectAllCB.isSelected()) {
                        list = new ArrayList<Integer>(24);
                        for (int i = 1; i < 25; i++) {
                             list.add(new Integer(i));
                   } else {
                        for (Object o : chromList.getSelectedValues()) {
                             if (!o.toString().equalsIgnoreCase("X")
                                       && !o.toString().equalsIgnoreCase("Y"))
                                  list.add(Integer.parseInt(o.toString()));
                             else if (o.toString().equalsIgnoreCase("x"))
                                  list.add(new Integer(23));
                             else
                                  list.add(new Integer(24));
                   return list;
              public void actionPerformed(ActionEvent e) {
                   System.out.println(e.getSource().toString());
                   System.out.println();
                   if (e.getSource() == selectAllCB) {
                        if (selectAllCB.isSelected()) {
                             chromList.setEnabled(false);
                             scrollPane.setEnabled(false);
                             scrollPane.getVerticalScrollBar().setEnabled(false);
                        } else {
                             System.out.println("Not selected");
                             chromList.setEnabled(true);
                             scrollPane.setEnabled(true);
                             scrollPane.getVerticalScrollBar().setEnabled(true);
         }Thanks for any insights, comments, help
    d

    hmm... still can't figure out what was causing the problem so I ended up
    just switching to BoxLayout with some extra panels to get the
    posistioning correct
    d

  • Funny Behaviour (scrollpane and jbutton tricking me)

    Hi,
    I'm close to freaking out. I'm building a GUI that acts as kind of data base editor. There is a combobox to select a table, a scrollpane for viewing and thre buttons to add/remov/edit rows. My test data comes from a Properties object and is transferred into a TableModel in order to create and display the table.
    I pick a table from the comobox and the the table is displayed and the buttons are enabled. As soon as the mouse leaves the scrollpane and enters it or one of the buttons again the buttons become disabled and the table disappears. Picking the table again shows everything again, apart from leaving the add-Button disabled from time to time.
    There is a method that is called when the user selects no table but the initial "Select a table" item in the combo box. This method is NOT called (there is debug output to indicate this). There is no MouseListener or MouseMotionListener added to any component.
    What is this??? Why are sometimes only 2 buttons enabled instead of all three?
    This is the event handling code
    private void displayCategory(String category){
            // get category data
            Properties data = getTestProps();
            // create table
            ProfileTableModel ptm = new ProfileTableModel(data);
            ptm.addTableModelListener(this);
            // show table
            JTable table = new JTable(ptm);
            table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            ListSelectionModel rowSM = table.getSelectionModel();
            rowSM.addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent e) {
                    //Ignore extra messages.
                    if (e.getValueIsAdjusting()) return;
                    ListSelectionModel lsm =
                            (ListSelectionModel)e.getSource();
                    if (lsm.isSelectionEmpty()) {
                        System.err.println("GUI no row selected");
                    } else {
                        int selectedRow = lsm.getMinSelectionIndex();
                        System.err.println("GUI row #" + selectedRow + " selected");
            profilePanel.displayTable(table, true);
        private void clearDisplay(){
            System.err.println("GUI DISPLAY NOTHING");
            profilePanel.displayNothing();
        public void itemStateChanged(ItemEvent e) {
            System.err.println("GUI ITEM STATE CHANGED " + e);
            if (e.getStateChange() == ItemEvent.SELECTED){
                if (e.getItem() instanceof BoxItem){
                    final String cmd = ((BoxItem)e.getItem()).getCommand();
                    (new Thread(new Runnable(){public void run(){displayCategory(cmd);}})).start();
                } else {
                    clearDisplay();
        }This is the GUI code
        protected void displayTable(JTable table, boolean editable){
            addButton.setEnabled(editable);
            removeButton.setEnabled(editable);
            editButton.setEnabled(editable);
            table.setPreferredScrollableViewportSize(new Dimension(400, 330));
            scroll.setViewportView(table);
        protected void displayNothing(){
            System.err.println("GUI display nothing . . . . . . . . . . .");
            scroll.setViewportView(blank);
            addButton.setEnabled(false);
            removeButton.setEnabled(false);
            editButton.setEnabled(false);
        }Cheers,
    Joachim

    There is a method that is called when the user
    selects no table but the initial "Select a table"
    item in the combo box. This method is NOT called
    But this method displayNothing() is the only place where buttons are
    disabled (at least acording to the posted code fragments).
    How can buttons be disabled when this method is not called?
    You see, it's difficult to test your code because it is not a self-contained
    compilable example.
    A short self-contained compilable example often helps you and
    others to discover an otherwise mysterious bug.

  • Changing ScrollPanes View after it has been packed

    Hello,
    I have a Frame which contains a JScrollPane. When I create the frame, the scrollpane has no content. After some event happens, I will add content to the pane. Then later another even could happen and I load different content into the pane. When I do this, the scrollpane scrolls VERY slow using the mouse wheel. I have tried everything I can find to made the scrollpane realize the true size of it's content. I have set the preferredsize to the preferredsize of the panel that is put into it, i have tried revalidating the scrollpane, doLayout, updateUI, etc. Nothing seems to make it realize the real size so that it doesn't scroll slow. Can anyone help me out? Below is a sample application which consists of 3 classes which demonstrate my problem. I'm running on Java 1.5.0_07 on Windows.
    Thanks!
    Andrew
    * ScrollPaneTest.java
    * Created on August 10, 2006, 1:21 PM
    import javax.swing.JPanel;
    public class ScrollPaneTest extends javax.swing.JFrame {
        /** Creates new form ScrollPaneTest */
        public ScrollPaneTest() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            mScrollPane = new javax.swing.JScrollPane();
            mChangeItButton = new javax.swing.JButton();
            mAddInitialButton = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            mChangeItButton.setText("Change It!");
            mChangeItButton.setEnabled(false);
            mChangeItButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    mChangeItButtonActionPerformed(evt);
            mAddInitialButton.setText("Add Initial Content");
            mAddInitialButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    mAddInitialButtonActionPerformed(evt);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(mScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .add(mAddInitialButton)
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(mChangeItButton)))
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(mScrollPane, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 224, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(mChangeItButton)
                        .add(mAddInitialButton))
                    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            pack();
        }// </editor-fold>
        private void mChangeItButtonActionPerformed(java.awt.event.ActionEvent evt) {
            JPanel panel = new SecondContentPanel();
            mScrollPane.setViewportView(panel);
        private void mAddInitialButtonActionPerformed(java.awt.event.ActionEvent evt) {
            JPanel panel = new InitialContentPanel();
            mScrollPane.setViewportView(panel);
            mScrollPane.setPreferredSize(panel.getPreferredSize());
            mChangeItButton.setEnabled(true);
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ScrollPaneTest().setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JButton mAddInitialButton;
        private javax.swing.JButton mChangeItButton;
        private javax.swing.JScrollPane mScrollPane;
        // End of variables declaration
    * InitialContentPanel.java
    * Created on August 10, 2006, 1:23 PM
    public class InitialContentPanel extends javax.swing.JPanel {
        /** Creates new form InitialContentPanel */
        public InitialContentPanel() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            jLabel1 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
            jScrollPane2 = new javax.swing.JScrollPane();
            jList1 = new javax.swing.JList();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            jLabel1.setText("My Label");
            jTextArea1.setColumns(20);
            jTextArea1.setRows(5);
            jScrollPane1.setViewportView(jTextArea1);
            jList1.setModel(new javax.swing.AbstractListModel() {
                String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
                public int getSize() { return strings.length; }
                public Object getElementAt(int i) { return strings; }
    jScrollPane2.setViewportView(jList1);
    jButton1.setText("jButton1");
    jButton2.setText("jButton2");
    org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(layout.createSequentialGroup()
    .addContainerGap()
    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
    .add(jLabel1)
    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
    .add(jButton2)
    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    .add(jButton1)))
    .addContainerGap())
    layout.setVerticalGroup(
    layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(layout.createSequentialGroup()
    .addContainerGap()
    .add(jLabel1)
    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 226, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 160, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    .add(jButton1)
    .add(jButton2))
    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    }// </editor-fold>
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration
    * SecondContentPanel.java
    * Created on August 10, 2006, 1:27 PM
    public class SecondContentPanel extends javax.swing.JPanel {
        /** Creates new form SecondContentPanel */
        public SecondContentPanel() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            jLabel1 = new javax.swing.JLabel();
            jRadioButton1 = new javax.swing.JRadioButton();
            jRadioButton2 = new javax.swing.JRadioButton();
            jRadioButton3 = new javax.swing.JRadioButton();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();
            jColorChooser1 = new javax.swing.JColorChooser();
            jLabel1.setText("Another Label");
            jRadioButton1.setText("jRadioButton1");
            jRadioButton1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
            jRadioButton1.setMargin(new java.awt.Insets(0, 0, 0, 0));
            jRadioButton2.setText("jRadioButton2");
            jRadioButton2.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
            jRadioButton2.setMargin(new java.awt.Insets(0, 0, 0, 0));
            jRadioButton3.setText("jRadioButton3");
            jRadioButton3.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
            jRadioButton3.setMargin(new java.awt.Insets(0, 0, 0, 0));
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane1.setViewportView(jTable1);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                        .add(jLabel1)
                        .add(jRadioButton1)
                        .add(jRadioButton2)
                        .add(jRadioButton3)
                        .add(jColorChooser1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(jScrollPane1, 0, 0, Short.MAX_VALUE))
                    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jLabel1)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jRadioButton1)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jRadioButton2)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jRadioButton3)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 275, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jColorChooser1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        }// </editor-fold>
        // Variables declaration - do not modify
        private javax.swing.JColorChooser jColorChooser1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JRadioButton jRadioButton1;
        private javax.swing.JRadioButton jRadioButton2;
        private javax.swing.JRadioButton jRadioButton3;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        // End of variables declaration

    Gee...Thanks for your helpful diagnosis there. I used Netbeans to quickly create an example of the problem. I do know how to develop an application without the use of a GUI builder and prior to Matise, I haven't liked GUI Builders at all. So if you are all knowing in swing, then maybe you could actually help with the problem. Would you like me to remove the editor folds, etc from the example before you can get started?? If anyone else could help out that would be great...

  • Help for scrollPane

    hi
    I'm adapting my source code, following the swing tutorial example for scrollbar pane.
    I ask you to check my code because I do not see what I want.
    my code is intended to put a panel on a scrollpane and then add a textfield to the panel.
    the scrollpane is already on my "design" tab (nebeans dev env).
    I do not see this.
    thanks in advance
    testPanel.setEnabled(true);
    testPanel.setBackground(Color.black);
    testPanel.setVisible(true);
    Dimension dimension1=new Dimension(60,60);;
    testPanel.setPreferredSize(dimension1);
    testPanel.setSize(dimension1);
    testPanel.setEnabled(true);
    testPanel.setBackground(new java.awt.Color(0, 0, 0));
    JTextField testTextField=new JTextField("prova");
    testTextField.setEnabled(true);
    testTextField.setBackground(new java.awt.Color(0, 102, 153));
    testPanel.add(testTextField,new org.netbeans.lib.awtextra.AbsoluteConstraints(272, 51, 316, -1));
    JLabel instructionsLeft = new JLabel("Click left mouse button to place a circle.");
    jScrollPane1.add(instructionsLeft);
    jScrollPane1.add(testPanel,new AbsoluteConstraints(140, 10, -1, -1));
    jScrollPane1.setEnabled(true);
    testPanel.repaint();
    jScrollPane1.repaint();
    this.repaint();

    P5music wrote:
    The only hint in the API document section is to use
    jScrollPane1.setViewportView(testPanel);
    Now, I used it instead of jScrollPane1.add(testPanel);
    but nothing changed....It's very hard to guess what you're doing wrong without compilable code. Unless someone very clever comes by soon who can instantly spot your problme, my recommendation that you create and post an SSCCE still stands. In fact odds are, if you create the SSCCE, you'll spot your error and be able to fix it yourself. Much luck.

  • Custom graphics in java.awt.ScrollPane

    Hi all,
    I have to draw a custom created image in a scroll pane. As the image is very large I want to display it in a scroll pane. As parts of the image may change within seconds, and drawing the whole image is very time consuming (several seconds) I want to draw only the part of the image that is currently visible to the user.
    My idea: creating a new class that extends from java.awt.ScrollPane, overwrite the paint(Graphics) method and do the drawings inside. Unfortunately, it does not work. The background of the scoll pane is blue, but it does not show the red box (the current viewport is not shown in red).
    Below please find the source code that I am using:
    package graphics;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.ScrollPane;
    import java.awt.event.AdjustmentEvent;
    public class CMyComponent extends ScrollPane {
         /** <p>Listener to force a component to repaint when a scroll bar changes its
          * position.</p>
         private final class ScrollBarAdjustmentListener implements java.awt.event.AdjustmentListener {
              /** <p>The component to force to repaint.</p> */
              private final Component m_Target;
              /** <p>Default constructor.</p>
               * @param Target The component to force to repaint.
              private ScrollBarAdjustmentListener(Component Target) { m_Target = Target; }
              /** <p>Forces to component to repaint upon adjustment of the scroll bar.</p>
               *  @see java.awt.event.AdjustmentListener#adjustmentValueChanged(java.awt.event.AdjustmentEvent)
              public void adjustmentValueChanged(AdjustmentEvent e) { m_Target.paint(m_Target.getGraphics()); }
         public CMyComponent() {
              // Ensure that the component repaints upon changing of the scroll bars
              ScrollBarAdjustmentListener sbal = new ScrollBarAdjustmentListener(this);
              getHAdjustable().addAdjustmentListener(sbal);
              getVAdjustable().addAdjustmentListener(sbal);
         public void paint(Graphics g) {
              setBackground(Color.BLUE);
              g.setColor(Color.RED);
              g.fillRect(getScrollPosition().x, getScrollPosition().y, getViewportSize().width, getViewportSize().height);
         public final static void main(String[] args) {
              java.awt.Frame f = new java.awt.Frame();
              f.add(new CMyComponent());
              f.pack();
              f.setVisible(true);
    }

    Dear all,
    I used the last days and tried several things. I think now I have a quite good working solution (just one bug remains) and it is very performant. To give others a chance to see what I have done I post the source code of the main class (a canvas drawing and implementing scrolling) here. As soon as the sourceforge project is accepted, I will publish the whole sources at there. Enjoy. And if you have some idea for my last bug in getElementAtPixel(Point), then please tell me.
    package internetrail.graphics.hexgrid;
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.Polygon;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import java.awt.geom.Area;
    import java.awt.image.BufferedImage;
    import java.util.WeakHashMap;
    import java.util.Map;
    /** <p>Hex grid view.</p>
    * <p>Visualizes a {@link IHexGridModel}.</p>
    * @version 0.1, 03.06.2006
    * @author Bjoern Wuest, Germany
    public final class CHexGridView extends Canvas implements ComponentListener, IHexGridElementListener {
         /** <p>Serial version unique identifier.</p> */
         private static final long serialVersionUID = -965902826101261530L;
         /** <p>Instance-constant parameter for the width of a hex grid element.</p> */
         public final int CONST_Width;
         /** <p>Instance-constant parameter for 1/4 of the width of a hex grid element.</p> */
         public final int CONST_Width1fourth;
         /** <p>Instance-constant parameter for 3/4 of the width of a hex grid element.</p> */
         public final int CONST_Width3fourth;
         /** <p>Instance-constant parameter for 1.5 times of the width of a hex grid element.</p> */
         public final int CONST_Width1dot5;
         /** <p>Instance-constant parameter for 4 times of the width of a hex grid element.</p> */
         public final int CONST_Widthquad;
         /** <p>Instance-constant parameter for the height of a hex grid element.</p> */
         public final int CONST_Height;
         /** <p>Instance-constant parameter for 1/2 of the height of a hex grid element.</p> */
         public final int CONST_Heighthalf;
         /** <p>Instance-constant parameter for the double height of a hex grid element.</p> */
         public final int CONST_Heightdouble;
         /** <p>The steepness of a side of the hex grid element (calculated for the upper left arc).</p> */
         public final double CONST_Steepness;
         /** <p>The model of this hex grid </p> */
         private final IHexGridModel m_Model;
         /** <p>A cache for already created images of the hex map.</p> */
         private final Map<Point, Image> m_Cache = new WeakHashMap<Point, Image>();
         /** <p>The graphical area to draw the selection ring around a hex element.</p> */
         private final Area m_SelectionRing;
         /** <p>The image of the selection ring around a hex element.</p> */
         private final BufferedImage m_SelectionRingImage;
         /** <p>The current position of the hex grid in pixels (top left visible corner).</p> */
         private Point m_ScrollPosition = new Point(0, 0);
         /** <p>Flag to define if a grid is shown ({@code true}) or not ({@code false}).</p> */
         private boolean m_ShowGrid = true;
         /** <p>Flag to define if the selected hex grid element should be highlighted ({@code true}) or not ({@code false}).</p> */
         private boolean m_ShowSelected = true;
         /** <p>The offset of hex grid elements shown on the screen, measured in hex grid elements.</p> */
         private Point m_CurrentOffset = new Point(0, 0);
         /** <p>The offset of the image shown on the screen, measured in pixels.</p> */
         private Point m_PixelOffset = new Point(0, 0);
         /** <p>The index of the currently selected hex grid element.</p> */
         private Point m_CurrentSelected = new Point(0, 0);
         /** <p>The width of a buffered pre-calculated image in pixel.</p> */
         private int m_ImageWidth;
         /** <p>The height of a buffered pre-calculated image in pixel.</p> */
         private int m_ImageHeight;
         /** <p>The maximum number of columns of hex grid elements to be shown at once on the screen.</p> */
         private int m_MaxColumn;
         /** <p>The maximum number of rows of hex grid elements to be shown at once on the screen.</p> */
         private int m_MaxRow;
         /** <p>Create a new hex grid view.</p>
          * <p>The hex grid view is bound to a {@link IHexGridModel} and registers at
          * that model to listen for {@link IHexGridElement} updates.</p>
          * @param Model The model backing this view.
         public CHexGridView(IHexGridModel Model) {
              // Set the model
              m_Model = Model;
              CONST_Width = m_Model.getElementsWidth();
              CONST_Height = m_Model.getElementsHeight();
              CONST_Width1fourth = CONST_Width/4;
              CONST_Width3fourth = CONST_Width*3/4;
              CONST_Width1dot5 = CONST_Width*3/2;
              CONST_Heighthalf = CONST_Height/2;
              CONST_Widthquad = CONST_Width*4;
              CONST_Heightdouble = CONST_Height*2;
              CONST_Steepness = (double)CONST_Heighthalf / CONST_Width1fourth;
              m_ImageWidth = getSize().width+CONST_Widthquad;
              m_ImageHeight = getSize().height+CONST_Heightdouble;
              m_MaxColumn = m_ImageWidth / CONST_Width3fourth;
              m_MaxRow = m_ImageHeight / CONST_Height;
              // Register this canvas for various notifications
              m_Model.addElementListener(this);
              addComponentListener(this);
              // Create the selection ring to highlight hex grid elements
              m_SelectionRing = new Area(new Polygon(new int[]{-1, CONST_Width1fourth-1, CONST_Width3fourth+1, CONST_Width+1, CONST_Width3fourth+1, CONST_Width1fourth-1}, new int[]{CONST_Heighthalf, -1, -1, CONST_Heighthalf, CONST_Height+1, CONST_Height+1}, 6));
              m_SelectionRing.subtract(new Area(new Polygon(new int[]{2, CONST_Width1fourth+2, CONST_Width3fourth-2, CONST_Width-2, CONST_Width3fourth-2, CONST_Width1fourth+2}, new int[]{CONST_Heighthalf, 2, 2, CONST_Heighthalf, CONST_Height-2, CONST_Height-2}, 6)));
              m_SelectionRingImage = new BufferedImage(CONST_Width, CONST_Height, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g = m_SelectionRingImage.createGraphics();
              g.setColor(Color.WHITE);
              g.fill(m_SelectionRing);
         @Override public synchronized void paint(Graphics g2) {
              // Caculate the offset of indexes to show
              int offsetX = 2 * (m_ScrollPosition.x / CONST_Width1dot5) - 2;
              int offsetY = (int)(Math.ceil(m_ScrollPosition.y / CONST_Height) - 1);
              m_CurrentOffset = new Point(offsetX, offsetY);
              // Check if the image is in the cache
              Image drawing = m_Cache.get(m_CurrentOffset);
              if (drawing == null) {
                   // The image is not cached, so draw it
                   drawing = new BufferedImage(m_ImageWidth, m_ImageHeight, BufferedImage.TYPE_INT_ARGB);
                   Graphics2D g = ((BufferedImage)drawing).createGraphics();
                   // Draw background
                   g.setColor(Color.BLACK);
                   g.fillRect(0, 0, m_ImageWidth, m_ImageHeight);
                   // Draw the hex grid
                   for (int column = 0; column <= m_MaxColumn; column += 2) {
                        for (int row = 0; row <= m_MaxRow; row++) {
                             // Draw even column
                             IHexGridElement element = m_Model.getElementAt(offsetX + column, offsetY + row);
                             if (element != null) { g.drawImage(element.getImage(m_ShowGrid), (int)(column*(CONST_Width3fourth-0.5)), CONST_Height*row, null); }
                             // Draw odd column
                             element = m_Model.getElementAt(offsetX + column+1, offsetY + row);
                             if (element!= null) { g.drawImage(element.getImage(m_ShowGrid), (int)(column*(CONST_Width3fourth-0.5)+CONST_Width3fourth), CONST_Heighthalf*(row*2+1), null); }
                   // Put the image into the cache
                   m_Cache.put(m_CurrentOffset, drawing);
              // Calculate the position of the image to show
              offsetX = CONST_Width1dot5 + (m_ScrollPosition.x % CONST_Width1dot5);
              offsetY = CONST_Height + (m_ScrollPosition.y % CONST_Height);
              m_PixelOffset = new Point(offsetX, offsetY);
              g2.drawImage(drawing, -offsetX, -offsetY, null);
              // If the selected element should he highlighted, then do so
              if (m_ShowSelected) {
                   // Check if the selected element is on screen
                   if (isElementOnScreen(m_CurrentSelected)) {
                        // Correct vertical offset for odd columns
                        if ((m_CurrentSelected.x % 2 == 1)) { offsetY -= CONST_Heighthalf; }
                        // Draw the selection circle
                        g2.drawImage(m_SelectionRingImage, (m_CurrentSelected.x - m_CurrentOffset.x) * CONST_Width3fourth - offsetX - ((m_CurrentSelected.x + 1) / 2), (m_CurrentSelected.y - m_CurrentOffset.y) * CONST_Height - offsetY, null);
         @Override public synchronized void update(Graphics g) { paint(g); }
         public synchronized void componentResized(ComponentEvent e) {
              // Upon resizing of the component, adjust several pre-calculated values
              m_ImageWidth = getSize().width+CONST_Widthquad;
              m_ImageHeight = getSize().height+CONST_Heightdouble;
              m_MaxColumn = m_ImageWidth / CONST_Width3fourth;
              m_MaxRow = m_ImageHeight / CONST_Height;
              // And flush the cache
              m_Cache.clear();
         public void componentMoved(ComponentEvent e) { /* do nothing */ }
         public void componentShown(ComponentEvent e) { /* do nothing */ }
         public void componentHidden(ComponentEvent e) { /* do nothing */ }
         public synchronized void elementUpdated(IHexGridElement Element) {
              // Clear cache where the element may be contained at
              for (Point p : m_Cache.keySet()) { if (isElementInScope(Element.getIndex(), p, new Point(p.x + m_MaxColumn, p.y + m_MaxRow))) { m_Cache.remove(p); } }
              // Update the currently shown image if the update element is shown, too
              if (isElementOnScreen(Element.getIndex())) { repaint(); }
         /** <p>Returns the model visualized by this grid view.</p>
          * @return The model visualized by this grid view.
         public IHexGridModel getModel() { return m_Model; }
         /** <p>Returns the current selected hex grid element.</p>
          * @return The current selected hex grid element.
         public IHexGridElement getSelected() { return m_Model.getElementAt(m_CurrentSelected.x, m_CurrentSelected.y); }
         /** <p>Sets the current selected hex grid element by its index.</p>
          * <p>If the selected hex grid element should be highlighted and is currently
          * shown on the screen, then this method will {@link #repaint() redraw} this
          * component automatically.</p>
          * @param Index The index of the hex grid element to become the selected one.
          * @throws IllegalArgumentException If the index refers to a non-existing hex
          * grid element.
         public synchronized void setSelected(Point Index) throws IllegalArgumentException {
              // Check that the index is valid
              if ((Index.x < 0) || (Index.y < 0) || (Index.x > m_Model.getXElements()) || (Index.y > m_Model.getYElements())) { throw new IllegalArgumentException("There is no hex grid element with such index."); }
              m_CurrentSelected = Index;
              // If the element is on screen and should be highlighted, then repaint
              if (m_ShowSelected && isElementOnScreen(m_CurrentSelected)) { repaint(); }
         /** <p>Moves the visible elements to the left by the number of pixels.</p>
          * <p>To move the visible elements to the left by one hex grid element, pass
          * {@link #CONST_Width3fourth} as the parameter. The component will
          * automatically {@link #repaint()}.</p>
          * @param Pixels The number of pixels to move to the left.
          * @return The number of pixels moved to the left. This is always between 0
          * and {@code abs(Pixels)}.
         public synchronized int moveLeft(int Pixels) {
              int delta = m_ScrollPosition.x - Math.max(0, m_ScrollPosition.x - Math.max(0, Pixels));
              if (delta != 0) {
                   m_ScrollPosition.x -= delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements up by the number of pixels.</p>
          * <p>To move the visible elements up by one hex grid element, pass {@link
          * #CONST_Height} as the parameter. The component will automatically {@link
          * #repaint()}.</p>
          * @param Pixels The number of pixels to move up.
          * @return The number of pixels moved up. This is always between 0 and {@code
          * abs(Pixels)}.
         public synchronized int moveUp(int Pixels) {
              int delta = m_ScrollPosition.y - Math.max(0, m_ScrollPosition.y - Math.max(0, Pixels));
              if (delta != 0) {
                   m_ScrollPosition.y -= delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements to the right by the number of pixels.</p>
          * <p>To move the visible elements to the right by one hex grid element, pass
          * {@link #CONST_Width3fourth} as the parameter. The component will
          * automatically {@link #repaint()}.</p>
          * @param Pixels The number of pixels to move to the right.
          * @return The number of pixels moved to the right. This is always between 0
          * and {@code abs(Pixels)}.
         public synchronized int moveRight(int Pixels) {
              int delta = Math.min(m_Model.getXElements() * CONST_Width3fourth + CONST_Width1fourth - getSize().width, m_ScrollPosition.x + Math.max(0, Pixels)) - m_ScrollPosition.x;
              if (delta != 0) {
                   m_ScrollPosition.x += delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements down by the number of pixels.</p>
          * <p>To move the visible elements down by one hex grid element, pass {@link
          * #CONST_Height} as the parameter. The component will automatically {@link
          * #repaint()}.</p>
          * @param Pixels The number of pixels to move down.
          * @return The number of pixels moved down. This is always between 0 and
          * {@code abs(Pixels)}.
         public synchronized int moveDown(int Pixels) {
              int delta = Math.min(m_Model.getYElements() * CONST_Height + CONST_Heighthalf - getSize().height, m_ScrollPosition.y + Math.max(0, Pixels)) - m_ScrollPosition.y;
              if (delta != 0) {
                   m_ScrollPosition.y += delta;
                   repaint();
              return delta;
         /** <p>Checks if the hex grid element of the given index is currently
          * displayed on the screen (even just one pixel).</p>
          * <p>The intention of this method is to check if a {@link #repaint()} is
          * necessary or not.</p>
          * @param ElementIndex The index of the element to check.
          * @return {@code true} if the hex grid element of the given index is
          * displayed on the screen, {@code false} if not.
         public synchronized boolean isElementOnScreen(Point ElementIndex) { return isElementInScope(ElementIndex, m_CurrentOffset, new Point(m_CurrentOffset.x + m_MaxColumn, m_CurrentOffset.y + m_MaxRow)); }
         /** <p>Checks if the hex grid element of the given index is within the given
          * indexes.</p>
          * <p>The intention of this method is to check if a {@link #repaint()} is
          * necessary or not.</p>
          * @param ElementIndex The index of the element to check.
          * @param ReferenceIndexLeftTop The left top index of the area to check.
          * @param ReferenceIndexRightBottom The right bottom index of the area to check.
          * @return {@code true} if the hex grid element of the given index is within
          * the given area, {@code false} if not.
         public synchronized boolean isElementInScope(Point ElementIndex, Point ReferenceIndexLeftTop, Point ReferenceIndexRightBottom) { if ((ElementIndex.x >= ReferenceIndexLeftTop.x) && (ElementIndex.x <= ReferenceIndexRightBottom.x) && (ElementIndex.y >= ReferenceIndexLeftTop.y) && (ElementIndex.y <= (ReferenceIndexRightBottom.y))) { return true; } else { return false; } }
         /** <p>Return the {@link IHexGridElement hex grid element} shown at the given
          * pixel on the screen.</p>
          * <p><b>Remark: There seems to be a bug in retrieving the proper element,
          * propably caused by rounding errors and unprecise pixel calculations.</p>
          * @param P The pixel on the screen.
          * @return The {@link IHexGridElement hex grid element} shown at the pixel.
         public synchronized IHexGridElement getElementAtPixel(Point P) {
              // @FIXME Here seems to be some bugs remaining
              int dummy = 0; // Variable for warning to indicate that there is something to do :)
              // Calculate the pixel on the image, not on the screen
              int px = P.x + m_PixelOffset.x;
              int py = P.y + m_PixelOffset.y;
              // Determine the x-index of the column (is maybe decreased by one)
              int x = px / CONST_Width3fourth + m_CurrentOffset.x;
              // If the column is odd, then shift the y-pixel by half element height
              if ((x % 2) == 1) { py -= CONST_Heighthalf; }
              // Determine the y-index of the row (is maybe decreased by one)
              int y = py / CONST_Height + m_CurrentOffset.y;
              // Normative coordinates to a single element
              px -= (x - m_CurrentOffset.x) * CONST_Width3fourth;
              py -= (y - m_CurrentOffset.y) * CONST_Height;
              // Check if the normative pixel is in the first quarter of a column
              if (px < CONST_Width1fourth) {
                   // Adjustments to the index may be necessary
                   if (py < CONST_Heighthalf) {
                        // We are in the upper half of a hex-element
                        double ty = CONST_Heighthalf - CONST_Steepness * px;
                        if (py < ty) { x--; }
                   } else {
                        // We are in the lower half of a hex-element
                        double ty = CONST_Heighthalf + CONST_Steepness * px;
                        if (py > ty) {
                             x--;
                             y++;
              return m_Model.getElementAt(x, y);
    }Ah, just to give you some idea: I use this component to visualize a hex grid map with more than 1 million grid elements. And it works, really fast, and requires less than 10 MByte of memory.

  • Design problem(split pane scrollpane Insets)

    hi,
    doing a exam simulator prgm
    design is like,
    Question (text area with scrollpane)
    Answers (checkbox inside panel with scrollpane)
    used split pane between qst and ans but big thick bar comes how to reduce size and it is not
    moving.
    used GridLayout for container and panel.
    PROBLEM is how to leave space qst textarea appears from very left edge of screen how to leave some space
    same prblm for checkbox they to appear extreme left on screen.

    Put those components in a JPanel overwriting the getInsets() method like this:
    JPanel cPane=new JPanel(){
        private final Insets _insets=new Insets(10,10,10,10);
        public Insets getInsets(){
            return _insets;
    };...should do the trick, take a look at the Insets class if you need information on how defining it...

  • Problem with drawing in a scrollpane using clipbounds

    Hello
    Setup is a JFrame containing a splitpane with on the left just some config buttons and on the right a scrollpane.
    Inside the scrollpane I want to draw big waveforms.
    This is represented by a long array of 1's and 0's for the Y coordinates.
    On drawing in paintComponents method I allways reconstruct a GeneralPath, based on the Clipbouns returned by the Graphics variable.
    I have to reconstruct the GeneralPath polygon because my data can be millions long. And therefor I have to limit the points that are drawn.
    When I allways reconstruct this GeneralPath, upon scrolling the polygon is shown scrappy, as in the line connecting the points will only be half shown or almost not.
    Resizing the window or just minimize maximize and it is shown ok.
    I do not have this problem when the GeneralPath I construct is only once made upfront and never remade in the paintComponent method.
    But as I need the clipbounds to know which part to construct I need to rebuild this polygon over and over again.
    I have tried to draw it with Line2D.Double but I get almost the same effect, parts of the lines not being drawn ok.
    Below is the code of the Panel inside the ScrollPane responsible for this drawing.
    public class Usr_Test_L extends JPanel
      final static Color bg   = Color.black;
      final static Color fg   = Color.white;
      final static Color wave = Color.red;
      final static Color txt  = Color.green;
      final static Color grid = Color.lightGray;
      private static final BasicStroke SOLID = new BasicStroke(1.0f);
      private static final BasicStroke BOLD  = new BasicStroke(3.0f);
      private double maxX = 0.0;
      private double maxY = 0.0;
      private double gridWidth;
      private double gridHeight;
      private int panelWidth;
      private int panelHeight;
      boolean firstTime = true;
      private double[] xPoints = null;
      private double[] yPoints = null;
      GeneralPath polygon;
      boolean polyOk = false;
      private double waveHeight = 0;
      private boolean gridOn = true;
      private Usr_Test_R scrollPane = null;
      Usr_Test_L(Usr_Test_R scrollPane)
        super(true);
        this.scrollPane = scrollPane;
        buildGui();
      void buildGui()
        setBackground(bg);
        setForeground(fg);
        //Let the user scroll by dragging to outside the window.
        setAutoscrolls(true); //enable synthetic drag events
    //    addMouseMotionListener(this); //handle mouse drags
        repaint();
      private void generateWave(int cycles, double height)
        waveHeight = height;
        xPoints = new double[cycles];
        yPoints = new double[cycles];
        Random r = new Random();
        for ( int i = 0; i < cycles; i++ )
          xPoints[i] = i;
          yPoints[i] = (int)( Math.pow(-1.0,i) ) * ( r.nextInt(2) );
    //      if ( ( i % 10 ) == 0 ) yPoints[i] = height;
    //      else                   yPoints[i] = height + gridHeight;
    //      System.err.println("P"+i+"("+xPoints[i]+","+yPoints[i]+")");
      private void generateSineWave(int cycles, double height)
        waveHeight = height;
        xPoints = new double[cycles];
        yPoints = new double[cycles];
        double j, xval, yval;
        j = 0;
        int i = 0;
        while (i < cycles)
          xval = j;
          yval = Math.sin(j) * 10.0 + 20;
          xPoints[i] = xval;
          yPoints[i] = yval;
          i++;
          j += 0.01;
      public Dimension getPreferredSize()  // <== used because of revalidate, parent scrollpane asks preferredsize ..., so we overruled the method
        return new Dimension(panelWidth, panelHeight);
      public void drawLine(int cycles, int height)
        generateWave(cycles,(int)(gridHeight*height));
        maxX = gridWidth  * cycles;
        maxY = gridHeight * cycles;
        while ( maxX > panelWidth  ) panelWidth  *= 2;
        while ( maxY > panelHeight ) panelHeight *= 2;
    //    polyOk = buildPolygon();
        revalidate();
        repaint();
      public void drawSine(int cycles, int height)
        generateSineWave(cycles,(int)(gridHeight*height));
        maxX = gridWidth  * cycles;
        maxY = gridHeight * cycles;
        while ( maxX > panelWidth  ) panelWidth  *= 2;
        while ( maxY > panelHeight ) panelHeight *= 2;
    //    polyOk = buildPolygon();
        revalidate();
        repaint();
      public void zoomIn()
        gridWidth  *= 2;
        gridHeight *= 2;
        repaint();
      public void zoomOut()
        gridWidth  /= 2;
        gridHeight /= 2;
        repaint();
      private void initPanel()
        Dimension d = getSize();
        panelWidth = d.width;
        panelHeight = d.height;
        maxX = panelWidth;
        maxY = panelHeight;
        gridWidth  = panelWidth / 8;
        gridHeight = panelHeight / 8;
        scrollPane.getHorBar().setUnitIncrement((int)(gridWidth*3));           // times 2 otherwise no clipbounds are allways too small
        scrollPane.getHorBar().setBlockIncrement((int)(gridWidth*3));
        scrollPane.getVerBar().setUnitIncrement((int)(gridHeight*3));
        scrollPane.getVerBar().setBlockIncrement((int)(gridHeight*3));
      public void grid()
        if ( gridOn ) gridOn = false;
        else          gridOn = true;
      private void drawGrid(Graphics2D g2, Rectangle clip)
        if ( ! gridOn ) return;
        // draw grid
        g2.setPaint(grid);
        // new good grid
        double startX = clip.getX() + ( gridWidth - ( clip.getX() % gridWidth ) );
        double endX   = clip.getX() + clip.getWidth();
        double startY = clip.getY() + ( gridHeight - ( clip.getY() % gridHeight ) );
        double endY   = clip.getY() + clip.getHeight();
        double y = startY;
        while ( startX < endX )
          while ( y < endY )
            g2.draw(new Rectangle2D.Double( startX - 0.5, y - 0.5, 1.0, 1.0 ));
            y += gridHeight;
          y = startY;
          startX += gridWidth;
      private boolean buildPolygon(Rectangle clip)
        if ( xPoints != null && yPoints != null )
          polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,xPoints.length);
        else
          return false;
        double x = xPoints[0] * gridWidth;
        double y = waveHeight;
        polygon.moveTo((float)xPoints[0], (float)yPoints[0]);
        for ( int index = 0; index < xPoints.length; index++ )
          x = xPoints[index] * gridWidth;
          y = waveHeight + ( yPoints[index] * gridHeight );
          if ( x > ( clip.getX() + clip.getWidth() ) ) break;
          if ( y < clip.getY() || y > ( clip.getY() + clip.getHeight() ) ) continue;
          if ( x < clip.getX() || x > ( clip.getX() + clip.getWidth()  ) ) continue;
          polygon.lineTo((float)x, (float)y);
        return true;
      private boolean drawLines(Graphics2D g2, Rectangle clip)
        if ( xPoints == null || yPoints == null ) return false;
        double x1 = xPoints[0] * gridWidth;
        double y1 = waveHeight;
        double x2, y2;
        boolean cont = false;
        for ( int index = 0; index < xPoints.length; index++ )
          x2 = xPoints[index] * gridWidth;
          y2 = waveHeight + ( yPoints[index] * gridHeight );
          if ( x1 > ( clip.getX() + clip.getWidth() ) )
            break;
          if ( x2 > ( clip.getX() + clip.getWidth() ) )
            break;
          if ( y2 < clip.getY() || y2 > ( clip.getY() + clip.getHeight() ) )
            cont = true;
          if ( x2 < clip.getX() || x2 > ( clip.getX() + clip.getWidth()  ) )
            cont = true;
          if ( ! cont ) g2.draw(new Line2D.Double(x1,y1,x2,y2));
          x1 = x2;
          y1 = y2;
          cont = false;
        return true;
      public void paintComponent(Graphics g)
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        if ( firstTime )
          initPanel();
          firstTime = false;
        // get clip bounds
        Rectangle clip = new Rectangle();
        clip = g2.getClipBounds(clip);
        // draw grid
        drawGrid(g2,clip);
        // draw waveform
        g2.setPaint(wave);
        g2.setStroke(SOLID);
        if ( buildPolygon(clip) ) g2.draw(polygon);
    //    if ( polyOk ) g2.draw(polygon);
    //    drawLines(g2,clip);
      }

    I have added a standalone testcase for ease.
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.util.*;
    public class Scrolling {
        public static void main(String[] args) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(new DrawPanel()));
            f.setSize(400,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    class DrawPanel extends JPanel {
        private GeneralPath polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,1000);
        private int[] coords;
        public DrawPanel() {
            setBackground(Color.white);
            buildPolygon();
        private void buildPolygon() {
         coords = new int[2000];
            Random r = new Random();
            int height = 80;
            int gridHeight = 10;
            int gridWidth = 10;
         int j = 0;       
            for (int i=0, dir=-1; i<1000; i++, dir=-dir) {
                coords[j++] = i * gridWidth;
                coords[j++] = height + dir*gridHeight*r.nextInt(2);
        private void drawPolygonClipped(Rectangle clip)
    polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,1000);
           polygon.moveTo(0,80);
           for ( int i = 0; i < 2000; i++ )
          if ( coords[i] > ( clip.getX() + clip.getWidth() ) ) break;
          if ( coords[i+1] < clip.getY() || coords[i+1] > ( clip.getY() + clip.getHeight() ) ) continue;
          if ( coords[i] < clip.getX() || coords[i] > ( clip.getX() + clip.getWidth()  ) ) continue;
                polygon.lineTo(coords[i++],coords);
    private void drawPolygon(Rectangle clip)
    polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,1000);
         polygon.moveTo(0,80);
         for ( int i = 0; i < 2000; i++ )
              polygon.lineTo(coords[i++],coords[i]);
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
         Rectangle clip = new Rectangle();
         g.getClipBounds(clip);
         drawPolygonClipped(clip);
         //drawPolygon(clip);
    g2.draw(polygon);
    public Dimension getPreferredSize() {
    return new Dimension(1500,500);

  • JScrollpane does not work properly when I interlinked to another Scrollpane

    Hi,
    I am trying to develop a small Editor using java Swing. I hav to display Line numbers also. for that i used another textarea and set the scrollbar model of that to the scrollbar model of text area where i type the programs. the module works perfectly in the first appearance.. scrolls same time..but the problem arises when i insert a new line into or delete a new line from the text area. when i am inserting or deleting the scrollbar of the prgram text area scrolls down immdtly after the insertion or deletion...
    I tried a lot to solve the problem. Please help me...

    I hav to display Line numbers ...Whatever component you use to display the line number you should add the component directly to the scroll pane that contains your main text area. You do this by using the scrollPane.setRowHeaderView(). I've posted several example of this if you search the forums.

  • How can i make my scrollpane in a way that at the opening of a frame it doe

    How can i make my scrollpane in a way that at the opening of a frame it does not scroll down automatically?
    code is below
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.net.*;
    import javax.swing.JOptionPane.*;
    import java.io.*;
    import javax.swing.colorchooser.*;
    import javax.swing.filechooser.*;
    import javax.accessibility.*;
    import javax.swing.border.*;
    import java.sql.*;
    public class Signup extends JFrame
         JLabel p1,p2,p3,p4,p5,p6,uid,upass,cpass,fname,sname,hint,sl,ed,age,adr,cit,zip;
         JTextField uname,fnamet,snamet,hintt,adrt,adrt1,city,zipcode;
         JPasswordField upassw,cpassw;     
         JComboBox sex,education,agegr;
         Signup()
         Container c=getContentPane();
         c.setLayout(null);
         c.setBackground(Color.white);
         /** JPanel c = new JPanel();
         c.setBackground(Color.white);
         int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
         int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
         JScrollPane jsp = new JScrollPane(c, v, h); ***/
    p1=new JLabel("Create Your Icafe!ID",10);
         p2=new JLabel("Personal Information");
         p3=new JLabel("User Address");
         p4=new JLabel("Tell Us About Your Hobbiess (Optional) ");
         p5=new JLabel("Tell us something about what you like. This will help us choose the kind of content to display on           your pages.");
         p6=new JLabel("--------------------------------------------------------------------------------");
    uid=new JLabel("User Id");
         upass=new JLabel("Password");
         cpass=new JLabel("Confirmation Password");
         fname=new JLabel("UserName");
         sname=new JLabel("SurName");
         hint=new JLabel("Hint Question");
    sl=new JLabel("Sex");
         ed=new JLabel("Education");     
         age=new JLabel("Age Group");     
         adr=new JLabel("Address");
    cit=new JLabel("City");
    zip=new JLabel("ZipCode");
         uname=new JTextField(10);
         uname.requestFocus();     
         uname.setToolTipText("UserName");
    upassw=new JPasswordField(10);
         upassw.setToolTipText("Password");
         upassw.setEchoChar('*');
         cpassw=new JPasswordField(10);
         cpassw.setToolTipText("Confirmation Password");
         cpassw.setEchoChar('*');
         fnamet=new JTextField(10);
         fnamet.setToolTipText("FullName");
         snamet=new JTextField(10);
         snamet.setToolTipText("SurName");
         hintt=new JTextField(10);
         hintt.setToolTipText("Hint Question");     
    String[] gender={"[Select one]","Male","Female"};
         sex = new JComboBox(gender);          
    String[] edu={"[Select one]","S.S.C","Inter","Graduate","Post Graduate"};
         education= new JComboBox(edu);     
    String[] ageg={"[Select one]","0 - 15","16 - 35","36 - 70","70 - 100"};
         agegr= new JComboBox(ageg);     
    adrt=new JTextField(15);
         adrt.setToolTipText("Address");
         adrt1=new JTextField(15);
         adrt1.setToolTipText("Address");
         city=new JTextField(15);
         city.setToolTipText("City");
    zipcode=new JTextField(15);
         zipcode.setToolTipText("ZipCode");
         p1.setBounds(200,70,160,30);
         uid.setBounds(350,100,160,30);
         uname.setBounds(400,100,160,30);
         upass.setBounds(335,140,160,30);
         upassw.setBounds(400,140,160,30);
         cpass.setBounds(260,180,160,30);
         cpassw.setBounds(400,180,160,30);
         p2.setBounds(200,220,160,30);
         fname.setBounds(330,260,160,30);
         fnamet.setBounds(400,260,160,30);
         sname.setBounds(335,300,160,30);
         snamet.setBounds(400,300,160,30);
    hint.setBounds(315,340,160,30);     
    hintt.setBounds(400,340,160,30);
         sl.setBounds(370,380,160,30);     
         sex.setBounds(400,380,160,30);
         ed.setBounds(335,420,160,30);     
         education.setBounds(400,420,160,30);
    age.setBounds(330,460,160,30);
    agegr.setBounds(400,460,160,30);
    p3.setBounds(200,500,160,30);
         adr.setBounds(340,540,160,30);
         adrt.setBounds(400,540,160,30);
         adrt1.setBounds(400,580,160,30);
         cit.setBounds(370,620,160,30);
         city.setBounds(400,620,160,30);
    zip.setBounds(590,620,160,30);
    zipcode.setBounds(640,620,160,30);
         Font font = new Font("SansSerif",Font.BOLD, 12);
         setFont(font);
         c.add(p1);
    c.add(uid);
         c.add(uname);     
         c.add(upass);
         c.add(upassw);
    c.add(cpass);
         c.add(cpassw);
    c.add(p2);
    c.add(fname);     
         c.add(fnamet);
    c.add(sname);
    c.add(snamet);
         c.add(hint);
    c.add(hintt);     
    c.add(sl);
    c.add(sex);
    c.add(ed);
         c.add(education);
    c.add(age);
         c.add(agegr);
    c.add(p3);
    c.add(adr);
         c.add(adrt);
         c.add(adrt1);
    c.add(cit);
    c.add(city);
    c.add(zip);
    c.add(zipcode);
         setResizable(false);
         //int a=DO_NOTHING_ON_CLOSE;
         //setDefaultCloseOperation(a);
         show();
         setSize(800,500);
    // Border raisedBorder = new BevelBorder(BevelBorder.RAISED);     
         setContentPane(c);     
    public static void main (String arg[])
         try{
         UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
         }catch(Exception s)
         Signup swu=new Signup();

    just try the following:
    jsp.getVerticalScrollbar().setValue(0);after inserting and adding all your components. this will set the vertical scrollbar up to the very first line.
    regards

  • How do I create an infinite drawing canvas in a ScrollPane?

    I wanted to figure this out on my own, but it is time to ask for help. I've tried too many different things. The closest I've come to the behaviour I want is with this code:
    final BorderPane root = new BorderPane();
    final Pane canvasWrapper = new Pane();
    canvasWrapper.setPrefSize(800, 500);
    canvasWrapper.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
    canvasWrapper.setStyle("-fx-background-color: lightgray; -fx-border-color: green; -fx-border-width: 2px;");
    final Group canvas = new Group();
    canvasWrapper.getChildren().add(canvas);
    final ScrollPane scroll = new ScrollPane();
    scroll.setContent(canvasWrapper);
    root.setCenter(scroll);
    // event code for adding circles and lines to the canvas
    I want the ScrollPane to be filled with the Pane, so it can catch events for drawing. When the stage is resized, the ScrollPane is resized too. This the result of the BorderPane. What I want is to expand the window and have canvasWrapper expand to fill the entire ScrollPane viewport. When the stage is made smaller the ScrollPane shrinks, but I want the canvasWrapper to retain its size. The idea is the drawing canvas can only grow. When it gets too large for the current stage/ScrollPane size, the scrollpane can be used to navigate around the canvas.
    I tried using
    scroll.setFitToHeight(true);
    scroll.setFitToWidth(true);
    but this causes the Pane to be made smaller when the viewport is made smaller.

    I figured it out!
    Use
    scroll.setFitToHeight(true);
    scroll.setFitToWidth(true);
    to resize the Pane as the view port changes.
    Save the canvas' size as the Pane's size.
    canvas.layoutBoundsProperty().addListener(new ChangeListener<Bounds>() {
                @Override
                public void changed(ObservableValue<? extends Bounds> ov, Bounds t, Bounds t1) {
                    canvasWrapper.setMinSize(t1.getMaxX(), t1.getMaxY());
    This forces the Pane to always be as large as the group is.
    Missed a piece of code - jrguenther

  • How to print the components in scrollpane

    hi there,
    can anyone tell me how to print the scrollpane components, i mean the headers & the main view of the component. i've a scrollpane with the following code and i want to print the components:
    JScrollPane pane = new JScrollPane(aTextPane);
    pane.setRowHeaderView(aLineNumberComponent);my requirement is i've a editor & lineno component as textpanes and added to scrollpane & when asked to print it should print the lineno component which resides in scrollpane's row header & the editor textpane which is the main view in the scrollpane. how can i achieve this?
    i'd would appreciate any suggestions & codes given.
    thanx in advance.

    After adding/removing components to/from a panel try:
    panel.revalidate();
    panel.repaint() // sometimes this is also needed, I'm
    not sure whyI'm not certain, but I think that panel.revalidate() implicitly calls repaint() only if something actually changed in the layout. If nothing changed, it sees no reason to repaint; hence, if something changed in appearance but not in layout, you have to repaint it yourself.
    Or something like that. I'm no expert. ;)

  • Is it possible to load .swfs on top of scrollpane

    I have a scrollpane that links to a movie clip in my library
    that holds about 40 buttons. I'm using the scrollpane since the
    layout doesn't have enough room to show them all at once. This way
    the user can scroll down to see all the names. These buttons have
    the names of various articles on them. Upon clicking on an article
    a flashpaper .swf file of that article is loaded. Right now the
    article is loading into my scrollpane and seems to be kicking out
    the movie clip that contains the buttons. Upon closing out the
    flashpaper article the buttons return and work fine. The only issue
    I have with this is that if the user scrolls down, clicks on an
    article and then closes it out, the buttons reappear, but they are
    back at the top. The user would then need to scroll back down to
    where they were if there were wanting to click on the next article
    in line. Not a big deal, but it gets kina annoying after a while.
    I'd like to figure out a way for the flashpaper articles to load on
    top of the scroll pane so that when the user closes the flashpaper
    article the links below are where they left off. So far no matter
    what I try the flashpapers keep loading inside the scroll pane.
    Here is the code I'm using as applied to one of the 40 buttons:
    on (release) {
    _parent.loadMovie("MM/flashpaper/art2_120106_prev_injuries_unint.swf",
    1);
    art2_120106_prev_injuries_unint.swf is the name of the
    flashpaper article being loaded.
    -I've tried changing the level number and that doesn't work
    -I've tried creating an empty movie clip in a layer above the
    buttons and that doesn't work:
    on (release) {
    _parent.loadMovie("MM/flashpaper/art2_120106_prev_injuries_unint.swf",
    "artMC");
    ("artMC" is the empty movie clip)
    -I've tride creating an empty movie clip in the main timeline
    above the scrollpane and that doesn't work either
    any thoughts on how I should handle this?
    thanks

    import mx.managers.DepthManager;
    movieclipyouwantontop.setDepthAbove(movieclipyouwantonbottom);
    use the creatEmptyMovieClip method you tried before then
    place it into what i gave

  • Problem adding a table to scrollpane

    Hi:
    I have created a JTable that I want to be in a scrollpane. When I tried to add this JTable to a scrollpane I get a null pointer error at execution time. But when I add this table directly to the frame I get no error at execution time.
    Here is my code:
    import java.awt.*;
    import java.awt.event .*;
    import javax.swing.*;
    import java.util.*;
    import javax.swing.event.*;
    import java.io.*;
    import javax.swing.table.*;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import java.net.*;
    import java.util.regex.*;
    // METHODS
    // =======
    // private String returnSelectedString( int col ))
    public class DialogFrame extends JFrame
    {     //===================
    //MEMBER VARIABLES
    //===================
    public JLabel topClassifiedLabel, bottomClassifiedLabel,printerCountLabel,defaultPrinterLabel ;
    public JPanel panelForLabel,topClassificationPanel , bottomClassificationPanel, SecBotPanel, ClassificationPanel,Classification_botPanel,firstTopPanel, titlePanel,titlePanel2,displayPanel,labelPanel,buttonPanel;
    public DefaultListModel listModel;
    public final String screenTitle = "Printer Configuration "
    + " CSS - 105";
    public JLabel localDisplay = new JLabel("Local: Printer directly connected to this computer");
    public JLabel remoteDisplay = new JLabel("Remote: Printer connected to another computer");
    public JLabel networkDisplay = new JLabel("Network: Printer connected to the LAN");
    public char hotKeys[] = { 'A', 'D', 'Q','T','R','I','Q','H' };
    public JPanel ConnectTypePanel = null, printCountPanel;
    public JScrollPane tabScrollPane;
    public JLabel l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,l11,l12,TitleLabel;
    public JButton addPrinterButton,setDefaultButton,restartPrintSystemButton, deletePrinterButton, displayQueueButton,
    ToggleBannerButton, RestartPrintSystemButton, InstallOpenPrintButton, QuitButton, continueButton,CancelButton,HelpButton;
    public Vector columnNames;
    public String line2 = "";
    public addPrinterDialog aPDialog;
    public printQueueDialog dQDialog;
    public String nextElement,name,Type,Interface,Description,Status,Queue,BannerPage;
    public JRadioButton networkButton, localButton, remoteButton;
    public JLabel nameLabel, descriptionLabel, modelLabel,ClassificationLabel,ClassificationLabel_bot,setL,defaultL;
    public JTextField nameTextField, descriptionTextField, modelTextField;
    private int printerCount = 0;
    static DefaultTableModel model;
    public JTable table;
    //=======================//
    //**Constructor
    //=========================//
    public DialogFrame()
    createTable();
    public void createTable()
    defaultPrinterLabel = new JLabel();
    printerCountLabel = new JLabel();
    //COLUMN FOR TABLE
    columnNames = new Vector();
    columnNames.add("Name");
    columnNames.add("Type");
    columnNames.add("Interface");
    columnNames.add("Description");
    columnNames.add("Status");
    columnNames.add("Queue");
    columnNames.add("BannerPage");
    Vector tableRow = new Vector();
    //tableRow = executeScript("perl garb.pl");
    // tableRow = executeScript("perl c:\\textx.pl");
    model = new DefaultTableModel( tableRow, columnNames ){
    public boolean isCellEditable(int row,int col) {
    return false;
    public Dimension getPreferredScrollableViewportSize() {
    return getPreferredSize();
    table = new JTable(model);
    JTableHeader header = table.getTableHeader();
    TableColumnModel colmod = table.getColumnModel();
    for (int i=0; i < table.getColumnCount(); i++)
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setHorizontalAlignment(SwingConstants.CENTER);
    colmod.getColumn(i).setCellRenderer(renderer);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setShowGrid( false );
    table.getTableHeader().setReorderingAllowed( false );
    table.setIntercellSpacing(new Dimension(0,0) );
    table.addMouseListener( new MouseAdapter () {
    public void mouseClicked( MouseEvent e) {
    if ((e.getModifiers() & InputEvent.BUTTON1_MASK) !=0)
    printSelectCell(table);
    this.setSize(900,900);
    //========================================//
    // Technique for centering a frame on the screen
    //===========================================//
    Dimension frameSize = this.getSize();
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    this.setLocation((screenSize.width - frameSize.width)/2,
    (screenSize.height - frameSize.height)/2);
    setResizable(false);
    // CREATE A FEW PANELS
    firstTopPanel = new JPanel();
    BoxLayout box = new BoxLayout(firstTopPanel, BoxLayout.Y_AXIS);
    firstTopPanel.setLayout(box);
    topClassificationPanel = new JPanel();
    topClassificationPanel.setBackground(new Color(45,145,71));
    bottomClassificationPanel = new JPanel();
    bottomClassificationPanel.setBackground(new Color(45,145,71));
    SecBotPanel = new JPanel();
    SecBotPanel.setLayout(new BorderLayout());
    buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridLayout(1,8));
    buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 0));
    buttonPanel.setBackground(new Color(170,187,119));
    panelForLabel = new JPanel();
    // panelForLabel.setBackground( Color.white );
    //Border etchedBorder = BorderFactory.createEtchedBorder();
    printerCountLabel.setHorizontalAlignment(SwingConstants.LEFT);
    printerCountLabel.setPreferredSize(new Dimension(700, 20));
    //printerCountLabel.setBorder(etchedBorder);
    printerCountLabel.setForeground(Color.black);
    defaultPrinterLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    defaultPrinterLabel.setText("Default Printer: " + name);
    defaultPrinterLabel.setForeground(Color.black);
    panelForLabel.add(printerCountLabel);
    panelForLabel.add(defaultPrinterLabel);
    titlePanel = new JPanel( );
    titlePanel.setBackground( Color.white );
    ConnectTypePanel = new JPanel();
    ConnectTypePanel.setBackground(new Color(219,223,224));
    ConnectTypePanel.setLayout( new GridLayout(3,1) );
    //CREATE A FEW LABELS
    topClassifiedLabel = new JLabel("UNCLASSIFIED", SwingConstants.CENTER );
    topClassifiedLabel.setForeground(Color.white);
    bottomClassifiedLabel = new JLabel("UNCLASSIFIED", SwingConstants.CENTER );
    bottomClassifiedLabel.setForeground(Color.white);
    TitleLabel = new JLabel( screenTitle, SwingConstants.CENTER );
    //ADD LABELS TO PANELS
    topClassificationPanel.add( topClassifiedLabel );
    bottomClassificationPanel.add( bottomClassifiedLabel );
    titlePanel.add( TitleLabel, BorderLayout.CENTER );
    ConnectTypePanel.add(localDisplay );
    ConnectTypePanel.add(remoteDisplay );
    ConnectTypePanel.add(networkDisplay );
    //Create the scrollpane and add the table to it.
    tabScrollPane = new JScrollPane(table);
    JPanel ps = new JPanel();
    ps.add(tabScrollPane);
    getContentPane().setLayout(
    new BoxLayout( getContentPane(), BoxLayout.Y_AXIS ) );
    getContentPane().add(firstTopPanel);
    getContentPane().add(panelForLabel);
    getContentPane().add(header);
    getContentPane().add(ps);//contain table
    getContentPane().add(SecBotPanel);
    WindowListener w = new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    DialogFrame.this.dispose();
    System.exit(0);
    this.addWindowListener(w);
    //==================================//
    // AddPrinterButton
    //==================================//
    addPrinterButton = new JButton();
    addPrinterButton.setLayout(new GridLayout(2, 1));
    l1 = new JLabel("Add", JLabel.CENTER);
    l1.setForeground(Color.black);
    l2 = new JLabel("Printer", JLabel.CENTER);
    l2.setForeground(Color.black);
    addPrinterButton.add(l1);
    addPrinterButton.add(l2);
    addPrinterButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    //(aPDialog == null) // first time
    aPDialog = new addPrinterDialog(DialogFrame.this);
    aPDialog.setLocationRelativeTo(null);
    aPDialog.pack();
    aPDialog.show(); // pop up dialog
    //======================================
    // DeletePrinterButton
    //=====================================
    deletePrinterButton = new JButton();
    deletePrinterButton.setLayout(new GridLayout(2, 1));
    l1 = new JLabel("Delete", JLabel.CENTER);
    l1.setForeground(Color.black);
    l2 = new JLabel("Printer", JLabel.CENTER);
    l2.setForeground(Color.black);
    deletePrinterButton.add(l1);
    deletePrinterButton.add(l2);
    deletePrinterButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    int sr = table.getSelectedRow();
    if (sr == -1)
    JOptionPane.showMessageDialog(null, "You have not selected a printer for this operation","NOSELECT",JOptionPane.INFORMATION_MESSAGE);
    else
    name = returnSelectedString(0);
    int ans = JOptionPane.showConfirmDialog(null,"Are you sure you want to delete printer " + name + "?","Delete",JOptionPane.YES_NO_OPTION);
    switch(ans) {
    case JOptionPane.NO_OPTION:
    return;
    case JOptionPane.YES_OPTION:
    // String machineName = returnSelectedString(0);
    int rowNumber = table.getSelectedRow();
    model.removeRow(rowNumber);
    //TiCutil.exe("/usr/lib/lpadmin -x " + machineName);
    decreasePrinterCount();
    JOptionPane.showMessageDialog(null, "Printer " + name + " have been successfully deleted","SUCCEED",JOptionPane.INFORMATION_MESSAGE);
    return;
    //==============================//
    //DisplayQueuePrinter //
    //================================//
    displayQueueButton = new JButton();
    displayQueueButton.setLayout(new GridLayout(2, 1));
    l5 = new JLabel("Display", JLabel.CENTER);
    l5.setForeground(Color.black);
    l6 = new JLabel("Queue", JLabel.CENTER);
    l6.setForeground(Color.black);
    displayQueueButton.add(l5);
    displayQueueButton.add(l6);
    displayQueueButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    Vector tab = new Vector();
    int sr = table.getSelectedRow();
    if (sr == -1)
    JOptionPane.showMessageDialog(null, "You have not selected a printer for this" +
    "operation","NOSELECT",JOptionPane.INFORMATION_MESSAGE);
    else
    name = returnSelectedString(0);
    //PASS TABLE HERE
    /*tab = executeScript("lpstat -o " + name + " | sed \'s/ on$//\'");
    System.out.println("lpstat -o " + name + " | sed \'s/ on$//\'");
    dQDialog = new printQueueDialog(DialogFrame.this, name, tab);
    dQDialog.setLocationRelativeTo(null);
    dQDialog.pack();
    dQDialog.show(); // pop up dialog */
    //===================================
    // SetDefaultButton
    //================================//
    setDefaultButton = new JButton();
    setDefaultButton.setLayout(new GridLayout(2, 1));
    setL = new JLabel("Set", JLabel.CENTER);
    setL.setForeground(Color.black);
    defaultL = new JLabel("Default", JLabel.CENTER);
    defaultL.setForeground(Color.black);
    setDefaultButton.add(setL);
    setDefaultButton.add(defaultL);
    setDefaultButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    int sr = table.getSelectedRow();
    if (sr == -1)
    JOptionPane.showMessageDialog(null, "You have not selected a printer for this operation","NOSELECT",JOptionPane.INFORMATION_MESSAGE);
    else
    name = returnSelectedString(0);
    JOptionPane.showMessageDialog(null, "printer " + name + " is now the default.","Succeed",JOptionPane.INFORMATION_MESSAGE);
    defaultPrinterLabel.setText("Default Printer: " + name);
    //==============================//
    // ToggleBannerButton
    //==============================//
    ToggleBannerButton = new JButton();
    ToggleBannerButton.setLayout(new GridLayout(2, 1));
    l7 = new JLabel("Toggle", JLabel.CENTER);
    l7.setForeground(Color.black);
    l8 = new JLabel("Banner", JLabel.CENTER);
    l8.setForeground(Color.black);
    ToggleBannerButton.add(l7);
    ToggleBannerButton.add(l8);
    ToggleBannerButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    int sr = table.getSelectedRow();
    System.out.println("sr :" + sr);
    if (sr == -1)
    JOptionPane.showMessageDialog(null, "You have not selected a printer for this operation","NOSELECT",JOptionPane.INFORMATION_MESSAGE);
    else
    String banner = returnSelectedString(6);
    name = returnSelectedString(0);
    String machineName = returnSelectedString(0);
    Type = returnSelectedString(1);
    if ( !(Type.equals("Remote")) )
    if( banner.equals("Yes") )
    JOptionPane.showMessageDialog(null,"Banner page will NOT be printed for printer "+ name ,"Succeed",JOptionPane.INFORMATION_MESSAGE);
    //TiCutil.exe("sed -e 's/^BANNER=\"yes\"/BANNER=\"\"/' /etc/lp/interfaces/" + machineName + " > /tmp/delete.txt" );
    //TiCutil.exe("mv /tmp/delete.txt /etc/lp/interfaces/" + machineName);
    table.setValueAt("No",sr,6);
    DefaultTableModel model = (DefaultTableModel)table.getModel();
    model.fireTableCellUpdated(sr,6);
    table.requestFocus();
    else
    JOptionPane.showMessageDialog(null,"Banner page WILL be printed for printer "+ name ,"Succeed",JOptionPane.INFORMATION_MESSAGE);
    //TiCutil.exe("sed -e 's/^BANNER=\"\"/BANNER=\"yes\"/' /etc/lp/interfaces/" + machineName + " > /tmp/delete.txt");
    //TiCutil.exe("mv /tmp/delete.txt /etc/lp/interfaces/" + machineName);
    table.setValueAt("Yes",sr,6);
    DefaultTableModel model = (DefaultTableModel)table.getModel();
    model.fireTableCellUpdated(sr,6);
    table.requestFocus();
    else
    JOptionPane.showMessageDialog(null,"Operation failed system respond \n" + "was:\n" + "cannot toggle the banner page for a\n" + "REMOTE printer." ,"OPFAIL",JOptionPane.INFORMATION_MESSAGE);
    //==================================//
    // RestartPrintSystemButton
    //==================================//
    restartPrintSystemButton = new JButton();
    restartPrintSystemButton.setLayout(new GridLayout(2, 1));
    l3 = new JLabel("Restart Print", JLabel.CENTER);
    l3.setForeground(Color.black);
    l4 = new JLabel("System", JLabel.CENTER);
    l4.setForeground(Color.black);
    restartPrintSystemButton.add(l3);
    restartPrintSystemButton.add(l4);
    restartPrintSystemButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    //==============================
    // InstallOpenPrint
    //================================
    InstallOpenPrintButton = new JButton();
    InstallOpenPrintButton.setLayout(new GridLayout(2, 1));
    l11 = new JLabel("Install Open", JLabel.CENTER);
    l11.setForeground(Color.black);
    l12 = new JLabel("Print", JLabel.CENTER);
    l12.setForeground(Color.black);
    InstallOpenPrintButton.add(l11);
    InstallOpenPrintButton.add(l12);
    InstallOpenPrintButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    int ans = JOptionPane.showConfirmDialog(null,"Are you sure you want to install OPENPrint?","Delete",JOptionPane.YES_NO_OPTION);
    switch(ans) {
    case JOptionPane.NO_OPTION:
    return;
    case JOptionPane.YES_OPTION:
    int cd,opinstall,banner_var,pwd;
    opinstall = runIt("open_print.ksh");
    banner_var = runIt("banner_var.ksh");
    System.out.println("opinstall: " + opinstall );
    System.out.println("banner_var: " + banner_var);
    if ( opinstall == 0 && banner_var == 0)
    JOptionPane.showMessageDialog(null, "OPENprint successfully added"
    ,"SUCCEED",JOptionPane.INFORMATION_MESSAGE);
    return;
    //==========================
    //QuitButton
    //============================
    QuitButton = new JButton("Quit");
    QuitButton.addActionListener (new ActionListener ()
    { public void actionPerformed (ActionEvent e){
    System.exit (0); }
    HelpButton = new JButton("Help");
    //ADD BUTTONS TO PANEL
    buttonPanel.add( addPrinterButton );
    buttonPanel.add( deletePrinterButton );
    buttonPanel.add( displayQueueButton );
    buttonPanel.add( setDefaultButton);
    buttonPanel.add( ToggleBannerButton );
    buttonPanel.add( restartPrintSystemButton );
    buttonPanel.add( InstallOpenPrintButton );
    buttonPanel.add( QuitButton );
    //buttonPanel.add( HelpButton );
    //END OF BUTTONS CREATION
    //ADD PANEL ON TO PANEL
    SecBotPanel.add(ConnectTypePanel, BorderLayout.CENTER);
    SecBotPanel.add(bottomClassificationPanel, BorderLayout.SOUTH);
    firstTopPanel.add(topClassificationPanel);
    firstTopPanel.add(titlePanel);
    firstTopPanel.add(buttonPanel);
    //===========================================================
    // METHODS
    //==========================================================
    public int runIt(String targetCode)
    int result = -1;
    try{
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec( targetCode );
    // Thread.sleep(20000);
    p.waitFor();
    result = p.exitValue();
    catch( IOException ioe )
    ioe.printStackTrace();
    catch( InterruptedException ie )
    ie.printStackTrace();
    return result;
    //====================================================
    public void increasePrinterCount()
    printerCount++;
    printerCountLabel.setText("Printer: " + printerCount);
    //===========================================================
    public void decreasePrinterCount()
    printerCount--;
    printerCountLabel.setText("Printer: " + printerCount);
    private String returnSelectedString( int col )
    int row = table.getSelectedRow();
    String word;
    //javax.swing.table.TableModel model = table.getModel();
    word =(String)model.getValueAt(row, col);
    return word; //return string
    //==============================================================================
    private Vector executeScript(String str)
    Vector tableOfVectors = new Vector();
    try{          
    String line;
    Process ls_proc = Runtime.getRuntime().exec(str);
    //get its output (your input) stream
    BufferedReader in = new BufferedReader( new InputStreamReader( ls_proc.getInputStream() ));
    //readLine reads in one line of text
    int k = 1, i = 0;
    //LOOK FOR THE "|"
    Pattern p = Pattern.compile(" ");
    while (( line = in.readLine()) != null)
    Vector data = new Vector();
    Matcher m = p.matcher(line);
    if(m.find() == true)//find " "
    line = line.replaceAll(" {2,}?", "|");
    //creates a new vector for each new line read in
    StringTokenizer t = new StringTokenizer(line,"|");
    while ( t.hasMoreTokens() )
    try
    nextElement = t.nextToken().trim();
    //add a string to a vector
    data.add(nextElement.trim());
    catch(java.util.NoSuchElementException nsx)
    System.out.println(nsx);
    tableOfVectors.add(data);
    //COUNT THE NUMBER OF PRINTER
    printerCount = k;
    printerCountLabel.setText("Printer: " + printerCount);
    k++;
    }//END OF WHILE
    in.close();
    }//END OF TRY
    catch (IOException e1) {
    System.err.println(e1);
    System.exit(1);
    return tableOfVectors;
    //==========================================================================================================
    private String getDefaultPrinter(String str)
    String groupStr = null;
    try{          
    String lin;
    Process ls_proc = Runtime.getRuntime().exec(str);
    BufferedReader in = new BufferedReader( new InputStreamReader( ls_proc.getInputStream() ));
    Pattern p2 = Pattern.compile("system default destination: (\\S+)");
    while (( lin = in.readLine()) != null)
    Matcher m2 = p2.matcher(lin);
    m2.reset(lin);
    if (m2.find() == true )
    groupStr = m2.group(1);
    in.close();
    catch (IOException e1) {
    System.err.println(e1);
    System.exit(1);
    return groupStr;
    //================================================================================
    public synchronized void clearTable()
    int numrows = model.getRowCount();
    for ( int i = numrows -1 ; i >= 0 ; i--)
    model.removeRow(i);
    //=======================================================================================================
    private void printSelectCell(JTable table )
    int numCols = table.getColumnCount();
    int row = table.getSelectedRow();
    System.out.println(row);
    javax.swing.table.TableModel model = table.getModel();
    for(int j=0;j < numCols; j++)
    System.out.println(" " + model.getValueAt(row,j));
    System.out.println();
    System.out.println("-----------------------------------------------");
    //CREATE ADD PRINTER DIALOG
    class addPrinterDialog extends JDialog
    public addPrinterDialog(JFrame owner)
    super(owner, "ap1", true);
    final ButtonGroup rbg = new ButtonGroup();
    JPane

    Ok  I have the table  on the page  I created a css with a background image called .search  How to I link that to the table so It shows the image
    I am only used to doing certain css items   Never didi this before
    THXS STeve

Maybe you are looking for

  • LR and IPTC fields

    I have been running a photoblog at Digital-Photo for over 3 years now. I have noticed that ever since I have started to use Lightroom it gave me an added value of populating IPTC fields in Gallery 2 (web gallery I use). The IPTC seems to be very broa

  • Facing a Runtime Error u201C GETWA_NOT_ASSIGNED u201C in report at background

    Hi All, I am facing a Runtime Error u201C GETWA_NOT_ASSIGNED u201C when a custom report is executed in the background, whereas the same report in getting executed properly in foreground. The reason, which, the Dump Analysis specifies is u201C Field s

  • Large / Long recording problem

    I use a my iPod and a iTalk to record some rather lengthy seminars, between five and twelve hours. The problem is when I try and listen to these recordings on my iPod later on. It will work for a bit, but if I stop listening (turning the iPod off) an

  • Home sharing with macbook pro (10.6.1) and Power pc G5 (10,5,8)

    I just installed the new iTunes 9 with home sharing on both copputers. I've activate the home sharing on both too, and then : I can see the sharing and the library of the macbook pro on the G5 But I cannot see the sharing and the library of the G5 on

  • Use the for-each to group the element across in output

    I have the report in XMLP for which we need to design the template to generate the output in excel. we need to group the element across the report. by default the for-each group the element top-down, is there any option to group the elements across.