Solved

Java Swing: Custom-Size ComboBox?

Posted on 2006-11-20
5
1,399 Views
Last Modified: 2013-11-23
Dear experts:

Hi again!

I have a simple code which include a combobox. The problem is that the combobox is displayed streched all the way from the left end of the window to the right end of the window. I would like the combobox displayed in a certain width (example: 50) and height (example: 10) at a location 100 px from the left end of the window.

I will truly appreciate if you experts may kindly teach me how to do that.

Thanks a lot!

duta

________________ Here is my latest code _________________

import javax.swing.JOptionPane;
import java.text.DecimalFormat;
import java.util.regex.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class PhoneBill3 extends JApplet
{
 // private JList planList;
  private JComboBox planList = new JComboBox(new Object[] { "Unlimited Plan", "300 Anytime Minutes" });
  private JPanel Pname;
  private JPanel Pusage;
  private JPanel Ptotal;
  private JPanel Pbutton;
 
 
  /////////////////
 
  private JRadioButton unlimited, limited;
  private ButtonGroup radioGroup;
  ///////////////
 
 
  private JTextField Fname;
  private JTextField Fusage;
  private JTextField Ftotal;
  private Container c = getContentPane ( );
 
 // private String plans [] = {"Unlimited Plan", "Limited Plan"};
  JComboBox plans = new JComboBox(new Object[] { "Unlimited Plan", "300 Anytime Minutes" });
 
  public void init ( )
  {
    // Methods to build the panels
    buildPlan ();
    buildName ();
    buildUsage ();
    buildTotal ();
    buildButton ();
   
    // Create a layout manager
    setLayout ( new GridLayout (5, 1 ) );
   
    // Add the panels to the content pane
    add ( Pname);
    add ( planList );
    add ( Pusage);
    add ( Ptotal );
    add ( Pbutton );
  }
 /////////// ?????????????????????????????????????????????????????????  
  private void buildPlan ()
  {
   
   
   
 
   // select the first button by default
   plans.setSelectedIndex (0);
 }
 /////  ?????????????????????????????????????????????????????????????????
  private void buildName ()
  {
    Pname = new JPanel ( );
    JLabel message1 = new JLabel ("Your Name : " );
    Fname =  new JTextField ( 20 );
   
    Pname.setLayout ( new FlowLayout ( FlowLayout.RIGHT ) );
    Pname.add (message1);
    Pname.add ( Fname );
  }
 
  private void buildUsage ()
  {
    Pusage = new JPanel ( );
    JLabel message2 = new JLabel ("Your Anytime Usage : " );
    Fusage =  new JTextField ( 20 );
   
    Pusage.setLayout ( new FlowLayout ( FlowLayout.RIGHT ) );
    Pusage.add (message2);
    Pusage.add ( Fusage );
  }
 
  private void buildTotal ()
  {
    Ptotal = new JPanel ( );
    JLabel message3 = new JLabel ("Your Total Charge: " );
    Ftotal =  new JTextField ( 20 );
    Ftotal.setEditable ( false );
   
    Ptotal.setLayout ( new FlowLayout ( FlowLayout.RIGHT ) );
    Ptotal.add (message3);
    Ptotal.add ( Ftotal );
  }
 
 private void buildButton ()
  {
    Pbutton = new JPanel ( );
    JButton calcButton = new JButton ( "Calculate");
    calcButton.addActionListener ( new ButtonListener ( ) );
    Pbutton.add ( calcButton );
  }
 
 // Private inner class that andles the action event that is generated
 // when the user clicks "Calculate" button.
 
 
 private class ButtonListener implements ActionListener
 {
   public void actionPerformed ( ActionEvent e )
   {
     String name = " ";
     int mins_used = 0;
     int plan = 0;
     float total = 0.0f;
     
     name = Fname.getText ();
     try
     {
          mins_used = Integer.parseInt (Fusage.getText () );
 
          plan = planList.getSelectedIndex ();
   ///  ??????????????????????????????????????????????????????????????????????
     
           if (plan==1 )
           {      
               if (mins_used <= 300 )
                {
                   total = 39.99f;
                   Ftotal.setText (""+total);
                }
               else
                 {
                  total = 39.99f + ((mins_used - 300) * 0.45f);
                  Ftotal.setText (""+total);
               }
                                }
            else
           {
                    total = 69.99f;
                    Ftotal.setText (""+total);
            }
     ///// ????????????????????????????????????????????????????????????????????????????
     }
     catch(NumberFormatException nfe)
     {
          Ftotal.setText ("Please enter an integer by usage.");
     }
         
    }
 }
}    
0
Comment
Question by:duta
  • 3
  • 2
