Multiple jpanels?

Hi, I want to draw some graphs of some data that will be controlled by an array of doubles, basically representing the array of doubles as a graph. The question I have is that I will have 5 different graphs all the same type just different runs, is there a way to put a button that can fire an event to put up the next graph, like say each graph is in a jpanel and have 5 jpanels in a jframe and then when the button is pushed the current panel is hidden and the next one is shown? Am I thinking about this right? what is the best way to do what I want to do? the graph should take up the whole window except for a little bit of room for a button to browse back and forward.
Thanks

Try using java.awt.CardLayout for your JFrame's content pane. That should solve your problem.
Sai Pullabhotla

Similar Messages

  • How do I add multiple JPanels to a JFrame?

    I've been trying to do my own little side project to just make something for me and my friends. However, I can't get multiple JPanels to display in one JFrame. If I add more than one JPanel, nothing shows up in the frame. I've tried with SpringLayout, FlowLayout, GridBagLayout, and whatever the default layout for JFrames is. Here is the code that's important:
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import javax.swing.*;
    public class CharSheetMain {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              CharSheetFrame frame=new CharSheetFrame();
              abilityPanel aPanel=new abilityPanel();
              descripPanel dPanel=new descripPanel();
              frame.setLayout(new FlowLayout());
              abilityScore st=new abilityScore();
              abilityScore de=new abilityScore();
              abilityScore co=new abilityScore();
              abilityScore in=new abilityScore();
              abilityScore wi=new abilityScore();
              abilityScore ch=new abilityScore();
              frame.add(aPanel);
              frame.add(dPanel);
              frame.validate();
              frame.repaint();
              frame.pack();
              frame.setVisible(true);
    }aPanel and dPanel both extend JPanel. frame extends JFrame. I can get either aPanel or dPanel to show up, but not both at the same time. Can someone tell me what I'm doing wrong?

    In the future, Swing related questions should be posted in the Swing forum.
    You need to read up on [How to Use Layout Managers|http://download.oracle.com/javase/tutorial/uiswing/layout/index.html]. The tutorial has working example of how to use each layout manager.
    By default the content pane of the frame uses a BorderLayout.
    For more help create a [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://sscce.org], that demonstrates the incorrect behaviour.
    The code you posted in NOT a SSCCE, since we don't have access to any of your custom classes. To do simple tests of adding a panel to frame then just create a panel, give it a preferred size and give each panel a different background color so you can see how it works with your choosen layout manager.

  • Multiple JPanels on top of each all receiving mouse events

    I have multiple JPanels that are painted on top of each other. Each one has mouse listeners that listen for mouse enters, exits, etc. However, it appears that Swing is only propagating the mouse events for the most visible panel (the one that is on top of all of the others). Is there a way to configure Swing in such a way that all JPanels on the screen will get the mouse events, even if they aren't entirely visible on the screen?
    Thanks,
    -- Ryan

    Hi,
    You can implement mouse listener for panel and you can identify buttons in the panel with the mouse event of panel using MouseEvent.getComponentAt(MouseEvent.getPoint()) instanceof JButton or not.
    I hope this will help,
    Kishore.

  • Simple FocusTraversalPolicy (multiple JPanels)

    I've seen quite a few posts on this topic, so I thought I'd share my own simple solution. It solves the problem of the tab order when you have multiple JPanels and want to enforce a specific tab order.
    class MyFocusTraversalPolicy extends FocusTraversalPolicy {
        Vector components;
        public MyFocusTraversalPolicy(Vector components) {
            this.components = components;
        public Component getComponentAfter(Container root, Component comp) {
            int ix = components.indexOf(comp) + 1;
            Component c;
            if(ix >= components.size())
                c = getFirstComponent(root);
            else
                c = (Component)components.get(ix);
            return c.isEnabled() ? c : getComponentAfter(root, c);
        public Component getComponentBefore(Container root, Component comp) {
            int ix = components.indexOf(comp) - 1;
            Component c;
            if(ix < 0)
                c = getLastComponent(root);
            else
                c = (Component)components.get(ix);
            return c.isEnabled() ? c : getComponentBefore(root, c);
        public Component getDefaultComponent(Container root) {
            return (Component)components.get(0);
        public Component getFirstComponent(Container root) {
            return (Component)components.get(0);
        public Component getLastComponent(Container root) {
            return (Component)components.get(components.size() - 1);
    }Create the Swing components as usual, add the components to a vector, in the order you want them to be tabbed:
    Vector comps = new Vector();
    comps.add(textField1);
    comps.add(comoboBox1);
    comps.add(((JSpinner.DefaultEditor)spinner1.getEditor()).getTextField()); 
    MyFocusTraversalPolicy policy = new MyFocusTraversalPolicy(comps);
    setFocusTraversalPolicy(policy);Note how the JSpinner component is added. This works fine with tabbing forwards and backwards; skips disabled components as expected.

    Hi AikoMuto,
    I want to traverse focus among some components(not all the components)
    lie in multiple panels which are in different classes. Following is my
    class structure.
    Class Test extends JPanel{
    PanelA panelA;
    PanelB panelB;
    PanelC panelC;
    public void jbInit()
    Vector comps = new Vector();
    comps.add(panelA.fieldA);
    comps.add(panelB.fieldB);
    for(int i=0;i<panelC.buttons.length;i++){
    comps.add(panelC.buttons);
    MyFocusTraversalPolicy policy = new MyFocusTraversalPolicy(comps);
    setFocusTraversalPolicy(policy);
    Class PanelA extends JPanel{
    JTextField fieldA;
    JScrollbar scrollA;
    Class PanelB extends JPanel{
    JTextField fieldB;
    JScrollbar scrollB;
    Class PanelC extends JPanel{
    JButton[] buttons;
    I want to traverse focus among fieldA -> fieldB -> buttons[0]
    -> buttons[1] -> ................ -> buttons[buttons.length -1].
    I used your code and checked whether it's working for my example. Setting traversal policy is done in parent panel i.e. in Test class. But
    unfortunately it doesn't capture both Tab and Tab+Shift keys. I
    debugged the code and found that it doesn't call either of
    getComponentAfter() or getComponentBefore() methods for above key
    events.
    I guess your code is not working as the panels are in different classes.
    Could you please help me to get this done?
    Thanks & Regards

  • Best recommendataion to work with one JFrame & Multiple Jpanels(or Windows)

    Hi all,
    I am a bit new(bie) to Java and Gui but not new to programming.
    I need to write an application in using Java. The Current editor I use is Netbeans.
    I have a rough idea on how to write this apps, but I would like to confirm if my idea is applicable to such application (from a performance and feasibility standpoint).
    The main idea for this application is to have multiple forms that users would populate, and the values entered will be stored in a Database.
    I had plan to use only one main Window (JFrame), and no MDI, no multiple Java windows.
    My plan was:
    -     Create the main form (JFrame) with menus, once the application is loaded, I will check if a database connection is available otherwise open a Jpanel to input database settings (which can be started from the menu).
    -     All menus and application/company settings would be set in the main form
    -     All features available in the Jpanel would be in a separate class for clarity/lisibility of my code. For instance : user settings would be a separate jpanel class; database settings is a new jpanel class
    -     Each Jpanel class would be stored in a separate java/class file.
    Here is my test example for now (file MainForm.java) :
    import javax.swing.*;
    public class MainForm extends JFrame {
        /* Initializing a few variables */
        String databaseServer = null;
        String databaseUserName = null;
        String databasePassword = null;
        /** Creates new form MainForm */
        public MainForm() {
            /* Initializing menus */
            initComponents();
           /* starting a new instance of database configuration */
            DbPanel test = new DbPanel();
        /* Initialization menu and graphical components */
        private void initComponents () {
            JMenuBar BarMenu;
            JMenu MenuConfiguration;
    /* �.*/
         BarMenu.add(MenuConfiguration);
         setJMenuBar(BarMenu);
         pack();
         * @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);
    } Here is my DBpanel class (file MainForm.java) :
    public class DbPanel extends javax.swing.JPanel {
        /** Creates new form DbPanel */
        public DbPanel() {
            initComponents();
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            java.awt.Button buttonClose;
            java.awt.Button buttonSave;
            java.awt.TextField dbName;
    /* � */
           gridBagConstraints.ipadx = 100;
            gridBagConstraints.insets = new java.awt.Insets(0, 21, 0, 21);
            add(dbPassword, gridBagConstraints);
    // </editor-fold>   
    }Here are then my questions:
    -     Would you think that is a practical plan to write such application?
    -     Once I display a Jpanel form and I close it (for instance myJpanel.setVisible=false), will the memory be freed?
    -     Is there any other way to remove entire a JPanel from RAM?
    -     How can I call my �external� Jpanel ? I have designed one Jpanel class for testing but I was not able to display it when I created the new instance of that class.
    -     Is there any other alternative to Jpanel for this application? I was thinking about opening a new window within my Jframe. But, ideally it would be best that multiple windows are not opened simultaneously.
    Thanks for your input

    I was thinking about this but requirements are the
    application development cost should be reduced to the
    minimum.
    thus one desktop application and one database
    server.Application development cost? If you are being paid to do this, the bulk of the cost will be your hourly rate times the number of hours it takes you to do it. Thus you want to minimize the number of hours it takes you to do it. Assuming that the cost of your learning Java is going to be charged to this project, it might well be a good idea for you to do it in a language you already know. Or one where it's easy to develop this sort of application.

  • 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

  • Unable to insert multiple JPanels  to JScrolPane

    hi, i've got a problem with the following code:
    private void fillComponents(JScrollPane thumbnailPanel, final List<Slide> list) {
            //thumbnailScrollPanel.set
            JSeparator separator = new JSeparator(SwingConstants.HORIZONTAL);
            separator.setSize(thumbnailPanel.getWidth(),8);
            separator.setVisible(true);
            JLabel label = null;
            for(Iterator<Slide> it = list.iterator();it.hasNext();){
                Slide val = it.next();
                //thumbnailPanel.getViewport().add(separator);
                thumbnailPanel.add(separator);
                SlideImageLoader sldim = new SlideImageLoader(val,thumbnailPanel.getWidth()-3, (int)(0.75*thumbnailPanel.getWidth()));
                sldim.addMouseListener(new java.awt.event.MouseListener() {
                    public void mouseClicked(MouseEvent e) {
                        if(e.getButton() == MouseEvent.BUTTON1){
                            int slideNo = ((SlideImageLoader)e.getSource()).getSlideNumber();
                            slidePanel.removeAll();
                            slidePanel.updateUI();
                            slidePanel.add(new SlideImageLoader(list.get(slideNo-1), slidePanel.getWidth(), slidePanel.getHeight()));
                            Navigator.setCurrentSlideNumber(slideNo-1);
                            userEnteredSlideNumber.setText(String.valueOf(slideNo));
                    public void mousePressed(MouseEvent e) {
                        //throw new UnsupportedOperationException("Not supported yet.");
                    public void mouseReleased(MouseEvent e) {
                        //throw new UnsupportedOperationException("Not supported yet.");
                    public void mouseEntered(MouseEvent e) {
                        //throw new UnsupportedOperationException("Not supported yet.");
                    public void mouseExited(MouseEvent e) {
                        //throw new UnsupportedOperationException("Not supported yet.");
                //thumbnailPanel.getViewport().add(sldim);
                thumbnailScrollPanel.add(sldim);
                label = new JLabel(String.valueOf(val.getId()));
                label.setVisible(true);
                label.setSize(thumbnailPanel.getWidth(), getFont().getSize());          
                thumbnailPanel.add(label);
                thumbnailPanel.add(separator);
                //thumbnailPanel.getViewport().add(label);
                //thumbnailPanel.getViewport().add(separator);
                //thumbnailPanel.updateUI();
        }and what i intended to achieve was to put components in the scrollpane one under another in a sequence:
    separator, panel, label, separator, panel, label,....., but components are added one on another and i see only the first one added ;/.
    the panel i'm adding to the scrollpane containts an Image, so it basically is a scrollable thumbnails viewer.
    any help appreciated. i've tried all managers, i even added another panel to the scrollpane but then every component was followed by a blank space equals to it's size and slider didn't show up. thanks in advance. cheers

    the code of the panel class:
    package logic;
    import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.io.File;
    import java.net.MalformedURLException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.ImageIcon;
    import javax.swing.JPanel;
    import schema.xsd.lecturedata.Slide;
    public class SlideImageLoader extends JPanel {
        Slide slide = null;
        //private transient final String  resources = "resources/";
        String path = null;
        //BigInteger id;
        int height;
        int width;
        int scallMethod = Image.SCALE_SMOOTH;
        Image img;
        public SlideImageLoader(Slide slide, int width, int height) {
            this.slide = slide;
            this.path = slide.getPath();
            this.width = width;
            this.height = height;       
            this.setBounds(0, 0, width, height);
            setLayout(new BorderLayout());
            img = getScaledImage();
        private Image getScaledImage(){
            File url = new File(path);
            System.out.println(path);
            System.out.println(url);      
            ImageIcon imaicon = null;
            try {
                imaicon = new ImageIcon(url.toURI().toURL());
            } catch (MalformedURLException ex) {
                Logger.getLogger(SlideImageLoader.class.getName()).log(Level.SEVERE, null, ex);
           return imaicon.getImage().getScaledInstance(width, height, scallMethod);
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            int x = 0;
            int y = 0;
            g.drawImage(img, x, y, this);
        public int getSlideNumber(){
            return Integer.valueOf(slide.getId().toString());
    }

  • Beginners Questions about Multiple JPanels in JFrame and event handling

    I am a newbie with SWING, and even a newerbie in Event Handling. So here goes.
    I am writing a maze program. I am placing a maze JPanel (MazePanel) at the center of a JFrame, and a JPanel of buttons (ButtonPanel) on the SOUTH pane. I want the buttons to be able to re-randomize the maze, solve the maze, and also ouput statistics (for percolation theory purposes). I have the backbone all done already, I am just creating the GUI now. I am just figuring out EventHandlers and such through the tutorials, but I have a question. I am adding an ActionListener to the buttons which are on the ButtonPanel which are on JFrame (SOUTH) Panel. But who do I make the ActionListener--Basically the one doing the work when the button is pressed. Do I make the JFrame the ActionListener or the MazePanel the ActionListener. I need something which has access to the maze data (the backbone), and which can call the Maze.randomize() function. I'm trying to make a good design and not just slop too.
    Also I was wondering if I do this
    JButton.addActionListener(MazePanel), and lets say public MazePanel implments ActionListenerdoesn't adding this whole big object to another object (namely the button actionlistener) seem really inefficient? And how does something that is nested in a JPanel on JFrame x get information from something nested in another JPanel on a JFrame x.
    Basically how is the Buttons going to talk to the maze when the maze is so far away?

    I'm not an expert, but here's what I'd do....
    You already have your business logic (the Maze classes), you said. I'm assuming you have some kind of public interface to this business logic. I would create a new class like "MazeGui" that extends JFrame, and then create the GUI using this class. Add buttons and panels as needed to get it to look the way you want. Then for each button that does a specific thing, add an anonymous ActionListener class to it and put whatever code you need inside the ActionListener that accesses the business logic classes and does what it needs to.
    This is the idea, though my code is totally unchecked and won't compile:
    import deadseasquirrels.mazestuff.*;
    public class MazeGui extends JFrame {
      JPanel buttonPanel = new JPanel();
      JPanel mazePanel = new JPanel();
      JButton randomizeB = new JButton();
      JButton solveB = new JButton();
      JButton statsB = new JButton();
      // create instanc(es) of your Maze business logic class(es)
      myMaze = new MazeClass();
      // add the components to the MazeGui content pane
      Component cp = getContentPane();
      cp.add(); // this doesn't do anything, but in your code you'd add
                // all of your components to the MazeGui's contentpane
      randomizeB.addActionListener(new ActionListener {
        void actionPerformed() {
          Maze newMaze = myMaze.getRandomMazeLayout();
          mazePanel.setContents(newMaze); // this is not a real method!
                                          // it's just to give you the idea
                                          // of how to manipulate the JPanel
                                          // representing your Maze diagram,
                                          // you will probably be changing a
                                          // subcomponent of the JPanel
      solveB.addActionListener(new ActionListener {
        void actionPerformed() {
          Solution mySolution = myMaze.getSolution();
          mazePanel.setContents(mySolution); // again, this is not a real
                                             // method but it shows you how
                                             // the ActionListener can
                                             // access your GUI
      // repeat with any other buttons you need
      public static void main(String[] args) {
        MazeGui mg = new MazeGui();
        mg.setVisible(true);
        // etc...
    }

  • Problems sizing multiple JPanels.

    I'm writing a survey program that needs to be formatted to a certain size. I'm using calls to panel.setsize( ) to set the size to 800 x 600.
    I have nine JPanels as globals, all of which are created and "packed" initially. These JPanels are supposed to display in a global JFrame, one at a time. After each "next button" click I call frame.remove(panel) to remove the current panel and frame.add(panel) to add the next. Then I call pack again.
    Everything works fine until looping from the final panel to the first. Upon doing so all of the elements in the JPanel disappear, (although hovering over the invisible elements makes them reappear.)
    Is there anything I'm doing wrong?

    Well, calling repaint after pack seemed to solve the problem.
    Does anyone care to provide insight as to why?
    Thanks.

  • Events across multiple JPanels

    Hello, I'm returning to programming after an absence and appreciate the assistance. Here's my application and challenge:
    I'm creating an application that animates an object based upon a number of factors (a mathematical function like the sin curve and a number of variables that impact its x and y coordinates).
    The application is composed of
    1) A JFrame, instantiated by the application's main class. This JFrame instantiates the next 2 panel components:
    2) A JPanel that contains input components that change the variables impacting the animation (sliders, buttons, checkboxes, etc)
    3) A JPanel subclass implementing runnable, managing the animation.
    My challenge is the event model.
    How do I notify the animation panel when events around variable changes are happening in the input panel? The application runs fine when I pack it all into one panel, but that won't allow me to scale.
    (What would be even nicer, would be my ability to make the sub-classed JPanel usable in the NetBeans UI, but I don't want to press my luck)
    The help is greatly appreciated!
    Russell

    growing_my_skills wrote:
    Hello, I'm returning to programming after an absence and appreciate the assistance. Here's my application and challenge:
    I'm creating an application that animates an object based upon a number of factors (a mathematical function like the sin curve and a number of variables that impact its x and y coordinates).
    The application is composed of
    1) A JFrame, instantiated by the application's main class. This JFrame instantiates the next 2 panel components:
    2) A JPanel that contains input components that change the variables impacting the animation (sliders, buttons, checkboxes, etc)
    3) A JPanel subclass implementing runnable, managing the animation.
    My challenge is the event model.
    How do I notify the animation panel when events around variable changes are happening in the input panel? The application runs fine when I pack it all into one panel, but that won't allow me to scale.
    - Group the properties to some input classes,
    - define events in the input panel
    - fire the according event if a property of a input class changes
    - listen in the parent (mediator)
    - send the updated information to the animation panel
    (What would be even nicer, would be my ability to make the sub-classed JPanel usable in the NetBeans UI, but I don't want to press my luck)
    If you mean the NetBeans Platform, then you could place each panel in a separate TopComponent and pass the information via the Lookup.
    -Puce

  • Drawing  Vector Data on Multiple JPanels

    Hi,
    Iam having some data in a vector which i wanted to draw on multiple panels.for example if there are 100 elements in vector i wanted to draw first 10 elements in panel 1,next 10 emenets in panel 2 etc.
    I created 10 panels and iam able to display first 10 elements on the first panel.But iam not able to draw the next 10 elements on the 2nd Panel.
    How can i do this.Anybody has any idea?Pls help me
    Thanks in Advance.
    Regards,
    virgo..

    Post your non working code, so we can see where it goes wrong.

  • Multiple JPanels, Single ActionListener?

    Hey all,
    This is more of a "proper design/software engineering" question. I'm a Swing noob, but I have made a nice little GUI consisting of several seperate extended/customized JPanel classes combined into a single Frame. This was done to reduce the lines of code in the main JPanel/Frame (i.e. seperating out all the Layout stuff and Component stuff, etc...). So if I have some buttons in a seperate JPanel, am I able to/what is the best way to have tie them to the ActionListener in the main JPanel class?
    Thanks!

    several options here, mostly stylistic...
    You can prodive an accessor method in your frame to the ActionListener
    If the frame itself is the listener, you can just say ...
    //in JFrame class
    MyPanel newPanel = new MyPanel();
    newPanel.addActionListener(this);really, there options are almost endless... you asked for the 'best' way, but that really is variable according to the overall design of your application. Do what feels the most natural to you.

  • AddMouseListener disable events of bottom multiple non opaque JPanel

    Hi fellow developpers..
    I'm creating an application in which I'm using a JPanel containing multiple JPanel ( a layered system ) with some components laid on them. Everything works fine, events are properly traversing non opaque multiple JPanel, and I can access components of bottom most to top most JPanels.
    But when I'm adding MouseListeners on my non opaque JPanels, mouse events are no more going through them, only the top most one is receiving events.. my JPanels are still non opaque because I can see through them but mouse events are working as if they were opaque.
    Is there a trick to catch mouse events on non opaque JPanel without blocking event traversing ?
    Alexis.

    How about this?
             final ListView<Node> fileList = new ListView<Node>();
            fileList.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
                @Override
                public void changed(ObservableValue<? extends Number> observableValue, Number oldv, Number newv) {
                    if (newv.intValue() == 4) {
                        fileList.getSelectionModel().select(oldv.intValue());
            });

  • How to give Common Background color for all JPanels in My Swing application

    Hi All,
    I am developing a swing application using The Swing Application Framework(SAF)(JSR 296). I this application i have multiple JPanel's embedded in a JTabbedPane. In this way i have three JTabbedPane embedded in a JFrame.
    Now is there any way to set a common background color for the all the JPanel's available in the application??
    I have tried using UIManager.put("Panel.background",new Color.PINK);. But it did not work.
    Also let me know if SAF has some inbuilt method or way to do this.
    Your inputs are valuable.
    Thanks in Advance,
    Nishanth.C

    It is not the fault of NetBeans' GUI builder, JPanels are opaque by default, I mean whether you use Netbeans or not.Thank you!
    I stand corrected (which is short for +"I jumped red-eyed on my feet and rushed to create an SSCCE to demonstrate that JPanels are... mmm... oh well, they are opaque by default... ;-[]"+)
    NetBeans's definitely innocent then, and indeed using it would be an advantage (ctrl-click all JPanels in a form and edit the common opaque property to false) over manually coding
    To handle this it would be better idea to make a subclass of JPanel and override isOpaque() to return false. Then use this 'Trasparent Panel' for all the panels where ever transparency is required.I beg to differ. From a design standpoint, I'd find it terrible (in the pejorative sense of the word) to design a subclass to inconsistently override a getter whereas the standard API already exposes the property (both get and set) for what it's meant: specify whether the panel is opaque.
    Leveraging this subclass would mean changing all lines where a would-be-transparent JPanel is currently instantiated, and instantiate the subclass instead.
    If you're editing all such lines anyway, you might as well change the explicit new JPanel() for a call to a factory method createTransparentJPanel(); this latter could, at the programmer's discretion, implement transparency whichever way makes the programmer's life easier (subclass if he pleases, although that makes me shudder, or simply call thePanel.setOpaque(false) before returning the panel). That way the "transparency" code is centralized in a single easy to maintain location.
    I had to read the code for that latter's UI classes to find out the keys to use (+Panel.background+, Label.foreground, etc.), as I happened to not find this info in an authoritative document - I see that you seem to know thoses keys, may I ask you where you got them from?
    One of best utilities I got from this forum, written by camickr makes getting these keys and their values very easy. You can get it from his blog [(->link)|http://tips4java.wordpress.com/2008/10/09/uimanager-defaults/]
    Definitely. I bit a pair of knucles off when discovered it monthes after cumbersomely traversing the BasicL&F code...
    Still, it is a matter-of-fact approach (and this time I don't mean that to sound pejorative), that works if you can test the result for a given JDK version and L&F, but doesn't guarantee that these keys are there to stand - an observation, but not a specification.
    Thanks TBM for highlighting this blog entry, that's the best keys list device I have found so far, but the questions still holds as to what specifies the keys.
    Edited by: jduprez on Feb 15, 2010 10:07 AM

  • How do we print multiple components each in a different page?

    hello
    I would like to print multiple JPanels (lets say an array) each in a different page.
    The question I ask is about the following code
             printerJob.setPrintable(printTable.getInstance(), pageFormat);
                  try
                        if (printerJob.printDialog())
                             printerJob.print();
                        }

    Lets say that we have the following code. How do we modify it?
    * This example is from the book "Java Foundation Classes in a Nutshell".
    * Written by David Flanagan. Copyright (c) 1999 by O'Reilly & Associates. 
    * You may distribute this source code for non-commercial purposes only.
    * You may study, modify, and use this example for any purpose, as long as
    * this notice is retained.  Note that this example is provided "as is",
    * WITHOUT WARRANTY of any kind either expressed or implied.
    import java.awt.*;
    import java.awt.print.*;
    import java.io.*;
    import java.util.Vector;
    public class PageableText implements Pageable, Printable {
      // Constants for font name, size, style and line spacing
      public static String FONTFAMILY = "Monospaced";
      public static int FONTSIZE = 10;
      public static int FONTSTYLE = Font.PLAIN;
      public static float LINESPACEFACTOR = 1.1f;
      PageFormat format;   // The page size, margins, and orientation
      Vector lines;        // The text to be printed, broken into lines
      Font font;           // The font to print with
      int linespacing;     // How much space between lines
      int linesPerPage;    // How many lines fit on a page
      int numPages;        // How many pages required to print all lines
      int baseline = -1;   // The baseline position of the font.
      /** Create a PageableText object for a string of text */
      public PageableText(String text, PageFormat format) throws IOException {
        this(new StringReader(text), format);
      /** Create a PageableText object for a file of text */
      public PageableText(File file, PageFormat format) throws IOException {
        this(new FileReader(file), format);
      /** Create a PageableText object for a stream of text */
      public PageableText(Reader stream, PageFormat format) throws IOException {
        this.format = format;
        // First, read all the text, breaking it into lines.
        // This code ignores tabs, and does not wrap long lines.
        BufferedReader in = new BufferedReader(stream);
        lines = new Vector();
        String line;
        while((line = in.readLine()) != null)
          lines.addElement(line);
        // Create the font we will use, and compute spacing between lines
        font = new Font(FONTFAMILY, FONTSTYLE, FONTSIZE);
        linespacing = (int) (FONTSIZE * LINESPACEFACTOR);
        // Figure out how many lines per page, and how many pages
        linesPerPage = (int)Math.floor(format.getImageableHeight()/linespacing);
        numPages = (lines.size()-1)/linesPerPage + 1;
      // These are the methods of the Pageable interface.
      // Note that the getPrintable() method returns this object, which means
      // that this class must also implement the Printable interface.
      public int getNumberOfPages() { return numPages; }
      public PageFormat getPageFormat(int pagenum) { return format; }
      public Printable getPrintable(int pagenum) { return this; }
       * This is the print() method of the Printable interface.
       * It does most of the printing work.
      public int print(Graphics g, PageFormat format, int pagenum) {
        // Tell the PrinterJob if the page number is not a legal one.
        if ((pagenum < 0) | (pagenum >= numPages))
          return NO_SUCH_PAGE;
        // First time we're called, figure out the baseline for our font.
        // We couldn't do this earlier because we needed a Graphics object
        if (baseline == -1) {
          FontMetrics fm = g.getFontMetrics(font);
          baseline = fm.getAscent();
        // Clear the background to white.  This shouldn't be necessary, but is
        // required on some systems to workaround an implementation bug
        g.setColor(Color.white);
        g.fillRect((int)format.getImageableX(), (int)format.getImageableY(),
                   (int)format.getImageableWidth(),
                   (int)format.getImageableHeight());
        // Set the font and the color we will be drawing with.
        // Note that you cannot assume that black is the default color!
        g.setFont(font);
        g.setColor(Color.black);
        // Figure out which lines of text we will print on this page
        int startLine = pagenum * linesPerPage;
        int endLine = startLine + linesPerPage - 1;
        if (endLine >= lines.size())
          endLine = lines.size()-1;
        // Compute the position on the page of the first line.
        int x0 = (int) format.getImageableX();
        int y0 = (int) format.getImageableY() + baseline;
        // Loop through the lines, drawing them all to the page.
        for(int i=startLine; i <= endLine; i++) {
          // Get the line
          String line = (String)lines.elementAt(i);
          // Draw the line.
          // We use the integer version of drawString(), not the Java 2D
          // version that uses floating-point coordinates. A bug in early
          // Java2 implementations prevents the Java 2D version from working.
          if (line.length() > 0)
            g.drawString(line, x0, y0);
          // Move down the page for the next line.
          y0 += linespacing; 
        // Tell the PrinterJob that we successfully printed the page.
        return PAGE_EXISTS;
       * This is a test program that demonstrates the use of PageableText
      public static void main(String[] args) throws IOException, PrinterException {
        // Get the PrinterJob object that coordinates everything
        PrinterJob job = PrinterJob.getPrinterJob();
        // Get the default page format, then ask the user to customize it.
        PageFormat format = job.pageDialog(job.defaultPage());
        // Create PageableText object, and tell the PrinterJob about it
        job.setPageable(new PageableText(new File("file.txt"), format));
        // Ask the user to select a printer, etc., and if not canceled, print!
        if (job.printDialog())
             job.print();
    }thank you in advance

Maybe you are looking for

  • ITunes accepts password for initial login but not for Match, account information or automatic downloads

    Hello all, I have an iMac with 2.0 Ghz core duo running Snow Leopard 10.6.8 and the latest iTunes 10.5.1.  iTunes will accept my initial login for purchases and access to the iTunes Store.  But if I attempt to access my account information, enable au

  • HT204053 Can I merge two Apple ID accounts

    I have two Apple IDs, just cos I didn't really understand what I was doing when I set the first one up years ago and now I have two. Some purchases are on one and some are on the other. It also gets confusing with iCloud. Is it possible to merge the

  • How to find out the locale setting in a browser?

    In my Java web project, the multi-lingual issue on the JSP pages is handled by JSTL. It works fine so far for any input messages. However, some messages come from the container. It is needed to find out the browser's country and language settings ins

  • Very Poor CDMA coverage - Downtown Sterling, MA

    Hoping a VZW rep can help, I'm fed up with VZW even as it is an otherwise flawless carrier. My home in Sterling, MA is located between two towers and nothing I do seems to help with calls.  They're dropping, spotty, and my phone is utterly unreliable

  • Horizontal menu bar height and formating

    I'm trying to put a horizontal menu bar into a table cell that's 507px wide by 21px high. I've run into two issues. First, adding a Spry MenuBar to this cell causes it to grow by 1px in height and thus throwing off all of my graphics in other cells.