Solved

Java Components (TextFields, Choice Boxes, etc.)

Posted on 1997-06-23
14
376 Views
Last Modified: 2010-04-16
I am wondering if you can hide the borders which appear around textboxes, choices, etc.  For example, if I am using a choice box, all that I want appearing on the applet is the arrow button which drops the list down, and the text of the item on the left of it.  I don't want any border or sunken in look.  Is this possible with Java?  If so, does someone know how to do this?
0
Comment
Question by:Bryan051997
  • 8
  • 6
14 Comments
 
LVL 6

Accepted Solution

by:
jpk041897 earned 50 total points
ID: 1221990
Yes its possible:

You need to subclass several methods for the components you wish to affect though. Specificaly, you need to subclass the paint() method, and any method that diplays text, setText(), appendText(), etc.

The general idea is that these text displaying rutines call your paint() method instead of the default, in other words: don't allow your subbclases setText() to call super.setText().

If this answer is not clear enough, post me a comment and I'll post back some pseudo code.
0
 

Author Comment

by:Bryan051997
ID: 1221991
I am still a little unclear.  I am very new to Java Programming.  If you could provide some code, that would help me a lot.  For example, let's say I have a textfield called tf1 and a choice list called cl1.  How could I make these borderless?
0
 
LVL 6

Expert Comment

by:jpk041897
ID: 1221992
The following code was posted as an answer to another question (How to limit the number of characters entered in a text field) but addresses your problem as well:

File TF.java

import java.awt.*;

//Define a custom TextField class that can respond to events.
//  Note that this class extends TextField.
class TF extends TextField{

  int maxCount = 5;
  int count = 0;       
  TF(String inString, int MaxCount){
     setText(inString);
     maxCount = MaxCount;
  }//end constructor

  //The following event handler method handles events at the
  // component level as opposed to the container level.
  public boolean handleEvent(Event evObj){
 
    switch(evObj.id){
      case Event.KEY_PRESS :
        if (count < maxCount){
             char[] c = new char[1];
             c[0]= (char) evObj.key;
             String s = new String(c);
             setText(getText() + s);
             count++;
          }
          break;
      default : //catch and display all other event types here
          break;
    }//end switch
    return super.handleEvent(evObj);
  }//end handleEvent() in class TF
 
}//end class TF
//===================================================================



File Event05.java

import java.awt.*;


public class Event05 extends Frame{

  public Event05(){
    TF myTextField = new TF("", 5);//instantiate custom TextField object
    add ("Center",myTextField);
    myTextField.setEditable(false);//make it non-editable

    resize(300,50);//set frame size    
   }//end constructor

  //Create and show the frame object
  public static void main(String[] args){
    Event05 displayWindow = new Event05(); //instantiate obj of this type
    displayWindow.show();//display the frame
  }//end main
 
 
  public boolean handleEvent(Event evObj){
    //Terminate program if user closes the window
    if(evObj.id == Event.WINDOW_DESTROY) System.exit(0);
    return super.handleEvent(evObj);                      
  }//end handleEvent()
 
}//end class Event05



If this is not close enough to what you need, let me know and I'll write up some more specific code.
0
 

Author Comment

by:Bryan051997
ID: 1221993
I am not sure what you mean, how does this relate to what I have to do.  I am very new to Java programming and I am unsure how to do what you are saying.  Could you elaborate more, maybe show me how you would do this with the above code example?
0
 
LVL 6

Expert Comment

by:jpk041897
ID: 1221994
Sorry about that, the code was intended to give you a general idea  but only served to confused you more.

Lets bring this down several notches and do the following:

First, instead of a textField, lets use a canvas.

class NBtextField extends Canvas{
   String txt;

   NBtextField(){
      super();
   }

   public void setText(String txt){
      this.txt = txt;
   }

   void paint(Graphics g){
      g.drawString(txt, 0,0);
   }
}

You will also need to implement data entry for the field (if desired). You can use this class for that:

import java.io.*;
/**
 ** Keyboard.java    Version 1.0    29 February 1996
 **
 ** Copyright (c) 1996     M. Dennis Mickunas.
 **                        Department of Computer Science
 **                        University of Illinois at Urbana-Champaign
 **                        mickunas@cs.uiuc.edu
 **
 ** All Rights reserved Permission to use, copy, modify, and distribute
 ** this software and its documentation for NON-COMMERCIAL purposes and
 ** without fee is hereby granted provided that this copyright notice
 ** appears in all copies.
 **
 **/

/**
 ** A class to read integers, floats, doubles, and quoted strings
 ** from the Keyboard.
 ** Version 1.0, 29 Feb 1996
 ** author M. Dennis Mickunas
 **/

public class Keyboard {

private static StreamTokenizer input=new StreamTokenizer(System.in);
private static int tokentype;
private static boolean iseof;

public static boolean eof () {
    return iseof;
    }

public static int readInt () throws IOException {
    System.out.flush();
    iseof=(input.nextToken()==input.TT_EOF);
    return (int) input.nval;
    }

public static float readFloat () throws IOException {
    System.out.flush();
    iseof=(input.nextToken()==input.TT_EOF);
    return (float)input.nval;
    }

public static double readDouble () throws IOException {
    System.out.flush();
    iseof=(input.nextToken()==input.TT_EOF);
    return input.nval;
    }

public static String readString () throws IOException {
    System.out.flush();
    iseof=(input.nextToken()==input.TT_EOF);
    return input.sval;
    }

}

Then you could invoke Keyboard.readString while processing a gotFocus() event for the NBtextField class we just defined.


You can edit and extend these classes to your hearts content (to obtain centered or aligned text, limit the number of charactes accepted, etc).

Hope this is clears it up for you.

