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:
Related
I am creating a simple Tic Tac Toe Application in Swing using setBounds (null Layout).
My problem is that whichever component i add in the end, is not visible in the frame, or distorts the complete GUI.
My code would better explain this
import java.awt.*;
import javax.swing.*;
class ZeroKata
{
ButtonGroup p1group,p2group;
Font f;
JButton begin,b1,b2,b3,b4,b5,b6,b7,b8,b9;
JCheckBox p1K,p2K,p1Z,p2Z;
JFrame frame;
JLabel player1,player2,p1Name,p2Name,p1Symbol,p2Symbol,status,dummy; // dummy label for my problem
JPanel buttons;
JTextField name1,name2;
private void addComponents(Container parent,JComponent...c)
{
for(JComponent C:c)
parent.add(C);
}
public ZeroKata()
{
frame = new JFrame("Tic Tac Toe");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(900,650);
frame.setResizable(true);
frame.setVisible(true);
buttons = new JPanel();
buttons.setLayout(new GridLayout(3,3,10,10));
begin = new JButton("START GAME");
b1 = new JButton(" ");
b2 = new JButton(" ");
b3 = new JButton(" ");
b4 = new JButton(" ");
b5 = new JButton(" ");
b6 = new JButton(" ");
b7 = new JButton(" ");
b8 = new JButton(" ");
b9 = new JButton(" ");
p1K = new JCheckBox("X");
p1Z = new JCheckBox("O");
p2K = new JCheckBox("X");
p2Z = new JCheckBox("O");
p1group = new ButtonGroup();
p2group = new ButtonGroup();
p1group.add(p1K);
p1group.add(p1Z);
p2group.add(p2K);
p2group.add(p2Z);
name1 = new JTextField(30);
name2 = new JTextField(30);
f = new Font("Georgia",Font.PLAIN,38);
player1 = new JLabel (" << PLAYER 1 >>");
p1Name = new JLabel ("NAME : ");
p1Symbol = new JLabel ("SYMBOL : ");
player2 = new JLabel ("<< PLAYER 2 >>");
p2Name = new JLabel ("NAME : ");
p2Symbol = new JLabel ("SYMBOL : ");
status = new JLabel ("GAME STATUS -->> ");
dummy = new JLabel (" ");
addComponents(buttons,b1,b2,b3,b4,b5,b6,b7,b8,b9);
player1.setBounds(100,100,100,30);
p1Name.setBounds(120,150,100,30);
p1Symbol.setBounds(120,200,60,30);
player2.setBounds(100,250,100,30);
p2Name.setBounds(120,300,100,30);
p2Symbol.setBounds(120,350,50,30);
name1.setBounds(200,150,150,30);
p1K.setBounds(200,200,50,30);
p1Z.setBounds(250,200,50,30);
name2.setBounds(200,300,150,30);
p2K.setBounds(200,350,50,30);
p2Z.setBounds(250,350,50,30);
buttons.setBounds(500,100,250,250);
dummy.setBounds(20,20,30,30);
begin.setBounds(200,500,150,30);
frame.add(player1);
frame.add(p1Name);
frame.add(p1Symbol);
frame.add(player2);
frame.add(p2Name);
frame.add(p2Symbol);
frame.add(name1);
frame.add(name2);
frame.add(begin);
frame.add(buttons);
frame.add(p1K);
frame.add(p1Z);
frame.add(p2K);
frame.add(p2Z);
/* u need to add a dummy label also to let GUI work correctly, dont know whyx !
frame.add(dummy); */
}
public static void main(String...args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ZeroKata();
}
});
}
}
It is a simple code, I just don't know where I am going wrong .
Thanks in advance !
The default layout manager is a BorderLayout (see JFrame overview), set it to null to allow for absolute positioning:
frame.setLayout(null);
My problem is that whichever component i add in the end, is not
visible in the frame, or distorts the complete GUI. My code would
better explain this
you added JComponents to the already visible JFrame,
move frame.setVisible(true); as last code line, after all JComponents are added
Swing GUI should be started on Initial Threads
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.
I'm preparing a simple system as my assignment, And I'm facing a problem where I dont know how to getText the value of String. I know how to do it with integer, but not with string.
I use Integer.parseInt(t2.getText()); in my code if i want to get an integer value
I have added my code into this.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class tollRate extends JFrame implements ActionListener {
JLabel L1 = new JLabel("Please insert your origin (in capital letter)");
JTextField t1 = new JTextField(20);
JLabel L2 = new JLabel("Please insert your destination (in capital letter)");
JTextField t2 = new JTextField(20);
JLabel L3 = new JLabel("Your vehicle class");
JTextField t3 = new JTextField(1);
JButton b1 = new JButton("Calculate");
JButton b2 = new JButton("Exit");
JLabel L4 = new JLabel("Class 0 : Motorcycles, bicycles, or vehicles with "
+ "2 or less wheels" + "\nClass 1 : Vehicles wit 2 axles and 3 "
+ "or 4 wheels excluding taxis" + "\nClass 2 : Vehicles with 2 "
+ "axles and 5 or 6 wheels excluding busses" + "\n Class 3 : "
+ "Vehicles with 3 or more axles" + "\nClass 4 : Taxis"
+ "\nClass 5 : Buses");
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JPanel p5 = new JPanel();
String i, j, k;
tollRate() {
JFrame a = new JFrame();
setTitle("Highway Toll Rates System");
setSize(600, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 2));
p1.setLayout(new GridLayout(1, 2));
p1.add(L1);
p1.add(t1);
p2.setLayout(new GridLayout(1, 2));
p2.add(L2);
p2.add(t2);
p3.setLayout(new GridLayout(1, 2));
p3.add(L3);
p3.add(t3);
p4.setLayout(new FlowLayout());
p4.add(b1);
p4.add(b2);
p5.setLayout(new FlowLayout());
p5.add(L4);
add(p1);
add(p2);
add(p3);
add(p4);
add(p5);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent a) {
Object source = a.getSource();
if (source == b2) {
this.dispose();
} else if (source == b1) {
i = Integer.parseInt(t1.getText());
j = Integer.parseInt(t2.getText());
k = Integer.parseInt(t3.getText());
}
}
public static void main(String[] args) {
tollRate a = new tollRate();
}
}
First of all String i, j, k;
i = Integer.parseInt(t1.getText());
j = Integer.parseInt(t2.getText());
k = Integer.parseInt(t3.getText());
This is wrong. You are assigning String for int. Correct them first. and if you want int values it is better to use
int i, j, k; and use trim() to avoid additional spaces.
i = Integer.parseInt(t1.getText().trim());
j = Integer.parseInt(t2.getText().trim());
k = Integer.parseInt(t3.getText().trim());
In your case use as follows
i = t1.getText();
j = t2.getText();
k = t3.getText();
to assign a string to a string all you need to do is
i = t1.getText();
j = t2.getText();
k = t3.getText();
as you have created them as strings already
I've been having problems running this program it compiles but doesn't run properly. When I run it and attempt to perform the calculations it spits out a bunch errors. I think it has to with variable types. Here is the program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class area extends JFrame implements ActionListener, ItemListener{
//row 1
JPanel row1 = new JPanel();
JLabel select = new JLabel("Please select what you would like to caculate the area and volume of.");
//row 2
JPanel row2 = new JPanel();
JCheckBox circle = new JCheckBox("Circle", false);
JCheckBox cube = new JCheckBox("Cube", false);
//row 3
JPanel row3 = new JPanel();
JLabel radlab = new JLabel("Radius of the circle (in cm)");
JTextField rad = new JTextField(3);
JLabel sidelab = new JLabel("A side of the cube (in cm)");
JTextField side = new JTextField(3);
//row4
JPanel row4 = new JPanel();
JButton solve = new JButton("Solve!");
//row 5
JPanel row5 = new JPanel();
JLabel areacallab = new JLabel("Area");
JTextField areacal = new JTextField(10);
JLabel volumelab = new JLabel("Volume");
JTextField volume = new JTextField(10);
public area(){
setTitle("Area Caculator");
setSize(500,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//disables all text areas
rad.setEnabled(false);
side.setEnabled(false);
areacal.setEnabled(false);
volume.setEnabled(false);
//add listeners
circle.addItemListener(this);
cube.addItemListener(this);
solve.addActionListener(this);
FlowLayout one = new FlowLayout(FlowLayout.CENTER);
setLayout(one);
row1.add(select);
add(row1);
row2.add(circle);
row2.add(cube);
add(row2);
row3.add(radlab);
row3.add(rad);
row3.add(sidelab);
row3.add(side);
add(row3);
row4.add(solve);
add(row4);
row5.add(areacallab);
row5.add(areacal);
row5.add(volumelab);
row5.add(volume);
add(row5);
}
public void circlepick(){
//cube.setCurrent(false);
cube.setEnabled(false);
rad.setEnabled(true);
}
public void cubepick(){
circle.setEnabled(false);
side.setEnabled(true);
}
#Override
public void itemStateChanged(ItemEvent event) {
Object item = event.getItem();
if (item == circle){
circlepick();
}
else if (item == cube){
cubepick();
}
}
#Override
public void actionPerformed(ActionEvent evt){
//String radi = rad.getText();
//String sid = side.getText();
//circlesolve();
//cubesolve();
String radi = rad.getText();
String sid = side.getText();
double radius = Double.parseDouble(radi);
double length = Double.parseDouble(sid);
double cirarea = Math.PI * Math.pow(radius, 2);
double cirvolume = (4.0 / 3) * Math.PI * Math.pow(radius, 3);
double cubearea = Math.pow(length, 2);
double cubevolume = Math.pow(length, 3);
areacal.setText("" + cirarea + cubearea + "");
volume.setText("" + cirvolume + cubevolume + "");
}
public static void main(String[] args) {
area are = new area();
}
}
Here are the errors is printing out when attempting to perform the math (sorry it really long).
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1038)
at java.lang.Double.parseDouble(Double.java:548)
at area.actionPerformed(area.java:112)
...
Thanks so much in advance for an help!
When calling the functions:
double radius = Double.parseDouble(radi);
double length = Double.parseDouble(sid);
either radi or sid is am Empty String, thats what
java.lang.NumberFormatException: empty String
tells you.
You might consider adding a System.out.println(raid + ", " + sid) before parsing to check what values are empty Strings and make sure, that the Strings are not empty.
Double.parseDouble(String s) throws a NumberFormatException when the given String s can not be parsed into a double value.
For some reason every time I have someone run this program in Vista it works flawlessly but as soon as I move it over to a Windows 7 PC it stops in the middle of the ActionListener's Action Performed Method meaning I can click my choices but it will never say size selected.
Is there any way to fix this?
import java.io.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class SizerFrame extends JFrame {
ButtonGroup buttons = new ButtonGroup();
JTextField width = new JTextField(2);
JTextField height = new JTextField(2);
double inchesPerTimeline = 2.1;
public SizerFrame()
{
super("Timeline Application");
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(screen.width/2-125,screen.height/2-90,250,180);
getContentPane().setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
int[] gridX = new int[]{0,0,0,0};
int[] gridY = new int[]{0,1,2,3};
int[] gridW = new int[]{1,1,2,5};
String[] titles = new String[]{"6\"","9\"","10\"","Custom"};
String[] actions = new String[]{"6","9","10","C"};
for (int a = 0; a < 4; a++)
{
JRadioButton current = new JRadioButton(titles[a]);
current.setActionCommand(actions[a]);
c.gridx = gridX[a];
c.gridy = gridY[a];
c.gridwidth = gridW[a];
buttons.add(current);
getContentPane().add(current,c);
}
c.gridwidth = 1;
String[] title = new String[]{" ","Width","Height"};
gridX = new int[]{9,10,12};
for (int a = 0; a< 3; a++)
{
c.gridx = gridX[a];
getContentPane().add(new JLabel(title[a]),c);
}
c.gridx = 11;
getContentPane().add(width,c);
c.gridx = 13;
getContentPane().add(height,c);
c.gridx = 11;
c.gridy = 0;
c.gridwidth = 2;
JButton button = new JButton("Done");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonModel x = buttons.getSelection();
String size = "XXX";
System.out.println("Getting screen resolution");
int screenRes = Toolkit.getDefaultToolkit().getScreenResolution();
System.out.println("Successfully got screen resolution");
if (x!=null)
size = x.getActionCommand();
try{
TimeTable.width = new Integer(size)*screenRes;
TimeTable.height = (int)((TimeTable.titleCount+1)*inchesPerTimeline*screenRes);
}
catch(NumberFormatException ex)
{
try{
TimeTable.width = (int)(new Double(width.getText().trim())*screenRes);
TimeTable.height = (int)(new Double(height.getText().trim())*screenRes);
}
catch (NumberFormatException except)
{
return;
}
}
TimeTable.ready = true;
System.out.println("Size selected");
dispose();
}
});
getContentPane().add(button,c);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent winEvt){
System.exit(0);
}
});
setVisible(true);
}
}
Concise explanation :
I have a macro that runs out of Excel in Windows Vista and I tried to distribute it to a Computer running Windows 7. Upon execution the code failed to continue executing after this point i.e. it never printed out the words "Size selected". The rest of the program brings in a csv file from a C:\Users\?\AppData\TimeLineMacroProgram folder and later creates an image in the same directory. But this is the portion of the code that is currently broken. Whenever the GUI pops up I select the option for 9" and click done which should pass in 9 as a parameter and then print out "Size Selected" but it doesn't it only disposes the window. Please help.
Longshot guess:
There is an exit from your action listener if width and height text fields don't have content: you return after two NumberFormatExceptions. This would prevent "Size selected" from being displayed, and not dispose the frame. If you got the output "Successfully got screen resolution" and then it appeared to stop working, this could possibly be why. But if you experience that, and then click something else and then Done, it would print size selected.