Add viewport to jpanel

i am really confused regarding the size of my Jpanel(it change as the frame, it shouldn t)
and the implementation of a view port with
could you help me is really important i have submission on monday
pls
package help;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.*;
public abstract class MyFrame extends JFrame {
private static final long serialVersionUID = 1L;
private static JButton drawCircle, drawRectangle, drawSquare, drawStar, start, clear,quit,back, screenshoot;
static final int FPS_MIN = 0;
static final int FPS_MAX = 150;
static final int FPS_INIT = 0;
static int fps;
double x1,x2;
double y1,y2;
int dr =1;
int dy= 1;
int Selection=0;
boolean click=true; //check if start has been clicked
int width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;  // screen width
int height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;     //screen higth
protected static int count;
int R,G,B;  //color
Cursor c;                    //cursor object
private static ShapePanel bpnl;
public MyFrame()
        R=G=B=0;
        int width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;
        int height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height-100;
        JFrame frame=new JFrame();
        BorderLayout layout=new BorderLayout();
        frame.setLayout(layout);
        frame.setTitle("Game");
        //panel to hold buttons
        JPanel upPanel = new JPanel();
        upPanel.setLayout(new FlowLayout());
        upPanel.setSize(width, height/5);
        //panel to hold SLIDERS
        JPanel leftPanel = new JPanel();
        leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
        leftPanel.setSize(50, height);
        //initialize buttons and add to the upPanel
        drawCircle=new JButton("Draw Circle");
        upPanel.add(drawCircle);
        drawStar=new JButton("Draw Star");
        upPanel.add(drawStar);
        drawRectangle=new JButton("Draw Rectangle");
        upPanel.add(drawRectangle);
        drawSquare=new JButton("Draw Square");
        upPanel.add(drawSquare);
        start=new JButton("Start");
        start.setBackground(Color.GREEN);
        //upPanel.add(start);
        clear=new JButton("Clear");
        upPanel.add(clear);
        back=new JButton("Back");
        upPanel.add(back);
        quit=new JButton("Quit");
        quit.setBackground(Color.red);
        upPanel.add(quit);  
        screenshoot=new JButton("ScreenShoot");
        c = new Cursor (Cursor.CROSSHAIR_CURSOR);     //Change cursor to cross hair
     this.setCursor (c);
        //new object spanel to hold TIMER
        JPanel spanel=new JPanel();
            spanel.setLayout(new GridLayout());
            //slider dimension construction
            JSlider sDimension = new JSlider(JSlider.HORIZONTAL,FPS_MIN, FPS_MAX, FPS_INIT);
            sDimension.setMajorTickSpacing(30);
            sDimension.setMinorTickSpacing(3);
            sDimension.setPaintTicks(true);
            sDimension.setPaintLabels(true);
            Font font = new Font("Serif", Font.ITALIC, 15);
            sDimension.setFont(font);
            sDimension.setBorder(BorderFactory.createTitledBorder("Shape Dimension"));
            //slider speed construction
            int FPS_MIN_s = 0;
            int FPS_MAX_s = 60;
            int FPS_INIT_s = 0;    //initial frames per second
            JSlider sSpeed = new JSlider(JSlider.HORIZONTAL,FPS_MIN_s, FPS_MAX_s, FPS_INIT_s);
            sSpeed.setBorder(BorderFactory.createTitledBorder("Shape Speed"));
         ////////////////////////// // slider colors////////////////////////////////////////////////////
            int FPS_MIN_C = 0;
            int FPS_MAX_C = 250;
            int FPS_INIT_C = 0;  
            JSlider sliderR= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
            sliderR.setBorder(BorderFactory.createTitledBorder("Red Channel"));
            JSlider sliderG= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
            sliderG.setMajorTickSpacing(50);
            sliderG.setMinorTickSpacing(25);
            sliderG.setPaintTicks(true);
            sliderG.setPaintLabels(true);
            sliderG.setFont(font);
            sliderG.setBorder(BorderFactory.createTitledBorder("Green Channel"));
            JSlider sliderB= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
            sliderB.setBorder(BorderFactory.createTitledBorder("Blue Channel"));
          //     spanel.add(sSpeed,BorderLayout.EAST);
              frame.add(upPanel,BorderLayout.NORTH);
              frame.add(leftPanel,BorderLayout.WEST);
              bpnl = new ShapePanel(3000,3000);
                    System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
                    bpnl.setFocusable(true);
              upPanel.setBackground(Color.DARK_GRAY);
              upPanel.setBorder(BorderFactory.createLineBorder(Color.white));
        frame.add(spanel,BorderLayout.SOUTH);       
        frame.add(bpnl, BorderLayout.CENTER);
        frame.setSize(width, height);
        frame.setVisible(true);               
           leftPanel.add(sliderR);
           leftPanel.add(sliderB);
           leftPanel.add(sliderG);
           leftPanel.add(sDimension,BorderLayout.WEST); 
             System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
          public static  int getPanelWidth()
              System.out.println("panel width   "+bpnl.getWidth());
              return bpnl.getWidth();
          public static  int getPanelHeigth()
              System.out.println("Panel heigth  " +bpnl.getHeight());
              return bpnl.getHeight();
          public static void main(String args[])
              new MyFrame() {};
package help;
import java.awt.Cursor;
import java.awt.Graphics;
import javax.swing.JPanel;
class ShapePanel extends JPanel  {
     private static final long serialVersionUID = 1L;
     private javax.swing.Timer animationTmr;
     private float heigth;
     private float width;
     private Cursor c;
     public ShapePanel(int w, int h) {
                int W=w;
                int H=h;
                c = new Cursor (Cursor.CROSSHAIR_CURSOR);     //Change cursor to cross hair
                this.setCursor (c); 
                this.setPreferredSize(3000,3000);
     public void paintComponent(Graphics g) {
          super.paintComponent(g);
          g.fillRect(0, 0, this.getWidth(), this.getHeight());
    private void setPreferredSize(int i, int i0) {
    thanks

a simple way
jScrollPane.removeMouseWheelListener(jScrollPane.getMouseWheelListeners()[0]);but if you want to retain the mouseWheelListener, add a mouseListener to the scrollPane,
and in the same method as your panel's code (mousePressed) dispatch the event to the panel

Similar Messages

  • How can we add components to JPanel so that they can be resizeable

    Is it possible to add components to JPanel so that we can resize them or drag them.

    You could try searching the forums, but I'll save you the trouble. tjacobs has oft posted code which does what you want, both dragging and resizing.
    You can find an example here or here.

  • Can we add JFrame to JPanel?

    hi
    I m trying to add JFrame which has JPanel with BufferedImage to another JPanel.
    Is it possible? if yes kindly tell me how to achieve this.
    thanx

    Just another cross poster.
    [http://www.java-forums.org/java-2d/16085-how-add-jframe-inside-jpanel.html]
    db

  • How to add component to JPanel

    Hello,
    I Try to add a JPnel to other JPnel
    but it works not ther is a error in this code ??
    class MyClass extends JFrame
        Container contentPane;
      public MyClass()
                  contentPane = this.getContentPane();
                  contentPane.setBorderLayout(new BorderLayout());
                 MainPanel();
    puplic void MainPanel()
         Dimension dim = new Dimension(w,h);
         Dimension aDim = new Dimension((w / 2),(h / 2));
         JPanel mainPanel = JPanel();
         mainPanel.setPrefferedSize(dim);
         mainPanel.setLayout(new BorderLayout());
         JPanel pp = getLanguagePanel(aDim);
         pp.revalidate();
         mainPanel.add(pp,BorderLayout.PAGE_END);
         mainPanel.revalidate();
         contentPane.add(mainPanel,BoderLayout.CENTER)
    public JPanel getLanguagePanel(Dimension aDim)
             JPanel retPanel = new JPanel();
         retPanel.setPreferredSize(aDim);
         retPanel.setBorder(null);
         JLabel L = new JLabel("Test Label");
         L.setBounds(50,50,250,30);
         retPanel.add(L);
         retPanel.setBackground(Color.GREEN);
         retPanel.setOpaque(true);
         retPanel.revalidate();
         retPanel.repaint();
         return retPanel;
    }thanks

    contentPane.setBorderLayout(...)There is no such method. Your compiler should be telling you this.
    puplic void MainPanel()There is no such modifier. Your compiler should be telling you this.
    mainPanel.setPrefferedSize(...)There is no such method. Your compiler should be telling you this.
    BoderLayout.CENTERThere is no such class. Your compiler should be telling your this.

  • Best way to add and remove JPanels?

    I have a question on the best practice in removing and then adding JPanels. I know a few ways about doing it but it never seems to work just how I want it to. Any help would be great. Also if anyone wants to give tips on better ways of writing this code I am out your any ideas.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    class test2 extends JFrame implements ActionListener {
        private static final int FRAME_WIDTH    = 575;
        private static final int FRAME_HEIGHT   = 500;
        private static final int FRAME_X_ORIGIN = 150;
        private static final int FRAME_Y_ORIGIN = 250;
        //jbutton
        String [] foodButton = {"Tofu Burger",   "Cajun Chicken",
                                "Buffalo Wings", "Rainbow Fillet",
                                "Rice Cracker",  "No Salt Fries",
                                "Zucchini",      "Brown Rice",
                                "Cafe Mocha",    "Cafe Latte",
                                "Espresso",      "Oolong Tea"};
        JButton b[]          = new JButton[foodButton.length];
        JButton orderButton  = new JButton("Order");
        JButton cancelButton = new JButton("Cancel");
        JButton backButton   = new JButton("Back");
        int [] foodCount     = new int [12];
        double [] foodCost   = {3.49, 4.59,
                                3.99, 2.99,
                                0.79, 0.69,
                                1.09, 0.59,
                                1.99, 1.99,
                                2.49, 0.99};
        double subtotal;
        JPanel outPut         = new JPanel();
        JLabel test           = new JLabel ("Subtotal: ");
        //constructor
        public test2() {
            setContentPane(outPut);
            foodButton();
            frame();
            setVisible(true);
        //frame
        public void frame() {
            setSize(FRAME_WIDTH, FRAME_HEIGHT);
            setResizable(true);
            setTitle("Welcome to Low Fat Burger");
            setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
        //button builder
        public void foodButton() {
            ImageIcon myIcon = new ImageIcon("C:/Documents and Settings/Keith/My Documents/My Pictures/Clip Art/lowFatBurger.jpg");
            JPanel header    = new JPanel();
            JPanel menu      = new JPanel();
            JPanel bottom    = new JPanel();
            JPanel subtotal  = new JPanel();
            JPanel itemCount = new JPanel();
            JPanel control   = new JPanel();
            outPut.setLayout(new BorderLayout(0, 0));
            //outPut.setBorder(BorderFactory.createLineBorder(Color.red));
            outPut.add(header,   BorderLayout.NORTH);
            outPut.add(menu,     BorderLayout.CENTER);
            outPut.add(bottom,   BorderLayout.SOUTH);
            header.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
            header.add(new JLabel(myIcon));
            menu.setLayout(new GridLayout(4, 3));
            //test.setLayout(new FlowLayout());
            //test.setBorder(BorderFactory.createLineBorder(Color.red));
            for(int i=0; i<foodButton.length; i++) {
                b[i] = new JButton (foodButton);
    //work area
    b[i].addActionListener(this);
    menu.add(b[i]);
    //add actionlistener to control buttons
    orderButton.addActionListener(this);
    cancelButton.addActionListener(this);
    backButton.addActionListener(this);
    bottom.setLayout(new BorderLayout(0, 0));
    bottom.add(subtotal, BorderLayout.NORTH);
    bottom.add(itemCount, BorderLayout.CENTER);
    bottom.add(control, BorderLayout.SOUTH);
    subtotal.add(test);
    control.add(orderButton);
    control.add(cancelButton);
    public void actionPerformed(ActionEvent event) {
    String straction = event.getActionCommand();
    //format
    DecimalFormat df = new DecimalFormat("0.00");
    for(int j=0; j<foodButton.length; j++) {;
    if(event.getSource() == b[j]) {
    int count = ++foodCount[j];
    double itemSubtotal = count * foodCost[j];
    for(int i=0; i<foodButton.length; i++) {
    subtotal = (foodCount[i] * foodCost[i]);
    test.setText("Subtotal: $" + df.format(subtotal));
    if(straction.equals("Cancel")) {
    }else if(straction.equals("Order")) {
    //menu.removeAll();
    //control.removeAll();
    //control.add(orderButton);
    //control.add(backButton);
    //menu.revalidate();
    //menu.repaint();
    }else if(straction.equals("Back")) {
    public static void main (String[] args) {
    new test();

    If you want a really cheap way to go about it, you could try setVisible(false) instead of removing the panel. It will result in the same visual effect, and if you ever need to add the component back, you just need to setVisible(true) again.
    But make sure you do it inside the event loop...
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            panel.setVisible(false);
    });

  • Add component to JPanel

    Hello everyone,
    I have a JComboBox, and when i select an Option i would like to add a new component to the JPanel (just below the JComboBox). This is what i have at the moment, but i must be doing something wrong because it does nothing.
    String[] choices = { "Choose option", "Option 1", "Option 2", "Option 3", "Option 4", "Option 5" };
                       mainPanelComponent5 = new JComboBox(choices );
                       mainPanelComponent5.setBounds(100, 70, 150, 20);
                       mainPanelComponent5.addItemListener(new ItemListener() {
                          public void itemStateChanged(ItemEvent e) {
                              if (e.getStateChange() == ItemEvent.SELECTED) {
                                   JLabel compId = new JLabel("TEST");
                                   compId.setBounds(210, 70, 250, 20);
                                   mainPanel.add(compId);
                      });Any help? thanks in advance

    mainPanel.revalidate();Thank you, it works

  • How to add separator on JPanel?

    How do you add a separator on a JPanel like shown on the following screen shot?:
    http://www.carpenterdev.com/scrn.jpg
    Thanks,
    --BobC                                                                                                                                                                                                                                                                               

    Thanks! I'll do that - upperPanel JSeparator lowerPanel; Makes sense.
    --BobC                                                                                                                                                                                   

  • How to add scrollbar to jpanel

    i created a jpanel with images & related text to images, which repaints dynamically according to width,now i wann to add a vertical scrollbar to it.
    plz..help me

    iam getting scrollbar but iam unable to get scrolling when i change the size
    my code like this....
    //here iam using jpanel to get images and text
    public class ImgNtext extends JPanel {
       public ImgNtext(){
           //to intialize values
           init_values();
      public void init_values{
       //In these init_values iam decalaring imageFile name & text using hashtable
       public void paintComponent(Graphics g) {
             super.paintComponent(g);
             //getting width of screen
             int gw = getWidth();
             //then iam retriving all the values using while loop
             while(i.hasMoreElements())
                        //accroding to width iam painting the components
                          if(gw<100){
                               g.drawImage(image,x,y,null);
                               g.drawString(string,x,y+80);
                               gw -=100;
                               x += 100;
                         else{
                               y += 100;
                               gw = getWidth();
    public class ImagePanel
           ImgNtext it = new ImgNtext();
           JScrollPane sp;
           public ImagePanel() {
                     JFrame jf = new JFrame();
                     jf.setSize(1000,1000);
                     scp = new                JScrollPane(it,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                     jf.getContentPane().add(scp);
                     jf.setVisible(true);
              public static void main(String s[]){
                   ImagePanel img = new ImagePanel();
    }

  • How to change properties or add components in JPanel after initialization ?

    Hi,
    I am working on an applet where an image will be loaded in a JPanel from an URL. The JPanel is inside a JscrollPane.
    1.The image will be added on the JPanel later , not during initialization.
    2. JPanel size will be the size of the image.
    3 .the image size may change when the image is changed. Then the JPanel size also has to be updated.
    FYI I am using MediaTracker to load the image.
    I was trying updateUI() for scrollPane. But it is not working.
    How can I do it? Any suggestion?
    Thanks in advance.

    I have to use JPanel because I need flexible control on the imageYou said previously that the panel was the size of the image, so I don't understand what kind of flexible control you are talking about. Presumably you have code in the paintComponent(...) method of the JPanel something like:
    g.drawImage(0, 0, width, height)
    Well that is exactly what a JLabel would do.
    So if you need further custom painting then you would just override the paintComponent(...) method of JLabel to do your custom painting.

  • Error in Jpanel add function in a loop...^Urgent^

    I have higlighted the error part as below code, i would appreciate if you can help ....thank you
    Jpanel p1
    p1.removeAll();
                                        p1.add(t_label);
                      p1.add(menuBar); 
                         try{
                         FileReader f= new FileReader(filename2);
                         BufferedReader b= new BufferedReader(f);
                         String s;
                         fileExtension = new JLabel("File Extension",Label.LEFT);
                         contents = new JLabel("Cotent Type",Label.LEFT);
                         fileExtension.setBounds(new Rectangle(10, 50, 100, 30));
                         contents.setBounds(new Rectangle(150, 50, 100, 30));
                         int space=50;
                         while((s=b.readLine())!=null)
                             System.out.println(s);
                             space=space+40;
                             StringTokenizer st2 = new StringTokenizer(s,";");
                             System.out.println(st2.nextToken());
                              System.out.println(st2.nextToken());
                             txtFld[n]=new JTextField();
                             txtFld[n].setText(st2.nextToken());
                             txtFld[n].setBounds(new Rectangle(10, space, 100, 30));
                             txtF[n]=new JTextField();
                             txtF[n].setText(st2.nextToken());
                             txtF[n].setBounds(new Rectangle(150, space, 100, 30));
                             p1.add(txtFld[n]);<<<<Error to add in to Jpanel
                             p1.add(txtF[n]);<<<<Error to add in to Jpanel
                             n++;
                         p1.add(fileExtension);
                         p1.add(contents);
                         p1.repaint();
                         f.close();
                         catch(Exception ef)
                             System.out.println("File read in error.");
                         }

    The error message as below:
    java.lang.NullPointerException
    at mypkg.gui.actionPerformed(gui.java:227)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
    at javax.swing.AbstractButton.doClick(AbstractButton.java:302)
    at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1000)
    at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1041)
    at java.awt.Component.processMouseEvent(Component.java:5488)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3126)
    at java.awt.Component.processEvent(Component.java:5253)
    at java.awt.Container.processEvent(Container.java:1966)
    at java.awt.Component.dispatchEventImpl(Component.java:3955)
    at java.awt.Container.dispatchEventImpl(Container.java:2024)
    at java.awt.Component.dispatchEvent(Component.java:3803)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
    at java.awt.Container.dispatchEventImpl(Container.java:2010)
    at java.awt.Window.dispatchEventImpl(Window.java:1778)
    at java.awt.Component.dispatchEvent(Component.java:3803)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

  • How to put a Jpanel always over a JtextArea ?

    I want to have a little Jpanel above a JTextArea.
    At the initialize section, I add first the Jpanel and after the JtextArea (both in a 'parent' Jpanel with null layout)
    When I run the program I see the Jpanel over the JtextArea, but when I write on it and it reaches the area when the Jpanel is placed, the JtexArea brings to front and the Jpanel is no longer visible.
    So, how can I have my Jpanel on top always ?
    And another question , is there a hierarchy that control that I Jpanel is always over a Jbutton (even if the initial z-order of the button is higher than the Jpanel's)
    Thanks
    ( I do not send any code because it is so simple as putting this two components into a Jpanel)

    tonnot wrote:
    And another question , is there a hierarchy that control that I Jpanel is always over a Jbutton (even if the initial z-order of the button is higher than the Jpanel's)JLayeredPane
    ( I do not send any code because it is so simple as putting this two components into a Jpanel)Try it with a JLayeredPane and if you still have problems, post a [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://mindprod.com/jgloss/sscce.html].
    db

  • How to add a table(from TableRenderDemo) to a JFrame again

    Hello again:
    Thanks for stephen andrews's adivice, I follow your adivice to add code (it is in
    EventHandeler of DrawCalendar class, and they indicated by ???????????), but it still not work, please check for me why, Thanks.
    My problem
    Please run my coding first, and get some view from my coding.
    At the movement, I got a problem, I have not idea how to add a table(it is from TableRenderDemo) to JFrame when I click on the button(from DrawCalendar) of the numer 20, and I want the table disply under the buttons(from DrawCalendar).
    Please help me to solve this problem, thanks.
    *This program for add some buttons and a table on JFrame
    import java.awt.*;
    import javax.swing.*;public class TestMain extends JFrame{
    private static TableRenderDemo tRD;
    private static TestMain tM;
    protected static Container c;
    private static DrawCalendar dC;
    public static void main(String[] args){
    tM = new TestMain();
    tM.setVisible(true);
         public TestMain(){
         super(" Test");
         setSize(800,600);
    //set up layoutManager
    c=getContentPane();
    c.setLayout ( new GridLayout(3,1));
    tRD=new TableRenderDemo();
    dC=new DrawCalendar();
    addItems();//add Buttons to JFrame
    private void addItems(){
         c.add(dC); //add Buttons to JFrame
         //c.add(tRD); //add Table to JFrame     
    *This program for add some buttons to JPanel
    *and add listeners to each button
    *I want to display myTable under the buttons,
    *when I click on number 20, but why it doesn't
    *work, The coding for these part are indicated by ??????????????
    [import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.GridLayout;
    public class DrawCalendar extends JPanel {
         private static DrawCalendar dC;
         private static TestMain tM;
         private static TableRenderDemo myTable;
         private static GridLayout gL;
         private static final int nlen = 35;
        private static String names[] = new String[nlen];
    private static JButton buttons[] = new JButton[nlen];
         public DrawCalendar(){
              gL=new GridLayout(5,7,0,0);
              setLayout(gL);
              assignValues();
              addJButton();
              registerListener();
    //assign values to each button
         private void assignValues(){
              names = new String[35];
         for(int i = 0; i < names.length; i++)
         names[i] = Integer.toString(i + 1);
    //create buttons and add them to Jpanel
    private void addJButton(){
         buttons=new JButton[names.length];
         for (int i=0; i<names.length; i++){
         buttons=new JButton(names[i]);
         buttons[i].setBorder(null);
         buttons[i].setBackground(Color.white);
         buttons[i].setFont(new Font ("Palatino", 0,8));
    add(buttons[i]);
    //add listeners to each button
    private void registerListener(){
         for(int i=0; i<35; i++)
              buttons[i].addActionListener(new EventHandler());          
    //I want to display myTable under the buttons,
    //when I click on number 20, but why it doesn't
    //work
    private class EventHandler implements ActionListener{
         public void actionPerformed(ActionEvent e){
         for(int i=0; i<35; i++){
         if(i==20){                  //????????????????????
              tM=new TestMain(); //I want to display myTable under the buttons,
              tM.c.removeAll(); //when I click on number 20, but why it doesn't
              tM.c.add(dC); //work
              tM.c.add(myTable); //???????????????????????????????????????
              tM.validate();
         if(e.getSource()==buttons[i]){
         System.out.println("testing " + names[i]);
         break;
    *This program create a table with some data
    [import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TableRenderDemo extends JScrollPane {
        private boolean DEBUG = true;
        public TableRenderDemo() {
          //  super("TableRenderDemo");
            MyTableModel myModel = new MyTableModel();
            JTable table = new JTable(myModel);
            table.setPreferredScrollableViewportSize(new Dimension(700, 70));//500,70
             //Create the scroll pane and add the table to it.
             setViewportView(table);
            //Set up column sizes.
            initColumnSizes(table, myModel);
            //Fiddle with the Sport column's cell editors/renderers.
            setUpSportColumn(table.getColumnModel().getColumn(2));
    * This method picks good column sizes.
    * If all column heads are wider than the column's cells'
    * contents, then you can just use column.sizeWidthToFit().
    private void initColumnSizes(JTable table, MyTableModel model) {
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    Object[] longValues = model.longValues;
    for (int i = 0; i < 5; i++) {
    column = table.getColumnModel().getColumn(i);
    try {
    comp = column.getHeaderRenderer().
    getTableCellRendererComponent(
    null, column.getHeaderValue(),
    false, false, 0, 0);
    headerWidth = comp.getPreferredSize().width;
    } catch (NullPointerException e) {
    System.err.println("Null pointer exception!");
    System.err.println(" getHeaderRenderer returns null in 1.3.");
    System.err.println(" The replacement is getDefaultRenderer.");
    comp = table.getDefaultRenderer(model.getColumnClass(i)).
    getTableCellRendererComponent(
    table, longValues[i],
    false, false, 0, i);
    cellWidth = comp.getPreferredSize().width;
    if (DEBUG) {
    System.out.println("Initializing width of column "
    + i + ". "
    + "headerWidth = " + headerWidth
    + "; cellWidth = " + cellWidth);
    //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
    column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    public void setUpSportColumn(TableColumn sportColumn) {
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Snowboarding");
    comboBox.addItem("Rowing");
    comboBox.addItem("Chasing toddlers");
    comboBox.addItem("Speed reading");
    comboBox.addItem("Teaching high school");
    comboBox.addItem("None");
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    sportColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = sportColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    class MyTableModel extends AbstractTableModel {
    final String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    final Object[][] data = {
    {"Mary ", "Campione",
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Sharon", "Zakhour",
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Angela", "Lih",
    "Teaching high school", new Integer(4), new Boolean(false)}
    public final Object[] longValues = {"Angela", "Andrews",
    "Teaching high school",
    new Integer(20), Boolean.TRUE};
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col < 2) {
    return false;
    } else {
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    if (data[0][col] instanceof Integer
    && !(value instanceof Integer)) {
    //With JFC/Swing 1.1 and JDK 1.2, we need to create
    //an Integer from the value; otherwise, the column
    //switches to contain Strings. Starting with v 1.3,
    //the table automatically converts value to an Integer,
    //so you only need the code in the 'else' part of this
    //'if' block.
    try {
    data[row][col] = new Integer(value.toString());
    fireTableCellUpdated(row, col);
    } catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(TableRenderDemo.this,
    "The \"" + getColumnName(col)
    + "\" column accepts only integer values.");
    } else {
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[i][j]);
    System.out.println();
    System.out.println("--------------------------");

    http://forum.java.sun.com/faq.jsp#format

  • Adding Canvas3D image to a JPanel or JFrame

    My team has developed a 3D game board and we want to add it to a JPanel. The test code below works fine but we want to add this to a JPanel. Can you put a Canvas3D in a JPanel?
    import java.applet.Applet;
    import java.awt.BorderLayout;
    import java.awt.Frame;
    import java.awt.event.*;
    import com.sun.j3d.utils.applet.MainFrame;
    import com.sun.j3d.utils.universe.*;
    import com.sun.j3d.utils.geometry.*;
    import javax.media.j3d.*;
    import javax.vecmath.*;
    import java.awt.event.*;
    import java.util.Enumeration;
    import com.sun.j3d.utils.behaviors.mouse.*;
    import com.sun.j3d.utils.behaviors.keyboard.*;
    public class ProxyBoard extends Applet
         public class SimpleBehave extends Behavior
              private TransformGroup targetTG;
              private Transform3D rotation = new Transform3D();
              private double angle = 0.0;
              SimpleBehave(TransformGroup targetTG)
                   this.targetTG = targetTG;
              public void initialize()
                   this.wakeupOn(new WakeupOnAWTEvent(KeyEvent.KEY_PRESSED));
              public void processStimulus(Enumeration criteria)
                   angle +=0.05;
                   rotation.rotX(angle);
                   targetTG.setTransform(rotation);
                   this.wakeupOn(new WakeupOnAWTEvent(KeyEvent.KEY_PRESSED));
         public ProxyBoard()
              setLayout(new BorderLayout());
              Canvas3D canvas3D = new Canvas3D(null);
              add("Center", canvas3D);
              SimpleUniverse simpleU = new SimpleUniverse(canvas3D);
              simpleU.getViewingPlatform().setNominalViewingTransform();
              BranchGroup scene = createSceneGraph(simpleU);
              scene.compile();
              simpleU.addBranchGraph(scene);
         public BranchGroup createSceneGraph(SimpleUniverse su)
              BranchGroup boardBG = new BranchGroup();
              TransformGroup vpTrans = null;
              BoundingSphere mouseBounds = null;
              vpTrans = su.getViewingPlatform().getViewPlatformTransform();
              mouseBounds = new BoundingSphere(new Point3d(), 1000.0);
              KeyNavigatorBehavior keyNavBeh = new KeyNavigatorBehavior(vpTrans);
              keyNavBeh.setSchedulingBounds(mouseBounds);
              boardBG.addChild(keyNavBeh);
              MouseRotate myMouseRotate = new MouseRotate(MouseBehavior.INVERT_INPUT);
              myMouseRotate.setTransformGroup(vpTrans);
              myMouseRotate.setSchedulingBounds(mouseBounds);
              boardBG.addChild(myMouseRotate);
              MouseTranslate myMouseTranslate = new MouseTranslate(MouseBehavior.INVERT_INPUT);
              myMouseTranslate.setTransformGroup(vpTrans);
              myMouseTranslate.setSchedulingBounds(mouseBounds);
              boardBG.addChild(myMouseTranslate);
              MouseZoom myMouseZoom = new MouseZoom(MouseBehavior.INVERT_INPUT);
              myMouseZoom.setTransformGroup(vpTrans);
              myMouseZoom.setSchedulingBounds(mouseBounds);
              boardBG.addChild(myMouseZoom);
              Board board = new Board();
              Transform3D pegPositions[] = new Transform3D[8];
              TransformGroup pegPositionsTG[] = new TransformGroup[8];
              Pegs pegs[] = new Pegs[8];
              Transform3D translate = new Transform3D();
              translate.set(new Vector3f(0.0f, -1.0f, -5.0f));
              TransformGroup boardTGT1 = new TransformGroup(translate);
              TransformGroup boardTGR1 = new TransformGroup();
              boardTGR1.setCapability(boardTGR1.ALLOW_TRANSFORM_WRITE);
              for(int i = 0; i < 8; i++)
                   pegs[i] = new Pegs();
                   pegPositions[i] = new Transform3D();
                   pegPositions.set(new Vector3f(-2.5f, 0, (float)(-i/4.0)));
                   pegPositionsTG[i] = new TransformGroup(pegPositions[i]);
                   pegPositionsTG[i].addChild(pegs[i].getTransformGroup());
                   boardTGT1.addChild(pegPositionsTG[i]);               
              boardTGR1.addChild(board.getBoard());
              SimpleBehave myRotate = new SimpleBehave(boardTGR1);
              myRotate.setSchedulingBounds(new BoundingSphere());
              boardBG.addChild(myRotate);
              boardTGT1.addChild(boardTGR1);
              boardBG.addChild(boardTGT1);                    
              boardBG.compile();
              return boardBG;
         public static void main(String[] args)
              Frame frame = new MainFrame(new ProxyBoard(), 800, 600);
    /*-------------Main Source Container------------------*/
    public class Proxy extends JFrame
         implements MouseMotionListener
         private JDesktopPane myDesktop;
         private JPanel panel;
         private JLabel statusBar, position;
         private JSlider zSlide, zSlide1;
         private ImageIcon test;
         private int i;
         public Proxy()
              super("Proxy Board Prototype 1.2.2");
              i=0;
              statusBar = new JLabel();
              getContentPane();
              myDesktop = new JDesktopPane();
              getContentPane().add(myDesktop);
    public static void main(String args[])
              Proxy app = new Proxy();
              //new MainFrame( new Proxy(), 800, 600 );
    //          app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    /*-------------JPanel I want to hold to the 3D Graphics--------*/
    class Session extends JPanel
         implements MouseMotionListener
         private ImageIcon test;
         private JLabel position;
         private JSlider zSlide;
         private JPanel panel, gPanel;
         static int openFrameCount = 0;
         public Session()
              //super("", true, true, true, true);
              setLayout(new FlowLayout());
              openFrameCount++;
         //setTitle("Untitled Message " + openFrameCount);
    ProxyBoard pb = new ProxyBoard();//<-Graphic Class
    gPanel = new JPanel();
    gPanel.add(pb);//<-I want the 3D Graphic here
              test = new ImageIcon("Layout.jpg");
              JLabel pic = new JLabel(test);
              addMouseMotionListener( this );
              zSlide = new JSlider(SwingConstants.VERTICAL, 600, 10);
              zSlide.setMajorTickSpacing(25);
              zSlide.setPaintTicks(true);
              zSlide.setToolTipText("Zoom");
              panel.add(zSlide, BorderLayout.NORTH);
              panel.add(gPanel, BorderLayout.CENTER);//<-Graphic Here
              panel.add(position, BorderLayout.SOUTH);
              add(panel);
              //pack();
              setSize(200,200);
              setVisible (true);

    Yes you can. Just use the add method of JPanel. However note this
    http://www.j3d.org/faq/swing.html (specially read this: http://java.sun.com/products/jfc/tsc/articles/mixing/)
    when mixing Lightweight (JPanel) and Heavyweight (Canvas3D) components.

  • JPanel as TreeCellRenderer not shown

    Hello all,
    I'm experiencing a rather strange problem using a custom JPanel as a TreeCellRenderer for a JTree. Basically I needed to show a JLabel and an JTextArea inside a JScrollPane for each Node in my JTree. So I created a subclass of JPanel, implementing the TreeCellRenderer interface and registered it on the tree. The problem I experience is, that nothing is shown in my tree. Instead of the JPanel and its components I see a white space exactly the size of the JPanel, but no components in it. When I try to add my custom JPanel to a regular other panel, it shows up perfectly. My source code for the renderer looks like this (the text is statically provided at the moment, so each node should display the same amount of information):
    public class XMLTreeCellRenderer extends JPanel implements TreeCellRenderer
        private javax.swing.JLabel jLabel1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextArea jTextArea1;
        private void initComponents()
            jPanel1 = new javax.swing.JPanel();
            jLabel1 = new javax.swing.JLabel();
            jPanel2 = new javax.swing.JPanel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
            jLabel1.setOpaque(true);
            jLabel1.setHorizontalAlignment(SwingConstants.LEFT);
            jLabel1.setVerticalAlignment(SwingConstants.CENTER);
            setLayout(new java.awt.BorderLayout(10, 10));
            setOpaque(true);
            setBackground(new java.awt.Color(255, 255, 255));
            setMinimumSize(new java.awt.Dimension(140, 100));
            jPanel1.setLayout(new java.awt.BorderLayout(10, 10));
            jPanel1.setBackground(new java.awt.Color(255, 255, 255));
            jPanel1.setPreferredSize(new java.awt.Dimension(140, 20));
            jLabel1.setBackground(new java.awt.Color(255, 255, 255));
            jLabel1.setText("Testvalue");
            jPanel1.add(jLabel1, java.awt.BorderLayout.CENTER);
            add(jPanel1, java.awt.BorderLayout.NORTH);
            jPanel2.setLayout(new java.awt.BorderLayout(10, 10));
            jPanel2.setPreferredSize(new java.awt.Dimension(140, 80));
            jScrollPane1.setBorder(new javax.swing.border.EtchedBorder());
            jTextArea1.setEditable(false);
            jTextArea1.setToolTipText("Current Value");
            jScrollPane1.setViewportView(jTextArea1);
            jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER);
            add(jPanel2, java.awt.BorderLayout.CENTER);
            validate();
            repaint();
        public XMLTreeCellRenderer()
            super();
            initComponents();
         * Returns the component that contains a rendered version of this node
         * @see javax.swing.tree.TreeCellRenderer#getTreeCellRendererComponent(javax.swing.JTree, java.lang.Object, boolean, boolean, boolean, int, boolean)
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus)
            LineBorder m_border;
            m_border = new LineBorder(Color.RED, 1, true);
            if (selected)
                setBorder(m_border);
            else
                setBorder(null);
            return this;
    }This is really driving me crazy. If I'm trying to return a simple JLabel, everything works ok, but whenever I want to show the JPanel, nothing happens.
    Thanks in advance for any suggestions,
    Sven

    Hello,
    no, I did not set a preferred size for the border; I did as shown in the code:
            m_border = new LineBorder(Color.RED, 1, true);
            if (selected)
                setBorder(m_border);
            else
                setBorder(null);
            }The only thing that I do is setting a minimum size.
    Sven

  • Switching JPanels

    I've 2 JPanels in a CordLayout.
    When I switch from one JPanel to the other by pressing a JButton some methods a running which take some time.
    I want to add a third JPanel which displays an Image with a "please stand by" text.
    public void actionPerformed(ActionEvent evt) {
    Object src = evt.getSource();
    if (src instanceof JButton) {
    if(src==switch) {
    myCardLayout.show(textContainer,"STANDBY");
    some methods...
    myCardLayout.show(textContainer,"2ndJPanel");
    The Problem is that the changes in the CardLayout are done after the rest of the Action is finished so that there is no visual effect.
    Any ideas?
    Thank you
    J&ouml;rn

    Thank you, but how does this work?
    I tried to define a new Thread as
    public class showWait extends Thread {
    CardLayout textLayout;          
    public showWait(CardLayout tL)
    textLayout=tL;
    public void run()
    textLayout.show(textContainer,"STANDBY");
    public CardLayout getLayout()
    return textLayout;
    and I used this thread in the actionPerformed method:
    showWait sw = new showWait(textLayout);
    sw.run();
    textLayout=sw.getLayout();
    but with this I have not divided the thread into 2 threads...
    So what am I doing wrong?

Maybe you are looking for

  • Has anyone tried to add a Dericam to Time Capsule

    I have a Dericam and I cannot get it to pare with Time Capksule.  I have been in contact with the manufacturer but they haven't been much help.  If anyone has had ant experience withe this product any help would be greatly appreciated.

  • ACE Policy is not working

    Hi, I have ACE 4710 in context mode. I am doing internet browsing (Port 80) redirection to two proxy servers (Transparent Proxy) as well as I am using this ACE box for multiple other servers load balancing. I have multiple policies applied on my LAN

  • FM transmitter and Pandora Radio

    I know that the FM transmitter is intended to work with the iPod on the iPhone but will the FM transmitter work with apps such as Pandora Radio so that I may listen in the car without the use of headphones.

  • Need to reinstall Itunes to import from CD??

    After installing latest v ITunes it looks to install ok. However when launching I get shown in order to import from CD I need to reinstall ITunes. I have tried several times, tried the hints on the Apple website but none of them work.... Any ideas it

  • Failing dock connection?

    This problem seems obvious enough, but I figured it wouldn't hurt to ask around and see if there are people out there with similar experiences. I have a 80GB iPod Classic. It gets connected and disconnected to a dock connection multiple times a day: