SetFont
Is' it possible change the font of a string in a Alert?
alert.setString(stringa);
I mean change the font of "stringa"?
and in a list:
lista.append(resP,null);
change the font of "resP"?
thanks
Use the search. These questions have been asked already a lot of times!
Similar Messages
-
[SOLVED]Setfont, showconsolefont and such don't work
Every time I open urxvt as a normal user, I get:
Couldn't get a file descriptor referring to the console
Couldn't get a file descriptor referring to the console
This doesn't happen when I open it with root privileges.
Also, every time I enter a "font-related" command, such as showconsolefont, without root privileges, I get a single:
Couldn't get a file descriptor referring to the console
The same commands with sudo don't produce the same problem, but, for example:
setfont fontnamehere
doesn't seem to change my terminal font at all. The:
sudo showconsolefont
output looks like this:
bug: getfont called with count<256
! " # $ % & ' ( ) * + , - . / 0
1 2 3 4 5 6 7 8 9 : ; < = > ? @
A B C D E F G H I J K L M N O P
Q R S T U V W X Y Z [ \ ] ^ _ `
! " # $ % & ' ( ) * + , - . / 0
1 2 3 4 5 6 7 8 9 : ; < = > ? @
A B C D E F G H I J K L M N O P
Q R S T U V W X Y Z [ \ ] ^ _ `
! " # $ % & ' ( ) * + , - . / 0
1 2 3 4 5 6 7 8 9 : ; < = > ? @
A B C D E F G H I J K L M N O P
Q R S T U V W X Y Z [ \ ] ^ _ `
! " # $ % & ' ( ) * + , - . / 0
1 2 3 4 5 6 7 8 9 : ; < = > ? @
A B C D E F G H I J K L M N O P
Q R S T U V W X Y Z [ \ ] ^ _ `
I searched the Internet for a solution, but to no avail. I'm not quite sure what's the problem here. I added i915 module and consolefont hook to /etc/mkinitcpio.conf(and regenerated it). My /etc/vconsole.conf looks as follows:
KEYMAP=pl
FONT=lat2-16
I'm new to GNU/Linux, this problem hasn't really caused me a lot of trouble, but it irritates me that I get the "Couldn't get a file descriptor referring to the console" every single time I open terminal. I really have no clue what I did wrong.
I'm using Start X at login and i3 as a windows manager; I'm not using any desktop environment.
My ~/.xinitrc:
#!/bin/sh
# ~/.xinitrc
# Executed by startx (run your window manager from here)
if [ -d /etc/X11/xinit/xinitrc.d ]; then
for f in /etc/X11/xinit/xinitrc.d/*; do
[ -x "$f" ] && . "$f"
done
unset f
feh --bg-scale ~/pics/wallpapers/nge/1412061334049.jpg
fi
[[ -f ~/.Xresources ]] && xrdb -merge ~/.Xresources
# exec gnome-session
# exec startkde
# exec startxfce4
# ...or the Window Manager of your choice
exec i3
My ~/.bash_profile:
# ~/.bash_profile
setfont ter-214b
[[ -f ~/.bashrc ]] && . ~/.bashrc
[[ -z $DISPLAY && $XDG_VTNR -eq 1 ]] && exec startx
My ~/.bashrc:
# ~/.bashrc
setfont ter-214b
export LANG=en_US.UTF-8
export LC_MESSAGES="C"
# If not running interactively, don't do anything
[[ $- != *i* ]] && return
alias ls='ls --color=auto'
PS1='[\u@\h \W]\$ '
I'm sorry for the lengthy post and for adding code which may not be needed. Any help would be greatly appreciated!
Last edited by ryachi (2014-11-21 21:11:23)None of those commands (related to console fonts) will work in X...
Your .xinitrc should not have the feh command inside the if block.
Remove the setfont command from your .bashrc and you'l stop getting those error messages every time you open a terminal.
There is a wiki article on setting fonts in the console (TTYs), please follow that. -
JMenuBar setFont problem.
Hi, I'm trying to change font for my menu bar, but it takes no effect.
Actually, my purpose is to set normal(not bold) font for menu.
Code:
JMenuBar menu=new JMenuBar();
menu.setFont(new Font("Serif", Font.PLAIN, 12));
//Adding menu items to the menubar.
I have tried to change font of menu items but it took no effect either.
Can anybody help me?
Thanks.Setting the font on the individual menu items should hve worked unless you don't have the specified font installed on your sytem.
However, if you want to change the font globally, use
UIManager.put(MenuItem.font, yourFont);
UIManager.put(Menu.font, yourFont);
This will change the fonts for all menus and menu items to whatever font you specify.
Sai Pullabhotla -
Memory leak in UIButton setFont method
Hi,
Hope you all doing well, I am getting a memory leak while setting the font of UIButton. This is the code which I am using to set the font,
[MyBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:12]];
whereas MyBtn is connected to IBOoutlet and I am not allocating memory to it.
I don't see any thing wrong in the code. Hopefully someone will help me out, I will be really thankful.In instrument the responsible library is UIKit and UILabel is the leaked object so I am also not sure whether instrument is pointing the right line or not.
Below is the function in which I am getting the leak,
- (void) LayoutUI
[bgImageView setImage:[UIImage imageNamed:@"bgImage.png"]];
[topImageHeaderView setImage:[UIImage imageNamed:@"headerImage.png"]];
[logoImageView setImage:[UIImage imageNamed:@"logo.png"]];
[HeaderImageView setImage:[UIImage imageNamed:@"headerImageView.png"]];
[BackBtn setTitle:@"Back" forState:UIControlStateNormal];
[BackBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:12]];
[BackBtn setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
//below is the Leaked line of code
[BackBtn.titleLabel setTextColor:[UIColor colorWithRed:(50.0/256.0) green:(100.0/256.0) blue:(200.0/256.0) alpha:1]];
[headerLbl setText:@"Header"];
//below two lines are leaked
[headerLbl setFont:[UIFont boldSystemFontOfSize:12]];
[headerLbl setTextColor:[UIColor colorWithRed:(50.0/256.0) green:(100.0/256.0) blue:(200.0/256.0) alpha:1]];
hopefully this will show a picture of what I am doing in my code.
One more thing all these UIlabels and UIImage are connected to IBOoutlet so I am not allocating memory to any of them but though I have tried to dealloc all of them in dealloc method but it didn't help me out. -
How to setFont in a List?
How can i setFont in a List for example setting it to SIZE_LARGE etc...,
thanks.i am able to setFont and run the MIDlet successfully on my WTK emulator but I am unable to see the font changes on my phone.
Please help please because I have no idea why is this happening.
I am using a SE K610i / Nokia 6280 -
Why can't change font of accelerator for menuitem by using setFont()
the method setFont() doesn't change the font of accelerator of menuitem, only it's left part text 's font is changed, how can i change
the font of the accelerator? Anyone can help me?Thanks very much VikingOSX
This solved my issue, but then I realised I have another. I'd like to be able to expand the size of the notes I can make. Perhaps there is another way in which I can get what I am after...?
Basically, I'd like to link a text box to a word(s) and be able to easily toggle between that text box being visible and hidden. The reason why is for chord charts/tablatures for music alongside lyrics. I'd like the lyrics and the chord chart/tablature to fit into the same file but I don't want to see the chords/tablature all the time. Only when I need to reference them.
Do you know if this is possible in either version of Pages?
Thanks -
SetFont throws ArithmeticException: / by zero
Hello,
I'm trying to properly display cp437 text file. I have found [perfect font|http://www.dafont.com/perfect-dos-vga-437.font] for this purpose. Loading font using Font.createFont is working, but when it should be used by calling jTextArea.setFont, it throws few times ArithmeticException. Font is working properly when it is installed to windows/fonts folder.
Exception in thread "AWT-EventQueue-0" java.lang.ArithmeticException: / by zero
at javax.swing.text.PlainView.paint(PlainView.java:256)
at javax.swing.plaf.basic.BasicTextUI$RootView.paint(BasicTextUI.java:1422)
at javax.swing.plaf.basic.BasicTextUI.paintSafely(BasicTextUI.java:722)
at javax.swing.plaf.basic.BasicTextUI.paint(BasicTextUI.java:869)
at javax.swing.plaf.basic.BasicTextUI.update(BasicTextUI.java:848)
at javax.swing.JComponent.paintComponent(JComponent.java:763)
at javax.swing.JComponent.paint(JComponent.java:1029)
at javax.swing.JComponent.paintChildren(JComponent.java:864)
at javax.swing.JComponent.paint(JComponent.java:1038)
at javax.swing.JViewport.paint(JViewport.java:747)
at javax.swing.JComponent.paintChildren(JComponent.java:864)
at javax.swing.JComponent.paint(JComponent.java:1038)
at javax.swing.JComponent.paintChildren(JComponent.java:864)
at javax.swing.JComponent.paint(JComponent.java:1038)
at javax.swing.JComponent.paintChildren(JComponent.java:864)
at javax.swing.JComponent.paint(JComponent.java:1038)
at javax.swing.JLayeredPane.paint(JLayeredPane.java:567)
at javax.swing.JComponent.paintChildren(JComponent.java:864)
at javax.swing.JComponent.paintToOffscreen(JComponent.java:5131)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(RepaintManager.java:1475)
at javax.swing.RepaintManager$PaintManager.paint(RepaintManager.java:1406)
at javax.swing.RepaintManager.paint(RepaintManager.java:1220)
at javax.swing.JComponent.paint(JComponent.java:1015)
at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:21)
at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:60)
at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:97)
at java.awt.Container.paint(Container.java:1780)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:814)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:714)
at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:694)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:128)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)It's weird. I dont think it's my fault. Look...
* To change this template, choose Tools | Templates
* and open the template in the editor.
* NewJFrame.java
* Created on 8.9.2009, 19:50:52
package fonttest;
import java.awt.Font;
import java.awt.FontFormatException;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
* @author filuta
public class NewJFrame extends javax.swing.JFrame {
/** Creates new form NewJFrame */
public NewJFrame() {
initComponents();
try {
Font dosfont = Font.createFont(Font.TRUETYPE_FONT,
new File("C:\\Users\\filuta\\Downloads\\dos437\\" +
"Perfect DOS VGA 437.ttf")).deriveFont(12f);
jTextArea1.setFont(dosfont);
catch (FontFormatException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
} -
SetFont for selected text in JTextArea
Hi there,
I'm trying to build a small Texteditor.
How do you set a selceted area of text to fx. BOLD font?
I can of course set the font for the whole JTextArea via the setFont method, but what about a smal selection.
Also: setFont seems to take no less than 3 arguments (fontname, style, size). Is it possible just to set the selected font as the same as before, but BOLD??
Kind Regards
ThomasAlright, so here I go :
I've been working for two months on a TextEditor/HTMLEditor, but I'm not allowed to share my code (I work for a company that wants to use this editor).
There are a lot of stuff that you should know about "javax.swing.text" package if you want to get initiated to Editors programming with Swing components.
Well, first of all, I'm going to answer to your punctual question :
You can't set style attributes ( color, bold, italic, ...) to specifc text elements in a JTextArea, you have got to use a JEditorPane or a JTextPane. (JTextPane lets you deal with the notion of "Styles"... but this is a bit complex for a simple editor, so I suggest you to just stick to the JEditorPane).
Any of these three Components has a document model related to it. These document models can be of different types. For example, PlainDocument, StyledDocument, HTMLDocument, etc...
A JTextArea can only have PlainDocument bound to it. These documents don't keep info about color, font, bold, and stuff for specific portions of text.They apply it to all content.
JEditorPane can have PlainDocuments, HTMLDocuments and I think they can have StyledDocuments.
To set bold to selected text you've got to do this :
import javax.swing.text.*;
int posStart = editorPane.getSelectionStart( );
int posEnd = editorPane.getSelectionEnd( );
int selLength = posEnd - posStart;
MutableAttributeSet atr = new SimpleAttributeSet();
StyleConstants.setBold(atr,true);
StyledDocument doc = editorPane.getDocument();
//Check out false in the following instruction
// it means that any other attribute existing should
// be kept if it has not be redefined in the attribute you are applying
doc.setCharacterAttributes(posStart,selLength,atr,false); That's it.. that's the way to do it.. the same principle applies for any other attribute,
for example if you also wanted to change font you could have added the following :
StyleConstants.setFontFamily(atr,"Arial");Alright, so know I'm going to give you the good adresses to learn stuff about Editors, here I go:
* The Swing Connection Articles (hard to understand for a newbie but really helpful ):
http://java.sun.com/products/jfc/tsc/articles/index.html (Check out the TextPackage Articles)
* Manning Matthew Robinson and Pavel Vorobiev Swing book (it's all online for free)
This is the absolute reference, step by step examples. Check out Chapter 20 : Constructing a
Word Processor. (This is I guess the best stuff available online about constructing Text and HTML Editors in Java with Swing)
http://www.spindoczine.com/sbe/ -
SetFont seems to work in Frame but not JFrame
Hi all,
The following code works when I use a Frame
Font f = new Font("SansSerif", Font.BOLD, 12);
frame.setFont(f);but when I switch to using a JFrame it doesn't use the font that I have set but the default one. Any ideas? I can provide more of the source code if anyone thinks it might help.
Thanks.I decided to use this solution:
public void paint(Graphics g){
g.setFont(font1);
}Then all the g.drawString(); statements used the font font1. -
[SOLVED] Questions about /etc/vconsole.conf and setfont command
Running setfont command, either
setfont Lat2-Terminus16
or
setfont /usr/share/kbd/consolefonts/Lat2-Terminus16
gets me "Couldn't get a file descriptor referring to the console"
When I installed the system I set my keymap to Lat2-Terminus16, doesn't this force the fonts to load in the bootup process?
Last edited by w201 (2013-02-12 19:27:14)karol wrote:
jasonwryan wrote:Please read the wiki page: the hook you want is not keymap.
I'm not sure I get it, but https://wiki.archlinux.org/index.php/Mk … mmon_hooks lists only keymap.
I posted this https://wiki.archlinux.org/index.php/Ta … onsolefont a year ago and didn't receive any response.
I was referring to this page: https://wiki.archlinux.org/index.php/Fo … sole_fonts
I guess consolefont is not considered "common"... -
SetFont() takes a lo...ong time
Hi all,
I am creating a splash screen with a background image and some text. The text is being created with different fonts. Here is the paint method of the JWindow component, I am using...
public void paint(Graphics g) {
g.setFont(new Font("Arial Black", Font.PLAIN, 30));
g.setColor(new Color(0, 51, 153));
g.drawString("Company Name", 171, 65);
I found that the "setFont" takes a long time, because of which my splash screen has only a background image for about 5 seconds, before the text is drawn. If I comment the "setFont", the text is instantly drawn.
Is the loading of the font that is taking time or the creation of the glyph? How I can make it faster?
Thanks,
GirishHi, I am facing the same problem while setting "monospaces" font. Please let me know if there is way to reduce the time.
Thanks,
Anil
Email : [email protected] -
JSpinner.setFont() does not work
Hi,
I tried to change the font on my JSpinner, but i does not work. :(
SpinnerDateModel sdmMonthModel = new SpinnerDateModel();
sdmMonthModel.setCalendarField(Calendar.MONTH);
JSpinner gMonthSpinner = new JSpinner(sdmMonthModel);
gMonthSpinner.setFont(FONT);
JSpinner.DateEditor deMonthEditor = new JSpinner.DateEditor(
gMonthSpinner, "MMMM"
deMonthEditor.setFont(FONT);
gMonthSpinner.setEditor(deMonthEditor);any suggestions?If you search the bug database for JSpinner setFont, you'll see this
bug at the top of the list.
http://developer.java.sun.com/developer/bugParade/bugs/4656590.html
This will be fixed in a future release. In the meantime, try:
deMonthEditor.getTextField().setFont(FONT);Leif Samuelsson
Java Swing Team
Sun Microsystems, Inc. -
JFileChooser setFont for Title - possible?
i searched the internationalisation forum also.
seems to be impossible.
OR
how to set the M$ Window's message box title font using java?
I tried:
Toolkit.getDefaultToolkit().setDesktopProperty("win.menu.font",java.awt.Font);
but it has protected access!
anuThank u Ritesh
anu
It's not possible to Title font. It is system
dependent.
Ritesh -
If Statement in java.awt paint
import java.applet.Applet; //bring in the applet class
import java.awt.*; //bring in the graphics class
import java.awt.event.*; //bring in the event class
import java.text.DecimalFormat; //bring in the decimal format class
import java.lang.Float; //bring in the float class
public class Bmi extends Applet implements ActionListener { //begin program and start ActionListener
Label weight, height; //define Label variable
TextField weighttext, heighttext; //define TextField variables
Button calculate; //define button variables
float index, wt, ht, max, min; //define float variables
DecimalFormat fmt2 = new DecimalFormat("#.00"); //set decimal format for reals
public void init() { //begin init()
weight = new Label("Please enter your weight in Kg. (2 decimal places): "); //define content of Label weight
weighttext = new TextField(6); //define size of TextField
height = new Label("Please enter your height in Metres (2 decimal places): "); //define content of Label height
heighttext = new TextField(5); //define size of TextField
calculate = new Button("Calculate!!"); //define content of Button
add(weight); //add Label weight to the GUI
add(weighttext); //add TextField weighttext to the GUI
add(height); //add Label height to the GUI
add(heighttext); //add TextField heighttext to the GUI
add(calculate); //add button calculate to the GUI
calculate.addActionListener(this); //wait for button to be returned
wt = 0; //reset wt to 0
index = 0; //reset index to 0
ht = 0; //reset ht to 0
max = 0; //reset max to 0
min = 0; //reset min to 0
public void actionPerformed( ActionEvent e ) { //run upon return of button
wt = Float.parseFloat(weighttext.getText()); //convert weighttext from String to Float
ht = Float.parseFloat(heighttext.getText()); //covert heighttext from String to Float
repaint(); //refresh paint area
public float indexer() //begin indexer method
float ind; //delare local variable ind
ind = wt/(ht*ht); //perform calculation
return ind; //make indexer() the value of variable ind
} // end of indexer method
public float maxWeight() //begin maxWeight method
float maxwt; //declare local variable maxwt
final float UPPER = 25.0f; //declare variable UPPER as a float with a decimal value of 25.0
maxwt = UPPER*ht*ht; //perform calculation
return maxwt; //make maxWeight() the value of variable maxwt
} // end of maxWeight method
public float minWeight() //begin minWeight method
float minwt; //declare local variable minwt
final float LOWER= 20.0f; //declare variable LOWER as a float with a decimal value of 20.0
minwt = LOWER*ht*ht; //perform calculation
return minwt; //make minWeight() the value of variable minwt
} // end of minWeight method
public void paint(Graphics g) //begin paint method, define g as Graphics
index=indexer(); //covert method indexer() to variable index
max=maxWeight(); //convert method maxWeight() to variable max
min=minWeight(); //convert method minWeight() to variable min
g.setFont(new Font("Verdana", Font.ITALIC, 15)); //define font, weight and size
g.setColor(new Color(90,90,90)); //set new colour
g.drawRect(5,100,300,75); //define size of rectangle
g.setColor(new Color(255,107,9)); //set new colour
g.drawString("BMI is " + fmt2.format(index) + " for " + fmt2.format(wt) + "kg",20,120); //create string in paint, define its on screen position
g.drawString("Maximum bodyweight is " + fmt2.format(max) + "kg", 20,140); //create string in paint, define its on screen position
g.drawString("Minimum bodyweight is " + fmt2.format(min) + "kg", 20,160); //create string in paint, define its on screen position
} // end of paint method
} // end of Bmi classI have written the above code to calculate someones BMI (Body Mass Index). Basically as you can see it recieves a weight and height from the user and calculates the rest. But whilst that good I would like to know how I can make it tell the user something to the effect of "Your overweight" or "Your underweight". The if statement runs like this:
if (wt > max)This forum doesn't quite handle <> properly. The greater and less than symbols. So above you will see > this is the html character code for a greater than symbol so please read it as such.
And then if wt is greater than max then it will say "Your overweight".
But I can't figure out how to include it in the above program. Becuase it won't run in paint, atleast it won't the way I have done it previously. So can you think of any other ways?
Help much appreciated,
SimonThanks very much that works well.
Simon
My code now looks like this: import java.applet.Applet; //bring in the applet class
import java.awt.*; //bring in the graphics class
import java.awt.event.*; //bring in the event class
import java.text.DecimalFormat; //bring in the decimal format class
import java.lang.Float; //bring in the float class
public class Bmi extends Applet implements ActionListener { //begin program and start ActionListener
Label weight, height; //define Label variable
TextField weighttext, heighttext; //define TextField variables
Button calculate; //define button variables
float index, wt, ht, max, min; //define float variables
DecimalFormat fmt2 = new DecimalFormat("#.00"); //set decimal format for reals
public void init() { //begin init()
weight = new Label("Please enter your weight in Kg. (2 decimal places): "); //define content of Label weight
weighttext = new TextField(6); //define size of TextField
height = new Label("Please enter your height in Metres (2 decimal places): "); //define content of Label height
heighttext = new TextField(5); //define size of TextField
calculate = new Button("Calculate!!"); //define content of Button
add(weight); //add Label weight to the GUI
add(weighttext); //add TextField weighttext to the GUI
add(height); //add Label height to the GUI
add(heighttext); //add TextField heighttext to the GUI
add(calculate); //add button calculate to the GUI
calculate.addActionListener(this); //wait for button to be returned
wt = 0; //reset wt to 0
index = 0; //reset index to 0
ht = 0; //reset ht to 0
max = 0; //reset max to 0
min = 0; //reset min to 0
public void actionPerformed( ActionEvent e ) { //run upon return of button
wt = Float.parseFloat(weighttext.getText()); //convert weighttext from String to Float
ht = Float.parseFloat(heighttext.getText()); //covert heighttext from String to Float
repaint(); //refresh paint area
public float indexer() //begin indexer method
float ind; //delare local variable ind
ind = wt/(ht*ht); //perform calculation
return ind; //make indexer() the value of variable ind
} // end of indexer method
public float maxWeight() //begin maxWeight method
float maxwt; //declare local variable maxwt
final float UPPER = 25.0f; //declare variable UPPER as a float with a decimal value of 25.0
maxwt = UPPER*ht*ht; //perform calculation
return maxwt; //make maxWeight() the value of variable maxwt
} // end of maxWeight method
public float minWeight() //begin minWeight method
float minwt; //declare local variable minwt
final float LOWER= 20.0f; //declare variable LOWER as a float with a decimal value of 20.0
minwt = LOWER*ht*ht; //perform calculation
return minwt; //make minWeight() the value of variable minwt
} // end of minWeight method
public void you(Graphics g)
String statement;
if(wt > max) statement="You are very fat";
else if(wt < min) statement="You are very thin";
else statement="You are in the recommended weight range for your height";
g.drawString(statement, 20,210);
public void paint(Graphics g) //begin paint method, define g as Graphics
you(g);
index=indexer(); //covert method indexer() to variable index
max=maxWeight(); //convert method maxWeight() to variable max
min=minWeight(); //convert method minWeight() to variable min
g.setFont(new Font("Verdana", Font.ITALIC, 15)); //define font, weight and size
g.setColor(new Color(90,90,90)); //set new colour
g.drawRect(5,100,300,75); //define size of rectangle
g.setColor(new Color(255,107,9)); //set new colour
g.drawString("BMI is " + fmt2.format(index) + " for " + fmt2.format(wt) + "kg",20,120); //create string in paint, define its on screen position
g.drawString("Maximum bodyweight is " + fmt2.format(max) + "kg", 20,140); //create string in paint, define its on screen position
g.drawString("Minimum bodyweight is " + fmt2.format(min) + "kg", 20,160); //create string in paint, define its on screen position
} // end of paint method
} // end of BmiThanks again,
Simon -
Hi All,
Can anyone kind enought to help me to add the START and STOP button for this "bouncing ball" program that i got from the internet ? Below is the java coding.
import java.awt.*;
import java.applet.*;
class Obstacle
public Rectangle r;
Graphics g;
public Obstacle(int x,int y,int w,int h)
r=new Rectangle(x,y,w,h);
public void paint(Graphics gr)
g=gr;
g.setColor(Color.lightGray);
g.draw3DRect(r.x,r.y,r.width,r.height,true);
class CollideBall
int width, height;
public static final int diameter=20;
//coordinates and value of increment
double x, y, xinc, yinc, coll_x, coll_y;
boolean collide;
Color color;
Graphics g;
Rectangle r;
//the constructor
public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c)
width=w;
height=h;
this.x=x;
this.y=y;
this.xinc=xinc;
this.yinc=yinc;
color=c;
r=new Rectangle(150,80,130,90);
public double getCenterX() {return x+diameter/2;}
public double getCenterY() {return y+diameter/2;}
public void alterRect(int x, int y, int w, int h)
r.move(x,y);
r.resize(w,h);
public void move()
if (collide)
double xvect=coll_x-getCenterX();
double yvect=coll_y-getCenterY();
if((xinc>0 && xvect>0) || (xinc<0 && xvect<0))
xinc=-xinc;
if((yinc>0 && yvect>0) || (yinc<0 && yvect<0))
yinc=-yinc;
collide=false;
x+=xinc;
y+=yinc;
//when the ball bumps against a boundary, it bounces off
if(x<6 || x>width-diameter)
xinc=-xinc;
x+=xinc;
if(y<6 || y>height-diameter)
yinc=-yinc;
y+=yinc;
//cast ball coordinates to integers
int x=(int)this.x;
int y=(int)this.y;
//bounce off the obstacle
//left border
if(x>r.x-diameter&&x<r.x-diameter+7&&xinc>0&&y>r.y-diameter&&y<r.y+r.height)
xinc=-xinc;
x+=xinc;
//right border
if(x<r.x+r.width&&x>r.x+r.width-7&&xinc<0&&y>r.y-diameter&&y<r.y+r.height)
xinc=-xinc;
x+=xinc;
//upper border
if(y>r.y-diameter&&y<r.y-diameter+7&&yinc>0&&x>r.x-diameter&&x<r.x+r.width)
yinc=-yinc;
y+=yinc;
//bottom border
if(y<r.y+r.height&&y>r.y+r.height-7&&yinc<0&&x>r.x-diameter&&x<r.x+r.width)
yinc=-yinc;
y+=yinc;
public void hit(CollideBall b)
if(!collide)
coll_x=b.getCenterX();
coll_y=b.getCenterY();
collide=true;
public void paint(Graphics gr)
g=gr;
g.setColor(color);
//the coordinates in fillOval have to be int, so we cast
//explicitly from double to int
g.fillOval((int)x,(int)y,diameter,diameter);
g.setColor(Color.white);
g.drawArc((int)x,(int)y,diameter,diameter,45,180);
g.setColor(Color.darkGray);
g.drawArc((int)x,(int)y,diameter,diameter,225,180);
public class BouncingBalls extends Applet implements Runnable
Thread runner;
Image Buffer;
Graphics gBuffer;
CollideBall ball[];
Obstacle o;
//how many balls?
static final int MAX=10;
boolean intro=true,drag,shiftW,shiftN,shiftE,shiftS;
boolean shiftNW,shiftSW,shiftNE,shiftSE;
int xtemp,ytemp,startx,starty;
int west, north, east, south;
public void init()
Buffer=createImage(size().width,size().height);
gBuffer=Buffer.getGraphics();
ball=new CollideBall[MAX];
int w=size().width-5;
int h=size().height-5;
//our balls have different start coordinates, increment values
//(speed, direction) and colors
ball[0]=new CollideBall(w,h,50,20,1.5,2.0,Color.orange);
ball[1]=new CollideBall(w,h,60,210,2.0,-3.0,Color.red);
ball[2]=new CollideBall(w,h,15,70,-2.0,-2.5,Color.pink);
ball[3]=new CollideBall(w,h,150,30,-2.7,-2.0,Color.cyan);
ball[4]=new CollideBall(w,h,210,30,2.2,-3.5,Color.magenta);
ball[5]=new CollideBall(w,h,360,170,2.2,-1.5,Color.yellow);
ball[6]=new CollideBall(w,h,210,180,-1.2,-2.5,Color.blue);
ball[7]=new CollideBall(w,h,330,30,-2.2,-1.8,Color.green);
ball[8]=new CollideBall(w,h,180,220,-2.2,-1.8,Color.black);
ball[9]=new CollideBall(w,h,330,130,-2.2,-1.8,Color.gray);
o=new Obstacle(150,80,130,90);
west=o.r.x;
north=o.r.y;
east=o.r.x+o.r.width;
south=o.r.y+o.r.height;
public void start()
if (runner == null)
runner = new Thread (this);
runner.start();
public void stop()
if (runner != null)
runner.stop();
runner = null;
public void run()
while(true)
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
try {runner.sleep(15);}
catch (Exception e) { }
//move our balls around
for(int i=0;i<MAX;i++)
ball.move();
handleCollision();
repaint();
boolean collide(CollideBall b1, CollideBall b2)
double wx=b1.getCenterX()-b2.getCenterX();
double wy=b1.getCenterY()-b2.getCenterY();
//we calculate the distance between the centers two
//colliding balls (theorem of Pythagoras)
double distance=Math.sqrt(wx*wx+wy*wy);
if(distance<b1.diameter)
return true;
return false;
void changeCursor(int x, int y)
Rectangle r=new Rectangle(o.r.x+1,o.r.y+1,o.r.width-1,o.r.height-1);
Frame BrowserFrame;
Component ParentComponent;
ParentComponent = getParent();
while ( ParentComponent != null &&
!(ParentComponent instanceof Frame))
ParentComponent = ParentComponent.getParent();
BrowserFrame = (Frame) ParentComponent;
if(shiftNW||shiftSE)
BrowserFrame.setCursor(Frame.SE_RESIZE_CURSOR);
else if(shiftNE||shiftSW)
BrowserFrame.setCursor(Frame.SW_RESIZE_CURSOR);
else if(shiftW)
BrowserFrame.setCursor(Frame.W_RESIZE_CURSOR);
else if(shiftN)
BrowserFrame.setCursor(Frame.N_RESIZE_CURSOR);
else if(shiftE)
BrowserFrame.setCursor(Frame.W_RESIZE_CURSOR);
else if(shiftS)
BrowserFrame.setCursor(Frame.N_RESIZE_CURSOR);
else if(r.inside(x,y))
BrowserFrame.setCursor(Frame.MOVE_CURSOR);
else
BrowserFrame.setCursor(Frame.DEFAULT_CURSOR);
public boolean mouseMove(Event evt,int x,int y)
//the corner areas of the obstacle
Rectangle nw,sw,ne,se;
nw=new Rectangle(o.r.x-2,o.r.y-2,4,4);
if(nw.inside(x,y))
shiftNW=true;
else shiftNW=false;
sw=new Rectangle(o.r.x-2,o.r.y+o.r.height-2,4,4);
if(sw.inside(x,y))
shiftSW=true;
else shiftSW=false;
ne=new Rectangle(o.r.x+o.r.width-2,o.r.y-2,4,4);
if(ne.inside(x,y))
shiftNE=true;
else shiftNE=false;
se=new Rectangle(o.r.x+o.r.width-2,o.r.y+o.r.height-2,4,4);
if(se.inside(x,y))
shiftSE=true;
else shiftSE=false;
if(x>o.r.x-2&&x<o.r.x+2&&y>o.r.y&&y<o.r.y+o.r.height)
shiftW=true;
else shiftW=false;
if(x>o.r.x+o.r.width-2&&x<o.r.x+o.r.width+2
&&y>o.r.y&&y<o.r.y+o.r.height)
shiftE=true;
else shiftE=false;
if(y<o.r.y+2&&y>o.r.y-2&&x>o.r.x&&x<o.r.x+o.r.width)
shiftN=true;
else shiftN=false;
if(y>o.r.y+o.r.height-2&&y<o.r.y+o.r.height+2
&&x<o.r.x+o.r.width)
shiftS=true;
else shiftS=false;
changeCursor(x,y);
return true;
public boolean mouseDown(Event evt,int x,int y)
Rectangle r=new Rectangle(o.r.x+2,o.r.y+2,o.r.width-4,o.r.height-4);
if(r.inside(x,y))
drag=true;
startx=x;
starty=y;
xtemp=o.r.x;
ytemp=o.r.y;
else drag=false;
changeCursor(x,y);
return true;
public boolean mouseDrag(Event evt,int x,int y)
intro=false;
Rectangle bounds=new Rectangle(5,5,size().width-5,size().height-5);
int endx, endy;
endx=x-startx;
endy=y-starty;
//disable mouse actions past boundaries
if(x<5)x=5;
if(y<5)y=5;
if(x>bounds.width)x=bounds.width;
if(y>bounds.height)y=bounds.height;
if(drag)
//disallow to move past border
int ox=endx+xtemp;
int oy=endy+ytemp;
if(ox<5)ox=5;
if(oy<5)oy=5;
if(ox>bounds.width-o.r.width)
ox=bounds.width-o.r.width;
if(oy>bounds.height-o.r.height)
oy=bounds.height-o.r.height;
o.r.move(ox,oy);
west=o.r.x;
north=o.r.y;
east=o.r.x+o.r.width;
south=o.r.y+o.r.height;
else
if(shiftNW){west=x;north=y;}
else if(shiftNE){east=x;north=y;}
else if(shiftSW){west=x;south=y;}
else if(shiftSE){east=x;south=y;}
else if(shiftW)west=x;
else if(shiftE)east=x;
else if(shiftN)north=y;
else if(shiftS)south=y;
//disallow resizing below 40*40
int MIN=40;
if(east-west<MIN)
//shiftNW=shiftNE=shiftSW=shiftSE=shiftW=shiftE=false;
if(shiftW||shiftNW||shiftSW)
west=east-MIN;
if(shiftE||shiftNE||shiftSE)
east=west+MIN;
if(south-north<MIN)
//shiftNW=shiftNE=shiftSW=shiftSE=shiftN=shiftS=false;
if(shiftN||shiftNW||shiftNE)
north=south-MIN;
if(shiftS||shiftSE||shiftSW)
south=north+MIN;
//report altering of obstacle to ball objects and obstacle
for(int i=0;i<MAX;i++)
ball[i].alterRect(o.r.x,o.r.y,o.r.width,o.r.height);
o.r.move(west,north);
o.r.resize(east-west, south-north);
changeCursor(x,y);
return true;
private void handleCollision()
//we iterate through all the balls, checking for collision
for(int i=0;i<MAX;i++)
for(int j=0;j<MAX;j++)
if(i!=j)
if(collide(ball[i], ball[j]))
ball[i].hit(ball[j]);
ball[j].hit(ball[i]);
public void update(Graphics g)
paint(g);
public void paint(Graphics g)
gBuffer.setColor(Color.lightGray);
gBuffer.fillRect(0,0,size().width,size().height);
gBuffer.draw3DRect(5,5,size().width-10,size().height-10,false);
//paint the obstacle rectangle
o.paint(gBuffer);
//paint our balls
for(int i=0;i<MAX;i++)
ball[i].paint(gBuffer);
if(intro)
gBuffer.setColor(Color.red);
gBuffer.setFont(new Font("Helvetica", Font.PLAIN, 12));
gBuffer.drawString("You can move and resize the rectangle!",20,30);
gBuffer.setFont(new Font("Helvetica", Font.PLAIN, 10));
g.drawImage (Buffer,0,0, this);Hello, please use code tags next time you post code. You can do so by adding [code] [/code] round blocks of code. So
[code]
class Code {
private static final String codeHere = "code here";
[/code]
will be rendered as
class Code {
private static final String codeHere = "code here";
We will not do your homework for you, we will however help when you are stuck and point you in the right direction. So what have you tried? What happened?
Don't know how to begin? What makes the ball move?
Maybe you are looking for
-
Installation problems under Ubuntu 6.10
I'm using Ubuntu 6.10 (Edgy Eft) and am having some problems installing Oracle Calendar. I've posted the output of my installation below. Any ideas? Preparing to install... Extracting the JRE from the installer archive... Unpacking the JRE... Extract
-
How to make screen bigger?
Is it possible to make the viewing screen bigger on my site? I added a game and part of it is being cut off. I need step by step instructions if possible. ,Miss Macintosh XOXO
-
Dang it! Safari keeps quitting on me.
My daughter loaned me her iMac G3 400 mghz with Mac OS X (10.2.8) until I can get my G4 Flat Panel fixed. But, Every time I type in a search field or in any other kind of field on Safari, Safari quits. Actually I never get past the first character. I
-
HT201150 How do I configure what the Power Button does?
How do I configure my power button so hitting it does not automatically put it to sleep? Because it is right by the delete key I am hitting it accidentally all the time. Also my cat is constantly putting my computer to sleep when I am working. Is t
-
Clicking on a link or email brings up a new tab when it should stay on existing page
Ever since I got Firefox 6, after 1-3 days of not rebooting, Firefox will start acting squirrelly: sometimes clicking on a web-based email will bring up the email in a new tab rather than on the same page. Today 1 of 2 open Firefox sessions kept chan