Center JComboBox in BoxLayout

I try to center a single JComboBox in a JPanel with BoxLayout. But it is still left aligned. I use:
jpanel.setLayout(new BoxLayout(jpanel,BoxLayout.X_AXIS));
...add(jpanel);
jcombo.setAlignmentX(0.5F);
jpanel.add(jcombo);
What is missing?

wow, it works, I'll give you my last two duke dollars. I should achieve new ones for my logins I expect.
Now, x-centering seems only to be possible if aligned along y-axis. So for the other panels where I have to align along x-axis because I have more than one combo included I can't make a simple centering? Do I have to use invisible components to have some centering effects?

Similar Messages

  • How to adjust for different numbers of components on a JTabbedPane

    Hi,
    I have five panels on a JTabbedPane. On one, I have six components, with each being an array of five (in other words, I have six "columns" of five "rows" each). On another pane, I have only two components (not arrays). I understand that the JTabbedPane will be as large as the largest panel. In my case, the panel with two components is as large as the one with the arrays and the two components take up the entire panel. I have tried to adjust this by using the createGlue(), createHorizontalStrut(), and createVerticalStrut() methods, but it is somewhat "ugly." I am also using the Box layout. Is there a better way to do this? I have included some of my code for reference; (sorry for its length; I am including the code for only two of the five panels). Any assistance would be appreciated.
    TIA,
    Jeff
    Here is the code that creates the panel with the "columns" and "rows":
    public MailGen construct()
        //- create the controls for the emocPanel
        JLabel emocActionLabel = new JLabel( "ACTION" );
        emocActionLabel.setHorizontalAlignment( JLabel.CENTER );
        JLabel emocOrgIdLabel = new JLabel( "ORGANIZATION" );
        emocOrgIdLabel.setHorizontalAlignment( JLabel.CENTER );
        JLabel emocAircraftLabel = new JLabel( "AIRCRAFT" );
        emocAircraftLabel.setHorizontalAlignment( JLabel.CENTER );
        JLabel emocCatLabel = new JLabel( "CAT." );
        emocCatLabel.setHorizontalAlignment( JLabel.CENTER );
        JLabel emocSequenceLabel = new JLabel( "SEQ. # STARTS WITH" );
        emocSequenceLabel.setHorizontalAlignment( JLabel.CENTER );
        JLabel emocQuantityLabel = new JLabel( "QTY OF EMAILS" );
        emocQuantityLabel.setHorizontalAlignment( JLabel.CENTER );
        JComboBox emocActionComboBox;
        JTextField emocOrgTextField;
        JTextField emocAircraftTextField;
        JComboBox emocCategoriesComboBox;
        JTextField emocSequenceTextField;
        JTextField emocQuantityTextField;
        //- create the boxes that will contain the EMOC labels and controls
        Box northEmocBox = new Box( BoxLayout.X_AXIS );
        Box centerEmocBox = new Box( BoxLayout.X_AXIS );
        Box southEmocBox = new Box( BoxLayout.X_AXIS );
        //- add the EMOC labels to the northEmocBox
        //- HERE I AM USING STRUTS
        northEmocBox = Box.createHorizontalBox();
        northEmocBox.add( Box.createHorizontalStrut( 15 ) );
        northEmocBox.add( emocActionLabel );
        northEmocBox.add( Box.createHorizontalStrut( 40 ) );
        northEmocBox.add( Box.createVerticalStrut( 25 ) );
        northEmocBox.add( emocOrgIdLabel );
        northEmocBox.add( Box.createHorizontalStrut( 40 ) );
        northEmocBox.add( Box.createVerticalStrut( 25 ) );
        northEmocBox.add( emocAircraftLabel );
        northEmocBox.add( Box.createHorizontalStrut( 40 ) );
        northEmocBox.add( Box.createVerticalStrut( 25 ) );
        northEmocBox.add( emocCatLabel );
        northEmocBox.add( Box.createHorizontalStrut( 5 ) );
        northEmocBox.add( Box.createVerticalStrut( 25 ) );
        northEmocBox.add( emocSequenceLabel );
        northEmocBox.add( Box.createHorizontalStrut( 15 ) );
        northEmocBox.add( Box.createVerticalStrut( 25 ) );
        northEmocBox.add( emocQuantityLabel );
        northEmocBox.add( Box.createHorizontalStrut( 15 ) );
        JPanel mainEmocPanel = new JPanel();
        mainEmocPanel.setLayout( new BoxLayout( mainEmocPanel, BoxLayout.Y_AXIS ) );
        mainEmocPanel.add( northEmocBox );
        //- add the EMOC controls to the centerEmocBox
        Object[][] emocFieldTable = new Object[5][6];
        for ( int index = 0; index < 5; index++ )
          centerEmocBox = Box.createHorizontalBox();
          emocFieldTable[index][0] = new JComboBox( actions );
          ( ( JComboBox ) emocFieldTable[index][0] ).setBorder(
          BorderFactory.createLineBorder( Color.BLACK, 1 ) );
          emocFieldTable[index][1] = new JTextField( 3 );
          ( ( JTextField ) emocFieldTable[index][1] ).setBorder(
          BorderFactory.createLineBorder( Color.BLACK, 1 ) );
          emocFieldTable[index][2] = new JTextField( 3 );
          ( ( JTextField ) emocFieldTable[index][2] ).setBorder(
          BorderFactory.createLineBorder( Color.BLACK, 1 ) );
          emocFieldTable[index][3] = new JComboBox( categories );
          ( ( JComboBox ) emocFieldTable[index][3] ).setBorder(
          BorderFactory.createLineBorder( Color.BLACK, 1 ) );
          emocFieldTable[index][4] = new JTextField( 3 );
          ( ( JTextField ) emocFieldTable[index][4] ).setBorder(
          BorderFactory.createLineBorder( Color.BLACK, 1 ) );
          emocFieldTable[index][5] = new JTextField( 3 );
          ( ( JTextField ) emocFieldTable[index][5] ).setBorder(
          BorderFactory.createLineBorder( Color.BLACK, 1 ) );
          centerEmocBox.add( ( JComboBox )emocFieldTable[index][0] );
          centerEmocBox.add( ( JTextField )emocFieldTable[index][1] );
          centerEmocBox.add( ( JTextField )emocFieldTable[index][2] );
          centerEmocBox.add( ( JComboBox )emocFieldTable[index][3] );
          centerEmocBox.add( ( JTextField )emocFieldTable[index][4] );
          centerEmocBox.add( ( JTextField )emocFieldTable[index][5] );
          mainEmocPanel.add( centerEmocBox );
        //- create the SEND and CANCEL buttons
        JButton emocSendButton = new JButton( "SEND EMAIL" );
        emocSendButton.setBackground( Color.white );
        emocSendButton.setBorder( raisedBevel );
        JButton emocCancelButton = new JButton( "CANCEL" );
        emocCancelButton.setBackground( Color.white );
        emocCancelButton.setBorder( raisedBevel );
        //- add the buttons to the southEmocBox
        southEmocBox = Box.createHorizontalBox();
        southEmocBox.add( emocSendButton );
        southEmocBox.add( emocCancelButton );
        mainEmocPanel.add( southEmocBox );Here is the code that creates the panel with only two components:
    //- create the controls for preguardPanel
        JLabel preguardActionLabel = new JLabel( "SELECT ACTION" );
        preguardActionLabel.setHorizontalAlignment( JLabel.CENTER );
        preguardActionLabel.setPreferredSize( new Dimension( 100, 10 ) );
        JComboBox preguardActionComboBox = new JComboBox( actions );
        preguardActionComboBox.setBorder( BorderFactory.createLineBorder(
            Color.BLACK, 1 ) );
        preguardActionComboBox.setPreferredSize( new Dimension( 30, 10 ) );
        //- create the SEND and CANCEL buttons
        JButton preguardSendButton = new JButton( "SEND ACTION" );
        preguardSendButton.setBackground( Color.white );
        preguardSendButton.setBorder( raisedBevel );
        JButton preguardCancelButton = new JButton( "CANCEL" );
        preguardCancelButton.setBackground( Color.white );
        preguardCancelButton.setBorder( raisedBevel );
        //- create the boxes that will contain the preguard label and control
        Box northPreguardBox = new Box( BoxLayout.X_AXIS );
        Box centerPreguardBox = new Box( BoxLayout.X_AXIS );
        Box southPreguardBox = new Box( BoxLayout.X_AXIS );
        //- add the preguard label to the northPreguardBox
        northPreguardBox = Box.createHorizontalBox();
        northPreguardBox.add( Box.createGlue() );
        //northPreguardBox.add( Box.createGlue() );
        northPreguardBox.add( preguardActionLabel );
        //northPreguardBox.add( Box.createGlue() );
        northPreguardBox.add( Box.createGlue() );
        JPanel mainPreguardPanel = new JPanel();
        mainPreguardPanel.setLayout( new BoxLayout(
            mainPreguardPanel, BoxLayout.Y_AXIS ) );
        mainPreguardPanel.add( northPreguardBox );
        //- add the preguard control to the centerPreguardBox
        //- HERE IS THE "GLUE" I AM USING
        centerPreguardBox = Box.createHorizontalBox();
        centerPreguardBox.add( Box.createGlue() );
        centerPreguardBox.add( Box.createGlue() );
        centerPreguardBox.add( Box.createGlue() );
        centerPreguardBox.add( Box.createGlue() );
        centerPreguardBox.add( preguardActionComboBox );
        centerPreguardBox.add( Box.createGlue() );
        centerPreguardBox.add( Box.createGlue() );
        centerPreguardBox.add( Box.createGlue() );
        centerPreguardBox.add( Box.createGlue() );
        mainPreguardPanel.add( centerPreguardBox );
        //- add the buttons to the southPreguardBox
        southPreguardBox = Box.createHorizontalBox();
        southPreguardBox.add( Box.createHorizontalStrut( 10 ) );
        southPreguardBox.add( preguardSendButton );
        southPreguardBox.add( preguardCancelButton );
        mainPreguardPanel.add( southPreguardBox );Here, I am adding the panels to the JTabbedPane:
    //- add the panels to the tabbed pane
       JTabbedPane pane = new JTabbedPane();
       pane.add( "EMOC", mainEmocPanel );
       pane.add( "PREGUARD", mainPreguardPanel );
    }

    This seems to be a commercial product. For the best chance at finding a solution I would suggest posting in the forum for HP Business Support!
    You can find the Commercial Designjet board here:
    http://h30499.www3.hp.com/t5/Printers-Designjet-Large-Format/bd-p/bsc-414
    Best of Luck!
    You can say thanks by clicking the Kudos Star in my post. If my post resolves your problem, please mark it as Accepted Solution so others can benefit too.

  • Validating strings

    Hey, how would i go about validating that a JTextField holds a string that doesn't contain any numbers or blank spaces? Obviously you would access the string using 'JTextField'.getText() but how would you parse through the letters to validate it?

    Heres the full code I'm working with. It's a GUI character creater and I need to validate the Name field, like I said it can't have numbers, blank spaces, or generally be null.
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.IllegalFormatException;
    import javax.swing.*;
    public class CharacterCreator extends JFrame {
        JButton CreateButton, ExitButton;
        JPanel MainPanel, ButtonPanel, Center, TextPanel, DropBox, RadioPanel, CheckBoxPanel, NamePanel, LevelPanel;
        JLabel TextArea, job, gender, level, heroic, name;
        JTextField textField1, textField2;
        String textCheck, textCheck1, textCheck2;
        JComboBox box;
        ButtonGroup buttonGroup;
        JCheckBox checkBox;
        JRadioButton button1, button2;
        int intCheck;
        public CharacterCreator(){
            this.setTitle("War Quest Character Creator");
            this.setSize(500, 400);
            this.setLocation(100, 100);
            this.addWindowListener(new ExitListener());
            CreateButton = new JButton("Create");
            CreateButton.addActionListener(new CreateListener());
            ExitButton = new JButton("Exit");
            ExitButton.addActionListener(new ExitListener());
            TextArea = new JLabel();
            TextArea.setSize(500,500);
            JPanel TextPanel = new JPanel(new FlowLayout());
            TextPanel.add(TextArea);
            JPanel ButtonPanel = new JPanel(new FlowLayout());
            ButtonPanel.add(CreateButton);
            ButtonPanel.add(ExitButton);
            JPanel Center = new JPanel();
            Center.setLayout(new BoxLayout(Center, BoxLayout.Y_AXIS ));
            Center.add(createNamePanel());
            Center.add(createComboBoxPanel());
            Center.add(createLevelPanel());
            Center.add(createRadioPanel());
            Center.add(createCheckPanel());
            JPanel MainPanel = new JPanel(new BorderLayout());
            MainPanel.add(ButtonPanel, BorderLayout.SOUTH);
            MainPanel.add(TextPanel, BorderLayout.NORTH);
            MainPanel.add(Center, BorderLayout.CENTER);
            this.setContentPane(MainPanel);
        private JPanel createLevelPanel(){
            textField1 = new JTextField();
            textField1.setEditable(true);
            textField1.setText("Enter Level");
            level = new JLabel("Level:");
            JPanel textFieldPanel = new JPanel();
            textFieldPanel.add(level);
            textFieldPanel.add(textField1);
            return textFieldPanel;
        private JPanel createNamePanel(){
            textField2 = new JTextField();
            textField2.setEditable(true);
            textField2.setText("Enter Name");
            name = new JLabel("Name:");
            JPanel textFieldPanel1 = new JPanel();
            textFieldPanel1.add(name);
            textFieldPanel1.add(textField2);
            return textFieldPanel1;
        private JPanel createCheckPanel(){
            checkBox = new JCheckBox();
            heroic = new JLabel("Heroic:");
            JPanel checkboxPanel = new JPanel();
            checkboxPanel.add(heroic);
            checkboxPanel.add(checkBox);
            return checkboxPanel;
        private JPanel createRadioPanel(){
            button1 = new JRadioButton("Male");
            button1.setSelected(true);
            button2 = new JRadioButton("Female");
            buttonGroup = new ButtonGroup();
            buttonGroup.add(button1);
            buttonGroup.add(button2);
            gender = new JLabel("Gender:");
            JPanel radioButtonPanel = new JPanel();
            radioButtonPanel.add(gender);
            radioButtonPanel.add(button1);
            radioButtonPanel.add(button2);
            return radioButtonPanel;
        private JPanel createComboBoxPanel() {
            String[] options = new String[3];
            options[0]="Barbarian";
            options[1]="Rogue";
            options[2]="Archer";
            box = new JComboBox(options);
            box.setEditable(false);
            box.setEnabled(true);
            box.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
            box.getInputContext();
            job = new JLabel("Job:");
            JPanel comboBoxPanel = new JPanel();
            comboBoxPanel.add(job);
            comboBoxPanel.add(box);
            return comboBoxPanel;
        public void create(){
         textCheck1 = textField1.getText();
         try{
           intCheck = Integer.parseInt(textCheck1);
         catch(IllegalArgumentException nfe) {
           System.out.println("NumberFormatException: Level must be a number between 1-70");
           return;
         if(intCheck>70){
             throw new NumberFormatException("NumberFormatException: Level must be a number between 1-70");
         else{
           TextArea.setText("Character Successfully Created");
           if(button1.isSelected()){
           System.out.println("Character: \n"+"Name: "+textField2.getText()+"\n"+"Job: "+box.getSelectedItem()+"\n"+"Level: "+textField1.getText()+"\n"+"Gender: Male"+"\n"+"Heroic: "+checkBox.isSelected()+"\n");
           else if(button2.isSelected()){
           System.out.println("Character: \n"+"Name: "+textField2.getText()+"\n"+"Job: "+box.getSelectedItem()+"\n"+"Level: "+textField1.getText()+"\n"+"Gender: Male"+"\n"+"Heroic: "+checkBox.isSelected()+"\n");
        private void exit() {
            System.exit(0);
        private class ExitListener extends WindowAdapter implements ActionListener {
            public void windowClosing(WindowEvent e) {
                exit();
             public void actionPerformed(ActionEvent e) {
                exit();
        private class CreateListener extends WindowAdapter implements ActionListener {
             public void actionPerformed(ActionEvent e) {
                create();
        public static void main(String[] args) {
            CharacterCreator character = new CharacterCreator();
            character.setVisible(true);
    } If I were to use a JFormatedTextField instead of a regular one, how would I then format the field? The sub-methods and Javadoc on the sun site don't make a lot of sense as a Java beginner. The way I originally though about doing this was by nesting another loop in the create() method that would parse the string and check for numbers or spaces but I couldn't figgure out how to do that either. If someone could help I'd appreciate it. Thanks.

  • JTable JCombox popup on click in table cell

    What is the recommended way of making a JComboBox that is in a JTable cell popup when the user clicks once anywhere in the cell?
    The popup is actually a calendar that works fine if the user clicks on the spot where the button shows up in the cell but sets the focus in the text box of the JComboBox is the click is anywhere else in the cell and the popup doesn't sho in that case. To get to the popup requires a click on the button.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame {
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        String[] head = {"One","Two","Three"};
        String[][] data = {{"R1-C1","R1-C2","R1-C3"},
                           {"R2-C1","R2-C2","R2-C3"},
                           {"R3-C1","R3-C2","R3-C3"}};
        JTable jt = new JTable(data, head);
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        JComboBox jcb = new JComboBox(head);
        jcb.addFocusListener(new FocusAdapter() {
          public void focusGained(FocusEvent fe) {
            ((JComboBox)fe.getSource()).showPopup();
        jt.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(jcb));
        setSize(200, 200);
        setVisible(true);
      public static void main(String[] args) { new Test(); }
    }

  • Align left panels inside BoxLayOut / Center a frame center screen

    Hi,
    I've googled for a good while now so now I'm posting the question I have not found a satisfactory answer. It may be that I've been searching by the wrong terms, because it's an easy thing in concept. This is a JSwing question and all terms below apply to that.
    I have a method which takes a container that has a BoxLayout manager. Each item I add is a new row, which is good. The bad thing is that each item is centered aligned. I'm adding a label and textfield into a panel which I then add to the container. I have tried .setAlignmentX to the label, textfield, panel, and all combination pertaining. I can not for the life of me do it. Please see below for pertinent code.
    public void addComponentsToPane(Container pane) {
    pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
    JPanel user = new JPanel();
    JLabel userL = new JLabel("Username: ");
    JTextField userT = new JTextField(20);
    user.add(userL);
    user.add(userT);
    user.setAlignmentX(Component.LEFT_ALIGNMENT);
    I hate to put two questions in one thread, but I'm stuck and it's been a long weekend. How come frame.setLocationRelativeTo(null); doesn't set the frame to the center of the window. It's slightly off center; too far to the right and down.
    Thanks in advance for any help given by the community. I appreciate it and hope I haven't broken any guidelines for the forum.

    Go through the [url http://download.oracle.com/javase/tutorial/uiswing/layout/box.html]tutorial for BoxLayout where you will find working code samples. After that, if you still have a problem, post a [url http://mindprod.com/jgloss/sscce.html]SSCCE (Short, Self Contained, Compilable and Executable) that members can copy and run to see where you've slipped up.
    db

  • Maximum size of a JComboBox in a GridBagLayout

    I'm having a problem with a JComboBox inside a GridBagLayout. The general layout is a GridBag with labels / combo / textfields on the first line, a large table in a scrollpane that takes all columns on the second line, and a few labels / combo / textfields on the third.
    As long as the combo on the first combo is empty, it looks fine. When it gets populated, the combo gets resized to the size of the largest text. I would like to have it smaller and truncate the text.
    I tried to set maximum size, but the GridBag doesnt care. I've been trying with weightx but no success.
    What should I do ?

    And I would be interested which LayoutManager you prefer using.I don't use a single Layout Manager. I use a combination of Layout Managers to do the job. Thats why this question doesn't have a specific example. Remember LayoutManagers can be nested. The default layout manager for a frame is a border layout. That great for the general look of your application.
    a) you add a toolbar to the north
    b) you add a status bar to the south
    c) you add your main panel to the center.
    the main panel in turrn may use nested panels depending on your requirements. I don't do a lot of screen design but I typically use BorderLayout, FlowLayout, GridLayout and BoxLayout. GridBagLayout and SpringLayout have too many constraints to learn and master. They may be good for a GUI tool that only uses a single layout manager for the entire GUI, but I believe a better design is to break down the form into smaller more manageable areas and group components and use the appropriate layout manager for the group. That may or may not be a GridBagLayout for the small group, but I don't think you should force the entire form to use a GridbagLayout.

  • JComboBox + Hasmap

    I know this must seem like a completely newbie question and I thought I was doing it correct but something somewhere is going wrong.
    I have a Hashmap that contains arrays of BigDecimal with keys such as 1.00,1.002, 12.004 etc. as strings.
    If surfacePipeNumber is the JComboBox shouldnt the next line return the contents of the selected item as a string?
    (surfacePipeNumber.getSelectedItem()).toString()
    I have added a actionListener to a JComboBox where it makes a clone of the correct array and sets the correct JTextFields with each part of the array.
    Heres an example:
         public void UpdateSurfaceFields(){
              System.out.println(surfaceWaterData.get(surfacePipeNumber.getSelectedItem()).toString());
              BigDecimal [] tempSurfaceArray = surfaceWaterData.get(surfacePipeNumber.getSelectedItem().toString()).clone();
              surfacePipeLength.setText(tempSurfaceArray[0].toString());
              surfaceDSInvertLevel.setText(tempSurfaceArray[1].toString());
              surfacePipeDiameter.setText(tempSurfaceArray[2].toString());
              surfacePipeSlope.setText(tempSurfaceArray[3].toString());
              surfaceUSEasting.setText(tempSurfaceArray[4].toString());
              surfaceUSNorthing.setText(tempSurfaceArray[5].toString());
              surfaceDSEasting.setText(tempSurfaceArray[6].toString());
              surfaceDSNorthing.setText(tempSurfaceArray[7].toString());
         }The test System.out.println line I added returns:
    [Ljava.math.BigDecimal;@1c282a1
    So is this a string or a BigDecimal?
    I dont know if this matters but I also have a refresh button which addItem to the JComboBox from a scanned in text file. I press the refresh button before I select the JcomboBox which succesfully updates the JComboBox and seems to run my method on its own for some reason but does it correctly, after that it returns a NullPointerException.
    I know if the Hashmap couldnt find the key it would return null but before when the JComboBox was a JTextField it worked fine.
    Thanks,
    Ken

    Yes sorry I didnt have much time to do it in the week but I have now done it,
    I've just tried to cut it down so its the same but with less data/fields to handle.
    Sorry if theres still alot.
    import javax.swing.JTextField;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JComboBox;
    import javax.swing.border.TitledBorder;
    import javax.swing.BorderFactory;
    import javax.swing.BoxLayout;
    import java.awt.GridLayout;
    import java.awt.BorderLayout;
    import java.util.HashMap;
    import java.math.BigDecimal;
    public class DrainageWorkbook extends JFrame{
         private JTextField surfacePipeLength;
         private JTextField surfaceDSInvertLevel;
         private JTextField surfacePipeDiameter;
         private JTextField foulPipeLength;
         private JTextField foulDSInvertLevel;
         private JTextField foulPipeDiameter;
         private JTextField surfaceFilePath, foulFilePath;
         private JButton surfaceBrowse, foulBrowse, refresh;
         private JComboBox surfacePipeNumber;
         private JComboBox foulPipeNumber;
         private static HashMap<String, Pipe> surfaceWaterData;
         private static HashMap<String, Pipe> foulWaterData;
         public static boolean dataImported = false;
         DrainageWorkbook(String title) {
              super(title);
              surfaceWaterData  = new HashMap<String, Pipe>();
              foulWaterData  = new HashMap<String, Pipe>();
              surfacePipeNumber = new JComboBox();
              foulPipeNumber = new JComboBox();
              //Surface Water Fields created and setup
              surfacePipeNumber.addActionListener(new pipeNameListener(surfaceWaterData, foulWaterData,surfacePipeNumber, surfacePipeLength, surfaceDSInvertLevel, surfacePipeDiameter, foulPipeNumber, foulPipeLength, foulDSInvertLevel, foulPipeDiameter));
              surfacePipeLength = new JTextField(10);
              surfacePipeLength.setEditable(false);
              surfaceDSInvertLevel = new JTextField(10);
              surfaceDSInvertLevel.setEditable(false);
              surfacePipeDiameter = new JTextField(10);
              surfacePipeDiameter.setEditable(false);
              //Foul Water Fields created and setup
              foulPipeNumber.addActionListener(new pipeNameListener(surfaceWaterData, foulWaterData, surfacePipeNumber, surfacePipeLength, surfaceDSInvertLevel, surfacePipeDiameter, foulPipeNumber, foulPipeLength, foulDSInvertLevel, foulPipeDiameter));
              foulPipeLength = new JTextField(10);
              foulPipeLength.setEditable(false);
              foulDSInvertLevel = new JTextField(10);
              foulDSInvertLevel.setEditable(false);
              foulPipeDiameter = new JTextField(10);
              foulPipeDiameter.setEditable(false);
              //Create Surface water panel that conatains all surface water fields
              JPanel SurfaceWaterPanel = new JPanel();
              SurfaceWaterPanel.setLayout(new GridLayout(0,2));
              SurfaceWaterPanel.add(new JLabel("Pipe Number: "));
              SurfaceWaterPanel.add(surfacePipeNumber);
              SurfaceWaterPanel.add(new JLabel("Pipe Length: "));
              SurfaceWaterPanel.add(surfacePipeLength);
              SurfaceWaterPanel.add(new JLabel("DS Invert Level: "));
              SurfaceWaterPanel.add(surfaceDSInvertLevel);
              SurfaceWaterPanel.add(new JLabel("Pipe Diameter: "));
              SurfaceWaterPanel.add(surfacePipeDiameter);
              TitledBorder surfaceWaterTitle;
              surfaceWaterTitle = BorderFactory.createTitledBorder("Surface Water Drainage");
              SurfaceWaterPanel.setBorder(surfaceWaterTitle);
              //Create Foul water panel that conatains all foul water fields
              JPanel FoulWaterPanel = new JPanel();
              FoulWaterPanel.setLayout(new GridLayout(0,2));
              FoulWaterPanel.add(new JLabel("Pipe Number: "));
              FoulWaterPanel.add(foulPipeNumber);
              FoulWaterPanel.add(new JLabel("Pipe Length: "));
              FoulWaterPanel.add(foulPipeLength);
              FoulWaterPanel.add(new JLabel("DS Invert Level: "));
              FoulWaterPanel.add(foulDSInvertLevel);
              FoulWaterPanel.add(new JLabel("Pipe Diameter: "));
              FoulWaterPanel.add(foulPipeDiameter);
              TitledBorder foulWaterTitle;
              foulWaterTitle = BorderFactory.createTitledBorder("Foul Water Drainage");
              FoulWaterPanel.setBorder(foulWaterTitle);
              //Buttons/Fields for locating drainage text files
              surfaceFilePath = new JTextField();
              surfaceBrowse = new JButton("Browse...");
              surfaceBrowse.addActionListener(new fileFinderListener(surfaceFilePath));
              foulFilePath = new JTextField();
              foulBrowse = new JButton("Browse...");
              foulBrowse.addActionListener(new fileFinderListener(foulFilePath));
              //Distance panel
              refresh = new JButton("Refresh");
              refresh.addActionListener(new refreshListener(surfaceFilePath, foulFilePath, surfaceWaterData, foulWaterData, surfacePipeNumber, surfacePipeLength, foulPipeNumber));
              JPanel distancePanel = new JPanel();
              distancePanel.setLayout(new BoxLayout(distancePanel,BoxLayout.LINE_AXIS));
              distancePanel.add(refresh);
              //Drainage text file panels
              JPanel surfaceFilePanel = new JPanel();
              surfaceFilePanel.setLayout(new BoxLayout(surfaceFilePanel,BoxLayout.LINE_AXIS));
              surfaceFilePanel.add(new JLabel("Surface water file Path:  "));
              surfaceFilePanel.add(surfaceFilePath);
              surfaceFilePanel.add(surfaceBrowse);
              JPanel foulFilePanel = new JPanel();
              foulFilePanel.setLayout(new BoxLayout(foulFilePanel,BoxLayout.LINE_AXIS));
              foulFilePanel.add(new JLabel("Foul water file Path:         "));
              foulFilePanel.add(foulFilePath);
              foulFilePanel.add(foulBrowse);
              //Combine all panels to go at bottom of program
              JPanel bottomPanel = new JPanel();
              bottomPanel.setLayout(new BoxLayout(bottomPanel,BoxLayout.PAGE_AXIS));
              bottomPanel.add(distancePanel);
              bottomPanel.add(surfaceFilePanel);
              bottomPanel.add(foulFilePanel);
              //Combined panel for surface water and foul water fields
              JPanel CombinedPanel = new JPanel();
              CombinedPanel.setLayout(new GridLayout(0,2));
              CombinedPanel.add(SurfaceWaterPanel);
              CombinedPanel.add(FoulWaterPanel);
              this.setLayout(new BorderLayout());
              this.add(CombinedPanel, BorderLayout.CENTER);
              this.add(bottomPanel, BorderLayout.SOUTH);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public static void main(String[] args) {
              DrainageWorkbook DWB = new DrainageWorkbook("DrainageWorkbook v0.1 Alpha");
              DWB.setSize(600,400);
              DWB.setVisible(true);
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.HashMap;
    import java.util.Scanner;
    import javax.swing.JComboBox;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class refreshListener implements ActionListener{
         private JTextField surfaceFilePath;
         private JTextField foulFilePath;
         private HashMap<String, Pipe> surfaceWaterData;
         private HashMap<String, Pipe> foulWaterData;
         private File surfaceFile, foulFile;
         private Scanner readSurfaceFile, readFoulFile, processSurfaceLine, processFoulLine;
         private JComboBox surfacePipeNumber, foulPipeNumber;
         public static boolean surfaceDataImported = false, foulDataImported = false;
         refreshListener(JTextField sfp, JTextField ffp, HashMap<String, Pipe> swd, HashMap<String, Pipe> fwd,
                             JComboBox spn, JTextField spl, JComboBox fpn){
              surfaceFilePath = sfp;
              foulFilePath = ffp;
              surfaceWaterData = swd;
              foulWaterData = fwd;
              surfacePipeNumber = spn;          
              foulPipeNumber = fpn;
         public void actionPerformed(ActionEvent e){
              UpdateSurfaceData();
              UpdateFoulData();
         public void UpdateSurfaceData(){
              try{
                   surfaceWaterData.clear();
                   surfacePipeNumber.removeAllItems();
                   surfaceFile = new File(surfaceFilePath.getText());
                   readSurfaceFile = new Scanner(surfaceFile);
                   while(readSurfaceFile.hasNextLine()){
                        String pipeName;
                        processSurfaceLine = new Scanner(readSurfaceFile.nextLine());
                        processSurfaceLine.useDelimiter(",");
                        pipeName = processSurfaceLine.next();
                        Pipe surfacePipe = new Pipe(pipeName, 'S');
                        surfacePipeNumber.addItem(surfacePipe.getName());
                        surfacePipe.setLength(processSurfaceLine.next());
                        surfacePipe.setDSInvertLevel(processSurfaceLine.next());
                        surfacePipe.setDiameter(processSurfaceLine.next());
                        surfacePipe.setSlope(processSurfaceLine.next());
                        surfaceWaterData.put(surfacePipe.getName(), surfacePipe);
                        surfaceDataImported = true;
                   JOptionPane.showMessageDialog(null, "Surface Water Data was successfully imported!\r\nType in the surface water pipe number to update the fields", "Surface Water Update Complete", JOptionPane.INFORMATION_MESSAGE);
              }catch (FileNotFoundException ex){
                   JOptionPane.showMessageDialog(null, "One of the drainage files could not be found", "File not found", JOptionPane.ERROR_MESSAGE);
              }finally{
                   if(readSurfaceFile != null)
                   readSurfaceFile.close();
                   if(processSurfaceLine != null)
                   processSurfaceLine.close();
         public void UpdateFoulData(){
              try{
                   foulWaterData.clear();
                   foulPipeNumber.removeAllItems();
                   foulFile = new File(foulFilePath.getText());
                   readFoulFile = new Scanner(foulFile);
                   while(readFoulFile.hasNextLine()){
                        String pipeName;
                        processFoulLine = new Scanner(readFoulFile.nextLine());
                        processFoulLine.useDelimiter(",");
                        pipeName = processFoulLine.next();
                        Pipe foulPipe = new Pipe(pipeName, 'F');
                        foulPipeNumber.addItem(foulPipe.getName());
                        foulPipe.setLength(processFoulLine.next());
                        foulPipe.setDSInvertLevel(processFoulLine.next());
                        foulPipe.setDiameter(processFoulLine.next());
                        foulPipe.setSlope(processFoulLine.next());
                        foulWaterData.put(foulPipe.getName(), foulPipe);
                        foulDataImported = true;
                   JOptionPane.showMessageDialog(null, "Foul Water Data was successfully imported!\r\nType in the foul water pipe numbers to update the fields", "Foul Water Update Complete", JOptionPane.INFORMATION_MESSAGE);
              }catch (FileNotFoundException ex){
                   JOptionPane.showMessageDialog(null, "One of the drainage files could not be found", "File not found", JOptionPane.ERROR_MESSAGE);
              }finally{
                   if(readSurfaceFile != null)
                   readSurfaceFile.close();
                   if(processSurfaceLine != null)
                   processSurfaceLine.close();
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.math.BigDecimal;
    import java.util.HashMap;
    import javax.swing.JComboBox;
    import javax.swing.JTextField;
    public class pipeNameListener implements ActionListener{
         private HashMap<String, Pipe> surfaceWaterData;
         private HashMap<String, Pipe> foulWaterData;
         private JTextField surfacePipeLength, surfaceDSInvertLevel, surfacePipeDiameter;
         private JTextField foulPipeLength, foulDSInvertLevel, foulPipeDiameter;
         private JComboBox surfacePipeNumber, foulPipeNumber;
         private Pipe surfacePipeSelected, foulPipeSelected;
         pipeNameListener(HashMap<String, Pipe> swd, HashMap<String, Pipe> fwd,
                   JComboBox spn, JTextField spl, JTextField sdsil, JTextField spd,
                   JComboBox fpn, JTextField fpl, JTextField fsail, JTextField fpd){
              surfaceWaterData = swd;
              foulWaterData = fwd;
              surfacePipeNumber = spn;
              surfacePipeLength = spl;
              surfaceDSInvertLevel = sdsil;
              surfacePipeDiameter = spd;
              foulPipeNumber = fpn;
              foulPipeLength = fpl;
              foulDSInvertLevel = fsail;
              foulPipeDiameter = fpd;
         public void actionPerformed(ActionEvent e) {
              if(refreshListener.surfaceDataImported)
                   UpdateSurfaceFields();
              if(refreshListener.foulDataImported)
                   UpdateFoulFields();
         public void UpdateSurfaceFields(){
              surfacePipeSelected = surfaceWaterData.get(surfacePipeNumber.getSelectedItem().toString());
              surfacePipeLength.setText(surfacePipeSelected.getLength().toString());
              surfaceDSInvertLevel.setText(surfacePipeSelected.getDSInvertLevel().toString());
              surfacePipeDiameter.setText(surfacePipeSelected.getDiameter().toString());
         public void UpdateFoulFields(){
              foulPipeSelected = foulWaterData.get((foulPipeNumber.getSelectedItem()));
              foulPipeLength.setText((foulPipeSelected.getLength()).toString());
              foulDSInvertLevel.setText(foulPipeSelected.getDSInvertLevel().toString());
              foulPipeDiameter.setText(foulPipeSelected.getDiameter().toString());
    import java.math.BigDecimal;
    import javax.swing.JOptionPane;
    public class Pipe{
    String Name;
    char type;
    BigDecimal Length;
    BigDecimal DSInvertLevel;
    BigDecimal Diameter;
    BigDecimal Slope;
         Pipe(String pipeName, char pipeType){
              Name = pipeName;
              type = pipeType;
         public String getName(){
              return Name;
         public void setLength(String l){
              try{
                   Length = new BigDecimal(l);
              }catch (NumberFormatException nf){
                   JOptionPane.showMessageDialog(null, "The length for pipe " + Name + " is in an incorrect number format.", "Number Format Error", JOptionPane.ERROR_MESSAGE);
         public BigDecimal getLength(){
              return Length;
         public void setDSInvertLevel(String dsil){
              try{
                   DSInvertLevel = new BigDecimal(dsil);
              }catch (NumberFormatException nf){
                   JOptionPane.showMessageDialog(null, "The Downstream invert level for pipe " + Name + " is in an incorrect number format.", "Number Format Error", JOptionPane.ERROR_MESSAGE);
         public BigDecimal getDSInvertLevel(){
              return DSInvertLevel;
         public void setDiameter(String d){
              try{
                   Diameter = new BigDecimal(d);
              }catch (NumberFormatException nf){
                   JOptionPane.showMessageDialog(null, "The diameter for pipe " + Name + " is in an incorrect number format.", "Number Format Error", JOptionPane.ERROR_MESSAGE);
         public BigDecimal getDiameter(){
              return Diameter;
         public void setSlope(String s){
              try{
                   Slope = new BigDecimal(s);
              }catch (NumberFormatException nf){
                   JOptionPane.showMessageDialog(null, "The slope for pipe " + Name + " is in an incorrect number format.", "Number Format Error", JOptionPane.ERROR_MESSAGE);
         public BigDecimal getSlope(){
              return Slope;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;
    import javax.swing.JFrame;
    import java.io.File;
    public class fileFinderListener implements ActionListener{
         private JTextField filePath;
         fileFinderListener(JTextField fp){
              filePath = fp;
         public void actionPerformed(ActionEvent e) {
              JFileChooser fc = new JFileChooser();
              fc.addChoosableFileFilter(new FileSelectFilter());
              fc.setAcceptAllFileFilterUsed(false);
            int returnVal = fc.showOpenDialog(new JFrame());
            if (returnVal == JFileChooser.APPROVE_OPTION){
                File file = fc.getSelectedFile();
                filePath.setText(file.getAbsolutePath()) ;
            } else {
                 JOptionPane.showMessageDialog(null, "File selection cancelled by user. ", "File Selection", JOptionPane.INFORMATION_MESSAGE );
    import javax.swing.filechooser.FileFilter;
    import java.io.File;
    public class FileSelectFilter extends FileFilter {
        //Accept all directories and all txt and csv files.
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            String extension = getExtension(f);
            if (extension != null) {
                if (extension.equals("txt") ||
                    extension.equals("csv")){
                        return true;
                } else {
                    return false;
            return false;
        public static String getExtension(File f) {
            String ext = null;
            String s = f.getName();
            int i = s.lastIndexOf('.');
            if (i > 0 &&  i < s.length() - 1) {
                ext = s.substring(i+1).toLowerCase();
            return ext;
        //The description of this filter
        public String getDescription() {
            return "Text Files (.txt, .csv)";
    }

  • Minimize size of a JComboBox

    Hi,
    i�ve got a JComboBox rendered into a JTable. This works fine but the ComboBox is much to big. I played around with setMaximumSize in several LayoutManagers. The problem is that at a certain size it cuts the JComboBox. What to do? thanks
    uri

    And I would be interested which LayoutManager you prefer using.I don't use a single Layout Manager. I use a combination of Layout Managers to do the job. Thats why this question doesn't have a specific example. Remember LayoutManagers can be nested. The default layout manager for a frame is a border layout. That great for the general look of your application.
    a) you add a toolbar to the north
    b) you add a status bar to the south
    c) you add your main panel to the center.
    the main panel in turrn may use nested panels depending on your requirements. I don't do a lot of screen design but I typically use BorderLayout, FlowLayout, GridLayout and BoxLayout. GridBagLayout and SpringLayout have too many constraints to learn and master. They may be good for a GUI tool that only uses a single layout manager for the entire GUI, but I believe a better design is to break down the form into smaller more manageable areas and group components and use the appropriate layout manager for the group. That may or may not be a GridBagLayout for the small group, but I don't think you should force the entire form to use a GridbagLayout.

  • Unexplained indentation after JComboBox

    Hey folks,
    I've got a bit of an odd problem here, which is either because of my ignorance of JComboBox behaviour or simply an odd bug or feature in said JComboBox component.
    Basically, I've got an Options window that, in my application, is opened using a JOptionPane. (So it's a Dialog instead of a Frame.) In this Options window, I've got a JPanel (holder) that holds another JPanel (copying). This JPanel holds another JPanel (bufferSize) and two JCheckBoxes. In the last JPanel (bufferSize) is a JLabel and a JComboBox.
    The problem lies with the JComboBox; below the JComboBox come the two JCheckBoxes that now have, unexplicably, an indentation of about 100 pixels. Below I've added the simplified code of the problem. If you guys want to see it for yourself, create three Java files with the said class names and run the ComboExample.java file. (It's the one with the main method... ;))
    So, essentially; any of you have a clue what's causing this indentation? More information available in the form of comments in the code. I've also got an email subscription to this thread, so feel free to ask any questions about the code and supply me with suggestions. I'll try to reply as soon as I get the email.. ;)
    import javax.swing.JFrame;
    public class ComboExample{
         public static void main(String args[]){
              GUI gui = new GUI();
              gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              gui.setSize(350, 75);
              gui.setTitle("Example app; opening the options menu");
              gui.setVisible(true);
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class GUI extends JFrame implements ActionListener{
         private JButton buttonOpenDialog;
         // Constructor; creates button, adds actionlistener and adds button to frame
         public GUI(){
              buttonOpenDialog = new JButton("Open the new dialog!");
              buttonOpenDialog.addActionListener(this);
              add(buttonOpenDialog);
         // Mandatory method that controls what happens when the button's pressed
         // (When pressed: new window opens called Options)
         public void actionPerformed(ActionEvent e) {
              if(e.getSource() == buttonOpenDialog){
                   Options options = new Options();
                   JOptionPane.showMessageDialog(null, options, "Options menu", JOptionPane.PLAIN_MESSAGE);
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.*;
    import javax.swing.border.TitledBorder;
    public class Options extends JPanel{
         private JCheckBox showCopyOverview;
         private JCheckBox showCopyErrorMessages;
         private JComboBox bufferSize;
         // Constructor calls createInterface method
         public Options(){
              createInterface();
          * Creates the interface. First a holder panel is created that uses a BorderLayout.
          * This is done for future implementations. Then there's a copying panel with its own
          * border and text on border. This panel uses a Vertical (Y_AXIS) BoxLayout. To these
          * the various options are added. Lastly, the Combobox is on its own panel so that
          * the label can appear next to it. This panel also uses a BoxLayout, but then a horizontal
          * (X_AXIS) variant.
          * My question now is; why do the two checkboxes below the JComboBox and JLabel have
          * that indentation that they do? I never tell them to do that.
          * Solutions tried:
          * - Setting a maximum size (setMaximumSize())
          * - Removing the JComboBox (worked partially; the indentation became smaller)
          * - Removing the JLabel (worked partially, see above)
          * - Removing the bufferSizePanel but leaving the JLabel and JComboBox
          * - Removing the bufferSizePanel, JLabel and JComboBox (works, but evidently not desired)
          * - Putting the two JCheckBoxes on a different JPanel
          * - Suggestions... ?
         public void createInterface(){
              // First create all the required panels
              JPanel panelHolder = new JPanel();
              panelHolder.setLayout(new BorderLayout());
              JPanel panelCopying = new JPanel();
              panelCopying.setLayout(new BoxLayout(panelCopying, BoxLayout.Y_AXIS));
              TitledBorder borderCopying = BorderFactory.createTitledBorder("Copying options");
              panelCopying.setBorder(borderCopying);
              JPanel panelBufferSize = new JPanel();
              panelBufferSize.setLayout(new BoxLayout(panelBufferSize, BoxLayout.X_AXIS));
              // Create all the elements that will inhabit the panels
              showCopyOverview = new JCheckBox("Option 1");
              showCopyErrorMessages = new JCheckBox("Option 2");
              JLabel labelBufferSize = new JLabel("Option 3: ");
              bufferSize = new JComboBox();
              bufferSize.setMaximumSize(new Dimension(65, 25));
              // Add all the elements to their respective panels
              panelBufferSize.add(labelBufferSize);
              panelBufferSize.add(bufferSize);
              panelCopying.add(panelBufferSize);
              panelCopying.add(showCopyOverview);
              panelCopying.add(showCopyErrorMessages);
              panelHolder.add(panelCopying, BorderLayout.CENTER);
              add(panelHolder);
    }Edited by: SEThorian on Dec 4, 2008 1:35 PM

    You are looking for JComponent#setAlignmentX(float).
    [How to Use BoxLayout (The Java™ Tutorials > Creating a GUI with JFC/Swing > Laying Out Components Within a Container)|http://java.sun.com/docs/books/tutorial/uiswing/layout/box.html]
    import java.awt.*;
    import javax.swing.*;
    public class ComboExample{
        public static void main(String[] args) {
            JOptionPane.showMessageDialog(null, new Options(),
                          "Options menu", JOptionPane.PLAIN_MESSAGE);
    class Options extends JPanel{
        private JCheckBox showCopyOverview;
        private JCheckBox showCopyErrorMessages;
        private JComboBox bufferSize;
        public Options(){
            super(new BorderLayout());
            createInterface();
        public void createInterface(){
            bufferSize             = new JComboBox();
            showCopyOverview       = new JCheckBox("Option 1");
            showCopyErrorMessages  = new JCheckBox("Option 2");
            JPanel panelBufferSize = new JPanel(new BorderLayout());
            panelBufferSize.add(new JLabel("Option 3: "), BorderLayout.WEST);
            panelBufferSize.add(bufferSize);
            Box panelCopying = Box.createVerticalBox();
            panelCopying.setBorder(
               BorderFactory.createTitledBorder("Copying options"));
            panelCopying.add(panelBufferSize);
            panelCopying.add(showCopyOverview);
            panelCopying.add(showCopyErrorMessages);
            panelBufferSize.setAlignmentX(Component.LEFT_ALIGNMENT);
            showCopyOverview.setAlignmentX(Component.LEFT_ALIGNMENT);
            showCopyErrorMessages.setAlignmentX(Component.LEFT_ALIGNMENT);
            add(panelCopying);
    }

  • BoxLayout: problems

    I've a frame this default BorderLayout. Then I create this Panel:
    JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));and insert it into east of the frame:
    frame.add(rightPanel, BorderLayout.EAST);Then I create a BoxLayout like this:
    JPanel boxPanel = new JPanel();
    boxPanel.setLayout(new BoxLayout(boxPanel,BoxLayout.Y_AXIS));And then insert 2 labels, a JComboBox and a JList into in:
    boxPanel.add(yearLabel);
    boxPanel.add(yearBox);
    boxPanel.add(raceLabel);
    boxPanel.add(scrollRaceListPanel);Then I adds the boxPanel into the rightPanel like this:
    rightPanel.add(boxPanel);Here you see the result of it:
    http://www.demaweb.dk/frame.jpg
    (notice the east-part)
    As you see the labels are centered, and the ComboBox are getting the same width as the BoxPanel. I wan't the labels to have left align.
    I hope somebody know why?

    Well, I got another problem.
    Here you see a example code:
    import javax.swing.*;
    import java.awt.*;
    public class Main {
        public static void main(String[] args) {
            JFrame frame = new JFrame("Test");     
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setResizable(false);
            JPanel rightPanel = new JPanel(new BorderLayout());
            JPanel rightCenterPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            //creating rightTop-panel
            Box rightTopPanel = new Box(BoxLayout.Y_AXIS);
            JLabel yearLabel = new JLabel("�r:");  
            yearLabel.setAlignmentX(rightTopPanel.LEFT_ALIGNMENT);
            JComboBox yearBox = new JComboBox();
            yearBox.setAlignmentX(rightTopPanel.LEFT_ALIGNMENT);
            yearBox.setPreferredSize(new Dimension(100,20));
            rightTopPanel.add(yearLabel);
            rightTopPanel.add(yearBox);
            //creating rightCenter-panel       
            JList raceList = new JList();
            raceList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            JScrollPane scrollRaceList = new JScrollPane(raceList);
            scrollRaceList.setPreferredSize(new Dimension(250,300));
            JPanel scrollRaceListPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            scrollRaceListPanel.add(scrollRaceList);
            rightCenterPanel.add(scrollRaceListPanel);
            rightPanel.add(rightTopPanel, BorderLayout.NORTH);
            rightPanel.add(rightCenterPanel, BorderLayout.CENTER);
            frame.add(rightPanel, BorderLayout.EAST);
            frame.pack();    
            frame.setVisible(true);
    }As you see, the ComboBox are getting full width. Why?

  • BoxLayout allignment

    I would like the JLabel "addedSectionLabel" to be left aligned however it is always center alligned, any ideas on how to achive this?
    JPanel topLeftPanel = new JPanel();
    topLeftPanel.setLayout(new BoxLayout(topLeftPanel, BoxLayout.PAGE_AXIS));
    JLabel addedSectionLabel = new JLabel("Added Sections:");
    addedSectionLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    topLeftPanel.add(addedSectionLabel);Thanks in advance
    Calyspo

    camikr I really wish you would stop flaming me, you seem to be suggesting that I never post an SSCCE, which I do. I didnt post one this time as it is a very simple question and I thought someone would be able to answer it without
    anyway here is a SSCCE:
    import java.awt.Dimension;
    import javax.swing.*;
    public class Alignment {
        private JFrame frame;
        private JList list;
        public void createGui() {
            list = new JList();
            list.setLayoutOrientation(JList.VERTICAL);
            JScrollPane listScroller = new JScrollPane(list);
            listScroller.setPreferredSize(new Dimension(120, 130));
            JPanel topLeftPanel = new JPanel();
            topLeftPanel.setLayout(new BoxLayout(topLeftPanel, BoxLayout.PAGE_AXIS));
            JLabel addedSectionLabel = new JLabel("Added Sections:");
            addedSectionLabel.setAlignmentX(JComponent.LEFT_ALIGNMENT);
            topLeftPanel.add(addedSectionLabel);
            topLeftPanel.add(Box.createGlue());
            topLeftPanel.add(listScroller);
            String[] sectionTypes = {"CHS", "RHS", "SHS"};
            JComboBox sectionTypesComboBox = new JComboBox(sectionTypes);
            topLeftPanel.add(sectionTypesComboBox);
            frame = new JFrame("Section Properties");
            frame.add(topLeftPanel);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            new Alignment().createGui();
    }

  • Jcombobox,JButton problem

    Hi,
    i would like my button to show a new java class,
    My button actionlistener
    select2 select = new select2();
    select.createAndShowGUI();but, i want to choose which class i will go through JComboBox.....
    Let's say my string on the JComboBox is frame1,frame2,frame3....
    how should i put it in way that....
    if frame1 is selected....
    i click the button, it will show frame1 class...
    if frame2 is selcted....
    after clicked the button, it will show frame2 class...
    Edited by: vanharu on May 27, 2008 8:38 PM

    i understand the codes u put there...
    but how do i implement it to my button action
    * @(#)select2.java
    * @author
    * @version 1.00 2008/5/28
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.BoxLayout;
    public class select2 extends JFrame  implements ActionListener
         public JComboBox CharList;
         public JLabel Char,title;
         public JButton Play, Preview;
        public select2()
            setTitle("Select Your Character");
            setSize(340, 400);
            getContentPane().setLayout(
                    new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
             Border raisedbevel, loweredbevel, compound;
             raisedbevel = BorderFactory.createRaisedBevelBorder();
            loweredbevel = BorderFactory.createLoweredBevelBorder();
              // Puts in array of strings to the combo box
            // Can select the arrays that is inserted in the combo box
                String hero[] = {"Naruto", "Sasuke", "Ichigo", "Ulqiourra"};
                CharList = new JComboBox(hero);
             //Shows that the combo box will start at 0,
             //which is naruto  
                CharList.setSelectedIndex(0);
                CharList.addActionListener(this);
                 //Set up the animation part
                    Char = new JLabel();
                  Char.setHorizontalAlignment(JLabel.CENTER);
                  updateLabel(hero[CharList.getSelectedIndex()]);
                  compound = BorderFactory.createCompoundBorder(raisedbevel, loweredbevel);
                  Char.setBorder(compound);
                  Char.setPreferredSize(new Dimension(320, 266));
                  //Set up button part
                  Play = new JButton("Select This Character");
                 Play.setHorizontalAlignment(4);
                 Play.setPreferredSize(new Dimension(100,40));
                 Play.addActionListener(new confirm());
                      Preview = new JButton("Preview This Character");
                      Preview.setHorizontalAlignment(4);
                      Preview.setPreferredSize(new Dimension(80, 40));
                      Preview.addActionListener(new preview());     
                      getContentPane().add(CharList);
                 CharList.setAlignmentX(Component.CENTER_ALIGNMENT);
                 getContentPane().add(Char);
                 Char.setAlignmentX(Component.CENTER_ALIGNMENT);
                 getContentPane().add(Play);
                 Play.setAlignmentX(Component.CENTER_ALIGNMENT);
                 getContentPane().add(Preview);
                  Preview.setAlignmentX(Component.CENTER_ALIGNMENT);
        public void actionPerformed(ActionEvent e)
                 JComboBox nm = (JComboBox)e.getSource();
                 String CharName = (String)nm.getSelectedItem();
                 updateLabel(CharName);
        class confirm implements ActionListener {
            public void actionPerformed(ActionEvent event)
               System.exit(0);
        class preview implements ActionListener {
            public void actionPerformed(ActionEvent event)
            //lets say, if the combobox selection is naruto...
            //then when i click this button
            //it will show naruto class
             should i put like something like
             combobox = naruto
             show naruto.class
         protected void updateLabel(String name) {
            ImageIcon icon = new ImageIcon("Resources/"+name+"Pose" + ".gif");
            Char.setIcon(icon);
            Char.setToolTipText(name);
            if (icon != null) {
                Char.setText(null);
            } else {
                Char.setText("UNDER CONSTRUCTION");
       public static void createAndShowGUI() {
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("Choose Your Character");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     
              //Display the window.
            select2 sel = new select2();
            sel.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            sel.setVisible(true);
         public static void main(String[] args) {
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }Edited by: vanharu on May 27, 2008 10:27 PM

  • JComboBox Lost Listener on Look and Feel change

    When the user change the Look And Feel on the Fly , any Listener that is done using
    myComboBox.getEditor().getEditorComponent().addXXXListener
    is lost
    I'm using Windows XP Service Pack 2, java 6 build 105
    Does someone have any inputs why this happen or how this can be "fixed" or maybe prevent. Do I'm doing something wrong?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    /* ComboBoxDemo2.java requires no other files. */
    public class ComboBoxDemo2 extends JPanel
                               implements ActionListener {
        static JFrame frame;
        JLabel result;
        String currentPattern;
        public ComboBoxDemo2() {
            setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
            String[] patternExamples = {
                     "dd MMMMM yyyy",
                     "dd.MM.yy",
                     "MM/dd/yy",
                     "yyyy.MM.dd G 'at' hh:mm:ss z",
                     "EEE, MMM d, ''yy",
                     "h:mm a",
                     "H:mm:ss:SSS",
                     "K:mm a,z",
                     "yyyy.MMMMM.dd GGG hh:mm aaa"
            currentPattern = patternExamples[0];
            //Set up the UI for selecting a pattern.
            JLabel patternLabel1 = new JLabel("Enter the pattern string or");
            JLabel patternLabel2 = new JLabel("select one from the list:");
            JComboBox patternList = new JComboBox(patternExamples);
            patternList.setEditable(true);
            patternList.addActionListener(this);
    //-------------------------------- XXX------------------------------------------
    //      This KeyListener it is lost when the user change the theme on the fly       
            patternList.getEditor().getEditorComponent().addKeyListener(new KeyAdapter()
            public void keyPressed(KeyEvent e)
             System.out.println(" Key pressed is "+e.getKeyCode());     
            //Create the UI for displaying result.
            JLabel resultLabel = new JLabel("Current Date/Time",
                                            JLabel.LEADING); //== LEFT
            result = new JLabel(" ");
            result.setForeground(Color.black);
            result.setBorder(BorderFactory.createCompoundBorder(
                 BorderFactory.createLineBorder(Color.black),
                 BorderFactory.createEmptyBorder(5,5,5,5)
            //Lay out everything.
            JPanel patternPanel = new JPanel();
            patternPanel.setLayout(new BoxLayout(patternPanel,
                                   BoxLayout.PAGE_AXIS));
            patternPanel.add(patternLabel1);
            patternPanel.add(patternLabel2);
            patternList.setAlignmentX(Component.LEFT_ALIGNMENT);
            patternPanel.add(patternList);
            JPanel resultPanel = new JPanel(new GridLayout(0, 1));
            resultPanel.add(resultLabel);
            resultPanel.add(result);
            patternPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
            resultPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
            add(patternPanel);
            add(Box.createRigidArea(new Dimension(0, 10)));
            add(resultPanel);
            setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
            reformat();
        } //constructor
        public void actionPerformed(ActionEvent e) {
             System.out.println("Action Event");                
            JComboBox cb = (JComboBox)e.getSource();
            String newSelection = (String)cb.getSelectedItem();
            currentPattern = newSelection;
            reformat();
        /** Formats and displays today's date. */
        public void reformat() {
             try {
            Date today = new Date();
            SimpleDateFormat formatter =
               new SimpleDateFormat(currentPattern);
                String dateString = formatter.format(today);
                result.setForeground(Color.black);
                result.setText(dateString);
            }catch (IllegalArgumentException iae) {     
            System.out.println("Ilegal argument Exception");   
            catch (Exception e) {
            System.out.println("Argument Exception");                
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            final JFrame frame = new JFrame("ComboBoxDemo2");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new ComboBoxDemo2();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setLayout(new BorderLayout());      
            //frame.setContentPane(newContentPane,BorderLayout.CENTER);
            JMenuBar menuBar = new JMenuBar();
            JMenu theme = new JMenu("Theme");
            ButtonGroup bttnGroup = new ButtonGroup();
            JCheckBoxMenuItem metal = new JCheckBoxMenuItem("Metal");
            bttnGroup.add(metal);
            metal.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
              try{
              UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
              SwingUtilities.updateComponentTreeUI(frame);
              }catch(Exception a){a.printStackTrace();}
              theme.add(metal);
            JCheckBoxMenuItem system = new JCheckBoxMenuItem("System");
            bttnGroup.add(system);
            system.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
              try{
              UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              SwingUtilities.updateComponentTreeUI(frame);
              }catch(Exception a){a.printStackTrace();}
            theme.add(system);
            menuBar.add(theme);     
            frame.setJMenuBar(menuBar);
            JToolBar jtb = new JToolBar();
            jtb.add(newContentPane);
            frame.add(jtb, BorderLayout.PAGE_START);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //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();
    }

    Thanks to both Rodney_McKay and jasper for their replys and ideas
    This code is working fine
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    /* ComboBoxDemo2.java requires no other files. */
    public class ComboBoxDemo2 extends JPanel
                               implements ActionListener {
        static JFrame frame;
        JLabel result;
        String currentPattern;
        private JComboBox patternList = new JComboBox();
        public ComboBoxDemo2() {
            setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
            String[] patternExamples = {
                     "dd MMMMM yyyy",
                     "dd.MM.yy",
                     "MM/dd/yy",
                     "yyyy.MM.dd G 'at' hh:mm:ss z",
                     "EEE, MMM d, ''yy",
                     "h:mm a",
                     "H:mm:ss:SSS",
                     "K:mm a,z",
                     "yyyy.MMMMM.dd GGG hh:mm aaa"
            currentPattern = patternExamples[0];
            //Set up the UI for selecting a pattern.
            JLabel patternLabel1 = new JLabel("Enter the pattern string or");
            JLabel patternLabel2 = new JLabel("select one from the list:");
            patternList = new JComboBox(patternExamples){
            public void updateUI(){
            System.out.println("UPDATE UI");
            super.updateUI();     
            changeUIAddEditorListener();
            changeUIAddEditorListener();
            patternList.setEditable(true);
            patternList.addActionListener(this);
            //Create the UI for displaying result.
            JLabel resultLabel = new JLabel("Current Date/Time",
                                            JLabel.LEADING); //== LEFT
            result = new JLabel(" ");
            result.setForeground(Color.black);
            result.setBorder(BorderFactory.createCompoundBorder(
                 BorderFactory.createLineBorder(Color.black),
                 BorderFactory.createEmptyBorder(5,5,5,5)
            //Lay out everything.
            JPanel patternPanel = new JPanel();
            patternPanel.setLayout(new BoxLayout(patternPanel,
                                   BoxLayout.PAGE_AXIS));
            patternPanel.add(patternLabel1);
            patternPanel.add(patternLabel2);
            patternList.setAlignmentX(Component.LEFT_ALIGNMENT);
            patternPanel.add(patternList);
            JPanel resultPanel = new JPanel(new GridLayout(0, 1));
            resultPanel.add(resultLabel);
            resultPanel.add(result);
            patternPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
            resultPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
            add(patternPanel);
            add(Box.createRigidArea(new Dimension(0, 10)));
            add(resultPanel);
            setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
            reformat();
        } //constructor
        public void actionPerformed(ActionEvent e) {
             System.out.println("Action Event");                
            JComboBox cb = (JComboBox)e.getSource();
            String newSelection = (String)cb.getSelectedItem();
            currentPattern = newSelection;
            reformat();
        /** Formats and displays today's date. */
        public void reformat() {
             try {
            Date today = new Date();
            SimpleDateFormat formatter =
               new SimpleDateFormat(currentPattern);
                String dateString = formatter.format(today);
                result.setForeground(Color.black);
                result.setText(dateString);
            }catch (IllegalArgumentException iae) {     
            System.out.println("Ilegal argument Exception");   
            catch (Exception e) {
            System.out.println("Argument Exception");                
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            final JFrame frame = new JFrame("ComboBoxDemo2");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new ComboBoxDemo2();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setLayout(new BorderLayout());      
            //frame.setContentPane(newContentPane,BorderLayout.CENTER);
            JMenuBar menuBar = new JMenuBar();
            JMenu theme = new JMenu("Theme");
            ButtonGroup bttnGroup = new ButtonGroup();
            JCheckBoxMenuItem metal = new JCheckBoxMenuItem("Metal");
            bttnGroup.add(metal);
            metal.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
              try{
              UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
              SwingUtilities.updateComponentTreeUI(frame);
              }catch(Exception a){a.printStackTrace();}
              theme.add(metal);
            JCheckBoxMenuItem system = new JCheckBoxMenuItem("System");
            bttnGroup.add(system);
            system.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
              try{
              UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              SwingUtilities.updateComponentTreeUI(frame);
              }catch(Exception a){a.printStackTrace();}
            theme.add(system);
            menuBar.add(theme);     
            frame.setJMenuBar(menuBar);
            JToolBar jtb = new JToolBar();
            jtb.add(newContentPane);
            frame.add(jtb, BorderLayout.PAGE_START);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //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();
       public void changeUIAddEditorListener() {
       patternList.getEditor().getEditorComponent().addKeyListener(new KeyAdapter()
       public void keyPressed(KeyEvent e)
       System.out.println(" Key pressed is "+e.getKeyCode());     
    }

  • How use JLabel and JCombobox on one string

    package ReplacementCode;
    import java.awt.BorderLayout;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    class MainFrame extends JFrame {
    private static JTextArea text = new JTextArea(ReadingFromFile.textFromFile.size(), 40);
    private static JScrollPane forText = new JScrollPane(text);
    private static JPanel westPanel = new JPanel();
    private static JPanel forAlphabet = new JPanel();
    private static JPanel forModifyChars = new JPanel();
    private static JLabel[] labels = new JLabel[Alphabet.russianAlphabet.length()];
    private static Object[] massiveOfAlphabet = new Object[Alphabet.russianAlphabet.length()];
    private static JComboBox[] comboBoxes = new JComboBox[Alphabet.russianAlphabet.length()];
    private static JButton startButton = new JButton("!&#1079;&#1072;&#1084;&#1077;&#1085;&#1080;&#1090;&#1100;!");
    private static BoxListener[] boxListeners = new BoxListener[Alphabet.russianAlphabet.length()];
    public MainFrame() {
    super("&#1086;&#1089;&#1085;&#1074;&#1086;&#1074;&#1085;&#1086;&#1077; &#1086;&#1082;&#1085;&#1086;");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    initiasizeCenter();
    initiasizeWest();
    JLabel jlab = new JLabel(Alphabet.russianAlphabet.toUpperCase());
    jlab.setOpaque(true);
    add(forText, BorderLayout.CENTER);
    add(westPanel, BorderLayout.WEST);
    add(startButton, BorderLayout.SOUTH);
    add(jlab, BorderLayout.NORTH);
    setSize(this.getMaximumSize());
    setVisible(true);
    private void initiasizeWest() {
    putAlphabet();
    forModifyChars.setLayout(new BoxLayout(forModifyChars, BoxLayout.Y_AXIS));
    forAlphabet.setLayout(new BoxLayout(forAlphabet, BoxLayout.Y_AXIS));
    for(int ii = 0; ii < Alphabet.russianAlphabet.length(); ii++) {
    comboBoxes[ii] = new JComboBox(massiveOfAlphabet);
    comboBoxes[ii].setSelectedIndex(ii);
    boxListeners[ii] = new BoxListener();
    comboBoxes[ii].addKeyListener(boxListeners[ii]);
    forModifyChars.add(comboBoxes[ii]);
    StringBuffer sb = new StringBuffer();
    sb.append(Alphabet.russianAlphabet.charAt(ii));
    labels[ii] = new JLabel(sb.toString().toUpperCase());
    labels[ii].setOpaque(true);
    labels[ii].setHorizontalTextPosition(JLabel.LEFT);
    labels[ii].setVerticalTextPosition(JLabel.CENTER);
    westPanel.add(forAlphabet);
    westPanel.add(Box.createHorizontalGlue());
    westPanel.add(forModifyChars);
    private static void initiasizeCenter() {
    text.setLineWrap(true);
    for(int ii = 0; ii < ReadingFromFile.textFromFile.size(); ii++)
    text.append(ReadingFromFile.textFromFile.elementAt(ii) + "\n");
    private static void initiasizeSouth() {}
    private static void initiasizeNorth() {}
    private static final void putAlphabet() {
    for(int ii = 0; ii < Alphabet.russianAlphabet.length(); ii++)
    massiveOfAlphabet[ii] = Alphabet.russianAlphabet.charAt(ii);
    private class BoxListener implements KeyListener {
    public BoxListener() {
    public void keyPressed(KeyEvent e) {
    System.out.println("&#1089;&#1083;&#1091;&#1096;&#1072;&#1077;&#1090;&#1083;&#1100; &#1085;&#1072;&#1078;&#1072;&#1090;&#1080;&#1103; &#1082;&#1083;&#1072;&#1074;&#1080;&#1096;&#1080; : " + e + "\n");
    public void keyReleased(KeyEvent e) {
    System.out.println("&#1089;&#1083;&#1091;&#1096;&#1072;&#1077;&#1090;&#1083;&#1100; &#1086;&#1090;&#1087;&#1091;&#1089;&#1082;&#1072;&#1085;&#1080;&#1103; &#1082;&#1083;&#1072;&#1074;&#1080;&#1096;&#1080; : " + e + "\n");
    public void keyTyped(KeyEvent e) {
    System.out.println("&#1089;&#1083;&#1091;&#1096;&#1072;&#1077;&#1090;&#1083;&#1100; &#1087;&#1077;&#1095;&#1072;&#1090;&#1072;&#1085;&#1080;&#1103; &#1089;&#1080;&#1084;&#1074;&#1086;&#1083;&#1072; : " + e + "\n");
    package ReplacementCode;
    import java.util.Vector;
    abstract class Alphabet {
    final static String russianAlphabet = new String("&#1072;&#1073;&#1074;&#1075;&#1076;&#1077;&#1105;&#1078;&#1079;&#1080;&#1081;&#1082;&#1083;&#1084;&#1085;&#1086;&#1087;&#1088;&#1089;&#1090;&#1091;&#1092;&#1093;&#1094;&#1095;&#1096;&#1097;&#1098;&#1099;&#1100;&#1101;&#1102;&#1103;");
    private static String replacementAlphabet;
    private static double[] ratesOfCharacters = new double[russianAlphabet.length()];
    static Vector<String> replacementedText = new Vector<String>();
    static final void generateAlphabetOfReplacement() {
    boolean[] occupancy = new boolean[russianAlphabet.length()];
    for(int ii = 0; ii < occupancy.length; ii++)
    occupancy[ii] = false;
    char[] ancillaryMassiveOfCharacters = new char[russianAlphabet.length()];
    for(int ii = 0; ii < ancillaryMassiveOfCharacters.length; ii++) {
    for(;;) {
    int ancillaryPositionOfCharacter = (int) (Math.random() * ancillaryMassiveOfCharacters.length);
    if(occupancy[ancillaryPositionOfCharacter] == false) {
    occupancy[ancillaryPositionOfCharacter] = true;
    ancillaryMassiveOfCharacters[ii] = russianAlphabet.charAt(ancillaryPositionOfCharacter);
    break;
    replacementAlphabet = new String(ancillaryMassiveOfCharacters);
    static final void workWithText(Vector<String> unreplacementText) {
    generateAlphabetOfReplacement();
    nullingOfRates();
    replacementedText.removeAllElements();
    for(int ii = 0; ii < unreplacementText.size(); ii++) {
    char[] occupancyMassive = unreplacementText.elementAt(ii).toCharArray();
    for(int jj = 0; jj < occupancyMassive.length; jj++) {
    //verification of agreement of character's in text with basic alphabet
    for(int kk = 0; kk < russianAlphabet.length(); kk++) {
    if(Character.isUpperCase(unreplacementText.elementAt(ii).charAt(jj)) &&
    occupancyMassive[jj] == Character.toUpperCase(russianAlphabet.charAt(kk))) {
    occupancyMassive[jj] = Character.toUpperCase(replacementAlphabet.charAt(kk));
    ratesOfCharacters[kk]++;
    break;
    if(Character.isLowerCase(unreplacementText.elementAt(ii).charAt(jj)) &&
    occupancyMassive[jj] == russianAlphabet.charAt(kk)) {
    occupancyMassive[jj] = replacementAlphabet.charAt(kk);
    ratesOfCharacters[kk]++;
    break;
    //save new replacemented text
    replacementedText.add(new String(occupancyMassive));
    //            System.out.println(unreplacementText.elementAt(ii));
    //            System.out.println(replacementedText.elementAt(ii));
    static final void workWithText(Vector<String> unreplacementText, String oldAlphabet, String newAlphabet) {
    nullingOfRates();
    replacementedText.removeAllElements();
    for(int ii = 0; ii < unreplacementText.size(); ii++) {
    char[] occupancyMassive = unreplacementText.elementAt(ii).toCharArray();
    for(int jj = 0; jj < occupancyMassive.length; jj++) {
    //verification of agreement of character's in text with basic alphabet
    for(int kk = 0; kk < oldAlphabet.length(); kk++) {
    if(Character.isUpperCase(unreplacementText.elementAt(ii).charAt(jj)) &&
    occupancyMassive[jj] == Character.toUpperCase(oldAlphabet.charAt(kk))) {
    occupancyMassive[jj] = Character.toUpperCase(newAlphabet.charAt(kk));
    ratesOfCharacters[kk]++;
    break;
    if(Character.isLowerCase(unreplacementText.elementAt(ii).charAt(jj)) &&
    occupancyMassive[jj] == oldAlphabet.charAt(kk)) {
    occupancyMassive[jj] = newAlphabet.charAt(kk);
    ratesOfCharacters[kk]++;
    break;
    //save new replacemented text
    replacementedText.add(new String(occupancyMassive));
    //            System.out.println(unreplacementText.elementAt(ii));
    //            System.out.println(replacementedText.elementAt(ii));
    private static void nullingOfRates() {
    for(int ii = 0; ii < ratesOfCharacters.length; ii++)
    ratesOfCharacters[ii] = 0;
    }the problem is in westPanel; how we can typed text from the Jlabel near JCombobox
    now - text from combobox we can see, and text from label - don't.
    and one of condition is don't crash massive of JCombobox and Jlabel
    please help me

    if if was different mod then only create many vertical Jpanels, with pair jlabel, jcombobox, please write...i don't want to do this because it wil bee many references on Jpanels-> many memory..

  • Not Updating the Values in the JComboBox and JTable

    Hi Friends
    In my program i hava Two JComboBox and One JTable. I Update the ComboBox with different field on A Table. and then Display a list of record in the JTable.
    It is Displaying the Values in the Begining But when i try to Select the Next Item in the ComboBox it is not Updating the Records Eeither to JComboBox or JTable.
    MY CODE is this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.DefaultComboBoxModel.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    public class SearchBook extends JDialog implements ActionListener
         private JComboBox comboCategory,comboAuthor;
         private JSplitPane splitpane;
         private JTable table;
         private JToolBar toolBar;
         private JButton btnclose, btncancel;
         private JPanel panel1,panel2,panel3,panel4;
         private JLabel lblCategory,lblAuthor;
         private Container c;
         //DefaultTableModel model;
         Statement st;
         ResultSet rs;
         Vector v = new Vector();
         public SearchBook (Connection con)
              // Property for JDialog
              setTitle("Search Books");
              setLocation(40,110);
              setModal(true);
              setSize(750,450);
              // Creating ToolBar Button
              btnclose = new JButton(new ImageIcon("Images/export.gif"));
              btnclose.addActionListener(this);
              // Creating Tool Bar
              toolBar = new JToolBar();
              toolBar.add(btnclose);
              try
                   st=con.createStatement();
                   rs =st.executeQuery("SELECT BCat from Books Group By Books.BCat");
                   while(rs.next())
                        v.add(rs.getString(1));
              catch(SQLException ex)
                   System.out.println("Error");
              panel1= new JPanel();
              panel1.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
              lblCategory = new JLabel("Category:");
              lblCategory.setHorizontalAlignment (JTextField.CENTER);
              c.gridx=2;
              c.gridy=2;
              panel1.add(lblCategory,c);
              comboCategory = new JComboBox(v);
              comboCategory.addActionListener(this);
              c.ipadx=20;
              c.gridx=3;
              c.gridwidth=1;
              c.gridy=2;
              panel1.add(comboCategory,c);
              lblAuthor = new JLabel("Author/Publisher:");
              c.gridwidth=2;
              c.gridx=1;
              c.gridy=4;
              panel1.add(lblAuthor,c);
              lblAuthor.setHorizontalAlignment (JTextField.LEFT);
              comboAuthor = new JComboBox();
              comboAuthor.addActionListener(this);
              c.insets= new Insets(20,0,0,0);
              c.ipadx=20;
              c.gridx=3;
              c.gridy=4;
              panel1.add(comboAuthor,c);
              comboAuthor.setBounds (125, 165, 175, 25);
              table = new JTable();
              JScrollPane scrollpane = new JScrollPane(table);
              //panel2 = new JPanel();
              //panel2.add(scrollpane);
              splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,panel1,scrollpane);
              splitpane.setDividerSize(15);
              splitpane.setDividerLocation(190);
              getContentPane().add(toolBar,BorderLayout.NORTH);
              getContentPane().add(splitpane);
         public void actionPerformed(ActionEvent ae)
              Object obj= ae.getSource();
              if(obj==comboCategory)
                   String selecteditem = (String)comboCategory.getSelectedItem();
                   displayAuthor(selecteditem);
                   System.out.println("Selected Item"+selecteditem);
              else if(obj==btnclose)
                   setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
              else if(obj==comboAuthor)
                   String selecteditem1 = (String)comboAuthor.getSelectedItem();
                   displayavailablity(selecteditem1);
                   //System.out.println("Selected Item"+selecteditem1);
                   System.out.println("Selected Author"+selecteditem1);
         private void displayAuthor(String selecteditem)
              try
              {     Vector data = new Vector();
                   rs= st.executeQuery("SELECT BAuthorandPublisher FROM Books where BCat='" + selecteditem + "' Group By Books.BAuthorandPublisher");
                   System.out.println("Executing");
                   while(rs.next())
                        data.add(rs.getString(1));
                   //((DefaultComboBoxModel)comboAuthor.getModel()).setVectorData(data);
                   comboAuthor.setModel(new DefaultComboBoxModel(data));
              catch(SQLException ex)
                   System.out.println("ERROR");
         private void displayavailablity(String selecteditem1)
                   try
                        Vector columnNames = new Vector();
                        Vector data1 = new Vector();
                        rs= st.executeQuery("SELECT * FROM Books where BAuthorandPublisher='" + selecteditem1 +"'");     
                        ResultSetMetaData md= rs.getMetaData();
                        int columns =md.getColumnCount();
                        String booktblheading[]={"Book ID","Book NAME","BOOK AUTHOR/PUBLISHER","REFRENCE","CATEGORY"};
                        for(int i=1; i<= booktblheading.length;i++)
                             columnNames.addElement(booktblheading[i-1]);
                        while(rs.next())
                             Vector row = new Vector(columns);
                             for(int i=1;i<=columns;i++)
                                  row.addElement(rs.getObject(i));
                             data1.addElement(row);
                             //System.out.println("data is:"+data);
                        ((DefaultTableModel)table.getModel()).setDataVector(data1,columnNames);
                        //DefaultTableModel model = new DefaultTableModel(data1,columnNames);
                        //table.setModel(model);
                        rs.close();
                        st.close();
                   catch(SQLException ex)
    }Please check my code and give me some Better Solution
    Thank you

    You already have a posting on this topic:
    http://forum.java.sun.com/thread.jspa?threadID=5143235

Maybe you are looking for

  • HT3910 How to format and erase Lion 10.7.3 completely?

    I've erased and reinstalled my Lion 10.7.3 but after rebooting, all my previous programs are also installed.How do I format and erase my HD completely so I get a clean OS like I had when I bought my Macbook Pro?

  • WebUtil 1.0.6 - GetClientInfo bean not found.

    I'm using Developer 10g Version 10.1.2.0.2 and the latest available Webutil-package 1.0.6. I installed all components and followed all the steps. When I execute the form test of webutil: WU_TEST_106 open a window with: oracle.forms.webutil.clientinfo

  • Disk still wakes up with laptop-mode-tools

    Hi all, I have a Thinkpad x61 and I'm trying to manage power use with laptop-mode-tools, but I'm having trouble with the harddrive waking up too much. I have it configured so that lm-tools activates when the power is disconnected, and sure enough, a

  • Making iDVD that will play on Windows machines

    Okay I need help. I've made an iDVD movie and it will play fine on all my mac's. However, I can't get it to play on Windows machines which most of the folks I will be sending the dvd to have. What am I not doing? I created the movie in iMovie and exp

  • How to get back my old account?

    Hello, I have an iTunes account which I keep seperate from my apple.com discussion/purchasing account. When I made my discussion account, I was a member of .mac and my apple discussion log-in was my e-mail address and password. Once my .mac address e