I was trying to build the Font window of Notepad using Java using the code shown below. But, I'm facing a problem in setting the size of the text as specified inside listbox.
I'm trying to get the respective size corresponding to the index of the selected item but couldn't find any such method.
f = new Frame("Font");
f.setLayout(new GridLayout(3, 3));
b1 = new Button("OK");
l1 = new Label("Font :");
l2 = new Label("Size :");
l3 = new Label("Font Style :");
lb1 = new List(10, false);
lb2 = new List(10, false);
lb3 = new List(5, false);
String [] s = {"Times New Roman", "Arial", "Verdana", "Trebuchet MS", "Papyrus","Monotype Corsiva","Microsoft Sans Serif", "Courier", "Courier New"};
for(int i = 0; i < s.length; i++)
{
lb1.add(s[i]);
}
for(int i = 8; i <=72; i += 2)
{
lb2.add(i + "");
}
String [] s1 = {"BOLD", "ITALIC", "PLAIN"};
for(int i = 0; i < s1.length; i++)
{
lb3.add(s1[i]);
}
f.add(l1);
f.add(l2);
f.add(l3);
f.add(lb1);
f.add(lb2);
f.add(lb3);
f.add(b1);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
if(lb3.isIndexSelected(0))
fo = new Font(lb1.getSelectedItem(), Font.BOLD, **lb2.getSelectedIndex**());
else if(lb3.isIndexSelected(1))
fo = new Font(lb1.getSelectedItem(), Font.ITALIC, lb2.getSelectedIndex());
else
fo = new Font(lb1.getSelectedItem(), Font.PLAIN, lb2.getSelectedIndex());
ta1.setFont(fo);
MyFrame15.f.dispose();
}
});
f.setSize(300, 300);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int)((d.getWidth() / 2) - 200);
int y = (int)((d.getHeight() / 2) - 200);
f.setLocation(x, y);
f.setVisible(true);
}
To get the size as required by user we can use:
lb2.getSelectedItem();
which returns a String but the third argument of Font constructor requires an integer.Therefore, we use parseInt() method of Integer class to convert the string received to integer.The code is as follows:
Font(lb1.getSelectedItem(), Font.BOLD, Integer.parseInt(lb2.getSelectedItem()));
I would suggest you use Swing for this. You can start with the Swing tutorial on Text Component Features which already contains a working example that does what you want.
Related
I posted my full code below so you guys could have a solid understanding of what I want. When I click send, the text field clears but is not ready for input. I have to click for the input. I want it to be ready for the input immediately and textfield.setText("") will not work. Any ideas?
package javaapplication2;
import java.util.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.io.*;
import javax.swing.*;//class to use to create GUI's
import javax.swing.border.Border;
import javax.swing.plaf.FontUIResource;
/**
*
* #author Jordan Anthony Hangman with dictionary
*/
public class JavaApplication2 extends JFrame{
static JLabel[] labels = new JLabel[20];//labels for displaying words under 20 characters
static int counter = 0;
static int badguess = 0;//keeps track of wrong guesses
static String wordbank = " Letter Bank:";
static char[] guesses = new char[26];
static int nguesses = 0;
static int amountc = 0;
public JavaApplication2(){
}
public static void main(String[] args) throws FileNotFoundException, IOException {
//Loading images to use for hangman game
ImageIcon hanginit = new ImageIcon("hangmaninit.jpg");
ImageIcon hang1 = new ImageIcon("hangman1.jpg");
ImageIcon hang2 = new ImageIcon("hangman2.jpg");
ImageIcon hang3 = new ImageIcon("hangman3.jpg");
ImageIcon hang4 = new ImageIcon("hangman4.jpg");
ImageIcon hang5 = new ImageIcon("hangman5.jpg");
ImageIcon hang6 = new ImageIcon("hangman6.jpg");
//initializing array for index values
int wordcount = 10;
String[] words1 = new String[wordcount];
int[] wordssel = new int[10];
for (int j=0; j<10; j++){
wordssel[j] = -1;
}
//setting instructions
String Instructions = "To start the game, click on the new game button. You get 6 incorrect guesses for every word. Once you get 6 guesses, the game will end. Click the end game button to go back to the home page. If you want to play again, you can click New Game and you will be able to guess a different word. After every game, a message will appear to tell you how many words you have guesses correctly. When all the words are played, a dialog box will be shown that says Game Over. Exit this box to exit the game.";
//reading in the words
int number = 0;
try(BufferedReader br = new BufferedReader(new FileReader("words.txt")))
{
String line = br.readLine();
while(line != null){
words1[number] = line;
number++;
line = br.readLine();
}
}
//randomizes words
boolean flag = false;
int rand = 0;
int count = 0;
int wordcounter = 0;
while(!flag){
Random random = new Random();
rand = random.nextInt(wordcount);
count = 0;
for (int o=0; o<wordcount; o++){
if(wordssel[o] != rand){
count++;
}
}
if(count == wordcount){
wordssel[wordcounter] = rand;
wordcounter++;
}
if(wordcounter == wordcount){
flag = true;
}
}
String[] randwords = new String[10];
for(int o=0; o<10; o++){
randwords[wordssel[o]] = words1[o];
}
//initializing label
for(int i=0; i<20; i++){
labels[i] = new JLabel(" ");
labels[i].setFont(new Font("Serif", Font.BOLD, 30));
}
//initializing guessedchar array
for(int i=0; i<26; i++){
guesses[i] = ' ';
}
//value for window size
int xlim = 1200;
int ylim = 1200;
int xlim2 = 1600;
int ylim2 = 1600;
int xlim3 = 900;
int ylim3 = 600;
//value for x and y centers
int xcent = xlim/2 - 20;
int ycent = ylim/2;
int xcent2 = xlim2/2;
int ycent2 = ylim2/2 - 20;
int xcent3 = xlim3/2;
int ycent3 = ylim3/2 - 20;
//creating frames
JFrame frame1 = new JFrame("Hangman");//creates a new frame or window
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// I thiunk exits when clicks on red x
frame1.setSize(xlim, ylim); //size of window in pixels
JFrame frame2 = new JFrame("Hangman");//creates a new frame or window
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// I thiunk exits when clicks on red x
frame2.setSize(xlim2, ylim2); //size of window in pixels
JFrame frame3 = new JFrame();
frame3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame3.setSize(xlim3, ylim3);
//change font size for label, button, and textfield
UIManager.put("Button.font", new FontUIResource(new Font("Dialog", Font.BOLD, 24)));
UIManager.put("Label.font", new FontUIResource(new Font("Dialog", Font.PLAIN, 24)));
UIManager.put("TextField.font", new FontUIResource(new Font("Dialog", Font.PLAIN, 24)));
UIManager.put("TextArea.font", new FontUIResource(new Font("Dialog", Font.PLAIN, 24)));
//creates buttons
JButton button1 = new JButton("New Game?");
button1.setBounds(xcent - 90, ycent - 165, 180, 130);//(xstart, ytop, width, height)
JButton button2 = new JButton("End Game?");
button2.setBounds(xcent - 90, ycent - 65, 180, 130);//(xstart, ytop, width, height)
JButton button3 = new JButton("Instructions");
button3.setBounds(xcent - 120, ycent, 240, 100);
JButton button4 = new JButton("Main Menu");
button4.setBounds(xcent - 100, ycent + 100, 200, 100);
//creating border
Border border = BorderFactory.createLineBorder(Color.BLACK, 4);
//creating labels
JLabel labelresult = new JLabel("");//label for win or losing game
labelresult.setBounds(400, 400, 400, 40);
JLabel labelhang = new JLabel();//label for hangman images
labelhang.setBounds(450, 375, 677, 620);
JLabel label3 = new JLabel("Hello");
label3.setBounds(200, 260, 500, 40);
JLabel label4 = new JLabel("Hello");
label4.setBounds(440, 1300, 800, 40);
JLabel label5 = new JLabel("Hello");
label5.setBounds(590, 1300, 800, 40);
JLabel label6 = new JLabel("Game Over");
label6.setBounds(380, 250, 200, 40);
JLabel lettersw = new JLabel();
JLabel label7 = new JLabel("How To Play");
label7.setBounds(500, 50, 200, 40);
JLabel label8 = new JLabel("Error");
label8.setBounds(590, 1300, 800, 40);
label8.setText("You can only enter one letter at a time.");
JLabel label9 = new JLabel("Error");
label9.setBounds(674, 1300, 800, 40);
label9.setText("You must enter a letter");
JLabel label10 = new JLabel(wordbank);
label10.setBounds(xcent2 - 200, 220, 400, 40);
JLabel label11 = new JLabel("You have already entered this letter.");
label11.setBounds(608, 1300, 800, 40);
JLabel label12 = new JLabel("You must exit game to guess.");
label12.setBounds(639, 1300, 800, 40);
//creating text area and setting properties
JTextArea texta1 = new JTextArea();
texta1.setOpaque(false);
texta1.setLineWrap(true);
texta1.setWrapStyleWord(true);
texta1.setBounds(100, 100, 1000, 600);
texta1.setText(Instructions);
//adding items to frames
frame1.add(button1);
frame1.add(button3);
frame2.add(button2);
frame2.add(labelhang);
frame3.add(label6);
frame2.add(label4);
frame2.add(label5);
frame3.add(label6);
frame1.add(label7);
frame1.add(texta1);
frame1.add(button4);
frame2.add(label8);
frame2.add(label9);
frame2.add(label10);
frame2.add(label11);
frame2.add(label12);
//set item properties
labelresult.setVisible(false);
button2.setVisible(false);
labelhang.setIcon(hanginit);
label4.setVisible(false);
label5.setVisible(false);
label7.setVisible(false);
texta1.setVisible(false);
button4.setVisible(false);
label8.setVisible(false);
label9.setVisible(false);
label10.setBorder(border);
label11.setVisible(false);
label12.setVisible(false);
//set frame properties
frame1.setLayout(null);
frame1.setVisible(true);//makes the frame visible to the user
frame3.setLayout(null);
//When End Game button is pressed
button2.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
//end of game conditions
label5.setVisible(false);
label4.setVisible(false);
label12.setVisible(false);
button2.setVisible(false);
frame2.setVisible(false);
wordbank = " Letter Bank:";
badguess = 0;
amountc = 0;
if(counter == wordcount){
frame3.setVisible(true);//frame after all words gone through
}
else{
labelhang.setIcon(hanginit);
frame1.setVisible(true);
}
}
});
//When Instructions button is pressed
button3.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
button1.setVisible(false);
button3.setVisible(false);
label7.setVisible(true);
texta1.setVisible(true);
button4.setVisible(true);
}
});
//When Main Menu is pressed
button4.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
button1.setVisible(true);
button4.setVisible(false);
button2.setVisible(true);
label7.setVisible(false);
texta1.setVisible(false);
button3.setVisible(true);
}
});
//When New Game is press
button1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
//set item properties
frame2.setLayout(null);
frame2.setVisible(true);
frame1.setVisible(false);
button2.setVisible(false);
label8.setVisible(false);
label9.setVisible(false);
wordbank = " Letter Bank:";
label10.setText(wordbank);
//initializes labels and word
for(int i=0; i<20; i++){
labels[i].setText(" ");
}
String currentword = randwords[counter];
counter++;
//initializing previos guesses
for(int i=0; i<26; i++){
guesses[i] = ' ';
}
nguesses = 0;
//creating panel and panel components always create panels and all components in the same place that they are being added
JButton send = new JButton("Send");
JButton clear = new JButton("clear");
JTextField tf = new JTextField(1);
JLabel label = new JLabel("Enter Guess");
JPanel panel = new JPanel();
panel.add(label);
panel.add(tf);
panel.add(send);
panel.add(clear);
panel.setBounds(xcent2 - 250, ylim2 - 102, 500, 40);
frame2.add(panel);
//placing labels for letters
int letters = currentword.length();
int spacing2 = 800-(int)(letters*12.5);
for (int i=0; i<letters; i++){
labels[i].setText("_");
int spacing = 25 * i;
labels[i].setBounds(spacing2 + spacing, 1100, 25, 40);
frame2.add(labels[i]);
}
//when clear button is pressed
clear.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
tf.setText("");
}
});
//when send button is pressed
send.addActionListener(new ActionListener(){
int amountc1 = 0;//keeps track of correctly guessed amount of words
int counter2 = 0;//keeps track of amount of correct letter guesses for each word
int letters2 = 0;
#Override
public void actionPerformed(ActionEvent e){
//initialize word and user guess
String currentword = randwords[counter-1];
letters2 = currentword.length();
char[] wordcurrent = new char[20];
wordcurrent = currentword.toCharArray();
String userguess = tf.getText();
userguess = userguess.toLowerCase();
tf.setText("");
//set properties
label4.setVisible(false);
label5.setVisible(false);
label8.setVisible(false);
label9.setVisible(false);
label11.setVisible(false);
//checking guess with word
boolean flag2 = false;
boolean flag3 = false;
//checking if word is already solved and user is entering data
System.out.println(badguess);
System.out.println(amountc);
System.out.println(nguesses);
if(nguesses > badguess + amountc){
label4.setVisible(false);
label5.setVisible(false);
label12.setVisible(true);
nguesses++;
flag2 = true;
}
else if(userguess.length() > 1){
label8.setVisible(true);
flag2 = true;
nguesses++;
}
else if(userguess.length() < 1){
label9.setVisible(true);
flag2 = true;
nguesses++;
}
else{
char[] guessuser = userguess.toCharArray();
char guessedchar = guessuser[0];
int charval = (int)guessedchar;//97-122 lowercase, 65-90 for uppercase
//checks for previous guesses
for(int t=0; t<=nguesses; t++){
if(guessedchar == guesses[t]){
flag3 = true;
break;
}
}
nguesses++;
//checking word against guess
for(int i=0; i<letters2; i++){
if(!flag3){
if(((charval>96 & charval<123))){
guesses[nguesses] = guessedchar;
if(wordcurrent[i] == guessedchar){
labels[i].setText(userguess);
labels[i].setVisible(true);
flag2 = true;
counter2++;
nguesses++;
amountc++;
}
}
else{
label9.setVisible(true);
flag2 = true;
}
}
else{
label11.setVisible(true);
flag2 = true;
}
}
}
//checks if full word is guessed correctly
if(counter2 == letters2){
this.amountc1++;
nguesses++;
button2.setVisible(true);
String correctword = "Well done! You have solved " + amountc1 + " out of " + counter;
label5.setText(correctword);
label5.setVisible(true);
counter2 = 0;
if(counter == wordcount){
label3.setText(correctword);
}
}
//checks for wrong guess and changes hangman picture accordingly
if (flag2 == false){
badguess++;
switch(badguess){
case 1:
wordbank += " " + userguess;
label10.setText(wordbank);
labelhang.setIcon(hang1);
break;
case 2:
wordbank += ", " + userguess;
label10.setText(wordbank);
labelhang.setIcon(hang2);
break;
case 3:
wordbank += ", " + userguess;
label10.setText(wordbank);
labelhang.setIcon(hang3);
break;
case 4:
wordbank += ", " + userguess;
label10.setText(wordbank);
labelhang.setIcon(hang4);
break;
case 5:
wordbank += ", " + userguess;
label10.setText(wordbank);
labelhang.setIcon(hang5);
break;
case 6:
nguesses++;
wordbank += ", " + userguess;
label10.setText(wordbank);
labelhang.setIcon(hang6);
button2.setVisible(true);
String incorrectword = "Sorry, The correct word was " + currentword + " You have solved " + amountc1 + " out of " + counter;
label4.setText(incorrectword);
label4.setVisible(true);
this.counter2 = 0;
if(counter == wordcount){
label3.setText(incorrectword);
}
break;
default:
break;
}
}
else{
nguesses--;
}
}
});
}
});
}
}
To focus text field after setText(""); method you can use the following,
textFieldName.requestFocus();
To center the text field you can use this code,
textFieldName.setHorizontalAlignment(JTextField.CENTER);
I am trying to change the Image on the panel when the any of the JButtons are pressed. I have set up an array of images and need it to change to the next image in the array once it has been pressed. Here is my code:
public class SimpleGui implements ActionListener {
JButton button = new JButton("Very Happy");
JButton buttonTwo = new JButton("Happy");
JButton buttonThree = new JButton("Neutral");
JButton buttonFour = new JButton("Sad");
JButton buttonFive = new JButton("Very Sad");
static int[] ButtonArray = new int[5];
private static String[] imageList = { "res/snow.jpg", "res/test-gm.jpg" };
public int i = 0;
public static void main(String[] args) throws FileNotFoundException {
SimpleGui gui = new SimpleGui();
gui.go();
File file = new File("out.txt");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
ButtonArray[0] = 0;
ButtonArray[1] = 0;
ButtonArray[2] = 0;
ButtonArray[3] = 0;
ButtonArray[4] = 0;
}
public void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
button.addActionListener(this);
buttonTwo.addActionListener(this);
buttonThree.addActionListener(this);
buttonFour.addActionListener(this);
buttonFive.addActionListener(this);
panel.add(button);
panel.add(buttonTwo);
panel.add(buttonThree);
panel.add(buttonFour);
panel.add(buttonFive);
frame.getContentPane().add(BorderLayout.EAST, panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(650, 600);
frame.setVisible(true);
ImageIcon image = new ImageIcon(imageList[i]);
ImageIcon image1 = new ImageIcon(imageList[i + 1]);
JLabel label = new JLabel("", image, JLabel.CENTER);
JPanel panel2 = new JPanel(new BorderLayout());
panel2.add(label, BorderLayout.CENTER);
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
frame.add(panel2, BorderLayout.CENTER);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == button) {
ButtonArray[0] = 1;
ButtonArray[1] = 0;
ButtonArray[2] = 0;
ButtonArray[3] = 0;
ButtonArray[4] = 0;
System.out.println("Very Happy");
}
// buttonTwo = (JButton) event.getSource();
if (event.getSource() == buttonTwo) {
ButtonArray[0] = 0;
ButtonArray[1] = 1;
ButtonArray[2] = 0;
ButtonArray[3] = 0;
ButtonArray[4] = 0;
System.out.println("Happy");
}
// buttonThree = (JButton) event.getSource();
if (event.getSource() == buttonThree) {
ButtonArray[0] = 0;
ButtonArray[1] = 0;
ButtonArray[2] = 1;
ButtonArray[3] = 0;
ButtonArray[4] = 0;
System.out.println("Neutral");
}
// buttonFour = (JButton) event.getSource();
if (event.getSource() == buttonFour) {
ButtonArray[0] = 0;
ButtonArray[1] = 0;
ButtonArray[2] = 0;
ButtonArray[3] = 1;
ButtonArray[4] = 0;
System.out.println("Sad");
}
// buttonFive = (JButton) event.getSource();
if (event.getSource() == buttonFive) {
ButtonArray[0] = 0;
ButtonArray[1] = 0;
ButtonArray[2] = 0;
ButtonArray[3] = 0;
ButtonArray[4] = 1;
System.out.println("Very Sad");
}
// System.out.println(Arrays.toString(ButtonArray));
// ImageIcon image = (imageList[i]);
}
}
I don't really see what most parts of you code are supposed to do. So instead, here's a minimal example that should do what you are asking about: One label, and two buttons setting different images to that label.
ImageIcon[] images = new ImageIcon[] {
new ImageIcon("foo.gif"),
new ImageIcon("bar.gif"),
new ImageIcon("blub.gif")
};
JFrame frame = new JFrame("Test");
frame.getContentPane().setLayout(new FlowLayout());
JLabel label = new JLabel(images[0]);
frame.getContentPane().add(label);
JButton button1 = new JButton("Image 1");
button1.addActionListener(e -> label.setIcon(images[0]));
frame.getContentPane().add(button1);
JButton button2 = new JButton("Image 2");
button2.addActionListener(e -> label.setIcon(images[1]));
frame.getContentPane().add(button2);
frame.pack();
frame.setVisible(true);
Note that this is using Lambda functions (Java 8) but you can do the same with one or more "real" ActionListener classes. The important part is that you call label.setIcon(theImage); this part seems to be missing in your code.
If instead you want to cycle through a list or array of pictures, you can do like this:
AtomicInteger index = new AtomicInteger(0);
JButton buttonCycle = new JButton("Cycle");
buttonCycle.addActionListener(e -> label.setIcon(images[index.getAndIncrement() % images.length]));
frame.getContentPane().add(buttonCycle);
Here, the AtomicInteger is used so I can declare it as a local variable and use it in the lambda. You can just as well use a regular int if you make it a member variable of the surrounding class.
private int c = 0;
...
buttonCycle.addActionListener(e -> label.setIcon(images[c++ % images.length]));
The takeaway is: Create a counter variable, increment it each time the button is called and set the label's icon to the element with that count, module the size of the array.
I have a problem.I created a program that will add two random numbers. I'm trying to put a Math.random() in a JTextField but it won't appear. Here's my code by the way:
public class RandomMathGame extends JFrame {
public RandomMathGame(){
super("Random Math Game");
int random2;
JButton lvl1 = new JButton("LEVEL 1");
JButton lvl2 = new JButton("LEVEL 2");
JButton lvl3 = new JButton("LEVEL 3");
JLabel line1 = new JLabel("Line 1: ");
final JTextField jtf1 = new JTextField(10);
JLabel line2 = new JLabel("Line 2: ");
final JTextField jtf2 = new JTextField(10);
JLabel result = new JLabel("Result: ");
final JTextField jtf3 = new JTextField(10);
JButton ans = new JButton("Answer");
JLabel score = new JLabel("Score: ");
JTextField jtf4 = new JTextField(3);
JLabel itm = new JLabel("Number of Items: ");
JTextField items = new JTextField(3);
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(lvl1);
add(lvl2);
add(lvl3);
add(line1);
add(jtf1);
add(line2);
add(jtf2);
add(result);
add(jtf3);
add(ans);
add(score);
add(jtf4);
add(itm);
add(items);
setSize(140,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
lvl1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int i, j = 10;
int i1 = Integer.valueOf(jtf1.getText());
int i2 = Integer.valueOf(jtf2.getText());
int i3 = i1 + i2;
final int random1 = (int)(Math.random() * 10 + 1);
for (i = 0; i <= j + 1; i++){
try{
jtf1.setText(String.valueOf(random1));
jtf2.setText(String.valueOf(random1));
jtf3.setText(String.valueOf(i3));
}catch(Exception ex){
ex.printStackTrace();
}
}
}
});
}
Never mind the lvl2 and lvl3 because it's the same in lvl1. And also, I want to loop them 10 times. I'm having difficulties on putting up those codes. Can someone help me? Thanks for your help. :)
Updating text fields in a loop won't produce the animated display that you likely want; only the last update will be seen. Instead, use a javax.swing.Timer to periodically update the fields. Related examples may be found here, here and here.
public class CustomCalculator extends Frame implements ActionListener{
Panel jp1 = new Panel();
Panel jp2 = new Panel();
Panel jp3 = new Panel();
Panel jp4 = new Panel();
Panel jp5 = new Panel();
Panel center_merge = new Panel();
Label l2 = new Label("Quantity : ");
TextField l2a = new TextField(20);
Label l3 = new Label("Invoice Value : ");
TextField l3a = new TextField(20);
Label l4 = new Label("Exchange Rate : ");
TextField l4a = new TextField(20);
Label l5 = new Label("Costing(A) : ");
TextField l5a = new TextField();
Label l6 = new Label("(A + 1%)(B) : ");
Label l6a = new Label();
Label l7 = new Label("BCD (C) : ");
Label l7a = new Label("");
Label l8 = new Label("CVD (D) : ");
Label l8a = new Label("");
Label l9 = new Label("Custom Education Cess (E) : ");
Label l9a = new Label("");
Label l10 = new Label("Custom Sec & Higher Edu.Cess (F) : ");
Label l10a = new Label("");
Label l11 = new Label("Additional Duty Imports (G) : ");
Label l11a = new Label("");
Label l12 = new Label("Total (H) : ");
Label l12a = new Label("");
Label l13 = new Label("Costing+Total (I) : ");
Label l13a = new Label("");
Label l14 = new Label("(H/Quantity) (J) : ");
Label l14a = new Label("");
Label l15 = new Label("4% SAD (G/Quantity) (K) : ");
Label l15a = new Label("");
Label l16 = new Label("Net Costing (L) : ");
Label l16a = new Label("");
Label l17 = new Label("Transportation (M) : ");
TextField l17a = new TextField(5);
Label l18 = new Label("Godown Rate (N) : ");
TextField l18a = new TextField(5);
Label l19 = new Label("Brokerage (O) : ");
TextField l19a = new TextField(5);
Label l20 = new Label("Actual Costing (P) : ");
Label l20a = new Label("");
Label l21 = new Label("Small Gatepass (Q) : ");
Label l21a = new Label("");
Label l22 = new Label("Big Gatepass (R) : ");
Label l22a = new Label("");
Button l2b = new Button("reset");
Button l3b = new Button("reset");
Button l4b = new Button("reset");
Button master_reset = new Button("reset all");
Button calc = new Button("Calculate");
public CustomCalculator()
{
super("Custom Calculator");
this.setSize(800,700);
jp1.setLayout(new FlowLayout());
//jp1.setBorder(BorderFactory.createLineBorder(Color.GRAY));
jp1.add(l2);
jp1.add(l2a);
jp1.add(l2b);
jp1.add(l3);
jp1.add(l3a);
jp1.add(l3b);
jp1.add(l4);
jp1.add(l4a);
jp1.add(l4b);
jp2.setLayout(new GridLayout(6,2));
//jp2.setBorder(BorderFactory.createLineBorder(Color.GRAY));
jp2.add(l5);
jp2.add(l5a);
jp2.add(l6);
jp2.add(l6a);
jp2.add(l7);
jp2.add(l7a);
jp2.add(l8);
jp2.add(l8a);
jp2.add(l9);
jp2.add(l9a);
jp2.add(l10);
jp2.add(l10a);
jp3.setLayout(new GridLayout(6,2));
//jp3.setBorder(BorderFactory.createLineBorder(Color.GRAY));
jp3.add(l11);
jp3.add(l11a);
jp3.add(l12);
jp3.add(l12a);
jp3.add(l13);
jp3.add(l13a);
jp3.add(l14);
jp3.add(l14a);
jp3.add(l15);
jp3.add(l15a);
jp3.add(l16);
jp3.add(l16a);
jp4.setLayout(new GridLayout(6,2));
//jp4.setBorder(BorderFactory.createLineBorder(Color.GRAY));
jp4.add(l17);
jp4.add(l17a);
jp4.add(l18);
jp4.add(l18a);
jp4.add(l19);
jp4.add(l19a);
jp4.add(l20);
jp4.add(l20a);
jp4.add(l21);
jp4.add(l21a);
jp4.add(l22);
jp4.add(l22a);
center_merge.setLayout(new GridLayout(1,3));
//center_merge.setBorder(BorderFactory.createLineBorder(Color.GRAY));
center_merge.add(jp2);
center_merge.add(jp3);
center_merge.add(jp4);
jp5.setLayout(new FlowLayout());
//jp5.setBorder(BorderFactory.createLineBorder(Color.GRAY));
jp5.add(calc);
jp5.add(master_reset);
this.setLayout(new BorderLayout());
this.add(jp1,BorderLayout.NORTH);
this.add(center_merge,BorderLayout.CENTER);
this.add(jp5,BorderLayout.SOUTH);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
l2b.addActionListener(this);
l3b.addActionListener(this);
l4b.addActionListener(this);
calc.addActionListener(this);
master_reset.addActionListener(this);
this.setVisible(true);
}
public static void main(String[] args) {
new CustomCalculator();
}
#Override
public void actionPerformed(ActionEvent ae) {
double quantity = 0;
double invoice_value = 0;
double exchange_rate = 0;
double A=0;
double B=0;
double C=0;
double D=0;
double E=0;
double F=0;
double G=0;
double H=0;
double I=0;
double J=0;
double K=0;
double L=0;
double M = 0;
double N = 0;
double O=0;
double P=0;
double Q=0;
double R=0;
try
{
quantity = Double.parseDouble(l2a.getText());
invoice_value = Double.parseDouble(l3a.getText());
exchange_rate = Double.parseDouble(l4a.getText());
M = Double.parseDouble(l17a.getText());
N = Double.parseDouble(l18a.getText());
O = Double.parseDouble(l19a.getText());
A = invoice_value*exchange_rate;
B = A+(0.01*A);
C = 0.075*B;
D = 0.12*(B+C);
E = 0.02*(C+D);
F = 0.01*(C+D);
G = 0.04*(B+C+D+E+F);
H = C+D+E+F+G;
I = A+H;
J = H/quantity;
K = G/quantity;
L = J-K;
P = L+M+N+O;
Q = (0.12*B)/quantity;
R = Q+K;
if(ae.getActionCommand().equals("calc"))
{
l5a.setText(String.valueOf(A));
l6a.setText(String.valueOf(B));
l7a.setText(String.valueOf(C));
l8a.setText(String.valueOf(D));
l9a.setText(String.valueOf(E));
l10a.setText(String.valueOf(F));
l11a.setText(String.valueOf(G));
l12a.setText(String.valueOf(H));
l13a.setText(String.valueOf(I));
l14a.setText(String.valueOf(J));
l15a.setText(String.valueOf(K));
l16a.setText(String.valueOf(L));
l20a.setText(String.valueOf(P));
l21a.setText(String.valueOf(Q));
l22a.setText(String.valueOf(R));
}
else if(ae.getActionCommand().equals("master_reset"))
{
l5a.setText("");
l2a.setText("");
l3a.setText("");
l4a.setText("");
}
}
catch (Exception ex)
{
l5a.setText(ex.toString());
// l3a.setText(ex.toString());
}
}
}
After I click the Calculate button (button calc) the calculated values do not appear in the respective labels and an exception is shown saying java.lang.NumberFormatException: Empty string. I am not able to figure out the solution. please help.
the line exchange_rate = Double.parseDouble(l4a.getText()); gives you this exception, because there is no value in l4a and you are trying to parse it into a double value,
try printing the exception in the catch clause.
It's probably a relatively safe bet to say that it is happening here at the beginning of your function, though you should provide the actual exception and line number for us.
quantity = Double.parseDouble(l2a.getText());
invoice_value = Double.parseDouble(l3a.getText());
exchange_rate = Double.parseDouble(l4a.getText());
M = Double.parseDouble(l17a.getText());
N = Double.parseDouble(l18a.getText());
O = Double.parseDouble(l19a.getText());
Make sure that each of these fields actually has numeric text in it. I would recommend putting a logging line or an alert line to state their values before this is executed. Better yet, you can catch the first line in a debugger and look at the the values of all of the items you're calling getText() on. I bet one has an empty string.
I am trying to create this program for my class project. The compiler says process completed but nothing shows up when I try to run it.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
public class Project extends Applet implements ActionListener {
Label sp = new Label("Receipt Calculator");
Panel pl = new Panel();
Label cndy = new Label("Candy:");
TextField cndyi = new TextField(5);
Label bred = new Label("Bread:");
TextField bredi = new TextField(5);
Label sop = new Label("Soap:");
TextField sopi = new TextField(5);
Label mlk = new Label("Milk:");
TextField mlki = new TextField(5);
Label ham = new Label("Ham:");
TextField hami = new TextField(5);
Label srdns = new Label("Sardines:");
TextField srdnsi = new TextField(5);
Label cfee = new Label("Coffee:");
TextField cfeei = new TextField(5);
Label ndls = new Label("Noodles:");
TextField ndlsi = new TextField(5);
Label salt = new Label("Salt:");
TextField salti = new TextField(5);
Label btrs = new Label("Batteries:");
TextField btrsi = new TextField(5);
Button co = new Button("Compute Price");
Panel pnl = new Panel();
Label st = new Label("");
Label tx = new Label("");
Label t = new Label("");
public void init() {
setLayout(new GridLayout(2, 2));
setBackground(Color.blue);
add(sp);
add(pl);
pl.setLayout(new GridLayout(11, 2));
pl.add(cndy);
pl.add(cndyi);
pl.add(bred);
pl.add(bredi);
pl.add(sop);
pl.add(sopi);
pl.add(mlk);
pl.add(mlki);
pl.add(ham);
pl.add(hami);
pl.add(srdns);
pl.add(srdnsi);
pl.add(cfee);
pl.add(cfeei);
pl.add(ndls);
pl.add(ndlsi);
pl.add(salt);
pl.add(salti);
pl.add(btrs);
pl.add(btrsi);
add(co);
co.addActionListener(this);
add(pnl);
pnl.setLayout(new GridLayout(3, 2));
pnl.add(st);
pnl.add(tx);
pnl.add(t);
}
public void actionPerformed(ActionEvent z) {
int a, b, c, d, e, f, g, h, i, j;
double nst, ntx, nt;
a = Integer.parseInt(cndyi.getText());
b = Integer.parseInt(bredi.getText());
c = Integer.parseInt(sopi.getText());
d = Integer.parseInt(mlki.getText());
e = Integer.parseInt(hami.getText());
f = Integer.parseInt(srdnsi.getText());
g = Integer.parseInt(cfeei.getText());
h = Integer.parseInt(ndlsi.getText());
i = Integer.parseInt(salti.getText());
j = Integer.parseInt(btrsi.getText());
nst = (a * 31.50) + (b * 35) + (c * 25) +
(d * 38.85) + (e * 43.15) + (f * 13) +
(g * 39) + (h * 7) + (i * 10) + (j * 30);
ntx = nst + (nst * .12);
nt = nst + ntx;
st.setText("Sub-total = " + nst);
tx.setText("Sub-total = " + ntx);
t.setText("Sub-total = " + nt);
}
public static void main(String[] args) {
new Project();
}
}
Try to put all the panels in a Frame. Try to use this tutorial. http://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html This is the Window used to display all the things, and make them visible.
This seems like a homework question to me. Problem is that you have nothing to run.
public static void main(String[] args) {
new Project();
}
All that does is make a new object but after that the program terminates: you need a loop.
Try this tutorial: Building Your First Java Applet.
Nothing shows up when I try to run it
That's because you haven't asked for anything. new Project() only creates a Project object and since you don't have a default constructor defined and you aren't explicitly calling any other methods, execution exits immediately. Make the following change
new Project().init();
You need to place your Panel in a JFrame to make it visible. Try something like the following in your init() method
JFrame frame = new JFrame();
frame.add(pl);
frame.pack();
frame.setVisible(true);
Your code runs fine for me. I see:
My guess is that you are trying to run it as a Java Application, instead of as a Java Applet. You do have main() method in your class, which is what might be causing this confusion. main() can be removed. In the case of applets, init() is the entry point, like main() would be if it was run as a application.
Right-click on the class and select Run As > Java Applet. For example: