Adding a JPanel to a JScrollPane?

I have a JPanel which may hold a lot of components, this may run off the end of the window so I want to add the components to a JPanel and the JPanel to a JScrollPane to deal with this can anyone tell me why the below code won't do this?
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
public class Test extends JScrollPane
     public JFrame testFrame;
     public JPanel testPanel;
     public JCheckBox checkBox;
     public static void main(String[] args)
          new Test();
     public Test()
          testFrame = new JFrame("test");
          //testFrame.getContentPane().setLayout(null);
          testPanel = new JPanel();          
          JScrollPane sp = new JScrollPane(testPanel);
          //add the panel to the scroll pane
          //sp.setViewportView(testPanel);
          //sp.getVerticalScrollBar();
          this.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
          this.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
          testFrame.getContentPane().add(sp);
          //add the scroll pane to the frame
         JLabel lbl1 = new JLabel("blah");
         testPanel.add(lbl1);
        testFrame.getContentPane().add(testPanel);
         for(int i=0; i==20; i++)
               checkBox = new JCheckBox(String.valueOf(i));
              //checkBox.addItemListener(this);
              JTextField txt1 = new JTextField(10);
              txt1.setText("hello world");
             testPanel.add(checkBox);
            testPanel.add(txt1);
        testPanel.validate();
        testPanel.setVisible(true);
        testFrame.pack();
        testFrame.setVisible(true);
        testFrame.setSize(100, 200);
        testFrame.show();
}

Actually not extending JScrollPane means that
this.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
this.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
raised compile errors so you've clearly not bothered to run it.
Anyway, I figured out the solution, for anyone who may find it useful here it is:
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
public class Test
     public JFrame testFrame;
     public JPanel testPanel;
     public JCheckBox checkBox;
     public JButton btnDone;
     public static void main(String[] args)
          new Test();
     public Test()
          testFrame = new JFrame("test");
          testPanel = new JPanel();
          testPanel.setLayout(new GridBagLayout());
          JScrollPane sp = new JScrollPane();
          GridBagConstraints gridBagConstraints = new GridBagConstraints();
         JLabel lbl1 = new JLabel("blah");
         testPanel.add(lbl1);
         for(int i=0; i<20; i++)
               checkBox = new JCheckBox(String.valueOf(i));
              //checkBox.addItemListener(this);
              JTextField txt1 = new JTextField(10);
              txt1.setText("hello world");
             gridBagConstraints.gridx = 0;
             gridBagConstraints.gridy = i+1;
             testPanel.add(checkBox, gridBagConstraints);
             gridBagConstraints.gridx = 1;
             gridBagConstraints.gridy = i+1;
             testPanel.add(txt1, gridBagConstraints);
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = gridBagConstraints.gridy+1;
        testPanel.add(btnDone = new JButton("Done"), gridBagConstraints);
          sp.setViewportView(testPanel);
         testFrame.getContentPane().add(sp);
         //btnDone.addActionListener(this);
        testPanel.validate();
        testFrame.pack();
        testFrame.setVisible(true);
        testFrame.setSize(200, 300);
        testFrame.show();
}

