Swing sizing woes

A JList in a scrollpane, placed in "Center" in a BorderLayout is taking only about half of the available space, obscuring much of the JList. I want to have the scrollpane fit to the available size, which isn't even something I've had to think about before.
This has baffled me for some hours now, and I've tried forcing it to size by using setSize() for the scrollpane as well as the JPanel it sits in. I've also tried every variation of revalidate/pack/doLayout/repaint for the JFrame, but I still get a tiny Jscrollpane.
My previous version of this drew itself fine but I have to change the code to allow for better data handling.
Please help if you see what I am missing.class MainFrame extends JFrame implements Constants
  //instance variables
  Dimension viewport = new Dimension(840,160);
  public static final int WIDTH = 850;
  public static final int HEIGHT = 300;
  MainFrame(TheTableModel model)
   //stuff
    setSize(WIDTH,HEIGHT);
    cp = this.getContentPane();
    cp.setLayout(new BorderLayout());
    northP = new JPanel();
    cp.add(northP,"North");
    southP = new JPanel();
    cp.add(southP,"South");
    tp = new TablePanel(model);
    tp.setSize(viewport);
    cp.add(tp,"Center");
    //some buttons
    //pack();
    //validate();
    //doLayout();
    setVisible(true);

Here's something odd:
when I replacecp.add(tp,"Center"); withcp.add(new JButton("this")); the button takes up all the space as expected. BUT, when I convert the JPanel tp to a JButton, like so:TablePanel(TheTableModel tm)
   allRecs = tm.allRecs;
    this.tm = tm;
    jl = new JList(tm);
    renderer = new TabListCellRenderer();
    renderer.setTabs(new int[] {40,140,240,340,440,540,640,740});
    jl.setCellRenderer(renderer);
    jl.setSelectionMode(
              ListSelectionModel.SINGLE_SELECTION);
    jl.addListSelectionListener(new
      ListSelectionListener()
        public void valueChanged(ListSelectionEvent e)
          Object select;//=(String)"objectString";
          if(!e.getValueIsAdjusting())
            select =jl.getSelectedValue();
    JScrollPane jsp = new JScrollPane(jl);
    add(new JButton("that"));
  } I get a small Jbutton when I add the tp object to the contentPane, as in my original post, with cp.add(tp,"Center").
Is that odd, or what? Why are the buttons different sizes, and how can I make the JPanel contents take up the appropriate space in the BorderLayout?