5 Comments
 
LVL 10

Accepted Solution

by:
ADSLMark earned 500 total points
ID: 17981586
Java has a number of LayoutManagers, these LayoutManagers, like the name says, manage the layout of your program. Let me explain the basic ones:

The running example is:

this.add(new JLabel("Label A"));
this.add(new JLabel("Label B"));
this.add(new JLabel("Label C"));
this.add(new JLabel("Label D"));

** FlowLayout
This is the default layout used, every component added to the content pane will be normally sized (can be parameterized) and all the components are put after eachother. So in a small picture:

+---------+ +---------+ +---------+ +---------+
| Label A | | Label B | | Label C | | Label D |
+---------+ +---------+ +---------+ +---------+

** BorderLayout
This layout requires us to add directions to the add method, so the running example code becomes, for example:

this.add(new JLabel("Label A"), BorderLayout.NORTH);
this.add(new JLabel("Label B"), BorderLayout.WEST);
this.add(new JLabel("Label C"), BorderLayout.EAST);
this.add(new JLabel("Label D"), BorderLayout.CENTER);

The component with the CENTER constant will be used to fill any excessive space. Small picture:

+-------------------------------------+
|               Label A               |
+-------------------------------------+
+---------+ +-------------+ +---------+
| Label B | |   Label D   | | Label C |
+---------+ +-------------+ +---------+

** GridLayout
This layout manager will set the components according to a grid, specified by the construction of the layoutmanager. For example new GridLayout(2,2) will result in a 2x2 matrix filled with the added components in the way they were added, left to right, top to bottom. Picture:

+---------+ +---------+
| Label A | | Label B |
+---------+ +---------+
+---------+ +---------+
| Label C | | Label D |
+---------+ +---------+

** No layout
If you specify no layout, setLayout(null), then you can use setBounds(x, y, width, height) on every component to set the precise position and dimensions. It speaks for itself that you can position everything what you want with this layout (rather no layout), but when the window resizes, the components don't resize.

There are several more layout managers available, but those are more difficult to explain.

An important note about making layouts is the use of JPanels, a JPanel can contain several components but it also has it's own layoutmanager. So you can use for example a GridLayout to position 4 JPanels, which each has a FlowLayout and add components to these JPanels will result in normally sized components.

Some example code:

-- LayoutExample.java
import java.awt.*;
import javax.swing.*;

class LayoutExample extends JFrame
{
    public LayoutExample()
    {
        this.setSize(800, 600);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        this.setLayout(new GridLayout(2,2));
        this.add(this.makeTopLeftPanel());
        this.add(this.makeTopRightPanel());
        this.add(this.makeBottomLeftPanel());
        this.add(this.makeBottomRightPanel());
    }

    public JPanel makeTopLeftPanel()
    {
        JPanel pnl = new JPanel();
        pnl.setLayout(new FlowLayout()); //default, line can be removed
        pnl.add(new JTextField("Label A"));
        pnl.add(new JTextField("Label B"));
        pnl.add(new JTextField("Label C"));
        pnl.add(new JTextField("Label D"));
        return pnl;
    }

    public JPanel makeTopRightPanel()
    {
        JPanel pnl = new JPanel();
        pnl.setLayout(new GridLayout(2,2));
        pnl.add(new JTextField("Label A"));
        pnl.add(new JTextField("Label B"));
        pnl.add(new JTextField("Label C"));
        pnl.add(new JTextField("Label D"));
        return pnl;
    }

    public JPanel makeBottomLeftPanel()
    {
        JPanel pnl = new JPanel();
        pnl.setLayout(new BorderLayout());
        pnl.add(new JTextField("Label A"), BorderLayout.NORTH);
        pnl.add(new JTextField("Label B"), BorderLayout.WEST);
        pnl.add(new JTextField("Label C"), BorderLayout.EAST);
        pnl.add(new JTextField("Label D"), BorderLayout.CENTER);
        return pnl;
    }

