JTextField resizing behaviour.

I would like to know how to consistently configure a JTextField to have a fixed size no matter the container's layout, the look and feel, and the field content.
Here is an example :
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DemoDateField2 {
    private static int currentLookAndFeelId;
    public static void main(String[] args) {
        final JTextField fixedColumnsField = new JTextField("It has 10 columns", 10);
        final JTextField notFixedColumnsField = new JTextField("It has no fixed columns");
        JComboBox comboBox = new JComboBox();
        comboBox.setPrototypeDisplayValue("01 Jan 1970");
        comboBox.setEditable(true);
        comboBox.setModel(new DefaultComboBoxModel(new String[]{"01 Jan 1970", "02 Jan 1970", "03 Jan 1970"}));
        JButton clearFixedButton = new JButton("Clear Fixed");
        JButton clearNotFixedButton = new JButton("Clear NotFixed");
        JButton lafButton = new JButton("Look and feel");
        JPanel panel = new JPanel();
        panel.add(fixedColumnsField);
        panel.add(notFixedColumnsField);
        panel.add(comboBox);
        panel.add(clearFixedButton);
        panel.add(clearNotFixedButton);
        panel.add(lafButton);
        final JFrame frame = new JFrame();
        frame.getContentPane().add(panel);
        frame.setSize(640, 480);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        clearFixedButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                fixedColumnsField.setText("");
        clearNotFixedButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                notFixedColumnsField.setText("");
        lafButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels();
                if (currentLookAndFeelId == infos.length - 1) {
                    currentLookAndFeelId = 0;
                else {
                    currentLookAndFeelId++;
                try {
                    UIManager.setLookAndFeel(infos[currentLookAndFeelId].getClassName());
                catch (Exception e1) {
                SwingUtilities.updateComponentTreeUI(frame);
}In this example, the first text field (the fixed column one) has a bad behaviour when switching LAF (the text is clipped in Windows LAF).
The second field is ok when switching LAF, but if you clear it and resize the frame, its widht is near zero.
The combo box behaves perfectly in both situations : LAF and clear&resize...
To sum it up : is it possible to have the same behaviour with a JTextField as with a JComboBox and its prototype method ?

Hello Phil,
yes, there are always side effects when changing the L&F. I have no perfect solution, but when you add a
import java.awt.*;
notFixedColumnsField.setPreferredSize(new Dimension (140,20));at least the shrinking doesn't happen any more when the field is empty.
You may also declare the field's dimension in dependence of another field such as
notFixedColumnsField.setPreferredSize(fixedColumnsField.getPreferredSize());hth
J�rg

Similar Messages

  • Component resizing behaviour when maximized

    I am wanting to change the behaviour when the main frame is re-sized that only one Jlist in a component consiting of multiple JLists is the only component resized.
    This is currently occuring, however it is the last JList, i wish to be able to nominate the JList that will be resized.
    i.e. the "Name" JList, no the "Up Rate" Jlist.
    This is the gui non-maximized:
    http://img225.imageshack.us/img225/5061/guinormal8xd.png
    This is the gui maximized as is:
    http://img225.imageshack.us/img225/9296/guimaximised5tb.png
    This is the gui as i would like it:
    http://img215.imageshack.us/img215/8238/guimaximised11el.png
    Can anyone give me a few pointers as to how to achieve this?

    [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use Layout Managers
    For example when using a BorderLayout. You could add one list to the "WEST" and one to the "CENTER". As the frame is resized the available space will be added (or removed) from the component in the center.
    Or, I believe a GridBadLayout has weightX paramenter which allows you to specify which component gets extra space when the frame is resized.

  • Stop JTextField resizing?

    I have a textfield which i have as not editable, and it is populated by a file browser (loads the file path into the text field) however if the file path is longer than the text field is wide, then the field simply resizes itself and becomes wider than the frame it is in.
    How do i stop it from resizing?

    agehoops wrote:
    Well, in the process of making the SSCCE it works, but not on my main project, only the SSCCE and the only thing different between the two is the L&F being used. Could that affect it?What happened when you changed the L&F being used in the main app.?

  • GUI building difficulties, nested Frames and other stuff

    I am currently working on a GUI and I am running into some difficulties. I have created a class which extends JFrame
    public class DelFace extends JFrame implements ActionListener, ItemListenerI am instantiating an object of this class from within another object of a different class as follows:
    DelFace DelGUI = new DelFace(this,MastFile);The creation of the object takes place within the listener methods of another object:
    public void actionPerformed(ActionEvent e)
      if(e.getActionCommand().equals("Delete"))
          DelFace DelGUI = new DelFace(this,MastFile);
      }The class that creates the object that makes this call does not contain the main method. Instead the afore mentioned object is created from a class that extends JFrame
    class GUI extends JFrame implements ActionListenerSo the code in it's order of activity is as follows:
    It breaks down hardcore at the beginning
    public class StartProgram {
      private static GUI LauncherGUI;
      private static FileOps MastFile;
      public static void main(String[] args)
      MastFile = new FileOps();
      MastFile.fileStatus();            //Create File object &/or file.
      MastFile.readFile();              //Read file contents if any.
      LauncherGUI = new GUI(StartProgram.MastFile);
    }A GUI object is created, - LauncherGUI = new GUI(StartProgram.MastFile);
    From here the code differentiates somewhat - FileOperations stem from here as do all code related to the complete construction of the General User Interface.
    Specifically my difficulties lie with the GUI, therefore I will present the next peice of code related to the GUI. The following code creates a JFrame and places a whole stack of buttons on it. Included with these buttons are menus. So basically the code creates a menu bar and adds menu items to that bar and so on until a menu similar to that found in any regular program is produced. Also contained on this part of the GUI are the five buttons that are fundemental to the programs operation.
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.EventObject; //Try removing this!!
    class GUI extends JFrame implements ActionListener
      private JButton button1;
      private JButton button2;
      private JButton button3;
      private JButton button4;
      private JButton button5;
      private String Path1;
      private String Path2;
      private String Path3;
      private String Path4;
      private String Path5;
      private FileOps MastFile;
      private DataEntryBox EntryBox;
      private HelpGUI Instruct;
      FrameListener GUIListener = new FrameListener();  //Listener object created.
      GUI(FileOps MastFile)
        this.MastFile = MastFile;          //Make MastFile objects methods available
                                           //to all of LauncherGUI object.
        Toolkit tk = Toolkit.getDefaultToolkit();       //intialize the toolkit.
        Dimension sSize = tk.getScreenSize();           //determine screen size.
        Container c = getContentPane();
        GridBagLayout gridbag2 = new GridBagLayout();    //GridBagLayout object
                                                        //instantiated.
        GridBagConstraints d = new GridBagConstraints();//GridBagConstraints object
                                                        //instantiated.
        c.setLayout(gridbag2);                          //Content pane's layout set
                                                        //to gridbag object.
        d.fill = GridBagConstraints.BOTH;               //Make all components fill
                                                        //their dispaly areas
                                                        //entirely.
        d.insets = new Insets(5,1,5,1);
        JMenuBar menuBar = new JMenuBar();  //Creates Menubar object called menuBar.
        setJMenuBar(menuBar);
        JMenu FMenu = new JMenu("File");    //File Menu object instantiated.
        FMenu.setMnemonic(KeyEvent.VK_F);   //Key that activates File menu...F.
        menuBar.add(FMenu);                 //File Menu added to menuBar object.
        JMenuItem NewItem = new JMenuItem("New");   //Creates New sub-menu object.
        NewItem.setMnemonic(KeyEvent.VK_N);         //Key that activates New sub-
                                                    //menu....N.
        FMenu.add(NewItem);
        NewItem.addActionListener(this);   //ActionListner for NewItem added.
        //Tutorial Note: Steps involved in creating a menu UI are as follows,
        //1). Create an instance of a JMenuBar.
        //2). Create an instance of a JMenu.
        //3). Add items to the JMenu (not to the JMenuBar).
        //Note: It is possible to include the Mnemonic activation key as part of
        //the JMenu or JMenuItem constructor. e.g.: JMenuItem NewItem = new JMenu
        //Item("New",KeyEvent.VK_N);
        JMenuItem DeleteItem = new JMenuItem("Delete");
        DeleteItem.setMnemonic(KeyEvent.VK_D);
        FMenu.add(DeleteItem);
        DeleteItem.addActionListener(this);
        JMenuItem ExitItem = new JMenuItem("Exit",KeyEvent.VK_E); //Mnemonic key
        //included with constructor method here and from now on.
        FMenu.add(ExitItem);
        ExitItem.addActionListener(this);
        JMenu HMenu = new JMenu("Help");
        HMenu.setMnemonic(KeyEvent.VK_H);
        menuBar.add(HMenu);
        JMenuItem InstructItem = new JMenuItem("Instructions",KeyEvent.VK_I);
        HMenu.add(InstructItem);
        InstructItem.addActionListener(this);
        JMenuItem AboutItem = new JMenuItem("About",KeyEvent.VK_A);
        HMenu.add(AboutItem);
        AboutItem.addActionListener(this);
        button1 = new JButton();
    /* The following if statments block first checks to see if the value held in the
    String array is equals to null (note: this only occurs when the program is first
    started and no data has been written to file). If the array is null then the
    buttons text is set to "". If the array value is not null (meaning that the file
    already holds data) then the value of the array is checked. If the value equals
    the String "null" then button text is set to "", otherwise button text is set to
    the relevant array value (a user defined shortcut name). Also the value of each
    buttons actionCommand is set to this string value. */
        if(MastFile.getFDArray(0) == null)
          button1.setText("");
          button1.setActionCommand("Link1");
        else
        if(MastFile.getFDArray(0) != null)
          if(MastFile.getFDArray(0).equals("null"))
            button1.setText("");
            button1.setActionCommand("Link1");
          else
            button1.setText(MastFile.getFDArray(0));
            button1.setActionCommand(MastFile.getFDArray(0));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 0;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button1, d);
        c.add(button1);
        button1.addActionListener(this);
        button2 = new JButton();
        if(MastFile.getFDArray(2) == null) //If the file contains no contents then..
          button2.setText("");
          button2.setActionCommand("Link2");
        else
        if(MastFile.getFDArray(2) != null)
          if(MastFile.getFDArray(2).equals("null"))//If the file contains the string
          {                                        //"null" then do as above.
            button2.setText("");
            button2.setActionCommand("Link2");
          else  //Set both button text and actionCommand to relevant shortcut name.
            button2.setText(MastFile.getFDArray(2));
            button2.setActionCommand(MastFile.getFDArray(2));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 1;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button2, d);
        c.add(button2);
        button2.addActionListener(this);
        button3 = new JButton();
        if(MastFile.getFDArray(4) == null)
          button3.setText("");
          button3.setActionCommand("Link3");
        else
        if(MastFile.getFDArray(4) != null)
          if(MastFile.getFDArray(4).equals("null"))
            button3.setText("");
            button3.setActionCommand("Link3");
          else
            button3.setText(MastFile.getFDArray(4));
            button3.setActionCommand(MastFile.getFDArray(4));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 2;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button3, d);
        c.add(button3);
        button3.addActionListener(this);
        button4 = new JButton();
        if(MastFile.getFDArray(6) == null)
          button4.setText("");
          button4.setActionCommand("Link4");
        else
        if(MastFile.getFDArray(6) != null)
          if(MastFile.getFDArray(6).equals("null"))
            button4.setText("");
            button4.setActionCommand("Link4");
          else
            button4.setText(MastFile.getFDArray(6));
            button4.setActionCommand(MastFile.getFDArray(6));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 3;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button4, d);
        c.add(button4);
        button4.addActionListener(this);
        button5 = new JButton();
        if(MastFile.getFDArray(8) == null)
          button5.setText("");
          button5.setActionCommand("Link5");
        else
        if(MastFile.getFDArray(8) != null)
          if(MastFile.getFDArray(8).equals("null"))
            button5.setText("");
            button5.setActionCommand("Link5");
          else
            button5.setText(MastFile.getFDArray(8));
            button5.setActionCommand(MastFile.getFDArray(8));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 4;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button5, d);
        c.add(button5);
        button5.addActionListener(this);
        Path1 = MastFile.getFDArray(1);       //Load Path variables with path
        Path2 = MastFile.getFDArray(3);       //details from String Array in
        Path3 = MastFile.getFDArray(5);       //MastFile object of FileOps class.
        Path4 = MastFile.getFDArray(7);       //Effectively loading these variables
        Path5 = MastFile.getFDArray(9);       //with file data.
        this.addWindowListener(GUIListener);  //Listener registered with Frame.
        setLocation(sSize.width*1/2,sSize.height*1/20);
        setSize(sSize.width*1/2,sSize.height*1/7);
        setTitle("Java QuickLaunch Toolbar");
        setVisible(true);
      /* The following methods return the ActionCommand and Text Label
         String values of the buttons */
      public String getButton1Command()
        return button1.getActionCommand();
      public String getButton2Command()
        return button2.getActionCommand();
      public String getButton3Command()
        return button3.getActionCommand();
      public String getButton4Command()
        return button4.getActionCommand();
      public String getButton5Command()
        return button5.getActionCommand();
      public String getBt1Text()
        return button1.getText();
      public String getBt2Text()
        return button2.getText();
      public String getBt3Text()
        return button3.getText();
      public String getBt4Text()
        return button4.getText();
      public String getBt5Text()
        return button5.getText();
      /* The following methods set the Path, Button and ActionCommand String values. */
      public void setPath1(String setPath)
        Path1 = setPath;
      public void setPath2(String setPath)
        Path2 = setPath;
      public void setPath3(String setPath)
        Path3 = setPath;
      public void setPath4(String setPath)
        Path4 = setPath;
      public void setPath5(String setPath)
        Path5 = setPath;
      public void setButton1(String setButton)
        button1.setText(setButton);
      public void setButton2(String setButton)
        button2.setText(setButton);
      public void setButton3(String setButton)
        button3.setText(setButton);
      public void setButton4(String setButton)
        button4.setText(setButton);
      public void setButton5(String setButton)
        button5.setText(setButton);
      public void setBt1Action(String setAct)
        button1.setActionCommand(setAct);
      public void setBt2Action(String setAct)
        button2.setActionCommand(setAct);
      public void setBt3Action(String setAct)
        button3.setActionCommand(setAct);
      public void setBt4Action(String setAct)
        button4.setActionCommand(setAct);
      public void setBt5Action(String setAct)
        button5.setActionCommand(setAct);
      /* actionPerformed methods */
      public void actionPerformed(ActionEvent e)
        if(e.getActionCommand().equals("New"))
          //Create a data entry box.
          EntryBox = new DataEntryBox(this,MastFile);
        else
        if(e.getActionCommand().equals("Delete"))//Example part of interest
          DelFace DelGUI = new DelFace(this,MastFile);   /// -------- ////
        else
        if(e.getActionCommand().equals("Exit"))
          System.exit(0);
        else
        if(e.getActionCommand().equals("Instructions"))
          Instruct = new HelpGUI();
        else
        if(e.getActionCommand().equals("About"))
          JOptionPane.showMessageDialog(this,"Java QuickLaunch Toolbar created by David "+
                                        "Dartnell.","Programming Credits",1);
        else
          if(e.getActionCommand().equals(button1.getActionCommand())) //Determine source of event.
          if(Path1 == null)                        //If Path var is a null reference
            EntryBox = new DataEntryBox(this,MastFile);//create a data entry box.
          else
          if(Path1 != null)                        //If not a null reference then...
            if(Path1.equals("null"))               //Determine if string is "null".
              EntryBox = new DataEntryBox(this,MastFile);
            else        //If both the reference and the String are not null then run
            {           //the relevant command/program.
              try
                Runtime.getRuntime().exec(new String[]{Path1});
              catch(IOException run){}
        else
        if(e.getActionCommand().equals(button2.getActionCommand()))
          if(Path2 == null)
            EntryBox = new DataEntryBox(this,MastFile);
          else
          if(Path2 != null)
            if(Path2.equals("null"))
              EntryBox = new DataEntryBox(this,MastFile);
            else
              try
                Runtime.getRuntime().exec(new String[]{Path2});
              catch(IOException run){}
        else
        if(e.getActionCommand().equals(button3.getActionCommand()))
          if(Path3 == null)
            EntryBox = new DataEntryBox(this,MastFile);
          else
          if(Path3 != null)
            if(Path3.equals("null"))
              EntryBox = new DataEntryBox(this,MastFile);
            else
              try
                Runtime.getRuntime().exec(new String[]{Path3});
              catch(IOException run){}
        else
        if(e.getActionCommand().equals(button4.getActionCommand()))
          if(Path4 == null)
            EntryBox = new DataEntryBox(this,MastFile);
          else
          if(Path4 != null)
            if(Path4.equals("null"))
              EntryBox = new DataEntryBox(this,MastFile);
            else
              try
                Runtime.getRuntime().exec(new String[]{Path4});
              catch(IOException run){}
        else
        if(e.getActionCommand().equals(button5.getActionCommand()))
          if(Path5 == null)
            EntryBox = new DataEntryBox(this,MastFile);
          else
          if(Path5 != null)
            if(Path5.equals("null"))
              EntryBox = new DataEntryBox(this,MastFile);
            else
              try
                Runtime.getRuntime().exec(new String[]{Path5});
              catch(IOException run){}
    Something to consider concerning actionListeners:
    It must be remembered that String values are in fact objects and as such
    they require the equals() method unlike their cousins the primitive data
    types (int, float, boolean, byte, short, long and double) which require
    the == operator.
    */A comment is placed next to the line of code that is of interest to my problem (///-------////).
    When a button is pressed in the menu section that reads "Delete" then an actionCommand event is fired and the program responds by creating a second general user interface.
    When DelFace is instantiated in the form of the object called DelGUI I am once again creating an object which extends JFrame. I now have two objects of type JFrame on the screen at once, and I conveniently position one over the top of the other, so to the general user the programs appearance has changed in only very specified ways (i.e.: I have decided to increase the GUI's dimensions in the area of height only and not width). The code that constitutes class DelFace is as follows:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class DelFace extends JFrame implements ActionListener, ItemListener
      private GUI TkBar;        //GUI object.
      private FileOps Fops;     //File Operations object.
      private JCheckBox ckbox1; //Delete shortcut 1.
      private JCheckBox ckbox2; //Delete shortcut 2.
      private JCheckBox ckbox3; //Delete shortcut 3.
      private JCheckBox ckbox4; //Delete shortcut 4.
      private JCheckBox ckbox5; //Delete shortcut 5.
      private JButton OkBtn;    //OK button.
      private JButton CnBtn;    //Cancel button.
      private JOptionPane confirm;
      private boolean short1 = false;  //Boolean variables indicate whether to
      private boolean short2 = false;  //delete a shortcut entry. True = delete.
      private boolean short3 = false;
      private boolean short4 = false;
      private boolean short5 = false;
      DelFace(GUI TkBar, FileOps Fops)
        this.TkBar = TkBar;
        this.Fops = Fops;
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension sSize = tk.getScreenSize();
        Container dcon = getContentPane();
        GridBagLayout gb = new GridBagLayout();
        GridBagConstraints bagcon = new GridBagConstraints();
        dcon.setLayout(gb);
        bagcon.fill = GridBagConstraints.BOTH;
        bagcon.gridwidth = GridBagConstraints.REMAINDER;
        JLabel TLabel = new JLabel("Delete Wizard",JLabel.CENTER);
        TLabel.setFont(new Font("Tahoma",Font.BOLD+Font.ITALIC,32));
        bagcon.gridx = 0;
        bagcon.gridy = 0;
        bagcon.weightx = 1.0;      //Take up all the 'x room' in this row.
        bagcon.weighty = 0.5;      //Take up all the 'y room' in this column.
        /* The weightx and weighty values are required otherwise all components will
           gravitate toward the center of screen. */
        gb.setConstraints(TLabel,bagcon);
        dcon.add(TLabel);
        JTextArea TxArea = new JTextArea("Tick the box(s) of the shortcut(s)"+
                               " that you would like to delete and"+
                               " press the Delete button. Alternatively"+
                               " press the Cancel button to exit.");
        TxArea.setLineWrap(true);
        TxArea.setWrapStyleWord(true);
        TxArea.setEditable(false);
        TxArea.setFont(new Font("Times New Roman",Font.PLAIN,15));
        TxArea.setBackground(this.getBackground());
        bagcon.gridx = 0;
        bagcon.gridy = 1;
        gb.setConstraints(TxArea,bagcon);
        dcon.add(TxArea);
        bagcon.gridwidth = 1;
        JPanel Nopan1 = new JPanel();
        bagcon.gridx = 0;
        bagcon.gridy = 2;
        gb.setConstraints(Nopan1,bagcon);
        dcon.add(Nopan1);
        ckbox1 = new JCheckBox(TkBar.getBt1Text());
        bagcon.gridx = 1;
        bagcon.gridy = 2;
        gb.setConstraints(ckbox1,bagcon);
        dcon.add(ckbox1);
        ckbox1.addItemListener(this);
        ckbox2 = new JCheckBox(TkBar.getBt2Text());
        bagcon.gridy = 3;
        gb.setConstraints(ckbox2,bagcon);
        dcon.add(ckbox2);
        ckbox2.addItemListener(this);
        ckbox3 = new JCheckBox(TkBar.getBt3Text());
        bagcon.gridy = 4;
        gb.setConstraints(ckbox3,bagcon);
        dcon.add(ckbox3);
        ckbox3.addItemListener(this);
        ckbox4 = new JCheckBox(TkBar.getBt4Text());
        bagcon.gridy = 5;
        gb.setConstraints(ckbox4,bagcon);
        dcon.add(ckbox4);
        ckbox4.addItemListener(this);
        ckbox5 = new JCheckBox(TkBar.getBt5Text());
        bagcon.gridy = 6;
        gb.setConstraints(ckbox5,bagcon);
        dcon.add(ckbox5);
        ckbox5.addItemListener(this);
        JPanel Nopan2 = new JPanel();
        bagcon.gridx = 1;
        bagcon.gridy = 7;
        gb.setConstraints(Nopan2,bagcon);
        dcon.add(Nopan2);
        OkBtn = new JButton("OK");
        OkBtn.addActionListener(this);
        bagcon.gridx = 1;
        bagcon.gridy = 8;
        gb.setConstraints(OkBtn,bagcon);
        dcon.add(OkBtn);
        OkBtn.addActionListener(this);
        CnBtn = new JButton("Cancel");
        CnBtn.addActionListener(this);
        bagcon.gridx = 2;
        bagcon.gridy = 8;
        gb.setConstraints(CnBtn,bagcon);
        dcon.add(CnBtn);
        CnBtn.addActionListener(this);
        JPanel Nopan3 = new JPanel();
        bagcon.gridx = 3;
        bagcon.gridy = 8;
        gb.setConstraints(Nopan3,bagcon);
        dcon.add(Nopan3);
        JPanel Nopan4 = new JPanel();
        bagcon.gridx = 0;
        bagcon.gridy = 9;
        gb.setConstraints(Nopan4,bagcon);
        dcon.add(Nopan4);
        setLocation(sSize.width*1/2,sSize.height*1/20);
        setSize(sSize.width*1/2,sSize.height*4/5);
        setTitle("Java QuickLaunch Toolbar");
        setResizable(false);
        setVisible(true);
      public void actionPerformed(ActionEvent e)
      { /*--- Code of INTEREST begins here!!!!!! -------
        if(e.getActionCommand().equals("OK"))   
          if(short1 || short2 || short3 || short4 || short5)
            //confirm = new JOptionPane();
            int n = confirm.showConfirmDialog(this,
                 "Do you really want to delete?","Delete Confirmation",
                 JOptionPane.YES_NO_OPTION);
            if(n == confirm.YES_OPTION)  //Works Fine!
              while(short1 || short2 || short3 || short4 || short5)
                if(short1)
                  TkBar.setBt1Action("Link1");
                  TkBar.setButton1("");
                  TkBar.setPath1("null");
                  Fops.setFDArray(0,"null");
                  Fops.setFDArray(1,"null");
                  short1 = false;
                else
                if(short2)
                  TkBar.setBt2Action("Link2");
                  TkBar.setButton2("");
                  TkBar.setPath2("null");
                  Fops.setFDArray(2,"null");
                  Fops.setFDArray(3,"null");
                  short2 = false;
                else
                if(short3)
                  TkBar.setBt3Action("Link3");
                  TkBar.setButton3("");
                  TkBar.setPath3("null");
                  Fops.setFDArray(4,"null");
                  Fops.setFDArray(5,"null");
                  short3 = false;
                else
                if(short4)
                  TkBar.setBt4Action("Link4");
                  TkBar.setButton4("");
                  TkBar.setPath4("null");
                  Fops.setFDArray(6,"null");
                  Fops.setFDArray(7,"null");
                  short4 = false;
                else
                if(short5)
                  TkBar.setBt5Action("Link5");
                  TkBar.setButton5("");
                  TkBar.setPath5("null");
                  Fops.setFDArray(8,"null");
                  Fops.setFDArray(9,"null");
                  short5 = false;
              Fops.destroyFile();   //Destroy the old (outdated) file.
              Fops.fileStatus();    //Create a new file.
              Fops.writeFile();     //Write updated data to new file.
              setVisible(false);
            if(n == confirm.NO_OPTION)  //** Does not work ***
              System.out.println("No Option is being heard");
              //Listeners are working.
              //confirm.setVisible(false);
            if(n == confirm.CLOSED_OPTION) //** Does not work ***
              System.out.println("Closed Option is being heard");
              //Listeners are working.
              //confirm.setVisible(false);
        --- Code of interest ENDS here --- */
        else
        if(e.getActionCommand().equals("Cancel"))
          setVisible(false); 
      public void itemStateChanged(ItemEvent f)
        int state = f.getStateChange();
        if(state == ItemEvent.SELECTED)   //If a checkbox has been selected.
          if(f.getItem() == ckbox1)
            short1 = true;
          else
          if(f.getItem() == ckbox2)
            short2 = true;
          else
          if(f.getItem() == ckbox3)
            short3 = true;
          else
          if(f.getItem() == ckbox4)
            short4 = true;
          else
          if(f.getItem() == ckbox5)
            short5 = true;
        if(state == ItemEvent.DESELECTED)  //If a checkbox has been deselected.
          if(f.getItem() == ckbox1)
            short1 = false;
          else
          if(f.getItem() == ckbox2)
            short2 = false;
          else
          if(f.getItem() == ckbox3)
            short3 = false;
          else
          if(f.getItem() == ckbox4)
            short4 = false;
          else
          if(f.getItem() == ckbox5)
            short5 = false;
    }The code that is of interest to my current programming challenge is marked in the above code block like this:
    //*** Code of INTEREST begins here!!!!!! ********** //
    This is where my programming twilight behaviour begins to kick in. From the DelGUI object I now listen to a button event, this event when triggered causes a JOptionPane.showConfirmDialog(), as can be seen in the specified code block above. I make the JOptionPane centered over the DelGUI object ("JFrame No.: 2") which is also centered over the LauncherGUI object ("JFrame No.: 1").
    The program begins to behave quite strangely after the creation of the JOptionPane object called confirm. The JOptionPane is presented on screen without any visiual difficulty but it behaves quite strangely when it's buttons are pressed. The JOptionPane contains three event sources, the YES, NO and Close buttons.
    In my program the YES button causes a set of file operations to take place and then sets the "JFrame No.: 2"(DelGUI) invisible. It does this via the method setVisible(false). "JFrame No.: 2" is effectively the JOptionPane's parent component and as soon as it is setVisible(false) the JOptionPane is also cleared from the screen. I believe from my research that this is the JOptionPane's default behaviour, meaning that as soon as a button or event source is activated the JOptionPane will destroy itself.
    The end of the trail is near, thankyou for reading this if you have got this far, and please carry on....
    The Challenge:
    The program does not behave as desired at the two points in the code commented as such: ** Does not work ***
    if(n == confirm.NO_OPTION)
              System.out.println("No Option is being heard");
              //confirm.setVisible(false);
            if(n == confirm.CLOSED_OPTION)
              System.out.println("Closed Option is being heard");
              //confirm.setVisible(false);
            }If the NO_OPTION or the CLOSED_OPTION are pressed then the JOptionPane remains visible. After pressing the JoptionPane's button a second time it will disappear completely. I have tried a number of things in an attempt to work this out. Firstly I have inserted println messages to ensure that the events are being detected. These messages are always displayed whenever either the NO or Close buttons are pressed.
    As these messages are being passed to the Standard Output, twice by the time the JOptionPane has disappeared, I can only assume that the events are being detected.
    In addition to checking the event situation I have attempted to explicity set the JOptionPane invisible, in the form:
    confirm.setVisible(false); The above line of code did not change the situation. Still I need two button clicks for the JOptionPane to display it's default behaviour which is to set itself invisible (or possibly the object is alloted to garbage collection), either way it is no longer on screen. I have also tried this code with no if statements related to NO_OPTION and CLOSE_OPTION. This was done in an attempt to allow the default behaviour to take place. Unfortunately two presses were still required in this situation.
    A forum member mentioned the possibility that two JOptionPanes are being created. I have checked my code and am confident that I have not explicitly created the JOptionPane twice (the code throughout this question should support this).
    Is it possible that two JOptionPanes are being created because of the nature of my code, the fact that there are two JFrames on the screen at once when the JOptionPane is instantiated? I am using the this keyword to specify the parent of the JOptionPan

    Well, I've checked your code and I've seen where is the error.
    In Delface constructor (Delface.java, line 127), you've got this block of code :
    1. OkBtn = new JButton("OK");
    2. OkBtn.addActionListener(this);
    3. bagcon.gridx = 1;
    4. bagcon.gridy = 8;
    5. gb.setConstraints(OkBtn,bagcon);
    6. dcon.add(OkBtn);
    7. OkBtn.addActionListener(this);
    Have a deep look at lines 2 and 7 : you're registering twice an actionListener on this button. Then you're receiving twice the event and it shows two JOptionPanes. In fact, you've also the problem with the 'ok' option, but you don't see it, because the 'n' variable in your event handler is global to your class, then it's shared between the two calls to the event handlers.

  • Best practice for adding text to Flex container?

    Hi,
    I'm having some troubles to lay a TextFlow class out properly
    inside a Flex container. What's the best practice to achieving
    this, for example adding a lot of text to a small Panel?
    Is it possible to pass anything other than a static width and
    height to DisplayObjectContainerController constructor, or is this
    not the place to implement this? I guess what I am looking for is
    the layout logic I'd normally pack into a custom Flex component and
    implement inside measure() and so on.
    My use case: a chat application which adds multiple TextFlow
    elements to a Flex container such as Panel. Or use TextFlow as a
    substitute for UITextField.
    Some example code would help me greatly.
    I'm using Flex 3.2.
    Regards,
    Stefan

    Thanks Brian, the example helps. However problems quickly
    arise if I modify it slightly to this (please compile it to see):
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute" initialize="init()">
    <mx:Script>
    <![CDATA[
    import flashx.textLayout.compose.StandardFlowComposer;
    import
    flashx.textLayout.container.DisplayObjectContainerController;
    import flashx.textLayout.container.IContainerController;
    import flashx.textLayout.elements.TextFlow;
    import flashx.textLayout.conversion.TextFilter;
    private var _container:Sprite;
    private var _textFlow:TextFlow;
    private function init():void
    _container = new Sprite();
    textArea.rawChildren.addChild(_container);
    var markup:String = "<TextFlow xmlns='
    http://ns.adobe.com/textLayout/2008'><p><span>Hello
    World! Hello World! Hello World! Hello World! Hello World! Hello
    World! Hello World! Hello World! Hello World! Hello World! Hello
    World! Hello World! </span></p></TextFlow>";
    _textFlow = TextFilter.importToFlow(markup,
    TextFilter.TEXT_LAYOUT_FORMAT);
    _textFlow.flowComposer.addController(new
    DisplayObjectContainerController(_container, 200, 50));
    _textFlow.flowComposer.updateAllContainers();
    ]]>
    </mx:Script>
    <mx:Canvas width="100" height="100" id="textArea" x="44"
    y="46" backgroundColor="#F5EAEA"/>
    </mx:Application>
    What is the best way to make my textflow behave like a
    'normal' UIComponent in Flex? Should I use UIComponent instead of
    Sprite as a Container? Will that take care of resize behaviour?
    I have never before needed to use rawChildren.addChild for
    example, maybe you can explain why that's needed here?
    I realise that the new Textframework works on an AS basis and
    is not Flex or Flash specific, but this also poses some challenges
    for those of us using the Flex framework primarily.
    I think it would help to have some more basic examples such
    as using the new text features in a 'traditional' context. Say for
    example a TextArea that is just that, a TextArea but with the
    addition of inline images. I personally feel that the provided
    examples largely try to teach me to run before I can walk.
    Many thanks,
    Stefan

  • Size in JTable

    Hi! I have a little problem with JTables. If I want to show more than 20 files (it�s 20 because of the size of the window, this number is not important), it only shows a certain number of them, the others don�t appear. The autoscrolls field is "true", but it seems don�t work properly.
    Does anybody know what�s wrong?
    Thanks in advance.

    hi! The scrollbars are enabled. I have increased the height in "constraints" parameters so the table is big enough to show more files, but it�s not the best thing because it only makes the table bigger, but it doesn�t have a "resize" behaviour", and that�s what i�m looking for.
    Thanks.

  • MinWidth = USE_COMPUTED_SIZE is ignored?

    I want to lay out a simple HBox like this:
    [label1] [label2...] [label3]
    I want label3 to be right-justified, and I am more interested in seeing the contents of label1 and label3 than label2 when the container shrinks. So naively, I'd think that I should set minWidth = USE_COMPUTED_SIZE for the important labels, and to make label3 right justified I'd set HBox.hgrow=ALWAYS for the middle label:
    <HBox xmlns:fx="http://javafx.com/fxml" spacing="5">
      <maxWidth>
        <Double fx:constant="MAX_VALUE" />
      </maxWidth>
      <Label fx:id="label1" text="Important Label">
        <minWidth>
          <Pane fx:constant="USE_COMPUTED_SIZE" />
        </minWidth>
      </Label>
      <Label fx:id="label2" text="Vastly less important message" HBox.hgrow="ALWAYS" />
      <Label fx:id="label3" text="Important Label">
        <minWidth>
          <Pane fx:constant="USE_COMPUTED_SIZE" />
        </minWidth>
      </Label>
    </HBox>But that doesn't work in either respect! label3 is not right-justified, and labels 1 and 3 shrink to ellipses as fast, if not faster, than label2 when I make the window narrower. A little experimentation reveals that setting a large maxwidth on label2 achieves the right-justification that I want, but minwidth is still a problem.
    On closer inspection, I find that USE_COMPUTED_SIZE (-1.0) is actually the default minwidth! What good is that?
    If instead of using USE_COMPUTED_SIZE, I simply set the minwidth of labels 1 & 3 to a real value like 99, they do indeed shrink later than label2 does. But of course, I don't want to hard-code a minwidth like that. What am I supposed to do?

    Try something like the following.
    Load it up in SceneBuilder 1.1+ and then choose Preview | Preview in Window and resize the preview window to test out the resizing behaviour:
    <?xml version="1.0" encoding="UTF-8"?>
    <?import java.lang.*?>
    <?import java.util.*?>
    <?import javafx.geometry.*?>
    <?import javafx.scene.control.*?>
    <?import javafx.scene.layout.*?>
    <?import javafx.scene.paint.*?>
    <StackPane id="StackPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="39.5" prefWidth="498.0000999999975" xmlns:fx="http://javafx.com/fxml">
      <children>
        <HBox prefHeight="39.5" prefWidth="496.0" spacing="5.0" style="-fx-background-color: cornsilk" StackPane.alignment="CENTER_RIGHT">
          <children>
            <Label minWidth="-Infinity" style="-fx-background-color: slategrey" text="Important Label" HBox.hgrow="SOMETIMES" />
            <Label style="-fx-background-color: lightgrey" text="Vastly less Important Label" HBox.hgrow="NEVER" />
            <Label alignment="CENTER_RIGHT" maxWidth="1.7976931348623157E308" minWidth="-Infinity" style="-fx-background-color: palegreen" text="Important Label" HBox.hgrow="ALWAYS" />
          </children>
          <padding>
            <Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
          </padding>
        </HBox>
      </children>
    </StackPane>It's probably not exactly what you want, but hopefully it is helpful.
    Oddly, in my tests, the HBox.hgrow SOMETIMES priority doesn't seem to have any preference over the NEVER priority. So when you resize the thing smaller, the first two labels start to get elided unless you start to specify minWidth values.
    So I set the minWidth of the first label to the preferred width (and same for the last label). That causes the two important labels to never get elided (which might be the behaviour you want for the important labels anyway).
    Setting the alignment of the HBox itself to CENTER_RIGHT means (in combination with the right most label's HBox.hgrow of ALWAYS and a minWidth of the preferred width) that the rightmost important label is always visible and the other labels get pushed off to the left hand side if there is not enough room.
    Setting the maxWidth of the rightmost label to MAX_VALUE and it's alignment to CENTER_RIGHT right aligns the label in the HBox.
    The styles are just in there so that it is easy to see how big each label is - normally you would stick that kind of stuff in a stylesheet.
    The values of things like minWidth="-Infinity" and maxWidth="1.7976931348623157E308" are weird constants because that is what SceneBuilder outputs rather than something sensical like Label.USE_PREF_SIZE or Double.MAX_VALUE
    And yeah, as you point out in your question "USE_COMPUTED_SIZE (-1.0) is actually the default minwidth", so there is no point in explicitly setting minWidth to that value.

  • Something Interesting...

    I want to create a window similiar to windows explorer. That would contain a split pane. and the left component of splitpane would be a component with a close button. Is there any built in method to have a component with close button?
    I used to InternalFrame, but that will have a frame header in blue color. Which I dont like to use..
    Thanks in advance for ur replies..
    Sapna

    Well a split pane would give you resize facilities, and a single click minimal size facility, a la netscrape 6. The easiest way of having a closeable component is simply to hide the component when you want to make it invisible. You'd have to add a button to the component to trigger the setVisible(false) action. You might have to revalidate the layout when you make it visible again though, and you'd have to implement resizing behaviour yourself. Your choice, really.
    Hope this helps.--
    <sig> http://www.itswalky.com http://www.crfh.net </sig>

  • Ellipsis in JTable

    Does anyone know how to prevent ellipsis (...) in the data of a JTable? What I want is for each column to be wide enough to display the longest string in the column without the use of ellipsis.
    Thanks so much,
    Jason

    Hi Jason,
    By default, "JTable" makes each column the same width and tries to make each column wide enough so that all of the columns are visible on the screen.
    The resize behaviour is determined by the "autoResizeMode". See the javadoc for more details.
    http://java.sun.com/j2se/1.4.1/docs/api/javax/swing/JTable.html
    To change the behaviour, you can use the "setAutoResizeMode()" method. Again, the javadoc explains what options are available and what they do.
    How you determine the largest size of the column depends on what type of data you are displaying in the column and what "JComponent" you are using to display it, so I can't really answer that based on the information you have provided.
    However, you need to set the preferred width for each column. You do this via the "setPreferredWidth()" method in class "javax.swing.table.TableColumn". You would probably require code something like this (note:- untested):
    JTable table = new JTable();
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    TableColumnModel tcm = table.getColumnModel();
    for (int i = 0; i < tcm.getColumnCount(); i++) {
      TableColumn tc = tcm.getColumn(i);
      tc.setPreferredWidth(99);
    }Hope this helps.
    Good Luck,
    Avi.

  • AutoOrient on Android is ugly! Any workarounds?

    I have just had my flex mobile app rejected from the Amazon Appstore because when you rotate the device (android), the view does a temporary resize which causes a rectangle of the app background color to display. If you slowly turn the device, you can easily see this strange resize behaviour as it goes from portrait to landscape or vice versa.
    I have autoOrient true. This can be reproduced by simply creating a default Flex Mobile Project with a Tabbed Application (Flash Builder 4.5.1 with Flex 4.5.1 SDK) and trying it out on an android device. Note that the emulator will not show the problem.
    I have tried to figure out how to stop this behaviour. It appears to be related to having the TabNavigator views with width and height of 100%. Having a fixed size stops the ugly look during rotation - but I'm unsure of what sizes to set them to for fear I will end up with something even uglier on a device I can't directly test on.

    Welcome to the Apple Community.
    That's not possible, A*****d phones are not compatible with iCloud.

  • Design a WPF Tab control similar to the Wpf Ribbon

    Hi,
      I have a requirement to show the list of tools similar to that of a Microsoft word's Ribbon, but then i find some limitations in the Wpf Ribbon i..e it can not be completely customised, for example- The Ribbon tab header's height has to be increased
    when selected as shown in the figure, but I couldn't  find any relevant solution to accomplish it, so I have decided to use the native Tab Control and make it look like a Ribbon bar as suggested by  Andy
    ONeill  
    Expected Ribbon Tab header Style(Done using native Tab Control)
       But the issue here is I'm not able to handle the resize behaviour of the Wpf tab control.. when the tab control is resized it has to arrange all the elements in the same way that the ribbon bar does
    on  Dynamic Resizing.. 
    can you help me building a Tab control with this feature...
    Thanks,
    Sai Kiran Reddy

    Thanks for your valuable reply Mr. Andy ONeill can you please tell me how to mimic the Dynamic
    Resizing behaviour of Ribbon bar using the WPF Tab Control.. 
    There is an awful lot of functionality in a ribbon.
    And it's pretty tricky to use.
    Personally, I usually go with a tabcontrol and then add functionality I need from there.
    Often two tabitems with horizontally arranged listviews are sufficient.
    You can see that approach in use in my article:
    http://social.technet.microsoft.com/wiki/contents/articles/28209.wpf-entity-framework-mvvm-walk-through-1.aspx
    <TabControl HorizontalAlignment="Left" x:Name="CommandTab">
    <TabItem Header="Navigate" FontSize="10">
    <ListView ItemsSource="{Binding Views}" BorderBrush="Transparent" FontSize="12" FontWeight="Bold"
    ScrollViewer.CanContentScroll="False"
    >
    <ListView.ItemsPanel>
    <ItemsPanelTemplate>
    <StackPanel Orientation="Horizontal"></StackPanel>
    </ItemsPanelTemplate>
    </ListView.ItemsPanel>
    <ListView.ItemTemplate>
    <DataTemplate>
    <Button Command="{Binding Navigate}"
    BorderThickness="0" Height="32" Width="100"
    Background="{StaticResource LightBrightGradientBrush}"
    Foreground="{StaticResource DarkDullBrush}"
    >
    <TextBlock Text="{Binding ViewDisplay}"
    TextAlignment="Center"
    />
    </Button>
    </DataTemplate>
    </ListView.ItemTemplate>
    </ListView>
    </TabItem>
    <TabItem Header="Edit" x:Name="EditTabItem" FontSize="10">
    <ListView ItemsSource="{Binding Commands}" BorderBrush="Transparent" FontSize="12" FontWeight="Bold"
    ScrollViewer.CanContentScroll="False"
    >
    <ListView.ItemsPanel>
    <ItemsPanelTemplate>
    <StackPanel Orientation="Horizontal"/>
    </ItemsPanelTemplate>
    </ListView.ItemsPanel>
    <ListView.ItemTemplate>
    <DataTemplate>
    <Button Command="{Binding Send}"
    BorderThickness="0"
    Margin="0" Padding="0"
    >
    <Path Data="{Binding IconGeometry}" Stretch="Uniform"
    Style="{StaticResource PathOpacityStyle}"
    Fill="{StaticResource MidDullBrush}" Width="32" Height="32"/>
    <Button.ToolTip>
    <TextBlock Text="{Binding CommandDisplay}"/>
    </Button.ToolTip>
    </Button>
    </DataTemplate>
    </ListView.ItemTemplate>
    </ListView>
    </TabItem>
    </TabControl>
    By the way.
    I think if you really work at it you can customise the ribbon by re templating the thing.
    On one project I ran  that work and wrangling the riibbon generally turned out to pretty much eat up all the time of one of my guys though. 
    Hope that helps.
    Recent Technet articles:
    Property List Editing ;  
    Dynamic XAML

  • Rounding errors when plotting rectangles (simple code snippet included)

    hi,
    I'm having a problem with rounding errors, and am unsure what the best thing to do is..
    If you run the snippet of code below, you'll see some rectangles with black lines between them. The range of values covered in the model behind the plot is contiguous, and its only after scaling the trouble begins..
    does anyone have suggestions for what to do here? I need this resize behaviour.. I'm unable to change the interval class :)
    thanks,
    asjf
    import java.awt.Color;
    import java.awt.Graphics;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    @SuppressWarnings("serial")
    public class RoundingError extends JPanel {
         List<Interval> intervals;
         private static final int WIDTH= 25000000;
         private static final int INC= 1000000;
         public RoundingError() {
              setBackground(Color.BLACK);
              intervals= new ArrayList<Interval>();
              for(int i=0; i<WIDTH; i+=INC) {
                   intervals.add(new Interval(i, i+INC));
         @Override
         protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              double scale= getWidth()/(double)WIDTH;
              for(Interval i : intervals) {
                   Random r= new Random(System.identityHashCode(i));
                   g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
                   int sx= (int) (i.start * scale);
                   int sy= getHeight()>>2;
                   int sw= (int) ((i.end-i.start) * scale);
                   int sh= getHeight()>>1;
                   g.fillRect(sx,sy,sw,sh);
         public static void main(String[] args) {
              JFrame frame= new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.getContentPane().add(new RoundingError());
              frame.setSize(800,600);
              frame.setVisible(true);
    class Interval {
         final int start, end;
          * @param start inclusive bound
          * @param end exclusive bound
         Interval(int start, int end) {
              this.start= start;
              this.end= end;
    }

    import java.awt.Color;
    import java.awt.Graphics;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    @SuppressWarnings("serial")
    public class RoundingError extends JPanel {
        List<Interval> intervals;
        private static final int WIDTH= 25000000;
        private static final int INC= 1000000;
        boolean firstTime = true;
        public RoundingError() {
            setBackground(Color.BLACK);
            intervals= new ArrayList<Interval>();
            for(int i=0; i<WIDTH; i+=INC) {
                intervals.add(new Interval(i, i+INC));
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            double scale= getWidth()/(double)WIDTH;
            int count = 0;
            int errorX = 0;
            int totalW = 0;
            int lastX = 0;
            int[] errors = new int[intervals.size()];
            for(Interval i : intervals) {
                Random r= new Random(System.identityHashCode(i));
                g.setColor(new Color(r.nextInt(256),
                                     r.nextInt(256), r.nextInt(256)));
                int sx= (int) (i.start * scale);
                int sy= getHeight()>>2;
                int sw= (int) ((i.end-i.start) * scale);
                int sh= getHeight()>>1;
                if(firstTime) {
                    totalW += sw;
                    if(count > 0) {
                        int error = sx - lastX;
                        if(error != 0) {
                            errors[count] = error;
                        errorX += error;
                    lastX = sx + sw;
                    System.out.printf("count = %2d  sx = %3d  sy = %3d  " +
                                      "sw = %3d  dh = %3d  totalW = %d%n",
                                       count++, sx, sy, sw, sh, totalW);
                g.fillRect(sx,sy,sw,sh);
            if(firstTime) {
                System.out.printf("errorX = %d%n" +
                                  "lastX - totalW = %d%n",
                                   errorX, lastX - totalW);
                for(int i = 0; i < errors.length; i++) {
                    if(errors[i] != 0) {
                        System.out.printf("errors[%2d] = %d%n", i, errors);
    firstTime = false;
    public static void main(String[] args) {
    JFrame frame= new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(new RoundingError());
    frame.setSize(800,600);
    frame.setVisible(true);
    class Interval {
    final int start, end;
    * @param start inclusive bound
    * @param end exclusive bound
    Interval(int start, int end) {
    this.start= start;
    this.end= end;
    This seems to work okay.
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    @SuppressWarnings("serial")
    public class RoundingErrorRx extends JPanel {
        List<Interval> intervals;
        private static final int WIDTH= 25000000;
        private static final int INC= 1000000;
        boolean firstTime = true;
        public RoundingErrorRx() {
            setBackground(Color.BLACK);
            intervals= new ArrayList<Interval>();
            for(int i=0; i<WIDTH; i+=INC) {
                intervals.add(new Interval(i, i+INC));
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            double scale= getWidth()/(double)WIDTH;
            int count = 0;
            double errorX = 0;
            double totalW = 0;
            double lastX = 0;
            double[] errors = new double[intervals.size()];
            for(Interval i : intervals) {
                Random r= new Random(System.identityHashCode(i));
                g.setColor(new Color(r.nextInt(256),
                                     r.nextInt(256), r.nextInt(256)));
                double sx= i.start * scale;
                double sy= getHeight()>>2;
                double sw= (i.end-i.start) * scale;
                double sh= getHeight()>>1;
                if(firstTime) {
                    totalW += sw;
                    if(count > 0) {
                        double error = sx - lastX;
                        if(error != 0) {
                            errors[count] = error;
                        errorX += error;
                    lastX = sx + sw;
                    System.out.printf("count = %2d  sx = %5.1f  sy = %5.1f  " +
                                      "sw = %5.1f  dh = %5.1f  totalW = %5.1f%n",
                                       count++, sx, sy, sw, sh, totalW);
                g2.fill(new java.awt.geom.Rectangle2D.Double(sx,sy,sw,sh));
            if(firstTime) {
                System.out.printf("errorX = %5.1f  lastX - totalW = %5.1f%n",
                                   errorX, lastX - totalW);
                for(int i = 0; i < errors.length; i++) {
                    if(errors[i] != 0) {
                        System.out.printf("errors[%2d] = %5.1f%n", i, errors);
    firstTime = false;
    public static void main(String[] args) {
    JFrame frame= new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(new RoundingErrorRx());
    frame.setSize(800,600);
    frame.setVisible(true);
    class Interval {
    final int start, end;
    * @param start inclusive bound
    * @param end exclusive bound
    Interval(int start, int end) {
    this.start= start;
    this.end= end;

  • Strange behaviour whit custom JTextField and JToolTip

    Hello everyone. I hope I'm writing in the right section and sorry if I did not search for this issue but I really don't know which keywords I should use.
    I'm using NetBeans 6.1 on WinXP and JDK 1.6.0_07, I have a custom JTextField with regex validation: when you type something that don't mach regex it shows a JToolTip. This JToolTip should disappear when the text typed is finally correct, or when the textfield loses focus (see code below).
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Point;
    import javax.swing.JToolTip;
    import javax.swing.Popup;
    import javax.swing.PopupFactory;
    public class MyJTextField extends javax.swing.JTextField implements FormComponent
    private static Popup popUpToolTip;
    private static PopupFactory popUpFactory = PopupFactory.getSharedInstance();
    private boolean isValidated = false;
    private String regEx = "a regex";
    public MyJTextField()
    this.addKeyListener(new java.awt.event.KeyAdapter()
    public void keyReleased(java.awt.event.KeyEvent evt)
    if(evt.getKeyCode()!=java.awt.event.KeyEvent.VK_ENTER)
    validateComponent();
    else if(evt.getKeyCode()==java.awt.event.KeyEvent.VK_ENTER)
    if(isValidated)
    ((Component)evt.getSource()).transferFocus();
    this.addFocusListener(new java.awt.event.FocusAdapter()
    public void focusLost(java.awt.event.FocusEvent evt)
    if(popUpToolTip!=null){popUpToolTip.hide();}
    public void validateComponent()
    if(text.matches(regex))
    isValidated = true;
    if(popUpToolTip!=null){popUpToolTip.hide();}
    else
    isValidated = false;
    if(popUpToolTip!=null){popUpToolTip.hide();}
    String error = "C'&egrave; un errore nella validazione di questo campo";
    JToolTip toolTip = createToolTip();
    toolTip.setTipText(error);
    popUpToolTip = null;
    popUpToolTip = popUpFactory.getPopup(
    this,
    toolTip,
    getLocationOnScreen().x,
    getLocationOnScreen().y - this.getPreferredSize().height -1
    popUpToolTip.show();
    }(I've cut it a bit, here's only the lines that involve JToolTip use)
    I have many of them in a form, and when the first tooltip appears (on the first textfield I type in) it never disappears, while nex textfields work just fine.It seems the first tooltip appearing can't be overwritten or something similar. If I use this same component on any other NetBeans project, everithing works without issues.
    I have some other custom components working the same way (JComboBox, JXDatePicker), and they had this "not disappearing tooltip" issue since I changed this
    popUpToolTip = popUpFactory.getPopup(this, toolTip, getLocationOnScreen().x, getLocationOnScreen().y - this.getPreferredSize().height -1);
    whit this
    popUpToolTip = popUpFactory.getPopup(null, toolTip, getLocationOnScreen().x, getLocationOnScreen().y - this.getPreferredSize().height -1);
    but if I try it on the JTextField all textfield's tooltips stay stuck there, not only the first one appeared (while other components still works fine).
    This thing is really driving me crazy. Someone has an hint (or a link to another thread) which could explain this strange behaviour?
    Thanks in advance.

    BoBear2681 wrote:
    Note that an SSCCE wouldn't require you to post any proprietary code.Hmmm... well, I'll try again to reproduce the issue and post an SSCCE.
    BoBear2681 wrote:
    That probably indicates that the problem is somewhere other than where you're currently looking.Yes, I suppose so. Maybe it's some interference between all the custom components I created, or maybe something else that apparently doesn't conern at all. If I cannot reproduce it in an SSCCE and I'll figure out what's the cause of this mess I'll post it here for future knowledge.
    Many thanks for your advices. :)

  • Weird colour behaviour in JTextField

    Hi,
    I've set the background color of my JTextFields, but they
    keep on changing hue, and fragments of text on the JPanel - for
    example, text from buttons, or from titles appear in the
    JTextFields.
    I've set the color like this:
    Color mandatory = new Color(100,0,0,77); //transparent red
    and then set the background colour as such:
    myJTextField.setBackground(mandatory);
    How do I stop this bizarre behaviour?
    Thanks,
    Hasanka.

    viravan,
    Great article on painting with the Java 2D API.
    The original question dealt with setting the text field background using a color with an alpha value:
    textField.setBackground( new Color(100, 0, 0, 77) );
    The reason this doesn't work is explained in the article:
    "Second, keep in mind the rules of component opacity when dealing with translucent painting. Since translucent items allow pixels behind them to show through, you'd be breaking the rules if you tried to fill the background of an opaque component with translucent painting (even by simply calling setBackground with a translucent color)."
    The key would appear to be the setOpaque(false) method. So if we wanted to use a color with alpha values we could change the paintComponent method as follows:
    public void paintComponent(Graphics g)
         // When transparent we must paint the background
         setOpaque( false );
         g.setColor( new Color(100, 0, 0, 77) );
         g.fillRect(0, 0, getWidth(), getHeight());
         // Paint the text
         super.paintComponent(g);
    }Your example of a semi-transparent background works well with a graph. The graph probably has multiple components layered on top of one another which shows the transparency effect. However I still don't see any difference when using a text field. The background still paints as the solid color represented by the color(172, 142, 141). I tried using an alphacomposite but got the same result.
    If you have sample code of a semi-transparent background of a text field I would be interested in seeing that.

  • How to Resize JButton,JTextArea and JTextFields on Mouse Over....

    Hi All...
    Hi friends.. I want to be implement my java swing application Resize the Width and Height wise of JButton,JLabel,JTextFields on mouse over etc.
    ============================
    Arjun Palanichamy.
    Senior Programmer.
    Chennai-India.

    Hi All...
    I am herewith enclosed my sample code for resize the JButton(),But This one resize the when will be extend the Button Caption letters,But i want mouse click resize the without button caption or with caption.
    sample code :
    package Resize;
    import java.awt.Container;
    import java.awt.FlowLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import java.awt.Dimension;
    import java.awt.ComponentOrientation;
    public class ReButton{
    public static boolean RIGHT_TO_LEFT = false;
    public static void addComponents(Container contentPane) {
    if (RIGHT_TO_LEFT) {
    contentPane.setComponentOrientation(
    ComponentOrientation.RIGHT_TO_LEFT);
    contentPane.setLayout(new FlowLayout());
    contentPane.add(new JButton("1"));
    contentPane.add(new JButton("100"));
    contentPane.add(new JButton("100 100"));
    contentPane.add(new JButton("100 100 100"));
    contentPane.add(new JButton("100 100 100 100"));
    contentPane.add(new JButton("5"));
    private static void createAndShowGUI() {
    JFrame frame = new JFrame("FlowLayoutDemo") {
    public Dimension getMinimumSize() {
    Dimension prefSize = getPreferredSize();
    return new Dimension(100, prefSize.height);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Set up the content pane.
    addComponents(frame.getContentPane());
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    for example can you Click this.....
    http://www.eclipse.org/vep/WebContent/docs/testcases/null-layout/null-layout.htm
    Thanks for your time.
    Arjun Palanichamy.
    Chennai-India.

Maybe you are looking for

  • Kl_virtual_keyboard_secure_input="on" validation error

    It looks like BC default inserts this in the input tag of a search form. kl_virtual_keyboard_secure_input="on" Wanted to know if anyone has experienced problems if its removed? w3c fails validation because of it: -="cat_textbox_small" id="CAT_Search"

  • Writing to a new line in a text files

    I have a servlet that collects results from a questionnaire by getting the parameter values of the radio buttons on a questionnaire page. I am trying to store the results of the questionnaire by writing them to a text file. I can get it to write to t

  • Incoming calls are not finding contact records

    I just upgraded phones from a 3GS to a 4S. The contact records transferred over and call history did as well. But the call history and incoming calls only show the number, they do not show the contact information. In the contact record, the phone num

  • HP Photosmart Studio running SLOW on my new iMac w/Leopard

    We just became Mac users with our new iMac less than a month ago. We got the HP 4400 all in one with the computer as well. I unloaded pics from my camera's card today and used the editing software for the first time....it was incredibly slow. Is ther

  • JSP + Tomcat start problems

    Hi all ,sorry fot desturbing with question that was descused befoure but I have problem to start JSP application on Tomcat server 1.I have created folder named my_folder and set my application here 2.I have created subfolder WEB-INF (but its empty be