0
 

Author Comment

by:Bryan051997
ID: 1221995
It is starting to become a little more clear now.  Could you possibly show me an example of how I would use this in an applet now?  Also, where would I add things like background and foreground color for the textfield, and how would I implement this in the applet?  Would it be the same as for the regular awt textfield class?
0
 
LVL 6

Expert Comment

by:jpk041897
ID: 1221996
To use it in an applet, instantiate and add a variable of type NBTextField in your layout as you would an ordinary pannel:

NBTextField data1 = new NBTextField();
add("whatever", data1);

you can then place text on it with:

data1.setText("Some Text");

regarding background and foreground colors, you can add the methods to NBTextFields class definitions using wichever names you want, including setBackground and setForeground.

Both setBackgound and setForeground are methods defined for panel  so no changes are needed there.

To handle data entry, you can use code allong the lines of:

public boolean gotFocus(Event e, Object o) {

   // place code to detect which component has the focus here
   String s = Keyboard.readString();
   ComponentThatHasTheFocus.setText(s);

   return true;
}

For info on how to find out which component generated the event see:

http://www.inf.uni-hohenheim.de/top/java/tutorial/ui/overview/events.html

and

http://www.mcp.com/que/et/se_java2e/19javafi.htm

For additional info on how to use pannels see:

http://www.inf.uni-hohenheim.de/top/java/tutorial/ui/components/panel.html
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:Bryan051997
ID: 1221997
I tried compiling the first class NBtextField, and I get the error:
Error: C:\VisualCafePro\NoBorderTest\NBtextfield.java(17): Methods can't be overridden to be more private. Method void paint(java.awt.Graphics) is in java.awt.Canvas
 
What does this mean?  How can I fix this?

Also, should the Keyboard class be included within the NBtextField class or is it a separate java file altogether?
0
 

Author Comment

by:Bryan051997
ID: 1221998
I have gotten the classes to compile, and I added the code you showed me in the applet, and that compiles, but when I run it, I do not see the textfield at all.  Here is the code in my applet:


import java.awt.*;
import java.applet.*;
import java.io.*;

public class NoBorderApplet extends Applet {
   
    NBtextfield tf1 = new NBtextfield();

      public void init() {
            super.init();

            //{{INIT_CONTROLS
            setLayout(null);
            addNotify();
            resize(426,266);
            setBackground(new Color(12632256));
            //}}

            tf1.setBackground(new Color(16711680));

            add("whatever", tf1);
            tf1.setText("Some text");
      }
      
      public boolean gotFocus(Event e, Object o)
      {
       // place code to detect which component has the focus here
       try {
       String s = Keyboard.readString();
       tf1.setText(s); }
       catch (IOException ioe) {
            System.out.println("IO Error:" + ioe.getMessage());
       }

       return true;
    }

      public boolean handleEvent(Event event) {
            return super.handleEvent(event);
      }

      //{{DECLARE_CONTROLS
      //}}
}

I am not sure why it does not work right.  Do you know what I need to change to get it to work?

0
 

Author Comment

by:Bryan051997
ID: 1221999
This is the NBtextfield class:

import java.awt.*;

class NBtextfield extends Canvas
{
    String txt;

    NBtextfield()
    {
        super();
    }

    public void setText(String txt)
    {
        this.txt = txt;
    }

    public void paint(Graphics g)
    {
        g.drawString(txt, 0,0);
    }
}


This is the Keyboard class:

import java.io.*;

public class Keyboard
{

    private static StreamTokenizer input=new StreamTokenizer(System.in);
    private static int tokentype;
    private static boolean iseof;

    public static boolean eof ()
    {
        return iseof;
    }

    public static int readInt () throws IOException
    {
        System.out.flush();
        iseof=(input.nextToken()==input.TT_EOF);
        return (int) input.nval;
    }

    public static float readFloat () throws IOException
    {
        System.out.flush();
        iseof=(input.nextToken()==input.TT_EOF);
        return (float)input.nval;
    }

    public static double readDouble () throws IOException
    {
        System.out.flush();
        iseof=(input.nextToken()==input.TT_EOF);
        return input.nval;
    }

    public static String readString () throws IOException
    {
        System.out.flush();
        iseof=(input.nextToken()==input.TT_EOF);
        return input.sval;
    }

}

0
 

Author Comment

by:Bryan051997
ID: 1222000
I created another class, but rather than extending Canvas I extended TextField, and it worked.  But I am not sure you understood my original question.  The textfield still had borders and a sunken look.  I am trying to create a textfield that looks like a label but acts like a textfield.  In other words I want a label where you can enter text into it like a textfield.  I would also like to do this with a choice list box.  Could this be done?
0
 
LVL 6

Expert Comment

by:jpk041897
ID: 1222001
Thats why I suggested you extend Canvas and not textField.

Canvas is drawn withowt a bounding rectangle (no sunken look) and can draw graphics (for check boxes and radio buttons).

You could also extend label, but check boxex and radio buttons woud be hard to implement, so you could extend label for the textField, but would still need to use the keyboard class for input as label does not support KB input either.

All told, using Cnvas has the added benefit of allowing you to define all the base functionality (setText, getText, setBackground, etc). And then extend this class for control specific work, such as check box support.
0
 

Author Comment

by:Bryan051997
ID: 1222002
I still can't get the Canvas extended NBtextField class to show up in the applet.  I set the background color to red and the applet background color to lightgray, and I don't see any red anywhere in the applet.  Do you know why it is not showing up?
0
 
LVL 6

Expert Comment

by:jpk041897
ID: 1222003
Send me the code you have so far to jkelleghan@usa.net and I'll see what I can do with it over the weekend.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

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

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

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now