    public JPanel makeBottomRightPanel()
    {
        JTextField lbl;
        JPanel pnl = new JPanel();
        pnl.setLayout(null);

        lbl = new JTextField("Label A");
        lbl.setBounds(10, 10, 50, 20);
        pnl.add(lbl);
        lbl = new JTextField("Label B");
        lbl.setBounds(100, 110, 10, 50);
        pnl.add(lbl);
        lbl = new JTextField("Label C");
        lbl.setBounds(200, 30, 22, 20);
        pnl.add(lbl);
        lbl = new JTextField("Label D");
        lbl.setBounds(50, 240, 50, 50);
        pnl.add(lbl);

        return pnl;
    }

    public static void main(String[] args)
    {
        LayoutExample le = new LayoutExample();
        le.setVisible(true);
    }
}

Compile with: javac LayoutExample.java
Run with: java LayoutExample

Good luck.
Mark
0
 

Author Comment

by:duta
ID: 17981846
Hi, Mark, thank you so much for your kind, prompt response again.

I will take time to carefully every line of your tip and try them with my code.

Thanks again!

duta
0
 

Author Comment

by:duta
ID: 17981959
Dear Mark:

Hi again!

I just wonder whether I may try your code as an applet?  I tried but, but nothing showed up.

Thanks again!



0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 17982049
I am sorry, I always use JFrame :-)
Anyway.. not much has to be changed.

-- Applet version
-- LayoutExample.java
import java.awt.*;
import javax.swing.*;

public class LayoutExample extends JApplet
{
    public void init()
    {
        Container content = getContentPane();
        content.setLayout(new GridLayout(2,2));
        content.add(this.makeTopLeftPanel());
        content.add(this.makeTopRightPanel());
        content.add(this.makeBottomLeftPanel());
        content.add(this.makeBottomRightPanel());
    }

    public JPanel makeTopLeftPanel()
    {
        JPanel pnl = new JPanel();
        pnl.setLayout(new FlowLayout()); //default, line can be removed
        pnl.add(new JTextField("Label A"));
        pnl.add(new JTextField("Label B"));
        pnl.add(new JTextField("Label C"));
        pnl.add(new JTextField("Label D"));
        return pnl;
    }

    public JPanel makeTopRightPanel()
    {
        JPanel pnl = new JPanel();
        pnl.setLayout(new GridLayout(2,2));
        pnl.add(new JTextField("Label A"));
        pnl.add(new JTextField("Label B"));
        pnl.add(new JTextField("Label C"));
        pnl.add(new JTextField("Label D"));
        return pnl;
    }

    public JPanel makeBottomLeftPanel()
    {
        JPanel pnl = new JPanel();
        pnl.setLayout(new BorderLayout());
        pnl.add(new JTextField("Label A"), BorderLayout.NORTH);
        pnl.add(new JTextField("Label B"), BorderLayout.WEST);
        pnl.add(new JTextField("Label C"), BorderLayout.EAST);
        pnl.add(new JTextField("Label D"), BorderLayout.CENTER);
        return pnl;
    }

    public JPanel makeBottomRightPanel()
    {
        JTextField lbl;
        JPanel pnl = new JPanel();
        pnl.setLayout(null);

        lbl = new JTextField("Label A");
        lbl.setBounds(10, 10, 50, 20);
        pnl.add(lbl);
        lbl = new JTextField("Label B");
        lbl.setBounds(100, 110, 10, 50);
        pnl.add(lbl);
        lbl = new JTextField("Label C");
        lbl.setBounds(200, 30, 22, 20);
        pnl.add(lbl);
        lbl = new JTextField("Label D");
        lbl.setBounds(50, 240, 50, 50);
        pnl.add(lbl);

        return pnl;
    }
}

HTML page should contain:
<applet code="LayoutExample" width="800" height="600"></applet>

Have fun.
Mark
0
 

Author Comment

by:duta
ID: 17982205
Mark, you are great. It is working great. I am going to play with your code to learn a lot.

Thanks again!

I am going to accept your tip as acceptable solution.

My salute to you!
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Jaspersoft Studio is a plugin for Eclipse that lets you create reports from a datasource.  In this article, we'll go over creating a report from a default template and setting up a datasource that connects to your database.
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now