Similar Messages

  • How can i  add more than 500 jPanels in a jScrollPane

    Hello to all ,
    I am facing a problem related to adding jPanels in jScrollPane. My application needs more than 500 jpanels in the jscrollpane.where in each jPanel 4 jtextboxes, 1 comboboxes, 1 check box is there.when the check box will be clicked then the total row( ie row means the panel containing the 4 jtextboxes, 1 comboboxes, 1 check box ).and when the user will click on move up or move down button then the selected jpanel will move up or down.
    The tool(sun java studio enterprise 8.1) is not allowing more Jpanels to add manually. so i have to add the jpanels by writing the code in to a loop. and the problem is that when i am trying to add the code in the code generated by the tool the code written out side the code by me is not integratable into the tool generated code.
    If u watch the code here am sending u ll get what am facing the problem. The idea of creating jpanels through loop is ok but when trying to impleent in tool facing difficulties.
    A example code am sending here. please tell me how i can add more panels to the scrollpane(it is the tool generated code)
    Thanks in advance , plz help me for the above
    package looptest;
    public class loopframe extends javax.swing.JFrame {
    /** Creates new form loopframe */
    public loopframe() {
    initComponents();
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    jPanel1 = new javax.swing.JPanel();
    jPanel2 = new javax.swing.JPanel();
    jTextField1 = new javax.swing.JTextField();
    jComboBox1 = new javax.swing.JComboBox();
    jPanel3 = new javax.swing.JPanel();
    jTextField2 = new javax.swing.JTextField();
    jComboBox2 = new javax.swing.JComboBox();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextField1.setText("jTextField1");
    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
    org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
    jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel2Layout.createSequentialGroup()
    .add(28, 28, 28)
    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 109, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(54, 54, 54)
    .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 156, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(35, Short.MAX_VALUE))
    jPanel2Layout.setVerticalGroup(
    jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel2Layout.createSequentialGroup()
    .addContainerGap()
    .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    .addContainerGap(21, Short.MAX_VALUE))
    jTextField2.setText("jTextField2");
    jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
    org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
    jPanel3.setLayout(jPanel3Layout);
    jPanel3Layout.setHorizontalGroup(
    jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel3Layout.createSequentialGroup()
    .add(20, 20, 20)
    .add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 111, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(33, 33, 33)
    .add(jComboBox2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 168, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(40, Short.MAX_VALUE))
    jPanel3Layout.setVerticalGroup(
    jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel3Layout.createSequentialGroup()
    .add(21, 21, 21)
    .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    .add(jComboBox2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    .addContainerGap(21, Short.MAX_VALUE))
    org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
    jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    .addContainerGap(58, Short.MAX_VALUE))
    jPanel1Layout.setVerticalGroup(
    jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel1Layout.createSequentialGroup()
    .add(21, 21, 21)
    .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(49, 49, 49)
    .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(66, Short.MAX_VALUE))
    jScrollPane1.setViewportView(jPanel1);
    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()
    .add(31, 31, 31)
    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 439, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(74, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(layout.createSequentialGroup()
    .add(30, 30, 30)
    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 254, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(55, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new loopframe().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration
    and
    package looptest;
    public class Main {
    public Main() {
    public static void main(String[] args) {
    new loopframe().setVisible(true);
    }

    Thanks for here kind attention to solve my problem.
    I am thinking to create the classes separately for the components (i.e the jpanel, combobox,textbox etc)and call their instaces from the for loop .But the problem is the jpanel will contain the other components and that jpanels (unlimited jpanels will be added later)will be later added to the jscrollpane.
    By writing code, the problem is to place components( the comboboxes,textboxes etc placed on the jpanel ) in appropriate coordinates . So i am doing it through tool .
    I am sending here the sample code related to my actual need . In this i have taken a jScrollPane, on that i have added jPanel1 and on jPanel1 i have added jPanel2.On jPanel2 jTextField1, jComboBox1,jCheckBox are added. If the u ll see the code u can understand what problem i am facing.
    If i am still not clearly explained ,please ask me. plz help me if u can as u have already handled a problem similar to this.
    package addpanels;
    public class Main {
    /** Creates a new instance of Main */
        public Main() {
        public static void main(String[] args) {
            new addpanels().setVisible(true);
    } and
    package addpanels;
    public class addpanels extends javax.swing.JFrame {
        /** Creates new form addpanels */
        public addpanels() {
            initComponents();
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            jPanel1 = new javax.swing.JPanel();
            jPanel2 = new javax.swing.JPanel();
            jTextField1 = new javax.swing.JTextField();
            jComboBox1 = new javax.swing.JComboBox();
            jCheckBox1 = new javax.swing.JCheckBox();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jTextField1.setText("jTextField1");
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
            jCheckBox1.setText("jCheckBox1");
            jCheckBox1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
            jCheckBox1.setMargin(new java.awt.Insets(0, 0, 0, 0));
            org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 131, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 144, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jCheckBox1)
                    .addContainerGap(39, Short.MAX_VALUE))
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
                    .addContainerGap(17, Short.MAX_VALUE)
                    .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jCheckBox1))
                    .addContainerGap())
            org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(34, Short.MAX_VALUE))
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .add(26, 26, 26)
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(152, Short.MAX_VALUE))
            jScrollPane1.setViewportView(jPanel1);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(36, Short.MAX_VALUE)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 449, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(18, 18, 18))
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(32, 32, 32)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 230, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(38, Short.MAX_VALUE))
            pack();
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new addpanels().setVisible(true);
        // Variables declaration - do not modify//GEN-BEGIN:variables
        private javax.swing.JCheckBox jCheckBox1;
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration//GEN-END:variables
    }

  • Problem with JPanel in a JScrollPane

    Hi all,
    I am devloping an application where in i insert the JPanel's object in the JScrollPane object. Intitially the size of the JPanel's object is more than the size of the JScrollPane object.At this point fo time i can drag the nob of the scrollpane to the extent of the size of the JPanel's object. Now When i move the mouse behond the size of the JPanel i am increasing the size of the JPanel's object but i cant move the nob of the scrollpane object behond the original limit.
    For example : when you open a notepad there will be scrollbar without the nob if you keep on pressing the enter key the size of the text area increases and we can see the scroll bar now. I what the similar functionality but
    instead of TextArea i need the panel.
    If any of you have solved this problem or know the solution please do inform. I need to solve this problem very urgently. Please do help me out.
    Thanks in Advance.
    regards
    Ravi

    Hi all,
    I got the solution.we need to revalidate the panel object.
    i.e JPanel.revalidate()
    regards
    Ravi Kumar

  • Adding a JPanel from one class to another Class (which extends JFrame)

    Hi everyone,
    So hopefully I go about this right, and I can figure out what I'm doing wrong here. As an exercise, I'm trying to write a Tic-Tac-Toe (TTT) game. However, in the end it will be adaptable for different variations of TTT, so it's broken up some. I have a TTTGame.java, and TTTSquareFrame.java, and some others that aren't relavent.
    So, TTTGame:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import joshPack.jUtil.*;
    public class TTTGame extends JFrame
         private Integer sides = 3;
         private TTTSquareFrame mainSquare;
         private TTTGame newGame;
         private Container contents;
         private JPanel mainSquarePanel, addPanel;
         public static void main(String [] args)
              TTTGame newGame = new TTTGame();
              newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TTTGame()
              super("Tic-Tac-Toe");
              contents = getContentPane();
              contents.setLayout(new FlowLayout());
              addPanel = startSimple();
              if(!addPanel.isValid())
                   System.out.println("Something's wrong");
              contents.add(addPanel);
              setSize(300, 300);
              setVisible(true);
         public JPanel startSimple()
              mainSquare = new TTTSquareFrame(sides);
              mainSquarePanel = mainSquare.createPanel(sides);
              return mainSquarePanel;
    }and TTTSquareFrame:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import joshPack.jUtil.Misc;
    public class TTTSquareFrame
         private JPanel squarePanel;
         private JButton [] squares;
         private int square, index;
         public TTTSquareFrame()
              System.out.println("Use a constructor that passes an integer specifying the size of the square please.");
              System.exit(0);
         public TTTSquareFrame(int size)
         public JPanel createPanel(int size)
              square = (int)Math.pow(size, 2);
              squarePanel = new JPanel();
              squarePanel.setLayout(new GridLayout(3,3));
              squares = new JButton[square];
              System.out.println(MIN_SIZE.toString());
              for(int i = 0; i < square; i++)
                   squares[i] = new JButton();
                   squares.setRolloverEnabled(false);
                   squares[i].addActionListener(bh);
                   //squares[i].setMinimumSize(MIN_SIZE);
                   squares[i].setVisible(true);
                   squarePanel.add(squares[i]);
              squarePanel.setSize(100, 100);
              squarePanel.setVisible(true);
              return squarePanel;
    }I've successfully added panels to JFrame within the same class, and this is the first time I'm modularizing the code this way. The issue is that the frame comes up blank, and I get the message "Something's wrong" and it says the addPanel is invalid. Originally, the panel creation was in the constructor for TTTSquareFrame, and I just added the mainSquare (from TTTGame class) to the content pane, when that didn't work, I tried going about it this way. Not exactly sure why I wouldn't be able to add the panel from another class, any help is greatly appreciated.
    I did try and cut out code that wasn't needed, if it's still too much let me know and I can try and whittle it down more. Thanks.

    Yea, sorry 'bout that, I just cut out the parts of the files that weren't relevant but forgot to compile it just to make sure I hadn't left any remnants of what I had removed. For whatever it's worth, I have no idea what changed, but something did and it is working now. Thanks for your help, maybe next time I'll post an actual question that doesn't somehow magically solve itself.
    EDIT: Actually, sorry, I've got the panel working now, but it's tiny. I've set the minimum size, and I've set the size of the panel, so...why won't it respond to that? It almost looks like it's being compressed into the top of the panel, but I'm not sure why.
    I've compressed the code into:
    TTTGame.java:
    import java.awt.*;
    import javax.swing.*;
    public class TTTGame extends JFrame
         private Integer sides = 3;
         private TTTSquareFrame mainSquare;
         private TTTGame newGame;
         private Container contents;
         private JPanel mainSquarePanel, addPanel;
         public static void main(String [] args)
              TTTGame newGame = new TTTGame();
              newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TTTGame()
              super("Tic-Tac-Toe");
              contents = getContentPane();
              contents.setLayout(new FlowLayout());
              mainSquare = new TTTSquareFrame(sides.intValue());
              contents.add(mainSquare);
              setSize(400, 400);
              setVisible(true);
    }TTTSquareFrame.java
    import java.awt.*;
    import javax.swing.*;
    public class TTTSquareFrame extends JPanel
         private JButton [] squares;
         private int square, index;
         private final Dimension testSize = new Dimension(50, 50);
         public TTTSquareFrame(int size)
              super();
              square = (int)Math.pow(size, 2);
              super.setLayout(new GridLayout(size, size));
              squares = new JButton[square];
              for(int i = 0; i < square; i++)
                   squares[i] = new JButton();
                   squares.setMinimumSize(testSize);
                   squares[i].setVisible(true);
                   super.add(squares[i]);
              setSize(200, 200);
              setVisible(true);
    I've made sure the buttons are smaller than the size of the panel, and the panel is smaller than the frame, so...
    Message was edited by:
    macman104

  • One JPanel is missing after adding two JPanels to a JFrame

    I have two classes, ScoreTableView and CardView, which both extends the JPanel class. ScoreTableView is used to show one table only, and CardView is to show a set of cards for a memory game. My objective is to separate the development of the panels, so that it will easier to modify either of them later. I add instances of these two class to the contentPane of my top level JFrame object. However, I can only see the ScoreTableView(which is supposed to show me a table only) on the top part of the frame, and the CardView panel never show up.
    ScoreTableView.java
      public ScoreTableView(int numberOfPlayer){
    //      Create a model of the data.
            scoreTable = new JTable();//this scoreTable is a JTable object
            scoreTable.setModel(scoreTableData);  //scoreTableData is my data    
            JScrollPane jsp = new JScrollPane(scoreTable);          
            p = this;
            p.setLayout(new BorderLayout());
            p.add(jsp, BorderLayout.CENTER);
        }CardView.java
    public CardView(int w, int h){
            cardWidth = w;
            cardHeight = h;
            JPanel cardPanel = new JPanel();
            cardPanel.setLayout(new GridLayout(cardWidth,cardHeight)); 
            CardImageButton[][] cardsButtons = new CardImageButton[cardWidth][cardHeight];
          // ... more other none GUI coiding 
             }Here's what I have in my main
            Container contentPane = jf.getContentPane();//jf is the JFrame object          
            contentPane.setLayout(new BorderLayout()); 
    //      create the score panel                 
            ScoreTableView scoreTableView = new ScoreTableView(4);
          contentPane.add( scoreTableView, BorderLayout.NORTH);
            //create the cards panel
            CardView cardPanel = new CardView(4,4);
            contentPane.add(cardPanel, BorderLayout.CENTER);
            jf.pack();
            jf.setVisible(true);      

    Sorry, but I copied the wrong files. Now both panels can show up, but the score table is on the NORTH, and the card panel is on the SOUTH(although I set it to CENTER and wish it can occupy the rest of the window), but the center part of the window has nothing. How can I get rid of the white space, so that the score panel can can 30% of the top part of the window(even after resize), and the card panel can occupy the remaining 70%? I can't attach pictures here, otherwise I can upload some screenshot to show you what's the problem I have. Thank you in advance.
    This is my CardView class, I didnt' copy all of them upstair.
    public class CardView extends JPanel{
        private int cardWidth;
        private int cardHeight;
        private CardModel cm;
        private JPanel cardPanel;
        public CardView(int w, int h){
            cardWidth = w;
            cardHeight = h;
            cardPanel = this;
            cardPanel.setLayout(new GridLayout(cardWidth,cardHeight)); 
            CardImageButton[][] cardsButtons = new CardImageButton[cardWidth][cardHeight];
            int[][] list  = init(cardWidth, cardHeight);       
            cm = new CardModel(list);
            int count = 0;
            for(int i=0;i<cardWidth;i++){
                for(int j=0;j<cardWidth;j++){
                    cardsButtons[i][j] = new CardImageButton("Press me"+count, cm, i, j, 0);
                    cardPanel.add(cardsButtons[i][j]);
                    count++;               
    public int[][] init(int n, int m){
            int[][] list  = {
                    {1, 2, 1, 1},
                    {2, 1, 2 , 2},
                    {1, 2, 1, 1},
                    {2, 1, 2 , 2} };
            return list;
        }This is from my main.
           //setup the content panel
            Container contentPane = jf.getContentPane();          
            contentPane.setLayout(new BorderLayout()); 
    //      create the score panel                 
            ScoreTableView scoreTableView = new ScoreTableView(4);
          contentPane.add( scoreTableView, BorderLayout.NORTH);
            //create the cards panel
            CardView cardPanel = new CardView(4,4);
            contentPane.add(cardPanel, BorderLayout.CENTER);
            jf.pack();
            jf.setVisible(true);   ScoreTableView.java
      public ScoreTableView(int numberOfPlayer){
    //      Create a model of the data.
    scoreTable = new JTable();//this scoreTable is a JTable object       
    scoreTable.setModel(scoreTableData);  //scoreTableData is my data            
    JScrollPane jsp = new JScrollPane(scoreTable);                  
    p = this;       
    p.setLayout(new BorderLayout());       
    p.add(jsp, BorderLayout.CENTER);   
    }

  • How to define the position of a JPanel in a JScrollPane?

    I have put a panel into scrollpane. The panel is used to draw some graphs, if the panel enlarge the scrollbar will dispaly. it works well. I use jScrollPane.getViewport().add(jPanelDraw, null) to add panel into the scrollpane. I found the panel is always in the top left coner of the scrollpane, how could i do if i want put the panel in the center of the scrollpane?

    Try something like this:
    BorderLayout bl = new BorderLayout();
    JPanel parent = new JPanel();
    JScrollPane scrollPane = new JScrollPane();
    Then set the layout:
    scrollPane.setLayout(bl); // Our BorderLayout
    To add a component in the center:
    scrollPane.getViewport().add(myJComponent, BorderLayout.Center);
    Then add the scoller to the parent
    parent.add(scrollPane);
    Of course you should also specify a layout for the parent, too...

  • Adding a JList to a JScrollPane

    Searching through the archives, this appears to be a pretty frequent question, but so far, none of the answers have worked for me. Behold, what I have:
    Filelist = new JList(Filelistmodel);
    FilePane = new JScrollPane();
    FilePane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    FilePane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    FilePane.setMaximumSize(new Dimension(650,150));
    FilePane.setMinimumSize(new Dimension(650,150));
    FilePane.setPreferredSize(new Dimension(650,150));
    FilePane.setBounds(150, 0, 650, 150);
    FilePane.setViewportView(Filelist);
    panel.add(FilePane);     Message was edited by:
    break_the_chain

    Ok, here's the context. It's not exactly simple, but it should compile and the rest of the code is more or less outside of the problem.
    package formshow;
    //import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.io.*;
    import java.util.*;
    public class Sync extends JApplet
         JButton bttn1;
         JComboBox Cbox_drives, Cbox_folders;
         JPanel panel;
         JFrame aframe;
         JScrollPane FilePane;
         DefaultListModel Filelistmodel;
         JList Filelist;
         class OnlyPRE implements FilenameFilter
           Vector PRE;
           public OnlyPRE(Vector PRE)
           {this.PRE = PRE;}
           public boolean accept(File dir, String name)
                              boolean accept = false;
              for (int i=0; i<PRE.size(); i++)
              if (name.startsWith((String)PRE.get(i)))
              accept = true;
           return accept;
         public void init()
              //applet listener
              this.addFocusListener( new FocusListener()
                public void focusGained(FocusEvent evt)
                                   getContentPane().invalidate();
                   getContentPane().validate();
              public void focusLost(FocusEvent evt)
                 getContentPane().invalidate();
                 getContentPane().validate();
                             //this applet
              this.setSize(800,150);
              //jpanel
              panel = new JPanel(null);
              //Button init stuff
              bttn1 = new JButton("Get Files");
              bttn1.setSize(150,50);
              bttn1.setLocation(0,100);
              bttn1.addActionListener( new ActionListener()
                 public void actionPerformed(ActionEvent evt)
                 {PopList();}
              panel.add(bttn1);
              //Cbox_drives init stuff
              int offset = 'a';                    
              Cbox_drives = new JComboBox();
              for (int i=0; i<26; i++)
              Cbox_drives.addItem((char)(offset+i)+":\\");               
              Cbox_drives.setSize(150,50);
              Cbox_drives.setLocation(0,0);
                              Cbox_drives.addActionListener( new ActionListener()
                public void actionPerformed(ActionEvent evt)
                   try                                  {
                    getPatFolders();
                  catch (Exception e)Cbox_drives.setBackground(Color.RED);}
              panel.add(Cbox_drives);
              //Cbox_folders init stuff
              Cbox_folders = new JComboBox();
              Cbox_folders.setLocation(0,50);
              Cbox_folders.setSize(150,50);
              Cbox_folders.addItem("Pick the drive letter you have mapped to 1416_a");
              panel.add(Cbox_folders);
              //Filelist init stuff
              Filelist = new JList();
              Filelist.setVisibleRowCount(5);
              //FilePane init stuff
              FilePane = new JScrollPane(Filelist);
              FilePane.setLocation(150,0);
              FilePane.setSize(650,150);
              panel.add(FilePane);
              getContentPane().add(panel);                              
              private int getPatFolders () throws Exception
                   String drive = (String) Cbox_drives.getSelectedItem();
                   String files[];
                   Vector prelist = new Vector();
                   prelist.addElement("PAT");
                   prelist.addElement("REL");
                   prelist.addElement("EME");
                   FilenameFilter onlyget = new OnlyPRE(prelist);
                   Cbox_folders.removeAllItems();
                   try{
                   File rootFolder = new File(drive);
                   files = rootFolder.list();
                   catch (Exception E)
                   files = new String[]{"Error Here"};
                   for (int i=0; i<files.length; i++)
                        Cbox_folders.addItem((String)files);               
                   return (1);
              private int PopList()
                   File StartFolder = new File(((String)Cbox_drives.getSelectedItem())+
    (String)Cbox_folders.getSelectedItem()));
                   PopList(getFiles(StartFolder));
                   Filelist.removeAll();
                   Filelist = new JList(Filelistmodel);
                   FilePane = new JScrollPane();
                   FilePane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                   FilePane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                   FilePane.setMaximumSize(new Dimension(650,150));
                   FilePane.setMinimumSize(new Dimension(650,150));
                   FilePane.setPreferredSize(new Dimension(650,150));
                   FilePane.setBounds(150, 0, 650, 150);
                   FilePane.setViewportView(Filelist);
                   panel.add(FilePane);     
                   getContentPane().invalidate();
                   getContentPane().validate();
                   return(1);
              private int PopList(Vector transmute)
                   Filelistmodel = new DefaultListModel();
                   for (int i=0; i<transmute.size(); i++)
                        Filelistmodel.addElement(transmute.elementAt(i));
                   return(1);
              private Vector getFiles(File ThisPath)
                   Vector ThisLevel = new Vector();               
                   String FileList[] = ThisPath.list();
                   for (int i=0; i<FileList.length; i++)
                             File afile = new File(ThisPath.getAbsolutePath()+"\\"+FileList[i]);
                             if (afile.isFile())
                                  ThisLevel.addElement(afile.getAbsolutePath());
                             else
                                  append(ThisLevel,getFiles(afile));                              
                   return ThisLevel;
              private Vector append(Vector Left, Vector Right)
                   for (int i=0; i<Right.size();i++)
                        Left.addElement(Right.get(i));
                   return Left;
    Ok, basically this is for windows users. Pick a drive letter, then pick a folder from the next combo box.
    Hit the button and a list of all of the files in the folders and subfolders shows up in the JList on the right.
    DO NOT try this when the second list box is pointing to something like windows or program files.
    I'd recommend creating your own folder that goes maybe one or two levels deep with just a bunch of empty text files.
    I will <3 anyone that can help me with this forever and bestow upon them rediculous numbers of dukestars.
    Message was edited by:
    break_the_chain

  • How to prevent scrolling if you have two Jpanels in a JScrollPane

    I have a JScrollPane with a JPanel for Linenumbers and one for a JTextArea,
    each time you have a new line in the JTextarea the propertyListenerEvent call a Method that sets the LineNumbers in the JPanel for Linenumbers, but then you get an unwanted behaviour of the scrollbar: The Scrollbar scrolls down to the last Line. (e.g. if youre writing in the first Line - LineNumber update after pressing return, set's the view to the last Line e.g. 200 - the caret/cursor is on the second) I tried to set the Linenumber Panel not focusable, but it doesn't work. Does anyone got a hint for me?

    Thanks for the answers.
    @itchyscratchy: didn't get it working with that workarround. but thanks a lot :)
    camickr: Since we can't see your code, we can't suggest what you might be doing wrong.I better kick my idea... thought it could be possible like: when
    LnNums=false after setLineNum Call in jTPaneCaretUpdate!?
    * LineNumberTest.java
    * Created on 12. Dezember 2006, 23:40
    public class LineNumberTest extends javax.swing.JFrame
        /** Creates new form LineNumberTest */
        public LineNumberTest()
            initComponents();
       // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents()
        jScrollPane1 = new javax.swing.JScrollPane();
            jPanel1 = new javax.swing.JPanel();
            jTxtArea1 = new javax.swing.JTextArea();
            jTLineNums = new javax.swing.JTextArea();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
           jPanel1.setLayout(new java.awt.BorderLayout());
            jTxtArea1.addCaretListener(new javax.swing.event.CaretListener() {
                public void caretUpdate(javax.swing.event.CaretEvent evt) 
                    jTxtArea1CaretUpdate(evt);
            jPanel1.add(jTxtArea1, java.awt.BorderLayout.CENTER);
            jTLineNums.setBackground(javax.swing.UIManager.getDefaults().getColor("TextField.disabledBackground"));
            jTLineNums.setEditable(false);
            jPanel1.add(jTLineNums, java.awt.BorderLayout.WEST);
            jScrollPane1.setViewportView(jPanel1);
            getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
            java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-400)/2, (screenSize.height-300)/2, 400, 300);
        // </editor-fold>
        private void jTxtArea1CaretUpdate(javax.swing.event.CaretEvent evt)
            //Caret
            ci = jTxtArea1.getCaretPosition();
            String sc;
            sc = Integer.toString(ci);
            String s = "0";
            sli=jTxtArea1.getLineCount();
            s = Integer.toString(sli);
            if(LnNums) {
                setLineNums();
               //LnNums =false;
             private void setLineNums()
            jTLineNums.setText("");
            //jTLNums.setFont (new Font (fName, Font.PLAIN, fSize));
            for (int i = 1; i <= sli; i++) {
                jTLineNums.append(i+" \r\n");
            //setFoc ();
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new LineNumberTest().setVisible(true);
        public javax.swing.JPanel jPanel1;
        public javax.swing.JScrollPane jScrollPane1;
        public javax.swing.JTextArea jTLineNums;
        public javax.swing.JTextArea jTxtArea1;
        boolean LnNums = true;
        int iLnNums, iSymBar, iCodeBar, iInv, sli, ci;
    }

  • Multiple JPanels, non-working JScrollPane

    So, I'm trying to make a scrollbar with multiple text areas, but I can't seem to get the scroll bar to appear when there's overflow. When I try, [this is an example of what I get|http://www.fileden.com/files/2010/3/9/2788777//scrollpane.png].
    Here is my code:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.KeyboardFocusManager;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.ScrollPaneConstants;
    public class SSCCE
         public SSCCE()
              JFrame f = new JFrame();
              JPanel p[] = {new JPanel(),new JPanel()};
              JScrollPane pane = new JScrollPane(p[0],ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              p[0].setLayout(new GridBagLayout());
              for(int i = 0 ; i < 16; i++)
                   addItem(p[0],createTextArea(""+i),0,i,GridBagConstraints.WEST);
              p[1].add(new JButton("Click"));
              pane.setBorder(BorderFactory.createLineBorder(Color.BLACK));
              f.add(pane,BorderLayout.NORTH);
              f.add(p[1],BorderLayout.SOUTH);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.setSize(500,300);
              f.setLocationRelativeTo(null);
              f.setVisible(true);
         private JTextArea createTextArea(String text)
              JTextArea t = new JTextArea(text,1,10);
              t.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
              t.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);
              return t;
         private static void addItem(JPanel p, JComponent c, int column, int row, int align)
              GridBagConstraints gc = new GridBagConstraints();
              gc.fill = GridBagConstraints.NONE;
              c.setFont(new Font("Courier New",Font.PLAIN,12));
              gc.gridx = column;
              gc.gridy = row;
              gc.gridwidth = 1;
              gc.gridheight = 1;
              gc.anchor = align;
              gc.weightx = 100;
              gc.weighty = 100;
              p.add(c, gc);
              p.validate();
         public static void main(String[] args)
              new SSCCE();
    }What do I do to get the scroll bar to appear?

    preferredSize worked. Thanks guys. :)
    Edit: BorderLayout.CENTER also worked. Thanks.
    Edited by: ElectrifiedBrain on Aug 14, 2010 12:57 AM

  • Component added to JPanel is invisible

    i have a JPanel ( called panelMap ) on a JPanel ( called uProfile ) and im simply adding a component ( in this case a JLabel ) to panelMap in the constructor of uProfile. But the component never displays.
    the code is as follows :
    public uProfile( ) {
    initComponents();
    JLabel lbl = new JLabel();
    lbl.setText("blah");
    lbl.setLocation(20,20);
    this.panelMap.add( lbl );
    }

    Hi chalcoprite,
    u didn't set the label.setSize()
    since u r adding the component as a dynamic one i think u need that.
    then, if your panel layout is just Null, then there is no meaning for that setLocation() method.
    else, u have to set that component in NORTH or CENTER or SOUTH of that LayoutManager which u used.
    Also after u added one component, call the validate() and repaint() in the panel.
    like
    panelMap.validate(); and panelMap.repaint();
    this will work i think..

  • JTextPanes added to JPanel

    I have several JTextPanes added to a JPanel. I just want the JTextPane that is currently focused shd be painted(visible) fully irrespective of the order in which it is added to the JPanel.
    My project is to develope a GUI similler to MS Powerpoint, using Java Swing
    Thanks in Advance
    anu

    Hey,
    Thank u.I solved that pbm.
    But one more pbm araise coz of that i think.
    Components caret & selected text are not visible.
    is it coz of removing & then adding components to JPanel?
    I've registered all listeners(Focus etc), when the components obj r created.
    It was working before that. ie omitting 3 lines indicated by //new
    anu
    sample codes from JPanel
    public void bringComponentToFront()
         if (focused == null)
         return;
         Vector tmpVector = new Vector();
         int compCount = getComponentCount();
         // bring component to front by inserting it first into the slide
         tmpVector.add((Component)focused);
         for(int i=0; i < compCount; i++) {
         Component tmpComp = getComponent(i);
         if (!tmpComp.equals(focused))
         tmpVector.add(tmpComp);
         removeAll();
         for(int i=0; i < compCount; i++)
         add((Component)(tmpVector.elementAt(i)));
         repaint();
    //before focusing a new component,the current order of components r saved
    public void saveOrder()
              int compCount = getComponentCount();
    tmpVector1.clear();
              for(int i=0; i < compCount; i++)
              Component tmpComp=getComponent(i);
              tmpVector1.add(tmpComp);
    //retriving the old order
    public void retryOrder()
    int compCount = getComponentCount();
    removeAll();
              for(int i=0; i < tmpVector1.size(); i++)
              add((Component)(tmpVector1.elementAt(i)));
              repaint();
    sample codes from JTextPane
    //constructor
    addFocusListener(new FocusListener)
         public void focusGained(FocusEvent e)
              parentSlide.saveOrder(); //new
              parentSlide.bringComponentToFront(); //new
         if (m_xStart>=0 && m_xFinish>=0)
         if (getCaretPosition()==m_xStart)
         setCaretPosition(m_xFinish);
         moveCaretPosition(m_xStart);
         else
         select(m_xStart, m_xFinish);
         public void focusLost(FocusEvent e)
         parentSlide.retryOrder(); //new
         m_xStart = getSelectionStart();
         m_xFinish = getSelectionEnd();
    focused: currently focused Component(JTextPane)
    parentSlide : current slide(JPanel) of PowerPoint
    tmpVector1: globally declared

  • Netbeans: adding to jPanel via code after init (jFreeChart)

    This will be my second post. Many thanks to those who replied to my first questions.
    I am using netbeans 5.5
    I am attempting to run the following jFreeChart demo but in netbeans.
    Original demo located here: http://www.java2s.com/Code/Java/Chart/JFreeChartPieChartDemo7.htm
    Instead of programically creating the jPanel like the demo does, i would like to do it using the netbeans GUI and then add the code to create the jFreeChart.
    In netbeans i create a new project, create a new jFrame and place a new jPanel on the form (keeping the variable name jPanel1) as illustrated below:
    * MainForm.java
    * Created on June 28, 2007, 1:48 PM
    package mypkg;
    import org.jfree.chart.ChartFactory;
    import org.jfree.chart.ChartPanel;
    import org.jfree.chart.JFreeChart;
    import org.jfree.chart.plot.PiePlot;
    import org.jfree.chart.plot.PiePlot3D;
    import org.jfree.data.general.DefaultPieDataset;
    import org.jfree.ui.ApplicationFrame;
    import org.jfree.ui.RefineryUtilities;
    * @author  me
    public class MainForm extends javax.swing.JFrame {
        /** Creates new form MainForm */
        public MainForm() {
            initComponents();
        /** Netbeans Auto-Generated Code goes here which I have omitted */                       
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MainForm().setVisible(true);
        private void CreateChart() {
            DefaultPieDataset dataset = new DefaultPieDataset();
            dataset.setValue("Section 1", 23.3);
            dataset.setValue("Section 2", 56.5);
            dataset.setValue("Section 3", 43.3);
            dataset.setValue("Section 4", 11.1);
            JFreeChart chart3 = ChartFactory.createPieChart3D("Chart 3", dataset, false, false, false);
            PiePlot3D plot3 = (PiePlot3D) chart3.getPlot();
            plot3.setForegroundAlpha(0.6f);
            plot3.setCircular(true);
            jPanel1.add(new ChartPanel(chart3));
            jPanel1.validate();
        // Variables declaration - do not modify                    
        private javax.swing.JPanel jPanel1;
        // End of variables declaration                  
    }I then attempted to call the CreateChart() function in several places (in the MainForm() function, in the pre and post creation code properties of the jPanel's properties dialog in netbeans (as well as pre and post init in the same screen)) and nothing seems to work. the program compiles and the jFrame comes up but the chart does not show.
    If i run the example at the above noted link it runs fine in netbeans if i copy and paste the code directly, it just doesnt work when i try to get it to work through the netbeans GUI builder and the jPanel i create through it.
    Can any more advanced netbeans/java users lend me a hand or point me in the right direction?
    NOTE: in the code pasted above, i am only trying to run one of the four chart demo's listed in the original source in the link.
    NOTE2: in the code pasted above it doesnt show me calling CreateChart() from anywhere, im hoping to get some advice on how to proceed from here.
    Message was edited by:
    amadman

    Here is the netbeans generated code that i had omitted in the post above:
    private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            CreateChart(); //this is one of the many places i tried sticking the function
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 546, Short.MAX_VALUE)
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 398, Short.MAX_VALUE)
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            pack();
        }// </editor-fold>   I believe this is what you mentioned looking for, or close to it:
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);any thoughts?

  • Help with adding a JPanel with multiple images to a JFrame

    I'm trying to make a program that reads a "maze" and displays a series of graphics depending on the character readed. The input is made from a file and the output must be placed in a JFrame from another class, but i can't get anything displayed. I have tried a lot of things, and i am a bit lost now, so i would thank any help. The input is something like this:
    20
    SXXXXXXXXXXXXXXXXXXX
    XXXX XXXXXXXXXXX
    X XXXXX
    X X XX XXXXXXXXXXXX
    X XXXXXXXXX XXX
    X X XXXXXXXXX XXXXX
    X XXXXX XXXXX XXXXX
    XX XXXXX XX XXXX
    XX XXXXX XXXXXXXX
    XX XX XXXX XXXXXXXX
    XX XX XXXXXXXX
    XX XXX XXXXXXXXXXXXX
    X XXXXXXXXXXXXX
    XX XXXXXXX !
    XX XXXXXX XXXXXXXXX
    XX XXXXXXX XXXXXXXXX
    XX XXXXXXXX
    XX XXXX XXXXXXXXXXXX
    XX XXXX XXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXX
    Generated by the Random Maze Generator
    And the code for the "translator" is this:
    package project;
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    public class Translator extends JFrame {
       private FileReader Reader;
       private int size;
       Image wall,blank,exit,start,step1,step2;
      public Translator(){}
      public Translator(File F){
      try {
           Reader=new FileReader(F);}
      catch (IOException e){
           JOptionPane.showMessageDialog(null,"Error Opening File","Error",JOptionPane.ERROR_MESSAGE);}
      try {
      size=Reader.read();
      System.out.write(size);}
      catch (IOException e){
           JOptionPane.showMessageDialog(null,"Error Opening File","Error",JOptionPane.ERROR_MESSAGE);}
      Toolkit theKit=Toolkit.getDefaultToolkit();
      wall=theKit.getImage("wall.gif");
      blank=theKit.getImage("blanktile.jpg");
      exit=theKit.getImage("exit.jpg");
      start=theKit.getImage("start.jpg");
      step1=theKit.getImage("start.jpg");
      step2=theKit.getImage("step1.jpg");
      JPanel panel=new JPanel(){
      public void paintComponent(Graphics g) {
      super.paintComponents(g);
      int ch=0;
      System.out.print("a1 ");
      int currentx=0;
      int currenty=0;
      try {ch=Reader.read();
          System.out.write(ch);}
      catch (IOException e){}
      System.out.print("b1 ");
      while(ch!=-1){
        try {ch=Reader.read();}
        catch (IOException e){}
        System.out.write(ch);
        switch (ch){
            case '\n':{currenty++;
                      break;}
            case 'X':{System.out.print(">x<");
                     g.drawImage(wall,(currentx++)*20,currenty*20,this);
                     break;}
           case ' ':{
                     g.drawImage(blank,(currentx++)*20,currenty*20,this);
                     break;}
            case '!':{
                     g.drawImage(exit,(currentx++)*20,currenty*20,this);
                      break;}
            case 'S':{
                     g.drawImage(start,(currentx++)*20,currenty*20,this);
                      break;}
            case '-':{
                     g.drawImage(step1,(currentx++)*20,currenty*20,this);
                      break;}
            case 'o':{
                      g.drawImage(step2,(currentx++)*20,currenty*20,this);
                      break;}
            case 'G':{ch=-1;
                      break;}
                  }//Swith
          }//While
      }//paintComponent
    };//Panel
    panel.setOpaque(true);
    setContentPane(panel);
    }//Constructor
    }//Classforget all those systems.out and that stuff, that is just for the testing
    i call it in another class in this way:
    public Maze(){
        firstFrame=new JFrame("Random Maze Generator");
        firstFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        Container c = getContentPane();
        c.setLayout(new FlowLayout());
        (...)//more constructor code here
        Translator T=new Translator(savefile);
        firstFrame.add(T);
        firstFrame.getContentPane().add(c);
        firstFrame.setBounds(d.width/3,d.height/3,d.width/2,d.height/4);
        firstFrame.setVisible(true);
        c.setSize(d.width/2,d.height/4);
        c.show();
        }i know it may be a very basic or concept problem, but i can't get it solved
    thanks for any help

    Try this. It's trivial to convert it to use your images.
    If you insist on storing the maze in a file, just read one line at a
    time into an ArrayList than convert to an array and pass that to the
    MazePanel constructor.
    Any questions, just ask.
    import java.awt.*;
    import javax.swing.*;
    public class CFreman1
         static class MazePanel
              extends JPanel
              private final static int DIM= 20;
              private String[] mMaze;
              public MazePanel(String[] maze) { mMaze= maze; }
              public Dimension getPreferredSize() {
                   return new Dimension(mMaze[0].length()*DIM, mMaze.length*DIM);
              public void paint(Graphics g)
                   g.setColor(Color.BLACK);
                   g.fillRect(0, 0, getSize().width, getSize().height);
                   for (int y= 0; y< mMaze.length; y++) {
                        String row= mMaze[y];
                        for (int  x= 0; x< row.length(); x++) {
                             Color color= null;
                             switch (row.charAt(x)) {
                                  case 'S':
                                       color= Color.YELLOW;
                                       break;
                                  case 'X':
                                       color= Color.BLUE;
                                       break;
                                  case '!':
                                       color= Color.RED;
                                       break;
                             if (color != null) {
                                  g.setColor(color);
                                  g.fillOval(x*DIM, y*DIM, DIM, DIM);
         public static void main(String[] argv)
              String[] maze= {
                   "SXXXXXXXXXXXXXXXXXXX",
                   "    XXXX XXXXXXXXXXX",
                   "X              XXXXX",
                   "X  X XX XXXXXXXXXXXX",
                   "X    XXXXXXXXX   XXX",
                   "X  X XXXXXXXXX XXXXX",
                   "X  XXXXX XXXXX XXXXX",
                   "XX XXXXX XX     XXXX",
                   "XX XXXXX    XXXXXXXX",
                   "XX  XX XXXX XXXXXXXX",
                   "XX  XX      XXXXXXXX",
                   "XX XXX XXXXXXXXXXXXX",
                   "X      XXXXXXXXXXXXX",
                   "XX XXXXXXX         !",
                   "XX  XXXXXX XXXXXXXXX",
                   "XX XXXXXXX XXXXXXXXX",
                   "XX          XXXXXXXX",
                   "XX XXXX XXXXXXXXXXXX",
                   "XX XXXX XXXXXXXXXXXX",
                   "XXXXXXXXXXXXXXXXXXXX"
              JFrame frame= new JFrame("CFreman1");
              frame.getContentPane().add(new MazePanel(maze));
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setResizable(false);
              frame.setVisible(true);
    }

  • Adding a JPanel to a JCheckBox (that's not a typo)

    Happy Friday everyone! Time for another slightly ridiculous question from yours truly.
    Long story short, I'm trying to create a JCheckBox with three potential states instead of two: checked, unchecked, and undetermined. My eventual goal is to use this as a renderer in a JTree of options with sub-options, etc.
    Don't read this paragraph if you don't care about my ultimate goal and want to get onto the SSCCE: For example, the JTree might contain a node that represents "all animals" and then underneath it is a list of animals. The user would be able to select the "all animals" JCheckBox, which would then select all of the animal JCheckBoxes underneath it (I already have this part working perfectly). However, what should happen when the user goes into the structure and deselects "ducks" from the animal tree? Currently the "all animals" JCheckBox becomes deselected, but this doesn't seem very intuitive to me. So I'd like a third option that basically means "some of my children are selected, some are deselected". (My actual program has nothing to do with animals, but it's a fun example)
    The meat and potatoes of the problem: In order to simulate the third state of the JCheckBox, I thought I'd add to it a JPanel that painted an X (or a slash, or whatever means "indeterminate") on itself. The problem is, all sorts of interesting things start happening when I do this. The JPanel is quite large before any repainting goes on. After the first call to repaint (I simulate this by resizing the JFrame a tiny tiny tiny bit), the JPanel isn't visible at all. And after that, only the JPanel is visible.
    Am I missing something? Is there a better way to do what I'm trying to do?
    The SSCCE:
    import javax.swing.JFrame;
    import java.awt.Dimension;
    import javax.swing.JCheckBox;
    import javax.swing.JPanel;
    import java.awt.Graphics;
    import javax.swing.BoxLayout;
    import javax.swing.UIManager;
    public class TestCheckBoxPanel{
         public TestCheckBoxPanel(){
              try {
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
              catch (Exception e) {
                   e.printStackTrace();
              JFrame frame = new JFrame("Testing JCheckBox");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
              JCheckBox regularCheckBox = new JCheckBox("CheckBox", true);
              final JCheckBox panelCheckBox = new JCheckBox("PanelCheckBox", false);
              JPanel panel = new JPanel(){
                   public void paintComponent(Graphics g){
                        super.paintComponent(g);
                        //this almost works, but what happens if the JCheckBox
                        //is a different size on a different computer?
                        //is that even possible?
                        setMinimumSize(new Dimension(10, 10));
                        setMaximumSize(new Dimension(10, 10));
                        setPreferredSize(new Dimension(10, 10));
                        //this makes the JPanel huge, and makes me cry
                        setMinimumSize(new Dimension(panelCheckBox.getWidth(), panelCheckBox.getHeight()));
                        setMaximumSize(new Dimension(panelCheckBox.getWidth(), panelCheckBox.getHeight()));
                        setPreferredSize(new Dimension(panelCheckBox.getWidth(), panelCheckBox.getHeight()));
                        g.drawLine(0, 0, getWidth(), getHeight());
                        g.drawLine(getWidth(), 0, 0, getHeight());
                   } //end paintComponent
              }; //end new JPanel
              panelCheckBox.add(panel);
              frame.add(regularCheckBox);
              frame.add(panelCheckBox);
              frame.pack();
              frame.setVisible(true);     
         public static void main(String [] args){
              new TestCheckBoxPanel();
    }

    jduprez wrote:
    Hello,
    First thank you for the humourous wording.Haha, I figure if I'm going to ask ridiculous questions, the least I can do is ask them in an entertaining way!
    Admittedly though, your problem is more complex than it seem.That's what I was afraid of :(
    I don't see you setting the layout of the JCheckbox (viewed as a Container of the JPanel). I tried experimenting with setting the JCheckBox's layout. Using a null layout and absolute positioning actually ends up with a monstrous looking cut-in-half JCheckBox with no text.
    Arguably, you know that the bounds are initially (0,0,0,0), but relying on the 0,0 origin assumes the box is always on the left side (which is not true as a JCheckbox can have a different alignment/orientation/don't remember the term.That should actually be okay, I can assume that the box will be on the left side for these purposes.
    Moreover, setting the size with a fixed value does not account for what may happen to the checkbox if you stretch it, change the font, change the spacing,...Exactly. That's why I wanted to use the JCheckBox's width and height, which ends up making the JPanel quite large instead of just the size of the box. I'd much rather prefer using a width and height that would change with the JCheckBox's size.
    When you say you have already dealt with the 3-state problem, you mean you have designed a custom model? Sort of. I wrote a custom renderer and nodes for my JTree. Each node contains its state (selected, deselected, and undetermined) which changes when the user selects a node in the JTree, and the renderer is to return a Component based on that status. The setting of the state works fine, it's just figuring out what the renderer should return.
    Then your component is no more a JCheckbox. I mean, do you still need that it extends JCheckbox?That's a good point. I was using a JCheckBox just because it seemed like the most logical/intuitive component, but I could use anything. The node's selected status is independent of the JCheckBox's selected status (I set the JCheckBox based off the node's state).
    If not, one thing you could try is to implement a 3StateCheckBox as a JPanel, which contains...I think what I might try to do is simply use a JLabel with an icon, and then have three separate icons for the three states (I might even use images of JCheckBoxes, haha).

  • Adding customized JPanel's to a frame

    This seems like a very easy solution, but I've been looking around and can't find a way to solve it.
    Let's say I have a class like:
    public class StickyPerson extends JComponent {
        private int x, y;
         * Set coordinates for the sticky person
         * @param x Position x
         * @param y Position y
        public void setCoordinates(int x, int y) {
            this.x = x;
            this.y = y;
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g2.drawOval(this.x, this.y, 50, 50);
    }and in my main class I do like that:
          StickyPerson aPerson = new StickyPerson();
          aPerson.setCoordinates(90, 100);
          frame.add(aPerson);
          aPerson.setCoordinates(290, 100);
          frame.add(aPerson);The problem I'm dealing with is that only the last StickyPerson object is drawn. I've tested with other shapes as well and got the same result, only the last object is shown.
    It's clear that I'm making a mistake somewhere but I can't find where. Any ideas?
    Thank you
    Edited by: Raisen on Sep 10, 2009 12:00 AM

    Thanks for all the replies. After reading more about the layout managers, I found out that in this specific project, I need to set the layout manager to null because I'm going to be dealing with drawings all over my frame.
    I've added setBounds and setSize inside the paintComponent method but somehow, whenever I add the component to the frame, the method is never called.
    Example:
    public class StickyPerson extends JComponent {
        public StickyPerson(JFrame aFrame) {
            super();
            insets = aFrame.getInsets();
        public void paintComponent (Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            GradientPaint redtowhite = new GradientPaint(0,0,Color.GRAY,
                    100, 0, Color.WHITE);
            g2.setPaint(redtowhite);
            g2.fill (new Ellipse2D.Double(this.x, this.y, this.w, this.h));
            g2.setColor(Color.BLACK);
            g2.drawString(this.text, this.x+25, this.y+25);
            this.setSize(w, h);
            this.setBounds(10 + this.insets.left, 50 + this.insets.top,
                    this.w, this.h);
    }and in my main code:
          JFrame frame = new JFrame("Example");
          frame.getContentPane().setLayout(null);
          frame.setSize(550, 400);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          StickyPerson stickyPerson = new StickyPerson(frame);
          stickyPerson.setCoordinates(10, 20, 200, 40);
          stickyPerson.setText("Hello World");
          frame.add(stickyPerson);
    code}
    I've omitted the other irrelevant methods to shorten the code. I've attached breakpoints inside the paintComponent method but it never reaches it. I've tried to use repaint(), validate(), repack().                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Maybe you are looking for