Height of "Choice" in AWT.

I have used a choice box in my Application Login Dialog.I mentioned the height of the choice box as '25'.and i was using jdk1.1.8 for my application.Everything was working fine.Now my client wanted me to port the application to jdk1.3.1. when i tried to run the same application in 1.3.1, i was surprised to see that the choice box is appearing smaller by 5 pixcels.where as the size of other components like the text field and panel where the same.Has anyone faced this problem.Does anyone have a solution for this.

This has been discussed a lot allready. Search the forum!
Ragnvald Barth
Software enigneerhttp://blake.prohosting.com/ragnvald

Similar Messages

  • Is there any way to set the height of choice list or list of values?

    Hello Everyone,
    (Jdeveloper: 11.1.2.1.0)
    I recently created a page with some fields as choice lists and some as list of values. Somehow the choice list when opened it is not displaying data properly (I have 3 rows, it is showing only 2 rows and have to scroll to see third row) . I would like to see if there is any way to set this so that I can see all three rows or set the height of choice list as a fixed height?
    Thanks,
    Ravi Nuka.

    Hi Manish,
    sorry for the delay, here the code for the list binding from vo.xml
      <ListBinding
        Name="LOV_SetOfBooks"
        ListVOName="NfSetOfBooksRVO1"
        ListRangeSize="-1"
        NullValueFlag="none"
        MRUCount="0"
        ComboRowCountHint="10">
        <AttrArray Name="AttrNames">
          <Item Value="SetOfBooks"/>
        </AttrArray>
        <AttrArray Name="ListAttrNames">
          <Item Value="SetOfBooksName"/>
        </AttrArray>
        <AttrArray Name="ListDisplayAttrNames">
          <Item Value="SetOfBooksName"/>
        </AttrArray>
        <DisplayCriteria/>
      </ListBinding>
    <ViewAttribute
        Name="SetOfBooks"
        PrecisionRule="true"
        EntityAttrName="SetOfBooks"
        EntityUsage="EdContractsEO"
        AliasName="SET_OF_BOOKS"
        LOVName="LOV_SetOfBooks">
        <Properties>
          <SchemaBasedProperties>
            <DISPLAYWIDTH
              Value="30"/>
            <CONTROLTYPE
              Value="combo_lov"/>
          </SchemaBasedProperties>
        </Properties>
      </ViewAttribute>Thanks,
    Ravi Nuka

  • Help Needed with Itemlsteners for Choice in AWT

    Hi,
    I am new to AWT prgramming .
    I have created a menu called " Menu System Test window " and it contains toplevel menu item "File" and File Menu contains subitems "Product Evaluation" and "Exit".
    When i click File->Product Evaluation it displays a new Frame named "ProductEvaluationMeasurementTool" with some check boxes ,radiobuttons, buttons , text fields and choice lists.
    The two Choices ie c1 and c2 contains items choice,choice2 and scale 1 and scale 2 respectively and i have added ItemListeners for both the choices.
    My question is when i select Both choice1 and scale 1 it shoulddisplay a new frame.
    (NOTE : THE NEW FRAME SHOULD BE DISPLAYED IF I SELECT BOTH CHOICE1 AND SCALE1 NOT EITHER CHOICE1 OR SCALE1)
    Similarly when i select Both choice2 and scale2 it should display another new frame. How can i do that? i am sending my code.
    Thanks in advance
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Component;
    import java.awt.Checkbox;
    import javax.swing.*;
    // Make a main window with a top-level menu: File 
    public class MainWindow extends Frame {
      public MainWindow() {
        super("Menu System Test Window");
        setSize(500, 500);
        // make a top level File menu
        FileMenu fileMenu = new FileMenu(this);
        // make a menu bar for this frame 
        // and add top level menus File and Menu
        MenuBar mb = new MenuBar();
        mb.add(fileMenu);
        setMenuBar(mb);
        addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            exit();
      public void exit() {
        setVisible(false); // hide the Frame
        dispose(); // tell windowing system to free resources
        System.exit(0); // exit
      public static void main(String args[]) {
        MainWindow w = new MainWindow();
        w.setVisible(true);
    // Encapsulate the look and behavior of the File menu
    class FileMenu extends Menu implements ActionListener {
        private MainWindow mw; // who owns us?
      private MenuItem itmPE   = new MenuItem("ProductEvaluation");
      private MenuItem itmExit = new MenuItem("Exit");
      public FileMenu(MainWindow main)
        super("File");
        this.mw = main;
        this.itmPE.addActionListener(this);
        this.itmExit.addActionListener(this);
        this.add(this.itmPE);
        this.add(this.itmExit);
      // respond to the Exit menu choice
      public void actionPerformed(ActionEvent e)
        if (e.getSource() == this.itmPE)
         Frame f = new Frame("ProductMeasurementEvaluationTool");
         f.setSize(1290,1290);
         f.setLayout(null);
         TextField t1 = new TextField("textField1");
         t1.setBounds(230, 630, 50, 24);
         f.add(t1);
         TextField t2 = new TextField("textField2");
         t2.setBounds(430, 630, 50, 24);
         f.add(t2);
         Choice c1 = new Choice();
         c1.addItem("Choice1");
         c1.addItem("Choice2");
         c1.addItemListener(new MyItemListener());
         f.add(c1);
         c1.setBounds(630, 600, 120, 24);
         Choice c2 = new Choice();
         c2.addItem("scale1");
         c2.addItem("scale2");
         c2.addItemListener(new MyItemListener());
         f.add(c2);
         c2.setBounds(840, 600, 120, 24);
         Label l1 = new Label("Select the appropriate metrics for Measurement Process Evaluation");
         l1.setBounds(380, 50, 380, 20);
         f.add(l1);
         Label l2 = new Label("Architecture Metrics");
         l2.setBounds(170, 100, 110, 20);
         f.add(l2);
         Label l3 = new Label("RunTime Metrics");
         l3.setBounds(500, 100, 110, 20);
         f.add(l3);
         Label l4 = new Label("Documentation Metrics");
         l4.setBounds(840, 100, 130, 20);
         f.add(l4);
         JRadioButton rb1 = new JRadioButton("Componenent Metrics",false);
         rb1.setBounds(190, 140, 133, 20);
         f.add(rb1);
         JRadioButton rb2 = new JRadioButton("Task Metrics",false);
         rb2.setBounds(540, 140, 95, 20);
         f.add(rb2);
         JRadioButton rb3 = new JRadioButton("Manual Metrics",false);
         rb3.setBounds(870, 140, 108, 20);
         f.add(rb3);
         JRadioButton rb4 = new JRadioButton("Configuration Metrics",false);
         rb4.setBounds(190, 270, 142, 20);
         f.add(rb4);
         JRadioButton rb6 = new JRadioButton("DataHandling Metrics",false);
         rb6.setBounds(540, 270, 142, 20);
         f.add(rb6);
         JRadioButton rb8 = new JRadioButton("Development Metrics",false);
         rb8.setBounds(870, 270, 141, 20);
         f.add(rb8);
         Checkbox  c10 = new Checkbox("Size");
         c10.setBounds(220, 170, 49, 20);
         f.add(c10);
         Checkbox c11 = new Checkbox("Structure");
         c11.setBounds(220, 190, 75, 20);
         f.add(c11);
         Checkbox c12 = new Checkbox("Complexity");
         c12.setBounds(220, 210, 86, 20);
         f.add(c12);
         Checkbox c13 = new Checkbox("Size");
         c13.setBounds(220, 300, 49, 20);
         f.add(c13);
         Checkbox c14 = new Checkbox("Structure");
         c14.setBounds(220, 320, 75, 20);
         f.add(c14);
         Checkbox c15 = new Checkbox("Complexity");
         c15.setBounds(220, 340, 86, 20);
         f.add(c15);
         Checkbox c19 = new Checkbox("Size");
         c19.setBounds(580, 170, 49, 20);
         f.add(c19);
         Checkbox c20 = new Checkbox("Structure");
         c20.setBounds(580, 190, 75, 20);
         f.add(c20);
         Checkbox c21 = new Checkbox("Complexity");
         c21.setBounds(580, 210, 86, 20);
         f.add(c21);
         Checkbox c22 = new Checkbox("Size");
         c22.setBounds(580, 300, 49, 20);
         f.add(c22);
         Checkbox c23 = new Checkbox("Structure");
         c23.setBounds(580, 320, 75, 20);
         f.add(c23);
         Checkbox c24 = new Checkbox("Complexity");
         c24.setBounds(580, 340, 86, 20);
         f.add(c24);
         Checkbox c28 = new Checkbox("Size");
         c28.setBounds(920, 170, 49, 20);
         f.add(c28);
         Checkbox c29 = new Checkbox("Structure");
         c29.setBounds(920, 190, 75, 20);
         f.add(c29);
         Checkbox c30 = new Checkbox("Complexity");
         c30.setBounds(920, 210, 86, 20);
         f.add(c30);
         Checkbox c31 = new Checkbox("Size");
         c31.setBounds(920, 300, 49, 20);
         f.add(c31);
         Checkbox c32 = new Checkbox("Structure");
         c32.setBounds(920, 320, 75, 20);
         f.add(c32);
         Checkbox c33 = new Checkbox("Complexity");
         c33.setBounds(920, 340, 86, 20);
         f.add(c33);
         ActionListener action = new MyActionListener(f, t1, t2);
         Button b1  = new Button("Button1");
         b1.setBounds(230, 600, 120, 24);
         b1.addActionListener(action);
         f.add(b1);
         Button b2  = new Button("Button2");
         b2.setBounds(430, 600, 120, 24);
         b2.addActionListener(action);
         f.add(b2);
               f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e)
              System.exit(0);
         f.show();
        else
       { mw.exit();}
    class MyActionListener implements ActionListener
      private Frame     frame;
      private TextField textField1;
      private TextField textField2;
      public MyActionListener(Frame frame, TextField tf1, TextField tf2)
        this.frame = frame;
        this.textField1 = tf1;
        this.textField2 = tf2;
      public void actionPerformed(ActionEvent e)
        String s = e.getActionCommand();
        if (s.equals("Button1"))
            Component[] components = this.frame.getComponents();
      int numOfCheckBoxes = 81;
      int numChecked = 0;
      for (int i = 0; i < components.length; i++)
            if (components[i] instanceof Checkbox)
              if (((Checkbox)components).getState())
    numChecked++;
    double ratio = (double) numChecked / (double) numOfCheckBoxes;
    this.textField1.setText(Double.toString(ratio));
    else
    if (s.equals("Button2"))
    Component[] components = this.frame.getComponents();
    int numOfCheckBoxes = 81;
    int numChecked = 0;
    for (int i = 0; i < components.length; i++)
    if (components[i] instanceof Checkbox)
    if (((Checkbox)components[i]).getState())
    numChecked++;
    double ratio = (double) numChecked / (double) numOfCheckBoxes;
    this.textField2.setText(Double.toString(ratio));
    class MyItemListener implements ItemListener {
         public void itemStateChanged(ItemEvent e) {
                   String command = (String) e.getItem();

    The easy answer is that you need to add state to one of your classes. What does this mean? Somewhere you will have to keep track of which items are selected in each Choice. There are a lot of ways to do this. One way is to pass a reference for each Choice, ie, c1 and c2, in to the constructor of MyItemListener and for each ItemEvent.SELECTED type of event:
    1 - check the selected item of each Choice and see if they have the same ending number, or are the same index in an array kept in your MyItemListener class or ... many ways;
    2 - decide what to do depending on what you find after checking.
    Since you have a separate class for the ItemListener this might be a good place to keep track of the selection status of the two Choice components. The member variables you use to keep track of things is the state.
    Another thing to consider is whether to add a separate listener to each Choice or to create a single instance and add it to each component. If you add a separate one then the Choice selections won't know about each other - each separate listener receives events from only one of the components. If you use a single instance for both components then you can get selection information from each of the Choice components. This way you can track things, or keep state, inside the class.
    I abbreviated the class name so you can run this without name-clashing in your computer.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Component;
    import java.awt.Checkbox;
    import javax.swing.*;
    public class MW extends Frame {
        public MW() {
            super("Menu System Test Window");
            setSize(500, 500);
            // make a top level File menu
            FileMenu fileMenu = new FileMenu(this);
            // make a menu bar for this frame 
            // and add top level menus File and Menu
            MenuBar mb = new MenuBar();
            mb.add(fileMenu);
            setMenuBar(mb);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    exit();
        public void exit() {
            setVisible(false); // hide the Frame
            dispose();         // tell windowing system to free resources
            System.exit(0);    // exit
        public static void main(String args[]) {
            MW w = new MW();
            w.setVisible(true);
    // Encapsulate the look and behavior of the File menu
    class FileMenu extends Menu implements ActionListener {
        private MW mw; // who owns us?
        private MenuItem itmPE   = new MenuItem("ProductEvaluation");
        private MenuItem itmExit = new MenuItem("Exit");
        public FileMenu(MW main) {
            super("File");
            this.mw = main;
            this.itmPE.addActionListener(this);
            this.itmExit.addActionListener(this);
            this.add(this.itmPE);
            this.add(this.itmExit);
        // respond to the Exit menu choice
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == this.itmPE) {
                final Frame f = new Frame("ProductMeasurementEvaluationTool");
                f.setSize(1290,1290);
                f.setLayout(null);
                MyItemListener itemListener = new MyItemListener(mw);
                TextField t1 = new TextField("textField1");
                t1.setBounds(230, 630, 50, 24);
                f.add(t1);
                TextField t2 = new TextField("textField2");
                t2.setBounds(430, 630, 50, 24);
                f.add(t2);
                Choice c1 = new Choice();
                c1.addItem("Choice1");
                c1.addItem("Choice2");
                c1.addItemListener(itemListener);
                f.add(c1);
                c1.setBounds(630, 600, 120, 24);
                Choice c2 = new Choice();
                c2.addItem("scale1");
                c2.addItem("scale2");
                c2.addItemListener(itemListener);
                f.add(c2);
                c2.setBounds(840, 600, 120, 24);
                Label l1 = new Label("Select the appropriate metrics for " +
                                     "Measurement Process Evaluation");
                l1.setBounds(380, 50, 380, 20);
                f.add(l1);
                Label l2 = new Label("Architecture Metrics");
                l2.setBounds(170, 100, 110, 20);
                f.add(l2);
                Label l3 = new Label("RunTime Metrics");
                l3.setBounds(500, 100, 110, 20);
                f.add(l3);
                Label l4 = new Label("Documentation Metrics");
                l4.setBounds(840, 100, 130, 20);
                f.add(l4);
                JRadioButton rb1 = new JRadioButton("Componenent Metrics",false);
                rb1.setBounds(190, 140, 133, 20);
                f.add(rb1);
                JRadioButton rb2 = new JRadioButton("Task Metrics",false);
                rb2.setBounds(540, 140, 95, 20);
                f.add(rb2);
                JRadioButton rb3 = new JRadioButton("Manual Metrics",false);
                rb3.setBounds(870, 140, 108, 20);
                f.add(rb3);
                JRadioButton rb4 = new JRadioButton("Configuration Metrics",false);
                rb4.setBounds(190, 270, 142, 20);
                f.add(rb4);
                JRadioButton rb6 = new JRadioButton("DataHandling Metrics",false);
                rb6.setBounds(540, 270, 142, 20);
                f.add(rb6);
                JRadioButton rb8 = new JRadioButton("Development Metrics",false);
                rb8.setBounds(870, 270, 141, 20);
                f.add(rb8);
                Checkbox  c10 = new Checkbox("Size");
                c10.setBounds(220, 170, 49, 20);
                f.add(c10);
                Checkbox c11 = new Checkbox("Structure");
                c11.setBounds(220, 190, 75, 20);
                f.add(c11);
                Checkbox c12 = new Checkbox("Complexity");
                c12.setBounds(220, 210, 86, 20);
                f.add(c12);
                Checkbox c13 = new Checkbox("Size");
                c13.setBounds(220, 300, 49, 20);
                f.add(c13);
                Checkbox c14 = new Checkbox("Structure");
                c14.setBounds(220, 320, 75, 20);
                f.add(c14);
                Checkbox c15 = new Checkbox("Complexity");
                c15.setBounds(220, 340, 86, 20);
                f.add(c15);
                Checkbox c19 = new Checkbox("Size");
                c19.setBounds(580, 170, 49, 20);
                f.add(c19);
                Checkbox c20 = new Checkbox("Structure");
                c20.setBounds(580, 190, 75, 20);
                f.add(c20);
                Checkbox c21 = new Checkbox("Complexity");
                c21.setBounds(580, 210, 86, 20);
                f.add(c21);
                Checkbox c22 = new Checkbox("Size");
                c22.setBounds(580, 300, 49, 20);
                f.add(c22);
                Checkbox c23 = new Checkbox("Structure");
                c23.setBounds(580, 320, 75, 20);
                f.add(c23);
                Checkbox c24 = new Checkbox("Complexity");
                c24.setBounds(580, 340, 86, 20);
                f.add(c24);
                Checkbox c28 = new Checkbox("Size");
                c28.setBounds(920, 170, 49, 20);
                f.add(c28);
                Checkbox c29 = new Checkbox("Structure");
                c29.setBounds(920, 190, 75, 20);
                f.add(c29);
                Checkbox c30 = new Checkbox("Complexity");
                c30.setBounds(920, 210, 86, 20);
                f.add(c30);
                Checkbox c31 = new Checkbox("Size");
                c31.setBounds(920, 300, 49, 20);
                f.add(c31);
                Checkbox c32 = new Checkbox("Structure");
                c32.setBounds(920, 320, 75, 20);
                f.add(c32);
                Checkbox c33 = new Checkbox("Complexity");
                c33.setBounds(920, 340, 86, 20);
                f.add(c33);
                ActionListener action = new MyActionListener(f, t1, t2);
                Button b1  = new Button("Button1");
                b1.setBounds(230, 600, 120, 24);
                b1.addActionListener(action);
                f.add(b1);
                Button b2  = new Button("Button2");
                b2.setBounds(430, 600, 120, 24);
                b2.addActionListener(action);
                f.add(b2);
                f.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        //System.exit(0);
                        f.dispose();
                f.setVisible(true);
            else {
                mw.exit();
    class MyActionListener implements ActionListener { 
        private Frame     frame;
        private TextField textField1;
        private TextField textField2;
        public MyActionListener(Frame frame, TextField tf1, TextField tf2) {
            this.frame = frame;
            this.textField1 = tf1;
            this.textField2 = tf2;
        public void actionPerformed(ActionEvent e) {
            String s = e.getActionCommand();
            if (s.equals("Button1")) {
                Component[] components = this.frame.getComponents();
                int numOfCheckBoxes = 81;
                int numChecked = 0;
                for (int i = 0; i < components.length; i++)
                    if (components[i] instanceof Checkbox)
                        if (((Checkbox)components).getState())
    numChecked++;
    double ratio = (double) numChecked / (double) numOfCheckBoxes;
    this.textField1.setText(Double.toString(ratio));
    else if (s.equals("Button2")) {
    Component[] components = this.frame.getComponents();
    int numOfCheckBoxes = 81;
    int numChecked = 0;
    for (int i = 0; i < components.length; i++)
    if (components[i] instanceof Checkbox)
    if (((Checkbox)components[i]).getState())
    numChecked++;
    double ratio = (double) numChecked / (double) numOfCheckBoxes;
    this.textField2.setText(Double.toString(ratio));
    class MyItemListener implements ItemListener {
    Frame owner;
    Dialog dialog;
    Label label;
    boolean haveScale1, haveScale2, haveChoice1, haveChoice2;
    public MyItemListener(MW mw) {
    owner = (Frame)mw;
    initializeDialog();
    haveScale1 = true;
    haveScale2 = false;
    haveChoice1 = true;
    haveChoice2 = false;
    public void itemStateChanged(ItemEvent e) {
    if(e.getStateChange() == ItemEvent.SELECTED) {
    String command = (String) e.getItem();
    System.out.println("command = " + command);
    if(command.equals("scale1")) {
    haveScale1 = true;
    haveScale2 = false;
    if(command.equals("scale2")) {
    haveScale2 = true;
    haveScale1 = false;
    if(command.equals("Choice1")) {
    haveChoice1 = true;
    haveChoice2 = false;
    if(command.equals("Choice2")) {
    haveChoice2 = true;
    haveChoice1 = false;
    if(haveScale1 && haveChoice1)
    launchDialog(1);
    if(haveScale2 && haveChoice2)
    launchDialog(2);
    private void launchDialog(int n) {
    label.setText("scale" + n + " and Choice" + n + " chosen");
    dialog.setVisible(true);
    private void initializeDialog() {
    label = new Label();
    label.setAlignment(Label.CENTER);
    dialog = new Dialog(owner, "item listener dialog", false);
    dialog.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    dialog.dispose();
    dialog.add(label); // to center of default BorderLayout
    dialog.setSize(200,100);
    dialog.setLocation(300,300);

  • Choice in AWT

    Can anyone tell me how to make the items in tthe choice in java.awt, editable

    If you mean that you want a Drop Down Listbox like in VB or C++ in MS Land then you use a JComboBox.
    Choice is not editable other than changing the list of items that you can choose from.

  • Invisible text in choice box!!!! HELP URGENT PLZ!

    after adding additems to a choice in awt, i cannot see the text, but the default option, but the list is white, the elements are there, I can click on them, but i cannot see the text ... can anyone help me ?

    By default it should be black ???
    myChoiceBox.setForeground(Color. ---- );

  • Choice item's value problem

    can I set the value of choice's String items?
    just like those in jsp
    for a jsp example
    <SELECT NAME="selectedfield" style=" WIDTH: 100px" Multiple>
    <OPTION value="ID">my ID</OPTION>
    <OPTION value="date">my birthday</OPTION>
    <OPTION value="money">money in wallet</OPTION>
    I means item's name not equals to item's value!
    can I achieve this in java awt choice?

    No, a Choice in AWT contains only String values and it's those String values that get displayed. There's no distinction between model and view.
    JComboBox in Swing has a more flexible approach whereby you can put an Object into the items and specify how it gets rendered separately.
    Hope this helps.

  • Import specific classes or whole packages?

    Since I began Java programming a few years ago, I have always used import functions to import whole packag.
    e.g. import java.util.* instead of java.util.ArrayList
    I have noticed that my IDE of choice (Eclipse) and many examples on the web use specific import statements instead of whole-package ones. Is there any advantage to this, performance or otherwise?
    thanks,
    Andrew

    nice advice, jackasspublic class Fred extends java.awt.Frame {
    public void paint(java.awt.Graphics g) {
    int width = getWidth();
    int height = getHeight();
    g.setColor(java.awt.Color.white);
    g.fillRect(0, 0, width, height);
    g.setColor(java.awt.Color.black);
    java.awt.FontMetrics fm = g.getFontMetrics();
    int sWidth = fm.stringWidth("Suck it");
    int sHeight = fm.getHeight();
    int x = (width - sWidth)/2;
    int y = (height - sHeight)/2;
    g.drawString("Suck it", x, y);
    public static void main(java.lang.String[] args) {
    Fred fred = new Fred();
    fred.addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent e) {
    java.lang.System.exit(0);
    fred.setSize(new java.awt.Dimension(400, 400));
    fred.setVisible(true);

  • Flash - Java - SerialData Translation issues

    This is for an art installation we're building in a gallery here in NYC. It opens Saturday, and we are in a jam with a problem.
    I'm using Dan O'Sullivan's Serial Server http://itp.nyu.edu/~dbo3/SerialServer/SerialServer.html , which is a little java server that connects to Flash via XML socket and to the serial port. It passes data back and forth since Flash doesn't talk to the serial port.
    The problem is this: Flash won't put the incoming data into the object and trigger the onData handler until it sees a null byte delimiter. On the other side, my serial device -- an encoder & adapter -- has no interest in producing a delimiter and cannot be programmed to do so. The data from the encoder is generally in the form of 4 bytes. You send it 1 byte to poll it.
    Thus the server app has to step in and patch things up, either (a) by indiscriminately appending 0's to everything it sees from the encoder (and figuring it all out in Flash) or better, (b) by having the server do the polling and keeping the current 4 bytes in a string, ready for when Flash requests it.
    This doesn't seem too bad - the server code is relatively simple - but I'm not a Java programmer (sorry, wish I were). I'm inserting the code here - any chance someone can help us out ... immediately?? Thanks very much.
    /Eric Liftin
    MESH Architectures http://mesh-arc.com
    * SerialServer.java
    * Title:               SerialServer
    * Description:          This relays bytes between a serial port and a socket connection.
    * @author               Administrator
    * @version               
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Frame;
    import java.awt.Toolkit;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.StringTokenizer;
    public class SerialServer extends java.applet.Applet  implements SerialListener {
         // IMPORTANT: Source code between BEGIN/END comment pair will be regenerated
         // every time the form is saved. All manual changes will be overwritten.
         // BEGIN GENERATED CODE
         // member declarations
         java.awt.Choice baud = new java.awt.Choice();
         java.awt.Checkbox interpretation = new java.awt.Checkbox();
         java.awt.Choice ports = new java.awt.Choice();
         java.awt.TextField socketPort = new java.awt.TextField();
         java.awt.Label softwarePort = new java.awt.Label();
         java.awt.Button sendToSocket = new java.awt.Button();
         java.awt.Button sendToSerial = new java.awt.Button();
         java.awt.TextField sendText = new java.awt.TextField();
         java.awt.TextArea traffic = new java.awt.TextArea();
         java.awt.Checkbox debugButton = new java.awt.Checkbox();
         java.awt.Label socketStatus = new java.awt.Label();
         java.awt.Label serialStatus = new java.awt.Label();
         java.awt.Label numbersFootnote = new java.awt.Label();
         java.awt.Button clearButton = new java.awt.Button();
         java.awt.Button cover = new java.awt.Button();
         // END GENERATED CODE
         String serialType = null;
         static Socketer mySocket;
         static Serial mySerial;
         boolean isStandalone = false;
         static boolean debug = false;
         public SerialServer() {}
         static HashMap argsHash;
         int substituteChar = 0;
         public void start() {
              //figure out what driver to use
              if (isStandalone == false) {
                        serialType =  getParameter("SerialDriver");
                   } else {
                        serialType = (String) argsHash.get("SerialDriver");
              if( serialType != null){  //if they did not specify
                   serialType= serialType.toLowerCase();
              newSerial();
              if (isStandalone == false) {
                   System.out.println("This is an Applet");
                   useParameters(getParameter("Baud"), getParameter("SerialPort"), getParameter("SocketPort"), getParameter("Sub0ForChar"), getParameter("SerialDriver"));
              } else {
                   useParameters((String) argsHash.get("Baud"), (String) argsHash.get("SerialPort"), (String) argsHash.get("SocketPort"), (String) argsHash.get("Sub0ForChar"),(String) argsHash.get("SerialDriver"));
              newSocket();
              connectSerial();
              //          event handling
              baud.addItemListener(new java.awt.event.ItemListener() {
                   public void itemStateChanged(java.awt.event.ItemEvent e) {
                        baudItemStateChanged(e);
              interpretation.addItemListener(new java.awt.event.ItemListener() {
                   public void itemStateChanged(java.awt.event.ItemEvent e) {
                        interpretationItemStateChanged(e);
              ports.addItemListener(new java.awt.event.ItemListener() {
                   public void itemStateChanged(java.awt.event.ItemEvent e) {
                        portsItemStateChanged(e);
              socketPort.addTextListener(new java.awt.event.TextListener() {
                   public void textValueChanged(java.awt.event.TextEvent e) {
                        socketPortTextValueChanged(e);
              sendToSocket.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        sendToSocketPerformed(e);
              sendToSerial.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        sendToSerialActionPerformed(e);
              sendText.addTextListener(new java.awt.event.TextListener() {
                   public void textValueChanged(java.awt.event.TextEvent e) {
                        sendTextTextValueChanged(e);
              ////     traffic.addTextListener(new java.awt.event.TextListener() {
              //     public void textValueChanged(java.awt.event.TextEvent e) {
              //          trafficTextValueChanged(e);
              debugButton.addItemListener(new java.awt.event.ItemListener() {
                   public void itemStateChanged(java.awt.event.ItemEvent e) {
                        debugItemStateChanged(e);
              clearButton.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        clearActionPerformed(e);
              //populatePorts();
         // Initialize the applet
         public void init() {
              try {
                   initComponents();
              } catch (Exception e) {
                   e.printStackTrace();
         public void useParameters(String _baud, String _serialPort, String _socketPort, String _subChar, String _serialType) {
              System.out.println("Input Parameters Baud:" + _baud + " SerialPort:" + _serialPort + " SocketPort:" + _socketPort + " SubChar:" + _subChar+ " SerialType:" + _serialType);
              if (_baud != null) {
                   baud.select(_baud);
              if (_subChar != null) {
                   substituteChar = Integer.parseInt(_subChar);
              } else {
                   substituteChar = 0;
              //else{
              //          baud.select("9600");
              if (_serialPort != null) {
                   ports.select(_serialPort);
              } //else{
              //     ports.select("COM1") ;
              //if ((_baud != null) || (_serialPort != null)){
              //     newSerial();
              if (_socketPort != null) {
                   socketPort.setText(_socketPort);
                   //     newSocket();
         public void initComponents() throws Exception {
              // IMPORTANT: Source code between BEGIN/END comment pair will be regenerated
              // every time the form is saved. All manual changes will be overwritten.
              // BEGIN GENERATED CODE
              // the following code sets the frame's initial state
              baud.setVisible(true);
              baud.setLocation(new java.awt.Point(222, 31));
              baud.setSize(new java.awt.Dimension(70, 21));
              interpretation.setVisible(true);
              interpretation.setLabel("Use decimals instead of letters.");
              interpretation.setLocation(new java.awt.Point(43, 175));
              interpretation.setSize(new java.awt.Dimension(200, 20));
              ports.setVisible(true);
              ports.setLocation(new java.awt.Point(222, 10));
              ports.setSize(new java.awt.Dimension(108, 21));
              socketPort.setLocation(new java.awt.Point(18, 10));
              socketPort.setVisible(true);
              socketPort.setText("9001");
              socketPort.setSize(new java.awt.Dimension(40, 20));
              softwarePort.setVisible(true);
              softwarePort.setLocation(new java.awt.Point(60, 10));
              softwarePort.setText("<Socket > ------------- <Serial>");
              softwarePort.setSize(new java.awt.Dimension(160, 20));
              sendToSocket.setVisible(true);
              sendToSocket.setLabel("<TestSend");
              sendToSocket.setLocation(new java.awt.Point(1, 60));
              sendToSocket.setSize(new java.awt.Dimension(80, 20));
              sendToSerial.setVisible(true);
              sendToSerial.setLabel("Test Send>");
              sendToSerial.setLocation(new java.awt.Point(279, 60));
              sendToSerial.setSize(new java.awt.Dimension(80, 20));
              sendText.setLocation(new java.awt.Point(82, 60));
              sendText.setVisible(true);
              sendText.setSize(new java.awt.Dimension(197, 20));
              traffic.setLocation(new java.awt.Point(5, 95));
              traffic.setVisible(true);
              traffic.setSize(new java.awt.Dimension(352, 80));
              debugButton.setFont(new java.awt.Font("Serif", 0, 12));
              debugButton.setVisible(true);
              debugButton.setLabel("debug");
              debugButton.setLocation(new java.awt.Point(130, 39));
              debugButton.setSize(new java.awt.Dimension(50, 20));
              socketStatus.setVisible(true);
              socketStatus.setAlignment(java.awt.Label.CENTER);
              socketStatus.setLocation(new java.awt.Point(65, 26));
              socketStatus.setSize(new java.awt.Dimension(45, 20));
              serialStatus.setVisible(true);
              serialStatus.setAlignment(java.awt.Label.CENTER);
              serialStatus.setLocation(new java.awt.Point(177, 26));
              serialStatus.setSize(new java.awt.Dimension(40, 20));
              numbersFootnote.setVisible(false);
              numbersFootnote.setLocation(new java.awt.Point(49, 79));
              numbersFootnote.setText("*Put spaces between numbers for test send.");
              numbersFootnote.setSize(new java.awt.Dimension(280, 20));
              clearButton.setVisible(true);
              clearButton.setLabel("Clear");
              clearButton.setLocation(new java.awt.Point(260, 178));
              clearButton.setSize(new java.awt.Dimension(58, 19));
              setLocation(new java.awt.Point(0, 0));
              setLayout(null);
              add(cover);
              add(baud);
              add(interpretation);
              add(ports);
              add(socketPort);
              add(softwarePort);
              add(sendToSocket);
              add(sendToSerial);
              add(sendText);
              add(traffic);
              add(debugButton);
              add(socketStatus);
              add(serialStatus);
              add(numbersFootnote);
              add(clearButton);
              setSize(new java.awt.Dimension(356, 274));
              // END GENERATED CODE
              baud.add("110");
              baud.add("300");
              baud.add("1200");
              baud.add("2400");
              baud.add("4800");
              baud.add("9600");
              baud.add("19200");
              baud.add("31250"); //   //31250
              baud.add("38400");
              baud.add("57600");
              baud.add("230400");
              baud.add("460800");
              baud.add("921600");
              baud.select("9600");
              cover.setVisible(true);
              //cover.setLayout(null);
              cover.setLocation(new java.awt.Point(-10, 57));
              cover.setSize(new java.awt.Dimension(964, 287));
         public void relayToSerial(int what) {
              boolean ok = mySerial.send(what).equals("OKAY");
              if (debug) {
                   socketStatus.setText("<IN>");
                   if (ok) {
                        serialStatus.setText("<OUT>");
                   showText(what);
         public void gotFromSerial(byte[] _byteArray){
         //public void relayToSocket(int what) {
             for(int i = 0; i < _byteArray.length; i++){
                 int what = (int) (_byteArray[i] & 0xff);
              if ((substituteChar != 0) && (what == substituteChar))
                   what = 0;
              boolean ok = mySocket.send(what).equals("OKAY");
              if (debug) {
                   serialStatus.setText("<IN>");
                   if (ok) {
                        socketStatus.setText("<OUT>");
                   showText(what);
         public void appendDebug(String what) {
              if (traffic.getText().toCharArray().length > 200)
                   traffic.setText(traffic.getText().substring(50));
              traffic.setText(traffic.getText() + "\n" + what + "\n");
              String strMessage = traffic.getText();
              traffic.setCaretPosition(strMessage.length());
         public void showText(int what) {
              if (interpretation.getState()) {
                   traffic.setText(traffic.getText() + " " + what);
              } else {
                   traffic.setText(traffic.getText() + ((char) what));
              String strMessage = traffic.getText();
              traffic.setCaretPosition(strMessage.length());
         // Standard method to start the applet
         //public void start() {
         //     newSocket();
         //     newSerial();
         public void populatePorts() {
              ports.removeAll();
              ArrayList portList = mySerial.getPortsList();
              for (int i = 0; i < portList.size(); i++) {
                   String[] portAndOwner = (String[]) portList.get(i);
                   System.out.println("owner" + portAndOwner[1]);
                   String port = portAndOwner[0];
                   String owner = portAndOwner[1];
                   //System.out.println(owner + " " + port + " number of Ports " + portList.size());
                   if (owner == null || owner.equals("Port currently not owned")) {
                        boolean alreadyThere = false;
                        for (int j = 0; j < ports.getItemCount(); j++) {
                             String alrdy = ports.getItem(j);
                             //System.out.println(port+ " Ports Already " + alrdy );
                             if (alrdy.equals(port)) {
                                  alreadyThere = true;
                                  break;
                        if (alreadyThere == false) {
                             ports.add(port);
                   } else {
                        System.out.println("Can't use it!" + port + owner);
                   //ports.add(((String) portList.get(i)));
         public void newSerial() {
              serialStatus.setText("!");
              mySerial = new Serial(this, serialType);
              if (ports.getItemCount() == 0) {
                   populatePorts();
         public void connectSerial() {
              if (ports.getItemCount() == 0) {
                   appendDebug("No serial ports found.");
              } else {
                   String status = mySerial.connect(ports.getSelectedItem(), Integer.parseInt(baud.getSelectedItem()));
                   if (status.startsWith("Got")) {
                        serialStatus.setText("<OK>");
                        //mySerial.start();
                   } else {
                        serialStatus.setText("Bad");
                        //populatePorts();
                   appendDebug(status);
         public void newSocket() {
              mySocket = new Socketer(Integer.parseInt(socketPort.getText()), this);
         public void socketStatus(String status) {
              if (status.startsWith("Got")) {
                   socketStatus.setText("<OK>");
              } else if (status.startsWith("Waiting")) {
                   socketStatus.setText("Waiting");
              } else {
                   socketStatus.setText("Bad");
              appendDebug(status);
         // Standard method to stop the applet
         public void stop() {
              mySerial.kill();
              mySocket.kill();
         // Standard method to destroy the applet
         public void destroy() {}
         // Main entry point when running standalone
         public static void main(String[] args) {
              SerialServer applet = new SerialServer();
              applet.isStandalone = true;
              Frame frame = new Frame();
              frame.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        Frame f = (Frame) e.getSource();
                        f.setVisible(false);
                        f.dispose();
                        System.exit(0);
              frame.setTitle("Serial Server");
              frame.add(applet, BorderLayout.CENTER);
              frame.setSize(400, 320);
              Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
              frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);
              frame.setVisible(true);
              applet.init();
              argsHash = new HashMap();
              for (int i = 0; i < args.length; i++) {
                   String pair = args;
                   String parts[] = pair.split(":");
                   if (parts.length == 2) {
                        argsHash.put(parts[0], parts[1]);
                   }else{
                        System.out.println("Problem with format of parameter "+ pair);
              applet.start();
              frame.pack();
         public void sendTextTextValueChanged(java.awt.event.TextEvent e) {}
         public void interpretationItemStateChanged(java.awt.event.ItemEvent e) {
              numbersFootnote.setVisible(interpretation.getState());
              System.out.println("Interpretation" + interpretation.isVisible());
         public void socketPortTextValueChanged(java.awt.event.TextEvent e) {
              mySocket.kill();
              mySocket = null;
              newSocket();
              System.out.println("Changed Socket");
         public void sendToSocketPerformed(java.awt.event.ActionEvent e) {
              if (interpretation.getState()) {
                   StringTokenizer st = new StringTokenizer(sendText.getText(), " ");
                   while (st.hasMoreTokens()) {
                        try {
                             int what = Integer.parseInt(st.nextToken());
                             if ((substituteChar != 0) && (what == substituteChar))
                                  what = 0;
                             //System.out.println(substituteChar + "debugSend" + what);
                             mySocket.send(what);
                        } catch (NumberFormatException nfe) {
                             System.out.println("You are are entering letters but you checked the decimal interpretation.");
              } else {
                   byte[] asbytes = sendText.getText().getBytes();
                   for (int i = 0; i < asbytes.length; i++) {
                        int what = asbytes[i];
                        if ((substituteChar != 0) && (what == substituteChar))
                             what = 0;
                        System.out.println(substituteChar + "debugSend" + what);
                        mySocket.send(what);
         public void sendToSerialActionPerformed(java.awt.event.ActionEvent e) {
              if (interpretation.getState()) {
                   StringTokenizer st = new StringTokenizer(sendText.getText(), " ");
                   while (st.hasMoreTokens()) {
                        try {
    mySerial.send(Integer.parseInt(st.nextToken()));
    } catch (NumberFormatException e1) {
         appendDebug("Enter a number.");
              } else {
                   byte[] asbytes = sendText.getText().getBytes();
                   for (int i = 0; i < asbytes.length; i++) {
                        mySerial.send(asbytes[i]);
         public void portsItemStateChanged(java.awt.event.ItemEvent e) {
              mySerial.kill();
              mySerial = null;
              newSerial();
              connectSerial();
              System.out.println("Serial Port Changed");
         public void baudItemStateChanged(java.awt.event.ItemEvent e) {
              mySerial.kill();
              mySerial = null;
              newSerial();
              connectSerial();
              System.out.println("Serial Baud Changed");
         public void debugItemStateChanged(java.awt.event.ItemEvent e) {
              debug = debugButton.getState();
              if (debug) {
                   cover.setLocation(-1000, -1000);
              } else {
                   cover.setLocation(-10, 57);
                   //cover.setVisible(true);
              //System.out.println("debugl Changed" + debug);
         public void clearActionPerformed(java.awt.event.ActionEvent e) {
              traffic.setText("");

    Whoops, I'll fix it up so it's more presentable
    for (int row = 0; row <= 8 ; row++){
        for (int column = 1; column <= row; column++ )
         System.out.print(" ");
        for (int i = 0; i < row; i++){
         System.out.print(" " + (int) Math.pow(2,i));
        for (int j = row-1; j >= 0; j--)
         System.out.print(" " + (int)Math.pow(2, j));
        System.out.println();
    }About the space, I was checking to see what adding and removing them would do, although even after fixing it I seem to get a bunched up mass.
    -edit-
    Another thing I've noted is that pasting the text here seems to throw off the indentations which look normal in eclipse.
    Edited by: Yummyfishman on Oct 5, 2007 8:33 PM
    Edited by: Yummyfishman on Oct 5, 2007 8:35 PM
    Edited by: Yummyfishman on Oct 5, 2007 8:36 PM
    Edited by: Yummyfishman on Oct 5, 2007 8:40 PM

  • CardLayout : problem on previous card

    I have a frame that is composed of several panels. One of those is a DisplayPanel for displaying drawings. I use CardLayout to display the drawings. Therefore, the uses can click on the next/previous button to look at the next/previous card of drawing that is shown in the displayPanel. I test the "next" button, and it works okay.
    However, when I click on the "previous button", it DOES NOT show the exact drawings that I have before navigating to the next card.
    Does anyone have any clue on why this will happen and how can I fix that?
    Here's the skeleton of my coding:
    public class drawMap extends JPanel
         // variable declaration
         public drawMap(Vector mapData, int index)
         public Dimension getPreferredSize()
              return new Dimension(width, height);
         public void paintComponent(Graphics g)
              // loop throught the mapData vector starting from the
              //       given index that is got from the constructor
              // draw two rows
    public class DisplayPanel extends JPanel implements ActionListener
         private JButton previousButton, nextButton;
         private JPanel allMaps = new JPanel(new CardLayout());
         DisplayPanel()
              add(mapPanel);
              add(buttonPanel);
         private JPanel mapPanel()
              int i=0, cardIndex=0;
              while (i < mapData.size())
                   DrawMap map = new DrawMap(mapData, i)
                   allMaps.add(map, String.valueOf(cardIndex));
                   i = findNextIndex(); // find the next index to start for the mapData
                   cardIndex++;
         private JPanel buttonPanel()
              JPanel p = new JPanel();
              previousButton = new JButton("Previous");
              previousButton.addActionListener(this);
              nextButton = new JButton("Next");
              nextButton.addActionListener(this);
              p.add(previousButton);
              p.add(nextButton);
              return p;
         private int findNextIndex()
              // find the next index to start
         public void actionPerformed(ActionEvent event)
              Object source = event.getSource();
              CardLayout cards = (CardLayout) (allMaps.getLayout());
              if (source == previousButton)
                   cards.previous(allMaps);
              else if (source == nextButton)
                   cards.next(allMaps);
    }

    Sorry for the long code. I minimize it as much as I can.
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import java.awt.*;
    public class MapFrame extends JPanel
        private SelectionList selection;
        private DisplayPanel display;
        public static void main(String[] args)
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
        private static void createAndShowGUI()
            JFrame frame = new JFrame("Drawing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new MapFrame());
            frame.pack();
            frame.setVisible(true);
            frame.setSize(500,500);
            frame.setLocationRelativeTo(null);
        public void setSelection(int c)
             display.setChoice(c);
        public MapFrame ()
            setLayout(new BorderLayout(5, 5));
            setPreferredSize(new Dimension(200, 200));
            add(display = new DisplayPanel(), BorderLayout.CENTER);
            add(selection = new SelectionList(this), BorderLayout.WEST);     
    class SelectionList extends JPanel implements ActionListener
         private MapFrame parent;
         private JRadioButton circleRadio, rectRadio;
         private static final int CIRCLE = 1;
         private static final int RECT = 2;
         public SelectionList(MapFrame theParent)
              this.parent = theParent;
              add(radioButton());
         public JPanel radioButton()
              JPanel p = new JPanel(new GridLayout(2,1));     
              circleRadio = new JRadioButton("Circle");
              rectRadio = new JRadioButton("Rect");
              circleRadio.addActionListener(this);
              rectRadio.addActionListener(this);
              ButtonGroup group = new ButtonGroup();
              group.add(circleRadio);
              group.add(rectRadio);
              p.add(circleRadio);
              p.add(rectRadio);
              return p;
         public void actionPerformed(ActionEvent event)
              Object source = event.getSource();
              if (source == circleRadio)
                   parent.setSelection(CIRCLE);
              else if (source == rectRadio)
                   parent.setSelection(RECT);
    class DisplayPanel extends JPanel implements ActionListener
         private static final int CIRCLE = 1;
         private static final int RECT = 2;
        private JButton previousButton, nextButton;
         private int choice = 0;
         private JPanel allMaps = new JPanel(new CardLayout());
         int [] list = {200, 100, 150, 100, 80, 125, 240};
         public DisplayPanel()
              GridBagConstraints gbc = new GridBagConstraints();
              gbc.anchor = GridBagConstraints.CENTER;
              gbc.insets = new Insets (5, 5, 5, 5);
              gbc.fill = GridBagConstraints.NONE;
              gbc.gridx = 0; gbc.gridy = 0; add(mapPanel(), gbc);
              gbc.gridy = 1; add(buttonPanel(), gbc);
         public void setChoice(int i)
              if (i == CIRCLE)
                   choice = CIRCLE;
              else
                   choice = RECT;
              mapPanel();
         private JPanel mapPanel()
              allMaps.removeAll();
              allMaps.validate();
              int i = 0;
              int cardIndex = 0;
              if (choice != 0)
                   while (i < list.length)
                        DrawMap map = new DrawMap(choice, i, list);
                        allMaps.add(map, String.valueOf(cardIndex));
                        int temp = findNextStart(map, i);
                        i = temp;                         
                        cardIndex++;
                   allMaps.validate();                    
              else
                   DrawMap map = new DrawMap(choice, i, null);
                   allMaps.add(map, String.valueOf(0));
                   allMaps.validate();
              return allMaps;
         public int findNextStart(DrawMap map, int i)
              int x = 0;
              int index = i;
              while (x <= 1)
                   int curXPosition = 0;
                   int nextLength = 0;
                   while (curXPosition + nextLength <= 400 && index < list.length)
                        int length = list[index];          
                        curXPosition += length;
                        index++;
                        if (index < list.length)
                             nextLength = list[index];
                   x++;
              return index;
         private JPanel buttonPanel()
              JPanel p = new JPanel();
              previousButton = new JButton("Previous");     
              previousButton.addActionListener(this);
              nextButton = new JButton("Next");     
              nextButton.addActionListener(this);
              p.add(previousButton);
              p.add(nextButton);
              return p;
         public void actionPerformed(ActionEvent event)
              Object source = event.getSource();
              CardLayout cards = (CardLayout) (allMaps.getLayout());
              if (source == previousButton)
                   cards.previous(allMaps);
              else if (source == nextButton)
                   cards.next(allMaps);
    class DrawMap extends JPanel
         private static final int D_WIDTH = 400;
         private static final int D_HEIGHT = 400;
         private static final int CIRCLE = 1;
         private static final int RECT = 2;
         int width, height;
         int choice;
         int [] list;
         int index;
         public DrawMap(int c, int counter, int[] l)
              width = D_WIDTH;
              height = D_HEIGHT;
              choice = c;
              index = counter;
              list = l;
         public Dimension getPreferredSize()
              return new Dimension(width, height);
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              Graphics2D g2d = (Graphics2D) g;
              if (list != null)
                   int x = 0;
                   while (x <= 1)
                        int gridYLine = (height/2) * x;
                        int curXPosition = 0;
                        int nextLength = 0;
                        while (curXPosition + nextLength <= width && index < list.length)
                             int length = list[index];
                             if (choice == CIRCLE)
                                  g2d.drawOval(curXPosition, gridYLine, length, length);
                             else
                                  g2d.drawRect(curXPosition, gridYLine,length, length);
                             curXPosition += length;
                             index++;
                             if (index < list.length)
                                  nextLength = list[index];
                        x++;
    }

  • Here the project i have to make

    First i have to create a GUI that contains the normal buttons with minimize, maximize, and X button.
    Well, i'm suppose to create 3 questions, and answer them in textbox. Following that, when i hit enter it is suppose to say if you are correct or not. The problem is that i can't seem to get my strings right to compare. It's either that or there is something wrong with my if- else statement. Basically i want it to show if they are correct or incorrect. Please help:
    package anaquiz;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    public class AnAQuiz extends JPanel {
    private JComboBox choice;
    private JLabel label;
    private JTextField text;
    Button CheckAnswer;
    Button TryAgain;
    private String string1 = "Wilson";
    private String string2 = " ";
    private String string3= "Ace";
    private String string4 = " " ;
    private String string5 = "Yes" ;
    private String string6 = " ";
    public AnAQuiz() {
    choice = new JComboBox();
    label = new JLabel();
    label.setBackground(Color.blue);
    text = new JTextField(42);
    CheckAnswer = new Button("Check Answer");
    TryAgain = new Button("Would you like to try again?");
    if (string1.equals(string2)) {
    label.setText("correct");
    } else if (string2 != (string1)) {
    label.setText("incorrect");
    if (string3.equals(string4)) {
    label.setText("correct");
    } else if (string4 != (string3)) {
    label.setText ("incorrect");
    if (string5.equals(string6)) {
    label.setText("correct");
    } else if (string6 != (string5)) {
    label.setText("correct");
    choice.addItem("Tennis Question #1");
    choice.addItem("Tennis Question #2");
    choice.addItem("Tennis Question #3");
    Listener listen = new Listener();
    choice.addActionListener(listen);
    add(choice);
    add(label);
    add(text);
    add(CheckAnswer);
    add(TryAgain);
    private class Listener implements ActionListener {
    public void actionPerformed(ActionEvent event) {
    int c = choice.getSelectedIndex();
    switch (c) {
    case 0:
    label.setText("Whats the famous tennis brand that begins with 'W'?");
    break;
    case 1:
    label.setText("What do you call when someone misses a serve?");
    break;
    case 2:
    label.setText("Should you shake hands after a match?");
    break;
    public static void main(String[] args) {
    JFrame frame = new JFrame("Quiz");
    frame.setForeground(Color.RED);
    frame.getContentPane().add(new AnAQuiz());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.show();
    frame.setVisible(true);
    Message was edited by:
    Vaust

    Hi
    I Have posted my small project of mine I think it should suffice you.
    I don't use database to store the question or the Answer Instead i have stored everything in a string and retriving it.
    Go through it and get some idea
    import java.awt. *;
    import java.awt. event.*;
    import javax.swing.*;
    class QuestionSeries{
    static String info ="Java Online Test Week  \n \nINSTRUCTIONS:\nThere are 25 questions in this test and 25 minutes to complete them all.\nThe finish button is highlighted in blue when you reach the end of the test. \nClicking the finish button will display the results with the correct answers marked in light red.  \n \nThe timecounter  begins when you click on the 'start' button \n \nBest of luck!\n";
    static String []question ={"Question 1:\nWhat is the result of attempting to compile and run the following program?\n\npublic class JavaAppclass{\npublic static void main(String args){\n   String myString = \"javaprograms\";\n   System.out.println(myString);\n   }\n}\n",
    "Question 2:\nWhat is the result of attempting to compile and run the following program with \n\n>javac JavaApp.java\n>java JavaApp\n\nclass TryFirst{\n   String myString = \"javatest\";\n}\n\nclass JavaApp{\n\npublic static void main(String[] arg){\n System.out.println(new TryFirst().myString);\n}\n}\n",
    "Question 3: \nWhat is the result of attempting to compile and run the following program with \n>javac JavaApp.java\n>java JavaApp\n\nclass MyJavaApp{ \n   String myString = \"elephants\"; \npublic static void main(String[] arg){ \n      System.out.println(myString); \n   } \n}\n",
    "Question 4:\nWhat is the result?\n\nclass JavaApp{ \n  public static void main(String[] a){ \n    String textstr = \"hello\";\n    for (int i=4; i<5; i++)\n      System.out.println(str); \n  } \n}\n",
    "Question 5:\nWhat is the result here?\n\nclass MyJavaApp{ \n  public static void main(String[] a){ \n    int j=0;\n    for (int i=0; i<3; i++) j=j+i;\n      System.out.println(j); \n  } \n}\n",
    "Question 6:\nWhat is the result?\n\nclass MyJavaApp{ \n  public static void main(String[] a){ \n    int num1;\n    int num2 = 7;\n    num2= num1 * 2 +3;\n    System.out.println(num2); \n  } \n}\n",
    "Question 7:\nWhat is the result?\n\nclass MyJavaApp{ \n  int num1;\n  public static void main(String[] a){ \n    number1=2;\n    int number2 = 7;\n    number2= number1 * 2 +3;\n    System.out.println(number2); \n  } \n}\n",
    "Question 8:\nWhat is the result?\n\nclass JavaApp{ \n  static int number1 = 4;\n  public static void main(String[] a){ \n    number1=2;\n    int number2 = 7;\n    number2= number1 * 2 +3;\n    System.out.println(number2); \n  } \n}\n",
    "Question 9:\nWhat is the result?\n\nclass JavaApp{ \n  static int number1 = 3;\n  public static void main(String[] arg)\n    int number2 = 7;\n    number2= number2 + number1 * 2 +3;\n    System.out.println(number2); \n  } \n}\n",
    "Question 10:\nWhat is the result of compiling and running the following code?\n\nclass JavaApp{ \n  public static void main(String[] a){\n    int x = (int) (Math.random());\n    System.out.println(x); \n  } \n}\n",
    "Question 11:\nWhat is the result?\n\nclass Tryclass{ \n  static String text = \"rabbit\";\n  public static void main(String[] a){\n    int num = text.length;\n    System.out.println(num); \n  } \n}\n",
    "Question 12:\nWhat would be the result here?\n\nclass Myclass{ \n  public static void main(String[] a){\n    char []rabbit={'a','b','c','d'};\n    int num = rabbit.length;\n    System.out.println(num); \n  } \n}\n",
    "Question 13:\nWhat is the result here?\n\nclass JavaApp{ \n  public static void main(String[] a){\n    int number = 10;\n    String mystr = Integer.toBinaryString(number);\n    System.out.println(mystr); \n  } \n}\n",
    "Question 14:\nWhat would be the result if we were to run this program with\n>java MyJavaApp hello java world ?\n\nclass MyJavaApp{ \npublic static void main(String[] args){\n    System.out.println(args[1]); \n  } \n}\n",
    "Question 15:\nWhat is the result of this program?\n\nclass MyJavaApp{ \n  public static void main(String[] a){\n    double d =1.75;\n    int i = d;\n    System.out.println(i++); \n  } \n}\n",
    "Question 16:\nWhat is the result of this program?\n\nclass MyJavaApp{ \n  public static void main(String[] a){\n    int 1stNum = 5;\n    int 2ndNum = 3;\n    double d =1.25 +1stNum/2ndNum;\n    System.out.println(d); \n  } \n}\n",
    "Question 17:\nWhat is the result of this program?\n\nclass MyJavaApp{ \n public static void main(String[] arg){\n    int Num1 = 5;\n    int Num2 = 4;\n    double d =1.25 +Num1/Num2;\n    System.out.println(d); \n  } \n}\n",
    "Question 18:\nWhat is the result of this program?\n\nclass TryJavaApp{ \n  static float f;\n  public static void main(String[] ar){\n    int Number = 5;\n    f = 1.25;    \n    System.out.println(f*4); \n  } \n}\n",
    "Question 19:\nWhat is the result of this program?\n\nclass JavaApp{ \n  static float f;\n  public static void main(String[] ar){\n    int Num = 2;\n    f = (float)1.25 * 2;    \n    System.out.println(f * Num); \n  } \n}\n",
    "Question 20:\nWhat is the result of this program?\n\nclass HelloJavaApp{ \n public static void main(String[] ar){\n    byte num = 64;\n    num += num;\n    System.out.println(num); \n  } \n}\n",
    "Question 21:\nWhat is the result of this program?\n\nclass JavaApp{ \n  public static void main(String[] a){\n  double d = 1.56789;\n    long num = Math.round(d);\n    System.out.println(num); \n  } \n}\n",
    "Question 22:\nWhat is the result of this program?\n\nclass JavaApp{ \n  public static void main(String[] a){\n    double d = 1.56789;\n    int num = (int)Math.round(d * d);\n    System.out.println(num); \n  } \n}\n",
    "Question 23:\nWhat is the result of this program?\n\nclass MyJavaApp{\npublic static void main(String[] arg){\n    double doub1 = 1.51;\n    int number1 = (int) (doub1 +0.5);\n    System.out.println(number1); \n    double doub2 = -1.51;\n    int number2 = (int) (doub2 +0.5);\n    System.out.println(number2); \n  } \n}\n",
    "Question 24:\nWhat is the result of this program?\n\nclass TryApp{ \npublic static void main(String[] arg){\n    int num = 4;\n    num = (num + 4/2) % num+1;\n    System.out.println(num); \n  } \n}\n",
    "Question 25:\nWhat is the result?\n\nclass MyApp{ \n  public static void main(String[] ar){\n    for(int i=0; i<3; i++)\n      for(int j=1; j<3; j++)\n        System.out.print(j+i+\",\"); \n  } \n}\n"
    static String [][]answers ={{"It will not compile as the main method  String is not an array\n","It will compile but there will be a runtime error if we try to run it with:- \n>java JavaApp\n","The program is fine, but we will need another program to run it and get the output.\n","It will compile and run and output \"java\" to the screen\n"},{"It will not compile as you cannot have 2 java source files on the same page\n"," \nIt will output \"javatest","It will not compile as the String myString is not-static and it is being accessed from a static method\n"," \nIt compiles but there is no output at runtime\n"},{" \nFine - it will output elephants\n","Runtime error MyJavaApp is not public\n","Compiler error myString is a non-static variable being accessed in a static method\n","Compile error in the main() method\n"},{" \nIt will output hello\n","The out put will be  \nhello\nhello\n"," \nNo output the for loop needs a ' ; ' at the end\n"," \nCompilation error for loops have to start with a zero\n"},{" \n3\n"," \n6\n"," \n4\n"," \n2\n"},{" \n17\n"," \n5\n"," \n3\n","It won't compile\n"},{" \n14\n"," \n7\n"," \n17\n"," \nError.\n"},{" \n16\n"," \n14\n"," \n7\n"," \nError\n"},{" \n15\n"," \n23\n"," \n50\n"," \nError\n"},{" \n1\n"," \nYou cannot predict the random result\n"," \n0\n"," \nError\n"},{" \n6\n"," \n5\n"," \n0\n"," \nError\n"},{" \n4\n"," \n3\n"," \n0\n"," \nError\n"},{" \n00001010\n"," \n10\n"," \n1010\n"," \nError\n"},{"hello java world\n"," \nhello\n"," \njava\n"," \nworld\n"},{" \n1.75\n"," \n2\n"," \n3\n"," \nError\n"},{" \n3.25\n"," \n2.25\n"," \n2.2... and a very long number\n"," \nThe code will not compile\n"},{" \n2.5\n"," \n2.25\n"," \n2.2 ... -something and a very long number\n"," \nThe code will not compile\n"},{" \nError float f is not initialised\n"," \noutput: 5\n"," \noutput: 5.0\n"," \nError, this is not a valid way to initialise a float type variable\n"},{" \n4.0\n"," \n5\n"," \n5.0\n"," \nError, it will not compile\n"},{" \n128\n"," \n-128\n"," \n1\n"," \nError, number is out of range\n"},{" \n1\n"," \n2\n"," \n1.0\n"," \nError\n"},{"3. - and to 15 decimal places\n"," \n2\n"," \n3\n"," \nError\n"},{" 2 \n-2\n"," 1\n-2\n"," 2\n-1\n"," 1\n-1\n"},{" \n1\n"," \n3\n"," \n4\n"," \n6\n"},{"1,2,2,3,3,4\n","1,2,3,3,4,6\n","1,2,3,4\n"," \n0,1,1,2,2,3,3,4\n"} };
    static int []n = {2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
    static String []choice= {"23","2","3","1","1","4","4","3","4","3","4","1","3","3","4","4","2","4","3","2","2","3","3","2","1"};
    static int tally = choice.length;
    static String testtitle="Java Programming Online Test";
    static int timeLimit =10;
    static int passMark = 15;
    /* OnlineTest class */
    public class OnlineTest extends JFrame{
        static String studentname ="";
        static int TOTAL=0;
         static {
         try{
         TOTAL = QuestionSeries.tally;          
         /*      The input window */
         studentname = JOptionPane.showInputDialog("Enter your name: ");
         if(studentname.length() < 1) studentname = "Anonymous   ";
         else studentname = studentname.trim() + " ";
         }catch(NullPointerException e){ System.exit(0); }
             int seconds, minutes;
             int quesnum, itemCheck, mark;
         final String TESTTITLE = QuestionSeries.testtitle;
             final int TIMELIMIT = QuestionSeries.timeLimit;
             final int PASS = QuestionSeries.passMark;
             String []answers = new String[TOTAL];
         JButton []choice_button = new JButton[6];
         JTextArea answerboxes[] = new JTextArea[4];
         JCheckBox []boxes = new JCheckBox[4];
             JTextPane pane = new JTextPane();
         JLabel student, choose, message, timecounter, testresult;
             boolean start_test, check_answer, allowRestart, finishtest;
         Northwindow panelNorth = new Northwindow();
         Southwindow panelSouth = new Southwindow();
         Centerwindow panelCenter = new Centerwindow();
    /*  OnlineTest Constructor */
         protected OnlineTest(){
            for (int i=0; i<TOTAL; i++) answers[i] ="";
              getContentPane().setLayout(new BorderLayout() );
              getContentPane().add("North", panelNorth);
              getContentPane().add("South", panelSouth);
              getContentPane().add("Center", panelCenter);
              int width = 0, height=0;
                 if(java.awt.Toolkit.getDefaultToolkit().getScreenSize().getWidth()<799){width=          640;           height=460; }
                 else {width=720; height=540; }
              setSize(width,height);
              Dimension dim = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
              setLocation((dim.width-width)/2, (dim.height-height)/2);
    **  Northwindow class
    class Northwindow extends JPanel{
    **  Northwindow constructor
        public Northwindow(){
              setLayout(new GridLayout(2,2));
              setBackground(new Color(230, 230, 255));
              student = new JLabel("\t Welcome : "+studentname+" to the Online Java Test");
              student.setFont(new Font("",Font.BOLD,16) );
              message = new JLabel();
              message.setForeground(Color.blue);
              add(student);
              add(message);
              add(new JLabel("               ") );
              add(new JLabel("               ") );
            setBorder(BorderFactory.createEtchedBorder() );
    **  Southwindow class
    class Southwindow extends JPanel{
         public Southwindow(){
              String []key = {"","start:","next:","finish:","check next:","check previous:"};
                   for(int i=0; i<choice_button.length; i++)
                        choice_button[i] = new JButton(key);
                        choice_button[i].addActionListener(new ActionHandler() );
                        if(i !=0)add(choice_button[i]);
    setBorder(BorderFactory.createEtchedBorder() );
    ** Centerwindow class
    class Centerwindow extends JPanel{
         public Centerwindow(){
              setLayout(new GridLayout(1,2) );
              JScrollPane west = new JScrollPane(pane);
              pane.setForeground(Color.red);     
              pane.setFont(new Font ("monospaced",0,12) );
              pane.setText(QuestionSeries.info);
              pane.setEditable(false);
              JPanel east = new JPanel();
              east.setLayout(new BorderLayout() );     
              JPanel northEast = new JPanel();
              northEast.setBackground(new Color(230, 230, 255) );
              east.add("North", northEast);
              JPanel westEast = new JPanel();
              westEast.setLayout(new GridLayout(6,1) );
              east.add("West", westEast);
              JPanel centerEast = new JPanel();
              centerEast.setLayout(new GridLayout(6,1) );
              centerEast.setBackground(new Color(255,255,200));
              east.add("Center", centerEast);
                   timecounter = new JLabel(" There are "+TOTAL+" questions in total");
                   timecounter.setFont(new Font ("Arial",Font.BOLD,16) );
                   timecounter.setForeground(new Color(0,90,20) );
                   northEast.add(timecounter);
                   westEast.add(new JLabel(" "));
    String []boxs = {" A ", " B ", " C ", " D "};
                   for(int i=0; i<boxes.length; i++) {
                        boxes[i] = new JCheckBox(boxs[i]);
                        boxes[i].addItemListener(new ItemHandler() );
                        westEast.add(boxes[i]);
    westEast.add(new JLabel() );
              choose = new JLabel(" CHOOSE CORRECT ANSWERS");
              choose.setBorder(BorderFactory.createEtchedBorder() );
              centerEast.add(choose);
    JScrollPane panes[] = new JScrollPane[4];
                   for(int i=0; i<answerboxes.length; i++){
                        answerboxes[i] = new JTextArea();
                   answerboxes[i].setBorder(BorderFactory.createEtchedBorder() );
                        answerboxes[i].setEditable(false);
                        answerboxes[i].setBackground(Color.white);
                        answerboxes[i].setFont(new Font("",0,12) );
         answerboxes[i].setLineWrap(true);
    answerboxes[i].setWrapStyleWord(true);
    panes[i] = new JScrollPane(answerboxes[i]);
                   centerEast.add(panes[i]);
              if(TIMELIMIT >0)testresult = new JLabel(studentname+", You have only : "+TIMELIMIT+" minutes to complete.");
              else testresult = new JLabel(" There is no time limit for this test");
              testresult.setBorder(BorderFactory.createEtchedBorder() );
              centerEast.add(testresult);
         add(west);
         add(east);
    ** ActionHandler class to handle all the action events from the buttons.
    class ActionHandler implements ActionListener{
    /* actionPerformed method */
         public void actionPerformed(ActionEvent evt){
         String source = evt.getActionCommand();
              if(source.equals("start:")){
                   choice_button[1].setVisible(false);
                   start_test=true;
                   allowRestart=true;
    if(TIMELIMIT >0)new Timer(); // inner Timer class
                   panelSouth.remove(choice_button[1]); //start
    displayquestion();
         if(start_test){
              if(source.equals("previous:")) {                
                   recordanswer();
                   quesnum--;
              if(quesnum == -1) quesnum=TOTAL-1;
                   checkteststatus();
    displayquestion();
              if(source.equals("next:")) {
                   recordanswer();
                   quesnum++;
                   if(quesnum == TOTAL-1) finishtest=true;
                   if(quesnum == TOTAL) quesnum=0;
    checkteststatus();
    displayquestion();
              if(source.equals("finish:")) {
                   if (finishtest){
                        recordanswer();
                        quesnum = 0;
                        choice_button[4].setBackground(Color.lightGray);
                        timecounter.setForeground(Color.blue);
                        timecounter.setFont(new Font ("Arial",0,14) );
                        start_test=false;
                        check_answer=true;
                        panelSouth.add(choice_button[0]);
                        mark_ques();
                        displayquestion();
                        checkteststatus();
                        calculateResult();
                   else JOptionPane.showMessageDialog(null,"Cycle through all questions before pressing finish",
                                                                                    "User Message",JOptionPane.INFORMATION_MESSAGE);
         if (check_answer){
              if(source.equals("check next:")) {
                   quesnum++;
                   if(quesnum == TOTAL) quesnum=0;
                   mark_ques();
                   displayquestion();
                   checkteststatus();
              if(source.equals("check previous:")) {
                   quesnum--;
                   if(quesnum == -1) quesnum=TOTAL-1;
                   mark_ques();
                   displayquestion();
                   checkteststatus();
         validate();
    /* Timer class */
    class Timer extends Thread implements Runnable{
         public Timer(){
              new Thread(this).start();
    public void run() {
              while(start_test){
    try {
    Thread.sleep(1000);
    seconds++;
                        if(seconds % 60 == 0 && seconds != 0){
    seconds -= 60;
    minutes++;
                        timecounter.setText(" Time Counter: "+minutes+" mins : "+seconds+" secs ");
                        if(minutes==TIMELIMIT){
                             start_test=false;
                             endTest();
    catch(InterruptedException ex) { System.out.print(ex); }
    /* checkteststatus method */
              public void checkteststatus(){
              if((quesnum == TOTAL-1)&&(start_test))choice_button[3].setBackground(Color.green);
              else choice_button[4].setBackground(Color.lightGray);
         if(answers[quesnum].length() >0){
                   for(int i=0; i<answers[quesnum].length(); i++)
                   boxes[Integer.parseInt(answers[quesnum].substring(i,i+1) )-1].setSelected               (true);
              else for(int i=0; i<boxes.length; i++)boxes[i].setSelected(false);
    /* displayquestion method */
         public void displayquestion(){
    int j = quesnum+1;
              pane.setText(QuestionSeries.question[quesnum]);
              if(start_test)message.setText("Question "+j+" out of "+TOTAL);
    for (int i=0; i<4; i++)answerboxes[i].setText(QuestionSeries.answers[quesnum][i]);
              if(start_test){
    String temp="";
                   if(QuestionSeries.n[quesnum]==1) temp="<html>   Choose only           <b>ONE</b> Option</html>";
                   else if(QuestionSeries.n[quesnum]==2) temp="<html>  Choose <b>TWO          </b> Options</html>";
              else if(QuestionSeries.n[quesnum]==3) temp="<html>  Choose <b>THREE</b>           Options</html>";
    else temp="<html>  <b>ALL are true</b> true</html>";
              choose.setText(temp);
              else {
              timecounter.setText(" Your choices are shown in the boxes");
    choose.setText(" Correct answers are marked in light red.");
    /* record answer method */
         public void recordanswer(){
              String tmp = "";
              for(int i=0; i<boxes.length; i++) if(boxes[i].isSelected() ) tmp +=i+1;
    answers[quesnum] = tmp;
    /* endTest method */
         public void endTest(){
              message.setText("TIME OVER: please press 'finish'");
    choice_button[2].setEnabled(false);
    choice_button[3].setEnabled(false);
    choice_button[4].setEnabled(true);
    /* mark_ques() method to highlight correct answers */
         public void mark_ques(){
              for(int i=0; i<answerboxes.length; i++) answerboxes[i].setBackground(Color.white);
              for(int i=0; i<QuestionSeries.choice[quesnum].length(); i++)
                   answerboxes[Integer.parseInt(QuestionSeries.choice[quesnum].substring(i,i+1))-1].setBackground(Color.red);
              if(QuestionSeries.choice[quesnum].equals(answers[quesnum])) message.setText("Answer correct, well done!");
              else message.setText("Sorry, you got this one wrong.");
         public void calculateResult(){
              mark=0;
              double temp=0.0;
    java.text.DecimalFormat df = new java.text.DecimalFormat("#0.#");
              for(int i=0; i<TOTAL; i++)if(QuestionSeries.choice[i].equals(answers[i]))mark++;
              temp=(double)mark;
              if(temp/TOTAL*100 >=PASS) testresult.setText(" Well done "+studentname.substring(0,studentname.indexOf(' ') )+", you passed");
              else testresult.setText(" Better luck next time "+studentname.substring(0,studentname.indexOf(' ') ) );
              student.setText(" Final score for "+studentname+": "+mark+" out of "+TOTAL+": "+df.format(temp/TOTAL*100)+"%");
              new Resultwindow().show();
    /* Resultwindow class */
    class Resultwindow extends JFrame{
              Resultwindow() {
         super( studentname+" results: " +(mark*100/TOTAL >=PASS?"PASS":"FAIL") );
              Container cont = getContentPane();
              cont.setLayout(new GridLayout(TOTAL/2+3,5,2,5) );
              cont.setBackground(new Color(255,220,255) );
              cont.add(new JLabel(" "+"Marks: "+mark+"/"+TOTAL+": "+"Percentage: "+(mark*100/TOTAL)+"%") );
    for(int i=0; i<3; i++)cont.add(new JLabel() );
         String temp[] = new String[TOTAL];
                   for(int i=0; i<TOTAL; i++){
                        if(QuestionSeries.choice[i].equals(answers[i])) temp[i]="correct";
                        else temp[i]="wrong";
                   for(int i=0; i<TOTAL; i++) cont.add(new JLabel(" Question "+(i+1)+": "+temp          [i]) );
              pack();
              setLocation(200,200);
    /* ItemHandler class */
    class ItemHandler implements ItemListener{
         public void itemStateChanged(ItemEvent evt){
         if(start_test){
              for(int i=0; i<boxes.length; i++) if(boxes[i].isSelected() ) itemCheck++;
              if(itemCheck > QuestionSeries.n[quesnum]){
                   java.awt.Toolkit.getDefaultToolkit().beep();
    if(QuestionSeries.n[quesnum]==1)     JOptionPane.showMessageDialog(null,"<html><font           size='4' color='00308a'><center>"+
         "There is only "+QuestionSeries.n[quesnum]+" possible<br> answer to question "+(quesnum+1)+
    "<html>","User Information Message",JOptionPane.INFORMATION_MESSAGE);
                   else JOptionPane.showMessageDialog(null,"<html><font size='4' color='00308a'><center>"+
    "There are only "+QuestionSeries.n[quesnum]+" possible<br> answers to question "+(quesnum+1)+
    "<html>","User Information Message",JOptionPane.INFORMATION_MESSAGE);
              itemCheck=0;
    /* main method */
         public static void main(String [] args){
              OnlineTest frame = new OnlineTest();
              frame.setTitle(" "+QuestionSeries.testtitle);
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.setVisible(true);

  • What is the best way to resize a JPEG and store it in the Filesystem

    Hi All,
    I have developped a CMS System that renders JPEGs if it does not have the images available within the desired width already. Within my development setup (Dell Latitude D800 with ubuntu dapper drake) everything works fine and fast, as expected. Then I uploaded the application to my V20Z Server with 4gb RAM and the systems performance goes to its knees. I have hooked in a Java Profiler to see where the problem is, and it showed me that it is hanging wthin
    sun.java2d.SunGraphics2D.drawImage(Image, int, int, ImageObserver) which I use to draw my Image to a BufferedImage. Below is my complete source code That I am using. Plus the orofiling results
    Do not be confused as I am using the Turbine Framework, which gives me a RawScreen which gives me Access to the HttpServletResponse...
    package de.ellumination.carmen.modules.screens;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.Iterator;
    import java.util.Locale;
    import javax.imageio.IIOImage;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageWriteParam;
    import javax.imageio.ImageWriter;
    import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
    import javax.imageio.stream.ImageOutputStream;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.log4j.Logger;
    import org.apache.turbine.modules.screens.RawScreen;
    import org.apache.turbine.util.RunData;
    import de.ellumination.carmen.om.ImagePeer;
    public class Image extends RawScreen
    public static final float DEFAULT_COMPRESSION_QUALITY = 1.0F;
    * Logger for this class
    private static final Logger log = Logger.getLogger(Image.class);
    @Override
    protected String getContentType(RunData data)
    return "image/jpeg";
    @Override
    protected void doOutput(RunData data) throws Exception
    int imageId = data.getParameters().getInt("id");
    int width = data.getParameters().getInt("width", -1);
    int height = data.getParameters().getInt("height", -1);
    HttpServletResponse response = data.getResponse();
    de.ellumination.carmen.om.Image image = ImagePeer.retrieveByPK(imageId);
    File imgFile = new File(image.getLocation());
    if(width > 0 || height > 0)
    outputScaledImage(imgFile, response, width, height);
    else
    outputImage(imgFile, response);
    private void outputScaledImage(File imageFile, HttpServletResponse response, int width, int height) throws Exception
    File scaledFile = new File(imageFile.getParent() + System.getProperty("file.separator") + width + "_" + imageFile.getName());
    if(scaledFile.exists())
    outputImage(scaledFile, response);
    else
    scaleImage(imageFile, scaledFile, width);
    outputImage(scaledFile, response);
    private void outputImage(File imageFile, HttpServletResponse response) throws Exception
    FileInputStream in = new FileInputStream(imageFile);
    response.setContentLength((int) imageFile.length());
    OutputStream out = response.getOutputStream();
    int bSize = 10240;
    byte[] buffer = new byte[bSize];
    int inBuffer = 0;
    while (inBuffer >= 0)
    inBuffer = in.read(buffer);
    if (inBuffer > 0)
    out.write(buffer, 0, inBuffer);
    * scales the image to its new size. while scaling the Image, the code first resizes the image using the new Width Parameter.
    * If the Image is to high after scaling, it then uses the Images height to determin the scaling Factor.
    * @param inputFile the original Image
    * @param outputFile the File to store the scaled image to
    * @param compressionQuality the compression Quality to use
    * @param newWidth the desired images width
    * @param newHeight the desired images height
    public static void scaleImage(File inputFile, File outputFile, float compressionQuality, int newWidth, int newHeight)
    try
    if (inputFile.exists())
    BufferedImage hiRes = ImageIO.read(inputFile);
    double scaleFactor = (double) newWidth / (double) hiRes.getWidth(null);
    int tempHeight = (int) (hiRes.getHeight(null) * scaleFactor);
    if (tempHeight > newHeight)
    scaleFactor = (double) newHeight / (double) hiRes.getHeight(null);
    int width = (int) (hiRes.getWidth(null) * scaleFactor);
    int height = (int) (hiRes.getHeight(null) * scaleFactor);
    scaleImage(outputFile, compressionQuality, hiRes, width, height);
    catch (IOException e)
    log.error("Unable to create the thumbnail " + outputFile.getAbsolutePath() + " from " + inputFile.getAbsolutePath() + " because of the following Reason.", e);
    * scales the image to its new size. while scaling the Image, the code first resizes the image using the new Width Parameter.
    * If the Image is to high after scaling, it then uses the Images height to determine the scaling Factor. This method uses the
    * default compression quality to store image data.
    * @param inputFile the original Image
    * @param outputFile the File to store the scaled image to
    * @param newWidth the desired images width
    * @param newHeight the desired images height
    public static void scaleImage(File inputFile, File outputFile, int newWidth, int newHeight)
    scaleImage(inputFile, outputFile, DEFAULT_COMPRESSION_QUALITY, newWidth, newHeight);
    * scales the image to its new size. while scaling the Image, the code first resizes the image using the new Width Parameter.
    * uses the highest image compression quality by default.
    * @param inputFile the original Image
    * @param outputFile the File to store the scaled image to
    * @param compressionQuality the compression Quality of the new Image
    * @param newWidth the desired images width
    public static void scaleImage(File inputFile, File outputFile, float compressionQuality, int newWidth)
    try
    if (inputFile.exists())
    BufferedImage hiRes = ImageIO.read(inputFile);
    double scaleFactor = (double) newWidth / (double) hiRes.getWidth(null);
    int width = (int) (hiRes.getWidth(null) * scaleFactor);
    int height = (int) (hiRes.getHeight(null) * scaleFactor);
    // draw original image to thumbnail image object and
    // scale it to the new size on-the-fly
    scaleImage(outputFile, compressionQuality, hiRes, width, height);
    else
    log.error("Unable to create the thumbnail " + outputFile.getAbsolutePath() + " from " + inputFile.getAbsolutePath() + " because inputFile not exists: " + inputFile.getName());
    catch (IOException e)
    log.error("Unable to create the thumbnail " + outputFile.getAbsolutePath() + " from " + inputFile.getAbsolutePath() + " because of the following Reason.", e);
    * scales the image to its new size. while scaling the Image, the code first resizes the image using the new Width Parameter.
    * uses the highest image compression quality by default.
    * @param inputFile the original Image
    * @param outputFile the File to store the scaled image to
    * @param newWidth the desired images width
    public static void scaleImage(File inputFile, File outputFile, int newWidth)
    scaleImage(inputFile, outputFile, DEFAULT_COMPRESSION_QUALITY, newWidth);
    * This private method actually scales the inputImage to the desired height, width and compression Quality
    * @param outputFile The File in which the Image should be stored.
    * @param compressionQuality The Compression Quality to be applied to the image
    * @param inputImage the original input Image
    * @param width the height of the new Image
    * @param height the width of the new Image
    * @throws IOException
    private static void scaleImage(File outputFile, float compressionQuality, BufferedImage inputImage, int width, int height) throws IOException
    BufferedImage lowRes = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    java.awt.Image image = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH);
    ImageWriter writer = null;
    Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
    if (iter.hasNext()) writer = (ImageWriter) iter.next();
    File outputPath = outputFile.getParentFile();
    if (outputPath != null)
    if (!outputPath.exists()) outputPath.mkdirs();
    lowRes.getGraphics().drawImage(image, 0, 0, null);
    ImageOutputStream ios = ImageIO.createImageOutputStream(outputFile);
    writer.setOutput(ios);
    ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
    iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwparam.setCompressionQuality(compressionQuality);
    // save thumbnail image to OUTFILE
    writer.write(null, new IIOImage(lowRes, null, null), iwparam);
    writer.dispose();
    ios.close();
    image.flush();
    inputImage.flush();
    lowRes.flush();
    * scales the image to its new size. while scaling the Image, the code first resizes the image using the new Width Parameter.
    * If the Image is to high after scaling, it then uses the Images height to determin the scaling Factor.
    * @param inputImage the original Image
    * @param outputFile the File to store the scaled image to
    * @param compressionQuality the compression Quality to use
    * @param newWidth the desired images width
    * @param newHeight the desired images height
    public static void scaleImage(BufferedImage inputImage, File outputFile, float compressionQuality, int newWidth, int newHeight)
    try
    double scaleFactor = (double) newWidth / (double) inputImage.getWidth(null);
    int tempHeight = (int) (inputImage.getHeight(null) * scaleFactor);
    if (tempHeight > newHeight)
    scaleFactor = (double) newHeight / (double) inputImage.getHeight(null);
    int width = (int) (inputImage.getWidth(null) * scaleFactor);
    int height = (int) (inputImage.getHeight(null) * scaleFactor);
    scaleImage(outputFile, compressionQuality, inputImage, width, height);
    catch (IOException e)
    log.error("Unable to create the thumbnail " + outputFile.getAbsolutePath() + " because of the following Reason.", e);
    All Threads     702.570     100 %
    java.lang.Thread.run()     551.322     78 %
    de.ellumination.carmen.modules.screens.Image.doOutput(RunData)     170.666     24 %
    de.ellumination.carmen.modules.screens.Image.outputScaledImage(File, HttpServletResponse, int, int)     170.108     24 %
                             de.ellumination.carmen.modules.screens.Image.scaleImage(File, File, int)     170.108     24 %
                                  de.ellumination.carmen.modules.screens.Image.scaleImage(File, File, float, int)     170.108     24 %
                                       de.ellumination.carmen.modules.screens.Image.scaleImage(File, float, BufferedImage, int, int)     165.787     24 %
                                            sun.java2d.SunGraphics2D.drawImage(Image, int, int, ImageObserver)     165.189     24 %
                                            com.sun.imageio.plugins.jpeg.JPEGImageWriter.write(IIOMetadata, IIOImage, ImageWriteParam)     397     0 %
                                            javax.imageio.ImageIO$ImageWriterIterator.next()     69     0 %
                                            javax.imageio.ImageIO.createImageOutputStream(Object)     47     0 %
                                            java.awt.image.BufferedImage.<init>(int, int, int)     36     0 %
                                            java.awt.Image.getScaledInstance(int, int, int)     23     0 %
                                            java.awt.image.BufferedImage.getGraphics()     21     0 %
                                       javax.imageio.ImageIO.read(File)     4.320     1 %
                        de.ellumination.carmen.om.BaseImagePeer.retrieveByPK(int)     557     0 %
                   de.ellumination.carmen.modules.screens.Index.doBuildTemplate(RunData, Context)     1.673     0 %
              org.apache.catalina.startup.Bootstrap.main(String[])     151.225     22 %
              org.quartz.core.QuartzSchedulerThread.run()     22     0 %
    Now I am looking for the Best way to solve my problem. Maybe I am wrong from the get go.
    Runtime Setup Java 1.5.0_04 Tomcat 5.5.12 V20z (AMD64 Opteron 4gb RAM)
    Any help is heighly appreciated
    Kind regards

    This is a bad thing to do with JPEGs. You're better off just reducing the 'q' if you want a smaller/faster/lower resolution image. That way you're throwing away resolution intelligently. Using scaling you're throwing resolution away unintelligently. I was on a project where 40,000 images were scaled when they should have been low-q'd. Don't do it.

  • Setting XML based exam to where there are two correct answers in a question

    I have an exam which pulls in questions from an XML file and to indicate what the correct answer is you would indicate in the XML as such:
    PROBLEM id="1">
                    <QUESTION>What is the State Capital of California:</QUESTION>
                    <CHOICE letter="a">San Fransisco.</CHOICE>
                    <CHOICE letter="b">San Diego.</CHOICE>
                    <CHOICE letter="c">Los Angelas.</CHOICE>
                    <CHOICE letter="d" correct="true">Sacremento.</CHOICE>
                </PROBLEM>
    There is one question, that is structured so there are two right answers, but when I add correct="true" to both answers I want as right only one is calculated correctly in the scoring. I thinking I need to make an adjustment in the code that pulls in the XML, but not sure where. Hoping someone can help.
    Here is the AS code.
    package exam {
        import flash.net.* //to create URLRequest and load XML file
        import flash.events.* //for Load events
        //import flash.display.* //for testing purposes - remove when testing complete
        //This class downloads the XML document, and then inserts info into arrays and variables.
        //Also provides text of questions and correct answers when requested.
        internal class XaMLDiplomat extends EventDispatcher {
            //VARIABLES:
            //for loaded XML doc
            private var myXML:XML;
            //for loading in XML
            private var examLoader:URLLoader;
            private var numQstns:Number; //count of total questions in a section
            private var sectStart:Number;
            //contains exam questions - ALL ARRAYS ARE ZERO RELATIVE -> actual question numbers = array index + 1
            private var questions:Array;
            //contain associated answer choices
            private var choiceA:Array;
            private var choiceB:Array;
            private var choiceC:Array;
            private var choiceD:Array;
            private var choiceE:Array;
            private var choiceF:Array;
            //array of the correct answers
            private var answers:Array;
            //use custom Mixer class to randomize order
            private var myMixer:Mixer;
            private var isRandom:Boolean;
            //CONSTRUCTOR
            public function XaMLDiplomat () { //NEED TO ADD ARGUMENTS (docLocation)
                //create URLRequest from argument
                var examSite:URLRequest = new URLRequest("protected/exam.xml");
                //create a loader for the XML
                examLoader = new URLLoader();
                //add listener for load completion
                examLoader.addEventListener(Event.COMPLETE, fullyLoaded);
                examLoader.load(examSite);
                //var ugly:Mixer = new Mixer(25);
            //Load listener - creates XML object, and checks it for multiple sections. If multiple, it asks users
            //which section they want - FIRST it needs to check database for any completed sections.
            //If single, it goes ahead and starts array creation for first (& only) section
            private function fullyLoaded (e:Event):void {
                myXML = new XML(examLoader.data);
                //myXML.prettyPrinting = false;
                //still need to pull out SYSTEM data and pass it along...
                var system:XMLList = myXML..SYSTEM;
                var sysObj:Object = new Object();
                sysObj.examTitle = system.TITLE.toString();
                sysObj.totalMin = system.MINUTES.toString();
                sysObj.retakePW = system.RETAKEPW.toString();
                var numSections:Number = myXML..SECTION.length();
                if (numSections == 1) {
                    generateArrays(1);
                dispatchEvent(new MultiSectEvent(MultiSectEvent.SECTIONS, numSections, sysObj));
            //Assigns arrays to instance variables for the selected section
            internal function generateArrays (sectn:Number):void {
                var whichSection:XMLList = myXML..SECTION.(@id == String(sectn));
                var probList:XMLList = whichSection.PROBLEM;
                numQstns = probList.length();
                sectStart = Number(probList[0].@id);
                questions = new Array();
                choiceA = new Array();
                choiceB = new Array();
                choiceC = new Array();
                choiceD = new Array();
                choiceE = new Array();
                choiceF = new Array();
                answers = new Array();
                for (var i:Number=0; i<numQstns; i++) {
                    var curProb:XMLList = probList.(@id == String(i+1));
                    if (curProb.QUESTION.hasSimpleContent()) {
                        questions[i] = curProb.QUESTION.toString();
                    }else {
                        //trace(curProb.QUESTION.toXMLString());
                        questions[i] = dropTags(curProb.QUESTION[0]);
                    choiceA[i] = curProb.CHOICE.(@letter == "a").toString();
                    choiceB[i] = curProb.CHOICE.(@letter == "b").toString();
                    choiceC[i] = curProb.CHOICE.(@letter == "c").toString();
                    choiceD[i] = curProb.CHOICE.(@letter == "d").toString();
                    choiceE[i] = curProb.CHOICE.(@letter == "e").toString();
                    choiceF[i] = curProb.CHOICE.(@letter == "f").toString();
                    answers[i] = curProb.CHOICE.(hasOwnProperty("@correct") && @correct == "true")[email protected]();
                //randomizing test
                //var makeRandom:Boolean;
                //system.RANDOM.toString() ==  'true' ? makeRandom = true : makeRandom = false;
                //myMixer = new Mixer(numQstns,makeRandom);
                trace("Question: "+questions[3]);
                trace("a: "+choiceA[3]);
                trace("b: "+choiceB[3]);
                trace("c: "+choiceC[3]);
                trace("d: "+choiceD[3]);
                trace("\r\n answer: "+answers[3]); */
            //method for external classes to acquire text of current exam question
            internal function getQuestion (qnum:Number):Object {
                var returnObj:Object = new Object();
                var randomQ:Number = myMixer.getRandomNumber(qnum-1);
                returnObj.q = questions[randomQ];
                returnObj.ca = choiceA[randomQ];
                returnObj.cb = choiceB[randomQ];
                returnObj.cc = choiceC[randomQ];
                returnObj.cd = choiceD[randomQ];
                returnObj.ce = choiceE[randomQ];
                returnObj.cf = choiceF[randomQ];
                returnObj.num = qnum;
                //trace(randomQ);
                return returnObj;
            private function dropTags (txt:XML):String {
                var txtString:String = "";
                for each (var child:XML in txt.*) {
                    if (child.nodeKind == "text") {
                        txtString += child.toString();
                    }else {
                        txtString += " " + child.toXMLString();
                //trace(txtString);
                return txtString;
            private function dropTags (txt:String):String {
                var sliceStart:Number = txt.indexOf(">");
                var sliceStop:Number = txt.lastIndexOf("<");
                return txt.slice((sliceStart+1), sliceStop);
            internal function getAnswer (num:Number):String {
                return answers[num];
            internal function getQCount ():Number {
                return numQstns;
            internal function getSectStart():Number {
                return sectStart;
            internal function getRealNum (num:Number):Number {
                return myMixer.getRandomNumber(num-1);

    this may or may not be the probel, but as it stands right now, when you select and anser it becomes hi-lighted and when you click off and select another answer the previous answer is deselected and the current answer is hi-lighted. I need to allow for multiple selections. This code is what is doing to current select/de-select functionality.
    package exam {
        import flash.display.*;
        import flash.events.*;
        import flash.text.*;
        //This class displays the current question, and contains the Choices for the question
        public class QMachine extends Sprite {
            //VARIABLES
            private var QObject:Object; //object from XaMLDiplomat, containing necessary text
            private var limit:Number;
            private var QNumTxt:TextField;
            private var QTxt:TextField;
            private var txtStyle:StyleSheet;
            private var choiceA:Choice;
            private var choiceB:Choice;
            private var choiceC:Choice;
            private var choiceD:Choice;
            private var choiceE:Choice;
            private var choiceF:Choice;
            //CONSTRUCTOR
            public function QMachine (hite:Number) {
                limit = hite;
                var style:Object = new Object();
                style.fontFamily = "Arial";
                //style.fontWeight = "bold";
                style.fontSize = "16";
                style.color = "#333333";
                txtStyle = new StyleSheet();
                txtStyle.setStyle("p",style);
                QNumTxt = new TextField();
                QNumTxt.styleSheet = txtStyle;
                //QNumTxt.embedFonts = true;
                QNumTxt.htmlText = "<p>1) </p>";
                QNumTxt.autoSize = TextFieldAutoSize.RIGHT;
                QNumTxt.x = 10;
                QNumTxt.mouseEnabled = false;
                QTxt = new TextField();
                QTxt.styleSheet = txtStyle;
                //QTxt.embedFonts = true;
                QTxt.width = 300;
                QTxt.multiline = true;
                QTxt.wordWrap = true;
                QTxt.autoSize = TextFieldAutoSize.LEFT;
                QTxt.htmlText = "<p>Question 1</p>";
                QTxt.x = 35;
                QTxt.mouseEnabled = false;
                addChild(QNumTxt);
                addChild(QTxt);
                choiceA = new Choice("a");
                choiceA.x = 350;
                addChild(choiceA);
                choiceB = new Choice("b");
                choiceB.x = 350;
                addChild(choiceB);
                choiceC = new Choice("c");
                choiceC.x = 350;
                addChild(choiceC);
                choiceD = new Choice("d");
                choiceD.x = 350;
                addChild(choiceD);
                choiceE = new Choice("e");
                choiceE.x = 350;
                addChild(choiceE);
                choiceF = new Choice("f");
                choiceF.x = 350;
                addChild(choiceF);
                addEventListener(MouseEvent.MOUSE_UP, selectResponse, true);
            internal function newQuestion (obj:Object, prior:String = ""):void {
                //trace(obj.num);
                QNumTxt.htmlText = "<p>"+ obj.num + ".</p>";
                QTxt.htmlText = "<p>"+ obj.q + "</p>";
                choiceA.deselect();
                choiceB.deselect();
                choiceC.deselect();
                choiceD.deselect();
                choiceE.deselect();
                choiceF.deselect();
                choiceA.resetSize();
                choiceB.resetSize();
                choiceC.resetSize();
                choiceD.resetSize();
                choiceE.resetSize();
                choiceF.resetSize();
                choiceA.changeTxt(obj.ca);
                choiceB.changeTxt(obj.cb);
                choiceB.y = choiceA.height + 5;
                if (obj.cc == undefined || String(obj.cc) == "") {
                    choiceC.visible = false;
                }else {
                    choiceC.changeTxt(obj.cc);
                    choiceC.y = choiceB.y + choiceB.height + 5;
                    choiceC.visible = true;
                if (obj.cd == undefined || String(obj.cd) == "") {
                    choiceD.visible = false;
                }else {
                    choiceD.changeTxt(obj.cd);
                    choiceD.y = choiceC.y + choiceC.height + 5;
                    choiceD.visible = true;
                if (obj.ce == undefined || String(obj.ce) == "") {
                    choiceE.visible = false;
                }else {
                    choiceE.changeTxt(obj.ce);
                    choiceE.y = choiceD.y + choiceD.height + 5;
                    choiceE.visible = true;
                if (obj.cf == undefined || String(obj.cf) == "") {
                    choiceF.visible = false;
                }else {
                    choiceF.changeTxt(obj.cf);
                    choiceF.y = choiceE.y + choiceE.height + 5;
                    choiceF.visible = true;
                var curHite:Number;
                if (choiceF.visible) {
                    curHite = choiceF.y + choiceF.height + 5;
                }else if (choiceE.visible) {
                    curHite = choiceE.y + choiceE.height + 5;
                }else if (choiceD.visible) {
                    curHite = choiceD.y + choiceD.height + 5;
                }else {
                    curHite = choiceC.y + choiceC.height + 5;
                if (curHite > (limit-150)) {
                    shrinkText();
                if (prior != "") {
                    if (prior == "a") {
                        choiceA.nowSelected();
                    }else if (prior == "b") {
                        choiceB.nowSelected();
                    }else if (prior == "c") {
                        choiceC.nowSelected();
                    }else if (prior == "d") {
                        choiceD.nowSelected();
                    }else if (prior == "e") {
                        choiceE.nowSelected();
                    }else if (prior == "f") {
                        choiceF.nowSelected();
            private function shrinkText() {
                choiceA.dropSize();
                choiceB.dropSize();
                choiceC.dropSize();
                choiceD.dropSize();
                choiceE.dropSize();
                choiceF.dropSize();
                choiceB.y = choiceA.y + choiceA.height + 5;
                choiceC.y = choiceB.y + choiceB.height + 5;
                choiceD.y = choiceC.y + choiceC.height + 5;
                choiceE.y = choiceD.y + choiceD.height + 5;
                choiceF.y = choiceE.y + choiceE.height + 5;
                var curHite:Number = 0;
                if (choiceF.visible) {
                    curHite = choiceF.y + choiceF.height + 5;
                }else if (choiceE.visible) {
                    curHite = choiceE.y + choiceE.height + 5;
                }else if (choiceD.visible) {
                    curHite = choiceD.y + choiceD.height + 5;
                }else {
                    curHite = choiceC.y + choiceC.height + 5;
                if (curHite > (limit-150)) {
                    shrinkText();
            private function selectResponse (e:MouseEvent):void {
                choiceA.deselect();
                choiceB.deselect();
                choiceC.deselect();
                choiceD.deselect();
                choiceE.deselect();
                choiceF.deselect();
                var letter:String = e.target.parent.getLetter();
                dispatchEvent(new ResponseEvent(ResponseEvent.SELECTION, letter));
            internal function setPriorResponse() {
                choiceA.deselect();
                choiceB.deselect();
                choiceC.deselect();
                choiceD.deselect();
                choiceE.deselect();
                choiceF.deselect();

  • How do you create different shaped borders?

    I need to create lots of different shaped borders that can be selected for a particular component, I know that you have to either extend AbstractBorder or implement Border interface, but I don't really know how to get the shape that I want, the most basic of which is a circle.
    Also will the component 'know' how to size the border so that the child components fit within it with no overlap?
    if anyone has an example border class they could donate to ease my confusion, i would be most grateful

    I have attached code for a border that draws a circle. If the insets are not large enough, then the child component will overlap. The large the child component needs to be, the large the insets should be in order for the oval to not be broken.
    // Border class
    public class OvalBorder implements javax.swing.border.Border {
        // insets used by the parent component for sizing the child component
        java.awt.Insets insets;
        public OvalBorder( ) {
            this( new java.awt.Insets( 20, 20, 20, 20 ) );
        public OvalBorder( java.awt.Insets insets ) {
            this.insets = insets;
        // Tell the parent component not to pain a backgroun underneath the border.
        public boolean isBorderOpaque( ) {
            return false;
        // Paint a simple oval border.
        public void paintBorder( java.awt.Component component, java.awt.Graphics g, int x, int y, int width, int height ) {
            g.setColor( java.awt.Color.white );
            g.fillOval( x, y, width, height );
            g.setColor( java.awt.Color.black );
            g.drawOval( x, y, width, height );
        // Return the insets that the parent component will use to size
        // the child component
        public java.awt.Insets getBorderInsets( java.awt.Component p1 ) {
            // Must do a clone so an outside source does not mess up the inset object.
            return (java.awt.Insets)insets.clone( );
        // A simple frame example of the border
        public static void main( String[ ] args ) {
            javax.swing.JFrame frame = new javax.swing.JFrame( );
            frame.setDefaultCloseOperation( javax.swing.JFrame.EXIT_ON_CLOSE );
            javax.swing.JPanel panel = new javax.swing.JPanel( new java.awt.GridLayout( 2, 1, 0, 0 ) );
            panel.setBorder( new OvalBorder( ) );
            frame.setContentPane( panel );
            javax.swing.JButton add = new javax.swing.JButton( "Add" );
            javax.swing.JButton minus = new javax.swing.JButton( "Minus" );
            frame.getContentPane( ).add( add );
            frame.getContentPane( ).add( minus );
            Inc inc = new Inc( add, minus, frame );
            add.addActionListener( inc );
            minus.addActionListener( inc );
            frame.pack( );
            frame.setVisible( true );
    // A support class that will cause the frame to resize equaly in both directions.
    class Inc implements java.awt.event.ActionListener {
        javax.swing.JButton add;
        javax.swing.JButton minus;
        javax.swing.JFrame frame;
        java.awt.Dimension pref;
        public Inc( javax.swing.JButton add, javax.swing.JButton minus, javax.swing.JFrame frame ) {
            this.add = add;
            this.minus = minus;
            this.frame = frame;
            pref = minus.getPreferredSize( );
            pref.width = pref.height<<1;
        public void actionPerformed( java.awt.event.ActionEvent event ) {
            if ( event.getSource( ) == add ) {
                pref.width+=2;
                pref.height++;
            } else {
                pref.width-=2;
                pref.height--;
            add.setPreferredSize( pref );
            minus.setPreferredSize( pref );
            System.out.println( pref );
            frame.pack( );
    }

  • How to give JComboBox JButton effects(urgent)

    hi,
    After selecting item in the JComboBox,when i perform action on the selected item, i am drawing a rectangle around the JComboBox. I want this rectangle to stay back till the operation is under processing, but i am not able to get it.
    i have used the following code for drawing rectangle around the combo
    private void drawRectangle(Graphics g,Insets inset,int width,int height)
    int top = inset.top;
    int bottom = inset.bottom;
    int left = inset.left;
    int right = inset.right;
    width = width - left - right;
    height = height - top - bottom;
    java.awt.Color col = g.getColor();
    g.setColor(java.awt.Color.black);
    BasicGraphicsUtils.drawDashedRect(g,2,2,width-20,height-2);
    try
    java.lang.Thread.currentThread().sleep(400);
    catch(InterruptedException ie)
    System.out.println("Catching Exception");
    g.setColor(col);
    }

    Don't use drawing, add a border instead

  • Strange Swing bug in Oracle's JDK7

    I have a strange bug with every java app i run with the Java 7 VM. Every frame is limited to a maximum width of 1024 pixels. Doesn't matter if you try to resize it by code or dragging the border with the mouse pointer.
    I have a Macbook with Mac OSX 10.7.5 (1280x800 resolution).
    If i try to run the apps with Apple's Java 6 VM all works as expected.
    Here is a POC:
    import javax.swing.*;
    import java.awt.*;
    public class JDK7Bug {
        public static void main(String[] args) throws InterruptedException {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
            frame.setSize(800, 400);
            Thread.sleep(100);
            System.out.println("frame.setSize(800, 400); " + frame.getSize());
            frame.setSize(1100, 400);
            Thread.sleep(100);
            System.out.println("frame.setSize(1100, 400); " + frame.getSize());
            frame.setSize(1000, 400);
            Thread.sleep(100);
            System.out.println("frame.setSize(1000, 400); "+frame.getSize());
            System.out.println("ScreenSize: "+Toolkit.getDefaultToolkit().getScreenSize());
    It outputs:
    frame.setSize(800, 400); java.awt.Dimension[width=800,height=400]
    frame.setSize(1100, 400); java.awt.Dimension[width=1024,height=400]
    frame.setSize(1000, 400); java.awt.Dimension[width=1000,height=400]
    ScreenSize: java.awt.Dimension[width=1280,height=800]

    Try wrapping everything inside main in a SwingUtilities.invokeLater. You should not do any Swing stuff outside the EDT and you can remove the Thread.sleep.
    I have tested on my Windows 8.1 with 7u45 and 7u60 and they both work
    I get the following in std.out:
    frame.setSize(800, 400); java.awt.Dimension[width=800,height=400]
    frame.setSize(1100, 400); java.awt.Dimension[width=1100,height=400]
    frame.setSize(1000, 400); java.awt.Dimension[width=1000,height=400]
    ScreenSize: java.awt.Dimension[width=2560,height=1440]

Maybe you are looking for