Similar Messages

  • Woes against Swing event handling.

    Hi,
    I understand that JComboBox fired itemStateChange event whenever the list item is being selected/deselected. This includes user manually select an item using a mouse click, or setSelectedItem() method being called.
    How do I prevent the event being fired whenever the item is being selected PROGRAMMATICALLY using setSelectedItem() ?
    There is a lot of times where I don't want the event to be fired whenever the component is being changed programmatically, but only fired if the component is being changed by the user interface.
    How do I do this?
    Regards,
    Thomas.

    You declare a boolean variable "programIsChangingCombo" and initialize it to false. When your program changes the combo box's selection, it should first set that variable to true and afterwards set it back to false. Then, your listener should examine the variable and bypass its regular code if the variable is true.

  • Listen for an events for Swing objects in a separate class?

    Hi all, sorry if this is in the wrong section of the forum but since this is a problem I am having with a Swing based project I thought i'd come here for help. Essentially i have nested panels in separate classes for the sake of clarity and to follow the ideas of OO based development. I have JPanels that have buttons and other components that will trigger events. I wish for these events to effect other panels, in the Hierachy of my program:
    MainFrame(MainPanel(LeftPanel, RightPanel, CanvasPanel))
    Sorry I couldnt indent to show the hierarchy. Here LeftPanel, RightPanel and CanvasPanel are objects that are created in the MainPanel. For example i want an event to trigger a method in another class e.g. LeftPanel has a button that will call a method in CanvasPanel. I have tried creating an EventListner in the MainPanel that would determine the source and then send off a method to the relevant class, but the only listeners that respond are the ones relevant to the components of class. Can I have events that will be listened to over the complete scope of the program? or is there another way to have a component that can call a method in the class that as an object, it has been created in.
    Just as an example LeftPanel has a component to select the paint tool (its a simple drawing program) that will change a color attribute in the CanvasPanel object. Of course I realize i could have one massive Class with everything declared in it, but I'd rather learn if it is possible to do it this way!
    Thanks in advance for any help you can offer
    Lawrence
    Edited by: insertjokehere on Apr 15, 2008 12:24 PM

    Thanks for the response, ive added ActionListneres in the class where the component is, and in an external class. The Listeners work inside the class, but not in the external class
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    public class LeftPanel extends JPanel implements ActionListener {  
        /* Constructing JButtons, null until usage of the constructor */
        JButton pencilBut;
        JButton eraserBut;
        JButton textBut;
        JButton copyBut;
        JButton ssincBut;
        JButton ssdecBut;
        ActionListener a = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.print("\nNot supported yet.");
        /* The Top Panel contains the title of program */
        public LeftPanel(Dimension d){
            /* Sets up the layout for the Panel */
            BoxLayout blo = new BoxLayout(this,BoxLayout.Y_AXIS);
            this.setLayout(blo);
            /* Sets Up the Appearance of the Panel */
            this.setMinimumSize(d);
            this.setBackground(Color.RED);
            this.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
            /* Pencil Tool */
            pencilBut = new JButton("Pencil");
            pencilBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            pencilBut.setActionCommand("pencil");
            pencilBut.addActionListener(a);
            this.add(pencilBut);
            /* Eraser Tool */
            eraserBut = new JButton("Eraser");
            eraserBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            eraserBut.addActionListener(a);
            this.add(eraserBut);
            /* Text Tool */
            textBut = new JButton("Text");
            textBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            textBut.addActionListener(a);
            this.add(textBut);
            /* Copy Previous Page */
            copyBut = new JButton("Copy Page");
            copyBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            copyBut.addActionListener(a);
            this.add(copyBut);
            /* Stroke Size Increase */
            ssincBut = new JButton("Inc");
            ssincBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            ssincBut.addActionListener(a);
            this.add(ssincBut);
            /* Stroke Size Decrease */
            ssdecBut = new JButton("Dec");
            ssdecBut.setAlignmentX(Component.CENTER_ALIGNMENT);
            ssdecBut.addActionListener(a);
            this.add(ssdecBut);
            System.out.print("\nLeftPanel Completed");
        public void actionPerformed(ActionEvent e) {
            System.out.print("\nAction Performed");
        }But this is not picked up in my external class here
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    public class MainPanel extends JPanel implements ActionListener {
        /* Creates a new the main JPanel that is used in the FlipBookFrame to contain all of the elements */
        public MainPanel(){
            /* TopPanel constraints*/
            tpcs.gridx = 1;
            tpcs.gridy = 0;
            tpcs.gridwidth = 1;
            tpcs.gridheight = 1;
            tpcs.fill = GridBagConstraints.BOTH;
            tpcs.weightx = 0.0;
            tpcs.weighty = 1.0;
            /* LeftPanel Constraints*/
            lpcs.gridx = 0;
            lpcs.gridy = 0;
            lpcs.gridwidth = 1;
            lpcs.gridheight = 3;
            lpcs.fill = GridBagConstraints.BOTH;
            lpcs.weightx = 1.0;
            lpcs.weighty = 1.0;
            /* CentrePanel Constraints*/
            cpcs.gridx = 1;
            cpcs.gridy = 1;
            cpcs.gridwidth = 1;
            cpcs.gridheight = 1;
            cpcs.fill = GridBagConstraints.NONE;
            cpcs.weightx = 0.0;
            cpcs.weighty = 0.0;
            /* RightPanel Constraints*/
            rpcs.gridx = 2;
            rpcs.gridy = 0;
            rpcs.gridwidth = 1;
            rpcs.gridheight = 3;
            rpcs.fill = GridBagConstraints.BOTH;
            rpcs.weightx = 1.0;
            rpcs.weighty = 1.0;
            /* BottomPanel Constraints*/
            bpcs.gridx = 1;
            bpcs.gridy = 2;
            bpcs.gridwidth = 1;
            bpcs.gridheight = 1;
            bpcs.fill = GridBagConstraints.BOTH;
            bpcs.weightx = 0.0;
            bpcs.weighty = 1.0;   
            this.setLayout(gblo);   //Sets the Layout of the panel to a GridBagLayout
            this.add(tp, tpcs); //Adds the TopPanel to the MainPanel using the TopPanel layout
            this.add(lp, lpcs); //Adds the LeftPanel to the MainPanel using the LeftPanel layout
            this.add(cp, cpcs); //Adds the CanvasPanel to the MainPanel using the CanvasPanel layout
            this.add(rp, rpcs); //Adds the RightPanel to the MainPanel using the RightPanel layout
            this.add(bp, bpcs); //Adds the BottomPanel to the MainPanel using the BottomPanel layout
            gblo.layoutContainer(this); //Lays Out the Container
        public PanelSizes getPanelSizes(){
            return ps;
        public void actionPerformed(ActionEvent e) {
            System.out.print("\nExternal Class finds event!");
            /*String command = e.getActionCommand();
            if (command.equals("pencil")){
                System.out.print("\nYESSSSSSSSSSSSSSSSSSSSS!");
        /* Create of objects using the PanelSizes funtions for defining the */
        PanelSizes ps = new PanelSizes();   //Creates a new PanelSizes object for sizing the panel
        CanvasPanel cp = new CanvasPanel(ps.getCentrePanelDimension()); //Creates a new Canvas Panel
        TopPanel tp = new TopPanel(ps.getHorizontalPanelDimension()); //Creates the TopPanel
        BottomPanel bp = new BottomPanel(ps.getHorizontalPanelDimension()); //Creates the BottomPanel
        LeftPanel lp = new LeftPanel(ps.getVerticalPanelDimension()); //Creates the LeftPanel
        RightPanel rp = new RightPanel(ps.getVerticalPanelDimension());   //Creates the RightPanel
        /* I have chosen to create individual constraints for each panel to allow for adding of all
         components a the end of the constructor. This will use slightly more memory but gives clarity
         in the code */
        GridBagConstraints cpcs = new GridBagConstraints();
        GridBagConstraints tpcs = new GridBagConstraints();
        GridBagConstraints bpcs = new GridBagConstraints();
        GridBagConstraints lpcs = new GridBagConstraints();   
        GridBagConstraints rpcs = new GridBagConstraints();
        GridBagLayout gblo = new GridBagLayout();
    }Any help will be greatly appreciated :-)

  • Issue with re-sizing JTable Headers, JTabbedPane and JSplit pane

    Ok, hopefully I'll explain this well enough.
    In my Swing application I have a split pane, on the left hand side is a JTable and on the right hand is a JTabbedPane. In the tabs of the JTabbedPane there are other JTables.
    In order to make the rows in the JTable on the left and the JTable(s) on the right line up, the Table Header of all the tables is set to the size of the tallest (deepest?) table header.
    Hopefully so far I'm making sense. Now to get to the issue. One of the tables has a number of columns equal to the value on a NumberSpinner (it represents a number of weeks). When this value is changed the table is modified so that it contains the correct number of columns. As the table is re-drawn the table header goes back to its default size so I call my header-resize method to ensure it lines up.
    The problem is this: if I change the number of weeks when selecting a tab other than the one containing my table then everything is fine, the table header is re-sized and everything lines up. If I change the number of weeks with the tab containing the table selected, the column headers stay at their standard size and nothing lines up.
    To make things more complicated, I also put System.out.println's in as every method called in the process to obtain the size of the table header. And every println returned the same height, the height the table header should be.. So I'm really confused.
    Could anyone shed any light on this?
    Thanks.

    Okay I managed to solve the problem by explicitly revalidating and repainting the table header.
    Not sure why it wasnt doing it properly for that table when all the others where fine.
    Oh well...

  • Swing Layouts

    Why is laying out component sizes in Swing so incredibly opaque?
    Each time I build a swing interface it seems to be a series of visual compromises, and ending up in more TLOC than any other part of even a complex application. Changing one value seems to always mess up everything else or have unexpected side-effects! Half the time, changing the most obvious values have no effect at all. I frequently end up just clearing out ALL layout hints/settings from the UI and starting from scratch with a GridBagLayout just to get something fairly sensible. Yes I am frustrated.
    If any part of the increasingly wonderful java platform needs a major review, then it is the Swing layout APIs or at least the documentation of the exact behaviour and dependencies of methods that influence sizes.
    Either I am stupid (which I would be most willing to accept), or component layout/orientation/sizing/behaviour is very, very far from intuitive.
    I'd love to become a Swing-super-guru-expert, but as I am expected to be an expert on so many other things, I simply do not have the time to spend on it. I believe that it would be much better for the platform as a whole if the UI platform was made more intuitive or at the very least much better documented.
    I am seriously considering moving to SWT, as I just don't have the time or energy to figure all this out.
    /k1

    Oh btw - all the GUI editors I've ever used tend to compound the problems by introducing their own
    quirks, dependencies and restrictions! That's been my experience to date which is why I've steered clear of them.
    As far as swing architecture not being mature. I think the architecture gives you the building blocks, from there any layout mangers can be created. Maybe Sun could provide a few more LayoutManagers but I suspect their tactic is to provide the minimum from which you can do everything so keeping the API size down.
    So don't restrict yourself to those available in the JDK. Have a google and get some freebies. There are all sorts of alternative Layouts there. The fact that these are freely available elsewhere is quite likely why SUn haven't bothered to introduce more themselves some that spring to mind are TableLayout, GridLayout, ProportionalLayout, LabelledLayout
    To my mind it's the beauty of swing that allows it to be so easily extended in this way.
    SpringLayout came in in JDK1.4 http://www.onjava.com/pub/a/onjava/2002/09/11/layout.html but I'm not familiar with that as yet as I write systems that must be JDK1.3 compatible. It looks like a better replacement for GridBagLayout there are probably alternative versions of this to be found on the web..

  • Problems printing on custom sized paper.

    Hello all,
    I am trying to iron out my problems with printing on custom sized tractor paper (using an impact printer). Every time I print a test page, the printer behaves as if it was loaded with tractor paper that is 11 inches long, rather then the 7 inches that the forms are on.
    Before I list my code, let me explain everything that I have done. I am running Windows XP, so I went to the Printers and Faxes folder, clicked File > Server Properties, and created a custom form size (8.5" wide by 7" long with zero margins). Going back to the Printers and Faxes folder, I right clicked on the impact printer and clicked properties. From there I clicked the Device tab and selected my custom form that I had created for the tractor feed section. I then clicked the general tab and clicked the printing preferences. From there I clicked the Paper/Quality tab and selected Tractor Feed for the source. Then I clicked the advance button and selected my custom form for paper size. I also changed the resolution to 360X180.
    The printer itself has hardware settings for paper size. I've went through the menu and selected 7 inches for the form length.
    Now going to the code, I created the paper object and set it size to 612 for width and 504 for height. I also changed the ImageableArea to the size of the paper (which I think eliminates the margins), and set its orientation to 0, 0. I then set the paper object to the PageFormat, and used drawString to test my settings.
    Program compiles fine. When I run it and click the button, I select the correct printer. I also went through the preferences to make sure that all the setting are correct (especially to make sure my custom form is selected.). The closest I can get the string to the corner of the page is 75, 80. On the paper it measures 7/8" from the left, and 1" from the top.
    I have tested my custom form settings with word 2007. I was able to get the text on the very corner of the paper, and the printer was able to determine where the next form started. I believe that my problem lies within my code. Any help would be greatly appreciated!
    Thanks!
    import java.awt.*; 
    import java.awt.event.*; 
    import javax.swing.*; 
    import java.awt.print.*; 
    public class Print01 implements Printable, ActionListener { 
        public int print(Graphics g, PageFormat pf, int page) throws 
                                                            PrinterException { 
            if (page > 0) {  
                return NO_SUCH_PAGE; 
            double width = 612; 
            double height = 504; 
            Paper custom = new Paper(); 
            custom.setSize(width,height); 
            custom.setImageableArea(0,0,width,height); 
            pf.setPaper(custom); 
            Graphics2D g2d = (Graphics2D)g; 
            g2d.translate(pf.getImageableX(), pf.getImageableY()); 
            //The following returns the correct dimensions (612 width, 504 height). 
            System.out.println("Width: "+pf.getImageableWidth()+" Height: "+pf.getImageableHeight()); 
            g.drawString("Testing", 75, 80); //Smaller values result in clipping. 
            return PAGE_EXISTS; 
        public void actionPerformed(ActionEvent e) { 
            PrinterJob job = PrinterJob.getPrinterJob(); 
            job.setPrintable(this); 
            boolean ok = job.printDialog(); 
            if (ok) { 
                try { 
                     job.print(); 
                } catch (PrinterException ex) { 
        public static void main(String args[]) { 
            UIManager.put("swing.boldMetal", Boolean.FALSE); 
            JFrame f = new JFrame("Test page printer."); 
            f.addWindowListener(new WindowAdapter() { 
                  public void windowClosing(WindowEvent e) {System.exit(0);}}); 
            JButton printButton = new JButton("Print test page."); 
            printButton.addActionListener(new Print01()); 
            f.add("Center", printButton); 
            f.pack(); 
            f.setVisible(true); 

    I have a similar code to print a jasperreport,
    when I ran on Windows, the report is printed normally, all the document appeared, but when I ran on Linux (Debian), the document is missing some parts of report, printed without lines, appear only the middle of report. I don't understand what happen, on windows is ok, but linux is wrong. I tried the margins, but didn't work.
    Some one have an idea that can help me?
    sorry my english, but I need print in linux.
    Thanks a lot
    JasperPrint jasperPrint = JasperFillManager.fillReport(diretorioProjetos, parametros, getConexao().getConnection());
                getConexao().close();
                PrinterJob job = PrinterJob.getPrinterJob();
                /* Create an array of PrintServices */
                PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
                int selectedService = 0;
                /* Scan found services to see if anyone suits our needs */
                for (int i = 0; i < services.length; i++) {
                    if (services.getName().toUpperCase().contains("HPD1360")) {
    /*If the service is named as what we are querying we select it */
    selectedService = i;
    job.setPrintService(services[selectedService]);
    PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
    MediaSizeName mediaSizeName = MediaSizeName.ISO_A4;
    printRequestAttributeSet.add(mediaSizeName);
    printRequestAttributeSet.add(new MediaPrintableArea(
    0f, 0f,
    85f,
    54f, Size2DSyntax.MM));
    //MediaSize.findMedia(85f, 54f, Size2DSyntax.MM);
    printRequestAttributeSet.add(new Copies(1));
    JRPrintServiceExporter exporter;
    exporter = new JRPrintServiceExporter();
    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
    /* We set the selected service and pass it as a paramenter */
    exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, services[selectedService]);
    exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET, services[selectedService].getAttributes());
    exporter.setParameter(JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET, printRequestAttributeSet);
    exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, Boolean.FALSE);
    exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.FALSE);
    exporter.exportReport();

  • WebView sizing issue

    Hi,
    I'm embedding a WebView through a JFXPanel in a existing Swing app and running into some issues regarding to sizing.
    My issue is that sometimes the height/width reported in JavaScript inside the WebView is 800*600, while most of the time it is reported to be equal to the dimensions of the WebView/Scene/JFXPanel. As the content I'm showing is a chart that renders itself to a size according to the dimensions of a parent DOM node, which is in this case the document.body, you can imagine that the results are wrong when the values reported in JavaScript for width and height are wrong.
    Ideally what I want is that the size of the body of the HTML document automatically follows the dimensions of the JFXPanel, meaning that is the JFXPanel gets resized, the dimensions of the scene/WebView follow suit. As this is not possible AFAIK, I've now setup a ComponentListener on the JFXPanel to update the dimensions of the WebView through the componentResized method of the ComponentListener. However, this still gives me the mixed results.
    I've setup a log of logging and I see that when the JavaScript layer reports the 800*600 dimensions, the dimensions of the WebView, Scene and JFXPanel are NOT reported as 800*600, but all report the actual size.
    My setup is as follows:
    - JFXPanel containing a Scene containing a WebView.
    - The scene is constructed without specifying a width/height
    - The JFXPanel is dimensioned by a special Swing layout manager
    - The WebView is loaded with custom HTML through loadContent() of the WebEngine
    - The body of the HTML document is sized 100%*100% through CSS
    - Dimensions in JavaScript are retrieved through document.body.getWidth/Height
    - In the custom HTML a chart is instantiated with the dimensions of the
    - Using Java 1.7 update 25 64bit on Windows with the bundled JavaFX
    Any thoughts appreciated.
    P.

    Please a correction i have seen that this error is produced on every scheduled report. The problem i am facing is that the campaign consolidated daily report is not imported in the specified folder.
    Help!

  • JTable column sizing

    Hi all. Getting frustrated. How can I size a column's width to fit the size its longest element?
    In the example below, "Test Column" gets sized to fit the width of the table instead of its data. So the first row's data is cut off. I want "Test Column" to auto resize itself to be as long as that String. Anyone know? Thanks.
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.table.DefaultTableModel;
    public class TableTest extends JPanel{
         GridBagConstraints gbc;
         public TableTest(){
              super(new GridLayout(1,0));
              createTable();
         public void createTable(){
              JPanel panel = new JPanel(new GridBagLayout());
              panel.setBorder(BorderFactory.createTitledBorder("Attributes"));
              DefaultTableModel model = new DefaultTableModel();
              model.addColumn("Test Column",new Object[]{"asdasdasdssssasdddddddddddddddddddddddddddssssssssssaSD"});
              JTable table = new JTable(model);
              table.setEnabled(false);    
         //     table.setPreferredSize(new Dimension(150,150));
              JScrollPane scroll = new JScrollPane(table);
              scroll.setPreferredSize(new Dimension(150,150));
              scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
              gbc = new GridBagConstraints();
              gbc.weightx = 1;
              gbc.weighty = 1;
              gbc.insets = new Insets(10,10,10,10);
              gbc.fill = GridBagConstraints.BOTH;
              panel.add(scroll, gbc);
              gbc = new GridBagConstraints();
              gbc.gridy = 1;
              gbc.weightx = 1;
              gbc.weighty = 1;     
              gbc.fill = GridBagConstraints.HORIZONTAL;
              gbc.anchor = GridBagConstraints.SOUTH;
              add(panel,gbc);
          private static void createAndShowGUI() {
                 //Create and set up the window.
                 JFrame frame = new JFrame("TableDemo");
                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 //Create and set up the content pane.
                 TableTest newContentPane = new TableTest();
                 newContentPane.setOpaque(true); //content panes must be opaque
                 frame.setContentPane(newContentPane);
                 //Display the window.
                 frame.pack();
                 frame.setVisible(true);
         public static void main(String[] args) {
              System.out.println("Start");
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    I'm aware of the recent problems with the forum search. What I suggested was that you spend some time reading answered posts relating to problems that you have an interest in.
    That's the way I learned pretty much all I know, so I'm not spouting hot air here :)
    db

  • Controlling the re-sizing of widgets:

    I have read several Swing tutorials, but many are limited in their scope.
    I have been searching for a way to control the resizing of my JPanels and widgets.
    A solution I found is to use transparent JPanels that have no content or borders. I give them weights and directions that serve as counter-weights for the JPanels I want to display and control the sizing of. Here is my code:
    public class Main extends JPanel {
        public Main() {
            super(new GridBagLayout());
            GridBagLayout gbLayout = (GridBagLayout) getLayout();
            setPreferredSize(new Dimension(250, 200));
            JPanel configPanel = new JPanel();
            configPanel.setBorder(new LineBorder(Color.blue, 2));
            configPanel.setPreferredSize(new Dimension(100, 50));
            GridBagConstraints configPanelGBConstraints = new GridBagConstraints();
            configPanelGBConstraints.fill = GridBagConstraints.HORIZONTAL;
            configPanelGBConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
            configPanelGBConstraints.weightx = 0.4f;
            gbLayout.setConstraints(configPanel, configPanelGBConstraints);
            add(configPanel);
            JPanel padding = new JPanel(); // <--- empty JPanel that servers as a counter-weight to control the sizing of "configPanel"
            padding.setPreferredSize(new Dimension(150, 50));
            GridBagConstraints paddingGBConstraints = new GridBagConstraints();
            paddingGBConstraints.fill = GridBagConstraints.HORIZONTAL;
            paddingGBConstraints.anchor = GridBagConstraints.FIRST_LINE_END;
            paddingGBConstraints.weightx = 0.7f;
            gbLayout.setConstraints(padding, paddingGBConstraints);
            add(padding);
    }So far, this is working ok.
    Resizing objects in a JFrame is extremely important, and I'd like to ask if this is a "standard practices" way to handle re-sizing?
    Maybe later on, I will get bitten by this bad technique?
    What do good Swing programmers do?
    Thanks.

    camickr wrote:
    A solution I found is to use transparent JPanelsYou could probably use Box.getHorizontalStrut(...) instead.
    But I don't know exactly what you are trying to achieve and the code is not executable.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    sorry, I should of posted all my code that compiles:
    import java.lang.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Main extends JPanel {
        public Main() {
            super(new GridBagLayout());
            GridBagLayout gbLayout = (GridBagLayout) getLayout();
            setPreferredSize(new Dimension(250, 200));
            JPanel configPanel = new JPanel();
            configPanel.setBorder(new LineBorder(Color.blue, 2));
            configPanel.setPreferredSize(new Dimension(100, 50));
            GridBagConstraints configPanelGBConstraints = new GridBagConstraints();
            configPanelGBConstraints.fill = GridBagConstraints.HORIZONTAL;
            configPanelGBConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
            configPanelGBConstraints.weightx = 0.4f;
            gbLayout.setConstraints(configPanel, configPanelGBConstraints);
            add(configPanel);
            JPanel counterweight = new JPanel();
            counterweight.setPreferredSize(new Dimension(150, 50));
            GridBagConstraints counterweightGBConstraints = new GridBagConstraints();
            counterweightGBConstraints.fill = GridBagConstraints.HORIZONTAL;
            counterweightGBConstraints.anchor = GridBagConstraints.FIRST_LINE_END;
            counterweightGBConstraints.weightx = 0.7f;
            gbLayout.setConstraints(counterweight, counterweightGBConstraints);
            add(counterweight);
        public static void createAndShowGUI() {
            JFrame mainFrame = new JFrame("test");
            mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JComponent newContentPane = new Main();
            newContentPane.setOpaque(true);
            mainFrame.setContentPane(newContentPane);
            mainFrame.pack();
            mainFrame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }This works.
    So, I am just wondering if I should use the general construct that for every JComponent, it often makes sense to use an equal and opposing (sometimes transparent) JComponent to control its re-sizing?

  • Question about relative sizing on JPanels

    Hi,
    My question is about relative sizing on components that are not drawn yet. For example I want to draw a JLabel on the 3rd quarter height of a JPanel. But JPanel's height is 0 as long as it is not drawn on the screen. Here is a sample code:
    JPanel activityPnl = new JPanel();
    private void buildActivityPnl(){
            //setting JPanel's look and feel
            activityPnl.setLayout(null);
            activityPnl.setBackground(Color.WHITE);
            int someValue = 30;  // I use this value to decide the width of my JPanel
            activityPnl.setPreferredSize(new Dimension(someValue, 80));
            //The JLabel's height is 1 pixel and its width is equal to the JPanel's width. I want to draw it on the 3/4 of the JPanel's height
            JLabel timeline = new JLabel();
            timeline.setOpaque(true);
            timeline.setBackground(Color.RED);
            timeline.setBounds(0, (activityPnl.getSize().height * 75) / 100 , someValue , 1);
            activityPnl.add(timeline);
        }Thanks a lot for your help
    SD
    Edited by: swingDeveloper on Feb 24, 2010 11:41 PM

    And use a layout manager. It can adjust automatically for a change in the frame size.
    Read the Swing tutorial on Using Layout Managers for examples of the different layout managers.

  • Undecorated JFrame in Swing editor

    I am creating an application which doesn't require window decorations and I use the appropriate call in the JFrame class to turn them off. The problem is that the swing editor in JDeveloper always has the decorations present so it's hard to get the placement of object and the sizing of the JFrame correct. Is there a setting in JDeveloper to modify this behaviour? As an aside there isn't a property to set or clear the decorations in the properties pane either.
    Any help would be most appreciated.

    dialog works pretty well
    here's a more complete example
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class Logon {
       public static void main(String[] a){
          JFrame f = new JFrame();
          f.setSize(400,400);
          f.show();
          LogonDial ld = new LogonDial(f,true);
          ld.setLocationRelativeTo(null);
          ld.show();
          if(ld.isAccept()){
             JOptionPane.showMessageDialog(null,"you are now logged on");
          else
             JOptionPane.showMessageDialog(null,"logon failed");
          ld.dispose();
          f.dispose();
          System.exit(0);
    import javax.swing.*;
    import java.awt.event.*;
    public class LogonDial extends JDialog{
       private boolean accept = false;
       private JButton logonButton;
       public LogonDial(JFrame f, boolean modal){
          super(f,modal);
          init();
       private void init(){
          setSize(200,200);
          logonButton = new JButton("logon");
          logonButton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent ae){
                   //if logon is correct
                   accept = true;
                   hide();
          getContentPane().add(logonButton);
          addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent we){
                   accept = false;
                   hide();
       public boolean isAccept(){
          return accept;
    }you should run it and see if it works for you.

  • Architecture for Design in Swing

    Hi,
    I am developing a standalone application using Swing.
    It is recommended to use GridBag Layout for the design.
    Grid Bag Constraints are having 11 parameters to be set to all the components.
    which will increase the lines of code and maintainability issues may raise.
    I request, to suggest an architecture for the same.
    A sample would be helpful to us to build on.
    Thanks in advance.
    Nagalakshmi

    Having started my first Java project (and first OO for that matter) at the beginning of the year, I was tasked to redesign our current GUI (non-Java), which is almost 100 frames. After reading up on different layout managers, the consensus from the books/tutorials that I read was that GridBag was the most complex, but also the most powerful. I tried a few others, but their limitations were obvious to me in short time. Ever since I turned to GridBag, I haven't looked back.
    I suggest you do not use GridBagLayout.
    It's inconvenient.I couldn't disagree more. What's inconvenient about total control?
    You can use BorderLayout, GirdLayout and FlowLayout to
    layout component in many case.True, but I can use GridBag in all cases.
    Grid Bag Constraints are having 11 parameters to be set to all the components.
    which will increase the lines of code and maintainability issues may raise.Very true if you let a GUI builder do it for you. I prefer to whiteboard the layout of my components first, then hand-code it. I also wrote some convenience methods to help me with the constraints and sizing and such, so that I don't have 12 lines of code each time that I want to add a single component, I just have one method call.
    Since I'm running 1.4, I haven't looked at SpringLayout yet (1.5 only, I believe). If DrLaszlo is endorsing it, then that's enough for me to know that I should at least check it out.
    Good luck.

  • JMenu sized/rendered inconsistently in 1.6

    We have a Swing application (Windows LAF) which consists of a JFrame with a JMenubar. Since switching to 1.6 JRE, the menus will occasionally be mis-rendered in one of the following ways upon application startup:
    - The menubar will take up the entire JFrame, but the text labels of the JMenus/JMenuItems are not displayed, so the whole JFrame is grey; moving the mouse seems to result in the 'hover' effect normally produced by mousing over a menubar, clicking anywhere will trigger a menu item, and once that is done, the application goes back to 'normal'
    or
    - One of the top-level JMenus will be sized incorrectly; resizing the JFrame will cause the incorrectly sized JMenu to be rendered properly
    Again, this behavior occurs sporadically; I would guess less than 5% of the time. Anyone else experience this?

    We have a Swing application (Windows LAF) which consists of a JFrame with a JMenubar. Since switching to 1.6 JRE, the menus will occasionally be mis-rendered in one of the following ways upon application startup:
    - The menubar will take up the entire JFrame, but the text labels of the JMenus/JMenuItems are not displayed, so the whole JFrame is grey; moving the mouse seems to result in the 'hover' effect normally produced by mousing over a menubar, clicking anywhere will trigger a menu item, and once that is done, the application goes back to 'normal'
    or
    - One of the top-level JMenus will be sized incorrectly; resizing the JFrame will cause the incorrectly sized JMenu to be rendered properly
    Again, this behavior occurs sporadically; I would guess less than 5% of the time. Anyone else experience this?

  • Book Recommendation for Building Swing Applications

    I'm looking for recommendations on books for building swing applications from the ground up.
    I'm not a strong GUI developer. 95% of my experience has been strictly on back end development in many other languages. What little GUI experience I have has been with C++ (years ago) and most recently with HTML.
    I know what I want to develop, and even have the GUI design for my application drawn out. I just need a good book that can walk me through developing the interface in Java.
    I already have several books on Java. But, I find them somewhat limiting because they don't help me build the app from the ground up.
    Yes, I've tried the online book on the Sun site, "The Jfc Swing Tutorial: Guide to Constructing Gui's".
    Please offer some recommendations and reasons on why you like the book.
    Thanks.

    A few comments to that ....
    the first thing is understanding the LayoutManagers, that are available.
    I will give you a short guideline where they are usefull:
    FlowLayout - usefull for JLabel-JTextField combinations or several JButtons
    BorderLayout - usefull for the structure of basic containers
    CardLayout - usefull for every area of the screen, where you want to appear different panels
    GridLayout - usefull for a group of same-sized components laid out in a grid
    GridBagLayout - usefull for a group of components, that have different sizes, very flexible
    JTabbedPane - a special container, that is similar to CardLayout but with visible tabs to switch panels
    Normally you can say "I want that group at the bottom of the frame, that other group at its left side, that toolbar at its top" - if you can say so - that shouts for BorderLayout. If you can say "in this area I want to use several panels" that means CardLayout or a JTabbedPane.
    You see, if you have an idea, what the LayoutManagers do, you know exactly which area needs what Layout - so you have a guideline, which LayoutManager to use in that panel.
    To make an example:
    You want 3 buttons centered at the bottom of a frame - this 3 buttoms should be of that size, that is needed by the button texts. So, what to do:
    1. create a JPanel with FlowLayout
    2. create the buttons and add it to that JPanel
    3. create another JPanel with BorderLayout
    4. add that first JPanel to the second JPanel at BorderLayout.CENTER
    5. add this Panel to the ContentPane of the frame at BorderLayout.SOUTH
    that is a simple panel in panel construct - placing 3 buttons centered at the bottom of the frame. You have to play with that different LayoutManagers a little bit - the way you stick one panel in another changes the look of the GUI - if you know, how it changes (by playing with the examples of the tutorial), you will have that "from the ground"-experience, you are looking for - believe me.
    greetings Marsian

  • Problem with threads in my swing application

    Hi,
    I have some problem in running my swing app. Thre problem is related to threads.
    What i am developing, is a gui framework where i can add different pluggable components to the framework.
    The framework is working fine, but when i press the close action then the gui should close down the present component which is active. The close action is of the framework and the component has the responsibility of checking if it's work is saved or not and hence to throw a message for saving the work, therefore, what i have done is that i call the close method for the component in a separate thread and from my main thread i call the join method for the component's thread.But after join the whole gui hangs.
    I think after the join method even the GUI thread , which is started for every gui, also waits for the component's thread to finish but the component thread can't finish because the gui thread is also waiting for the component to finish. This creates a deadlock situation.
    I dont know wht's happening it's purely my guess.
    One more thing. Why i am calling the component through a different thread, is because , if the component's work is not saved by the user then it must throw a message to save the work. If i continue this message throwing in my main thread only then the main thread doesnt wait for user press of the yes no or cancel button for saving the work . It immediately progresses to the next statement.
    Can anybody help me get out of this?
    Regards,
    amazing_java

    For my original bad thread version, I have rewritten it mimicking javax.swing.Timer
    implementation, reducing average CPU usage to 2 - 3%.
    Will you try this:
    import javax.swing.*;
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    public class SamurayClockW{
      JFrame frame;
      Container con;
      ClockTextFieldW ctf;
      public SamurayClockW(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        con = frame.getContentPane();
        ctf = new ClockTextFieldW();
        con.add(ctf, BorderLayout.SOUTH);
        frame.setBounds(100, 100, 300, 300);
        frame.setVisible(true);
        ctf.start();
      public static void main(String[] args){
        new SamurayClockW();
    class ClockTextFieldW extends JTextField implements Runnable{
      String clock;
      boolean running;
      public ClockTextFieldW(){
        setEditable(false);
        setHorizontalAlignment(RIGHT);
      public synchronized void start(){
        running = true;
        Thread t = new Thread(this);
        t.start();
      public synchronized void stop(){
        running = false;
      public synchronized void run(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try{
          while (running){
            clock = sdf.format(new Date());
            SwingUtilities.invokeLater(new Runnable(){
              public void run(){
                setText(clock);
            try{
              wait(1000);
            catch (InterruptedException ie){
              ie.printStackTrace();
        catch (ThreadDeath td){
          running = false;
    }

Maybe you are looking for

  • I have several users who have updated to the new iOS 5 and now are unable to get to the apple store

    I have several users with ipads who have updated to the new iOS5 and are now unable to access the itunes store.  It loads about half way and then nothing.  Any ideas on how to fix this?

  • Sending a JMS message from a Servlet

    Hello All I�m using the Sun Java Sysytem Application Server and have been trying to implement a servlet which on receipt of a Post message, takes the message and sends it using JMS to a message queue. I�m developing my first web application so all is

  • Formatting a WD Elements 3TB external drive...temporary file normal?

    Hi All, I am, I hope, at the end of a 36+ hour formatting process with this WD Elements 3TB external drive. I decided to zero out the drive and when I went to bed last night at around 12am, there were about 6 hours left in the process. This morning a

  • Which approach to take ? Request your suggestions

    Hello all, We are planning to implement custom work flow for a process in our group. The work flow is not related to any transaction in SAP. It is a request for a form release, where the entire process is happening outside SAP. Please find the follow

  • Disc Burning Help

    I have burned files before onto a DVD+R, and for some reason, any DVD+R i put in isnt showing up anywhere on my Mac, even in Disk Utility.  I also tried burning to it, and it keeps spitting the disc out, tried several discs.  Any thoughts? thank you!