Need help with basic Java programming

I'm having a little bit of trouble with my code. For the sake of argument, I've removed the code I'm having trouble with, because I know it was inaccurate. I'm trying to create a loop so that this program will keep going through and through until the user enters an invalid variable. I thought the default after the case statements was supposed to make the system exit and output my message. Those two problems, the loop and the default, are what I'm really having problems with. My code is posted below.
import javax.swing.JOptionPane;
import java.util.Locale;
import java.text.NumberFormat;
public class Retail
public static void main(String args[])
String firstNum;
String secondNum;
String result;
int prodNum;      //first number to input
double quantity; //second number to input
double total = 0.0;     //total of Prod * Quantity Sold for all items
// To use American Dollar
NumberFormat moneyFormat = NumberFormat.getCurrencyInstance( Locale.US );
// first number entered as string
firstNum = JOptionPane.showInputDialog( "Enter product number 1-5" );
// second number entered as string
secondNum = JOptionPane.showInputDialog( " Enter quantity of items sold" );
// convert values to type double or int from type string
prodNum = Integer.parseInt( firstNum );
quantity = Double.parseDouble( secondNum);
result="";
if ( prodNum >=1 && prodNum <=5 ) {
switch (prodNum)
case 1: // 1st product
total = 2.98 * quantity;
break;
case 2: // 2nd product
total = 4.50 * quantity;
break;
case 3: // 3rd product
total = 9.98 * quantity;
break;
case 4: //4th product
total = 4.49 * quantity;
break;
case 5:
total = 6.87 * quantity;
break;
default: JOptionPane.showMessageDialog( null, "Wrong product number entered" );
JOptionPane.showMessageDialog( null, moneyFormat.format(total), "Total Price of Items Purchased", JOptionPane.INFORMATION_MESSAGE );
System.exit(0);
***I know I need to put something in the user input message to state that any value other than 1-5 entered will cause the program to skip to the output, I'll put that in later.***

When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read and prevents accidental markup from array indices like [i].

Similar Messages

  • Need Help with a JAVA programming assignment

    How do I write a JAVA program that could be used as the start of an MS-DOS/Windows simulation of the IEEE 802.3 protocol? I am to only code the parts necessary to build the 802.3 frame. For the initial implementation, the Checksum function need not be a CRC function, and the Destination and Source addresses wil be in input, stored, and output, and in dotted-decimal format.
    I need:
    1. A record to describe the frame, with each field being a (byte-) string of the required size, except that the Data field is of variable size. Although the "Source address" and "Destination address" would be 6 bytes for a real implementation, for this first implementation you can either assume they'll be text strings in the usual "dotted decimal" form (e.g. "14.04.05.18.01.25" as a typical example--from Tanenbaum, p. 429), or 6 hex digits.
    2. Suitable constant declarations for values such as the standard "Preamble" and "Start of Frame" values.
    3. Suitable functions to Get the three variable values "Destination address", "Source address", and "Data" from the standard input device.
    4. A suitable function to display each of the fields of a given frame in a format such as:
    Preamble: ...
    StartofFrame: ...
    Destination: ...
    etc.
    5. A suitable function to generate a "Pad" field if necessary.
    6. A "dummy" Checksum-generating function which just takes the first 32 bits (4 bytes) of the Data (or Data+Pad, if necessary) rather than an actual CRC algorithm.
    I have no experience with Java. Can you help me or start me in the right direction?
    Thanks...........TK

    If you have no experience with Java, then it seems to me your first step should be to start learning the language. But it's difficult to advise how, since we don't know anything about your background. There are many good books available on Java, some are for beginners and some are for advanced programmers, so I'd suggest you go somewhere that has a large selection and start looking for something that doesn't seem completely over your head.

  • Need Help with a Java programming exercise.

    I have to Write a program that reads two times in military format (0900, 1730) and prints the number of hours and minutes between two times. Supply your own test program. Here are two sample runs. User inputs are the numbers.
    Please enter the first time: 0900
    Please enter the second time: 1730
    8 hours 30 minutes
    Please enter the first time: 1730
    Please enter the second time: 0900
    15 hours 30 minutes
    Test Program I can write up myself. But the entire constructor I have no idea how to start. This is basic Java Coding. no C++ no importing anything.
    So far this is what I got and I'm sure it's wrong:
    public class TimeInterval
    private double hours;
    private double minutes;
    public TimeInterval(double Time1, double Time2)
    hours =
    minutes =
    }

    tad2382 wrote:
    Jverd,
    I'm guessing that in your early days on this forum you must have spent a lot of time explaining constructors, object creation, etc. Now, after some 40K posts to the forum, you figure newbies should just go and read the documentation. Is that what a lot of veteran posters feel?Perhaps the OP is not aware of the fact the Sun has a good deal of high quality study material published on their website. What's wrong with posting it in a thread? Why should one copy the same thing over and over again? If after reading that tutorial, the OP still has some questions about it, s/he is free to post a follow up question. I am sure that many of the regulars here are more than happy to answer them.
    Also note that the OP's problem description is rather vague. A "I don't know where to start" is IMO best answered by a link to a comprehensive tutorial or a beginners book.
    Being one of the (relatively) novice posters on the forum, I still feel the need to customize posts,Well, by all means: do so.
    trying to see things from the poster's side. Maybe after a few thousand posts, I'll just keep throwing the same documentation at newbies, instead of detailed customized responses, heh.IMO, that's a load of cr@p.

  • Need Help with a Java program

    Hey
    I am doing a bachelor of Multimedia and for some reason I was forced to do Programming 1 which is just Java programing.I have been doing pretty well but we have the final exam coming up on Thursday and they told us to learn how to do this question but I have no idea how to do it, could someone please help me?
    Write a program that reads a file containing a list of students' student numbers and names, and then writes out another file in which the students have been formed into project groups.
    Sample input file:
    96439530 Naranek, Kosh
    08532109 Ivanova, Susan
    87642078 Sheridan, John
    44327889 Varner, Dell
    98100023 Kotto, Vir
    66345689 Sinclair, Jeffrey
    77421009 Garibaldi, Michael
    88775544 Winters, Talia
    54321098 Alexander, Lyta
    12345098 Mollari, Londo
    03465499 Takashima, Laurel
    88765432 Kyle, Benjamin
    08876500 Keffer, Warren
    07687878 Cole, Marcus
    For the project course: no group should have more than 5 members; and it is desireable that all groups have as close to 5 members as possible; and that students be allocated to groups alphabetically by family name, as in this sample output file:
    Group 1:
    Lyta Alexander (54321098)
    Susan Ivanova (08532109)
    Benjamin Kyle (88765432)
    John Sheridan (87642078)
    Dell Varner (44327889)
    Group 2:
    Marcus Cole (07687878)
    Warren Keffer (08876500)
    Londo Mollari (12345098)
    Jeffrey Sinclair (66345689)
    Talia Winters (88775544)
    Group 3:
    Michael Garibaldi (77421009)
    Vir Kotto (98100023)
    Kosh Naranek (96439530)
    Laurel Takashima (03465499)
    Students' names are first sorted (Alexander, Cole, Garibaldi, Ivanova, ...), then allocated to the tutes in rotation (Alexander to 1, Cole to 2, Garibaldi to 3, Ivanova to 1, ...).
    Note also that the student's details are written in a different format from the input. You may make the (usually wrong!) assumption that each student has a simple one-word family name and one other name.

    I'm sorry too annoy you again but I don't know how to implement what you told me. Here is my current code:
    import java.io.*;
    import java.util.*;
    class DetailSortTest {
         public void run() {
              try {
                   BufferedReader in = new
                   BufferedReader(new FileReader ("Data.txt"));
                   String line = in.readLine();
                   String[] names = new String [10];
                   int i = 0;
                   PrintWriter FileOut = new
                   PrintWriter(new FileWriter ("Data 2.txt"));
                   processFilesTest(in, FileOut);
                   in.close();
                   FileOut.close();
              } catch (FileNotFoundException f) {
                   System.out.println("Could Not Open The File");
              } catch (IOException i){
                   System.out.println(i.getMessage());
         public void processFilesTest (BufferedReader in, PrintWriter FileOut)
         throws IOException {
              String data[] = new String[100];
              List dList = new ArrayList();
              String NLine = in.readLine();
              FileOut.println(NLine);
         public static void main(String[] args) {
              DetailSortTest anObject = new
              DetailSortTest();
              anObject.run();
    How would I do it I tried:
    NLine.split(data[2]+""+data[1]+""+data[0]);
    But all that displays is null, null, null
    I know I am probably so stupid but I really appreciate the help

  • Need help with a simple program (should be simple anyway)

    I'm (starting to begin) writing a nice simple program that should be easy however I'm stuck on how to make the "New" button in the file menu clear all the fields. Any help? I'll attach the code below.
    ====================================================
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Message extends JFrame implements ActionListener {
         public void actionPerformed(ActionEvent evt) {
         text1.setText(" ");
         text2.setText("RE: ");
         text3.setText(" ");
         public Message() {
         super("Write a Message - by Kieran Hannigan");
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setSize(370,270);
         FlowLayout flo = new FlowLayout(FlowLayout.RIGHT);
         setLayout(flo);
         //Make the bar
         JMenuBar bar = new JMenuBar();
         //Make "File" on Menu
         JMenu File = new JMenu("File");
         JMenuItem f1 = new JMenuItem("New");f1.addActionListener(this);
         JMenuItem f2 = new JMenuItem("Open");
         JMenuItem f3 = new JMenuItem("Save");
         JMenuItem f4 = new JMenuItem("Save As");
         JMenuItem f5 = new JMenuItem("Exit");
         File.add(f1);
         File.add(f2);
         File.add(f3);
         File.add(f4);
         File.add(f5);
         bar.add(File);
         //Make "Edit" on menu
         JMenu Edit = new JMenu("Edit");
         JMenuItem e1 = new JMenuItem("Cut");
         JMenuItem e2 = new JMenuItem("Paste");
         JMenuItem e3 = new JMenuItem("Copy");
         JMenuItem e4 = new JMenuItem("Repeat");
         JMenuItem e5 = new JMenuItem("Undo");
         Edit.add(e5);
         Edit.add(e4);
         Edit.add(e1);
         Edit.add(e3);
         Edit.add(e2);
         bar.add(Edit);
         //Make "View" on menu
         JMenu View = new JMenu("View");
         JMenuItem v1 = new JMenuItem("Bold");
         JMenuItem v2 = new JMenuItem("Italic");
         JMenuItem v3 = new JMenuItem("Normal");
         JMenuItem v4 = new JMenuItem("Bold-Italic");
         View.add(v1);
         View.add(v2);
         View.add(v3);
         View.addSeparator();
         View.add(v4);
         bar.add(View);
         //Make "Help" on menu
         JMenu Help = new JMenu("Help");
         JMenuItem h1 = new JMenuItem("Help Online");
         JMenuItem h2 = new JMenuItem("E-mail Programmer");
         Help.add(h1);
         Help.add(h2);
         bar.add(Help);
         setJMenuBar(bar);
         //Make Contents of window.
         //Make "Subject" text field
         JPanel row2 = new JPanel();
         JLabel sublabel = new JLabel("Subject:");
         row2.add(sublabel);
         JTextField text2 = new JTextField("RE:",24);
         row2.add(text2);
         //Make "To" text field
         JPanel row1 = new JPanel();
         JLabel tolabel = new JLabel("To:");
         row1.add(tolabel);
         JTextField text1 = new JTextField(24);
         row1.add(text1);
         //Make "Message" text area
         JPanel row3 = new JPanel();
         JLabel Meslabel = new JLabel("Message:");
         row3.add(Meslabel);
         JTextArea text3 = new JTextArea(6,22);
         messagearea.setLineWrap(true);
         messagearea.setWrapStyleWord(true);
         JScrollPane scroll = new JScrollPane(text3,
                                  JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                  JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
         //SpaceLine
         JPanel spaceline = new JPanel();
         JLabel spacer = new JLabel(" ");
         spaceline.add(spacer);
         row3.add(scroll);
         add(row1);
         add(row2);
         add(spaceline);
         add(spaceline);
         add(row3);
         setVisible(true);
         public static void main(String[] arguments) {
         Message Message = new Message();
    }

    persiandude wrote:
    Topic: Need help with if, else, and which statements and loops.
    How would I display 60 < temp. <= 85 in java
    System.out.println("60 < temp. <= 85 in java");
    another question is how do I ask a question like want to try again (y/n) after a output and asking that everytime I type in yes after a output and terminate when saying No.Sun's [basic Java tutorial|http://java.sun.com/docs/books/tutorial/]
    Sun's [New To Java Center|http://java.sun.com/learning/new2java/index.html].Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    [http://javaalmanac.com|http://javaalmanac.com]. A couple dozen code examples that supplement [The Java Developers Almanac|http://www.amazon.com/exec/obidos/tg/detail/-/0201752808?v=glance].
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's [Thinking in Java|http://mindview.net/Books/DownloadSites] (Available online.)
    Joshua Bloch's [Effective Java|http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683/ref=pd_bbs_1?ie=UTF8&s=books&qid=1214349768&sr=8-1]
    Bert Bates and Kathy Sierra's [Head First Java|http://www.amazon.com/exec/obidos/tg/detail/-/0596004656?v=glance].
    James Gosling's [The Java Programming Language|http://www.bookpool.com/sm/0321349806].

  • Need help with my addressbook program

    hi,
    i need help with my program here. this one should works as:
    - saves user input into a txt file
    - displays name of the saved person on the jlist whenever i run the program
    - displays info about the person when clicked via textboxes given by reading the txt file where the user inputs are
    - should scroll when the list exceeds the listbox
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JList;
    import java.awt.event.ActionListener;
    import java.io.*;
    import javax.swing.event.*;
    import java.io.FilterInputStream;
    public class AddressList extends JPanel implements ActionListener
         JTextField txt1 = new JTextField();
         JTextField txt2 = new JTextField();
         JTextField txt3 = new JTextField();
         DefaultListModel mdl = new DefaultListModel();
         JList list = new JList();
         JScrollPane listScroller = new JScrollPane(list);
         ListSelectionModel listSelectionModel;
         File fob = new File("Address3.txt");
         String name;
         char[] chars;     
         public void ListDisplay()
              try
                   RandomAccessFile rand = new RandomAccessFile(fob,"rw");
                   BufferedReader br = new BufferedReader(new FileReader("Address3.txt"));
                   if(fob.exists())
                         while((name = rand.readLine()) != null)
                              chars = name.toCharArray();
                              if(chars[0] == '*')
                                   mdl.addElement(name);
                                   list.setModel(mdl);
                              if(chars[0] == '#')
                                   continue;
                    else
                        System.out.println("No such file..");
              catch(IOException a)
                         System.out.println(a.getMessage());
         public AddressList()
              this.setLayout(null);
              listSelectionModel = list.getSelectionModel();
            listSelectionModel.addListSelectionListener(new ListInfo());
              list.setBounds(10,40,330,270);
              listScroller.setBounds(320,40,20,100);
              add(list);
              add(listScroller);
              JLabel lbl4 = new JLabel("Name: ");
              lbl4.setBounds(400,10,80,30);
              add(lbl4);
              JLabel lbl5 = new JLabel("Cellphone #: ");
              lbl5.setBounds(400,50,80,30);
              add(lbl5);
              JLabel lbl6 = new JLabel("Address: ");
              lbl6.setBounds(400,90,80,30);
              add(lbl6);
              JLabel lbl7 = new JLabel("List ");
              lbl7.setBounds(10,10,100,30);
              add(lbl7);
              txt1.setBounds(480,10,200,30);
              add(txt1);
              txt2.setBounds(480,50,200,30);
              add(txt2);
              txt3.setBounds(480,90,200,30);
              add(txt3);
              JButton btn1 = new JButton("Add");
              btn1.setBounds(480,130,100,30);
              btn1.addActionListener(this);
              btn1.setActionCommand("Add");
              add(btn1);
              JButton btn2 = new JButton("Save");
              btn2.setBounds(480,170,100,30);
              btn2.addActionListener(this);
              btn2.setActionCommand("Save");
              add(btn2);
              JButton btn3 = new JButton("Cancel");
              btn3.setBounds(480,210,100,30);
              btn3.addActionListener(this);
              btn3.setActionCommand("Cancel");
              add(btn3);
              JButton btn4 = new JButton("Close");
              btn4.setBounds(480,250,100,30);
              btn4.addActionListener(this);
              btn4.setActionCommand("Close");
              add(btn4);
         public static void main(String[]args)
              JFrame frm = new JFrame("Address List");
              AddressList panel = new AddressList();
              frm.getContentPane().add(panel,"Center");
              frm.setSize(700,350);
              frm.setVisible(true);
              panel.ListDisplay();
         public void actionPerformed(ActionEvent e)
              String cmd;
              cmd = e.getActionCommand();
              if(cmd.equals("Add"))
                   txt1.setText("");
                   txt2.setText("");
                   txt3.setText("");
              else if(cmd.equals("Save"))
                   mdl.addElement(txt1.getText());
                   list.setModel(mdl);
                   try
                   RandomAccessFile rand = new RandomAccessFile(fob,"rw");
                   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                   LineNumberReader line = new LineNumberReader(br);
                    if(fob.exists())
                              rand.seek(fob.length());
                              rand.writeBytes("* " + txt1.getText());
                              rand.writeBytes("\r\n" + "# " + txt2.getText());
                              rand.writeBytes("\r\n" + "# " + txt3.getText() + "\r\n");
                    else
                         System.out.println("No such file..");
                        txt1.setText("");
                        txt2.setText("");
                        txt3.setText("");
                    catch(IOException a)
                         System.out.println(a.getMessage());
              else if(cmd.equals("Cancel"))
                   txt1.setText("");
                   txt2.setText("");
                   txt3.setText("");
              else if(cmd.equals("Close"))
                   System.exit(0);
    class ListInfo implements ListSelectionListener
         public void valueChanged(ListSelectionEvent e)
              ListSelectionModel lsm = (ListSelectionModel)e.getSource();
              int minIndex = lsm.getMinSelectionIndex();
            int maxIndex = lsm.getMaxSelectionIndex();
              try //*this one should display the info of the person whenever i click the person's name at the list box via textbox.. but i cant seem to get it right since it always display the info of the first person inputed.. i tried to get the program to display them whenever it reads lines with * on them....
                   File fob = new File("Address3.txt");
                   RandomAccessFile rand = new RandomAccessFile(fob,"rw");
                   BufferedReader br = new BufferedReader(new FileReader("Address3.txt"));
                   LineNumberReader line = new LineNumberReader(br);
                   if(fob.exists())
                              for(int i = minIndex; i<=maxIndex; i++)
                                   if(lsm.isSelectedIndex(i))
                                        while((name = rand.readLine()) != null)
                                             chars = name.toCharArray();
                                             if(chars[0] == '#')
                                                  continue;
                                             if(chars[0] == '*')
                                                  txt1.setText(rand.readLine());
                                                 txt2.setText(rand.readLine());
                                                 txt3.setText(rand.readLine());
                    else
                              System.out.println("No such file..");
              catch(IOException a)
                         System.out.println(a.getMessage());
    }the only problem now is about how it should display the right info about the person whenever i click its name on the list.. something about file reading or something, i just cant figure it out.
    and also about how to make it scroll once it exceeds the list.. i cant make it work, maybe something about wrong declaration..
    thanks in advance..
    Edited by: syder on Mar 14, 2008 2:26 AM

    Like said before, do one thing at a time. At startup, something like:
    //put all the content in a list
    ArrayList<String> lines = new ArrayList<String>();
    while(String line=rand.readLine()!=null) {
        lines.add(line);
    }If you follow the good advice to create a class to encapsulate the entries, you could populate a list of such entries like this:
    static final int ENTRY_SIZE = 3;//you have 3 fields now, better to have a constant if that changes
    ArrayList<Entry> entries = new ArrayList<Entry>();
    for(int i=0; i<lines.size(); i+=ENTRY_SIZE) {
        Entry entry = new Entry(lines.get(i), lines.get(i+1), lines.get(i+2);
        entries.add(newEntry);
    }You could also do both of the above in one run, but I think you will understand better what's happening if you do one thing at a time.
    If you don't want to put the entries in an encapsulating class, you can still access this without looping:
    int listStartIdx = <desired_entry_index>*ENTRY_SIZE;
    String att1 = lines.get(listStartIdx).substring(1);
    String att2 = lines.get(listStartIdx+1).substring(1);
    String att3 = lines.get(listStartIdx+2).substring(1);

  • Need help with a rudimentary program

    I'm sort of new at this so i need help with a few things... I'm making a program to compile wages and i need answers with three things: a.) what are the error messages im getting meaning? b.) How can i calculate the state tax as 2% of my gross pay with the first $200 excluded and c.) how can i calculate the local tax as a flat $10 with $2 deducted for each dependant. any help is appreciated
    Here is what i have so far:
    public class WagesAsign1
              public static void main(String[] args)
                   int depend=4;
                   double hrsWork=40;
                   double payRate=15;
                   double grossPay;
                   grossPay=payRate*hrsWork;
                   double statePaid;
                   double stateTax=2.0;
                   statePaid=grossPay*(stateTax/100);
                   double localPaid;
                   double localTax=10.0;
                   localPaid=grossPay*(localTax/100);
                   double fedPaid;
                   double fedTax=10.0;
                   double taxIncome;
                   fedPaid=taxIncome*(fedTax/100);
                   taxIncome=grossPay-(statePaid+localPaid);
                   double takeHome;
                   System.out.println("Assignment 1 Matt Foraker\n");
                   System.out.println("Hours worked="+hrsWork+" Pay rate $"+payRate+" per/hour dependants: "+depend);
                   System.out.println("Gross Pay $"+grossPay+"\nState tax paid $"+statePaid+"\nLocal tax paid $"+localPaid+"\nFederal tax paid $"+fedPaid);
                   System.out.println("You take home a total of $"+takeHome);
    and these are the error messages so far:
    WagesAsign1.java:23: variable taxIncome might not have been initialized
                   fedPaid=taxIncome*(fedTax/100);
    ^
    WagesAsign1.java:29: variable takeHome might not have been initialized
                   System.out.println("You take home a total of $"+takeHome);
    ^

    edit: figured it out... please delete post
    Message was edited by:
    afroryan58

  • Need Help With D&D Program

    Hi, I'm not sure if I'm allowed to post questions on this forum but I can't find anywhere to talk to helpful people about programming.
    I'm making a dnd interface for JComponents. So far I've made a simple program that has a Component that can be lifted from a container and braught to the glass pane then later moved to anywhere on the screen and dropped into the container below it. Here's where my problems come:
    1) Rite now my 'Movable Component' is a JPanel which is just colored in. I want to either take a Graphic2d from a JComponent/Component and draw it on the JPanel or change the JPanel to the component I want to paint and disable the component.
    The problem with getting the Graphics2d is that if the component isn't on the screen it doesn't make a graphic object. I tried messing with the ui delicate and overriding parental methods for paintComponent, repaint, and that repaintChildren(forget name) but I haven't had luck getting a good graphics object. I was thinking of, at the beginning of running the program, putting 1 of each component onto the screen for a second then removing it but I'd rather not. I'd also like to change the graphics dynamicly if someone stretches the component there dropping and what not.
    The problem with disabling is that it changes some of the visual features of Components. I want to be able to update the Component myself to change how it looks and I don't want disabling to gray out components.
    I mainly just dont want the components to do any of there normal fuctions. This is for a page builder, by the way.
    Another problem I'm having is that mouseMotionListener is allowing me to select 2 components that are on top of one another when there edges are near each other. I don't know if theres a fix to this other than changing the Java Class.
    My next problem is a drop layout manager, but I'm doing pretty good with that rite now. It'll problem just move components out of the way of the falling component.
    One last thing I need help with is that I don't want the object that's being carried to go across the menu bar and certain areas. When I'm having the object being carried I have it braught up to the glass pane which allows it to move anywhere. Does anyone have any idea how I could prevent the component from being over the menu bars and other objects? I might have to make 1 panel is the movable area that can then be broken down into the 'component bank', 'building page' and whatever else I'm gonna need.
    This is all just test code to get together for when I make the real program but I need to make sure it'll be possible without a lot of hacking of code.
    Sorry for the length. Thanks for any help you can give.

    The trick to making viewable components that have no behaviour, is to render them onto an image of some sort (eg a BufferedImage). You can then display the Image on a JLabel that can be dragged around the desktop.
    Here is a piece of code that does the component rendering for you. This particular example uses a fixed component size, but you can modify that as you choose of course...public class JComponentImage
         private static GraphicsConfiguration gConfig;
         private static Dimension compSize = new Dimension(80, 22);
         private static Image image = null;
         public static Image getImage(Class objectClass)
              if (gConfig == null)
                   GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
                   GraphicsDevice gDevice = gEnv.getDefaultScreenDevice();
                   gConfig = gDevice.getDefaultConfiguration();
              image = gConfig.createCompatibleImage(compSize.width, compSize.height);
              JComponent jc = (JComponent) ObjectFactory.instantiate(objectClass);
              jc.setSize(compSize);
              Graphics g = image.getGraphics();
              g.setColor(Color.LIGHT_GRAY);
              g.fillRect(0, 0, compSize.width, compSize.height);
              g.setColor(Color.BLACK);
              jc.paint(g);
              return image;
    }And here is the class that makes the dragable JLabel using the class above...public class Dragable extends JLabel
         private static DragSource dragSource = DragSource.getDefaultDragSource();
         private static DragGestureListener dgl = new DragMoveGestureListener();
         private static TransferHandler th = new ObjectTransferHandler();
         private Class compClass;
         private Image image;
         Dragable(Class compClass)
              this.compClass = compClass;
              image = JComponentImage.getImage(compClass);
              setIcon(new ImageIcon(image));
              setTransferHandler(th);
              dragSource.createDefaultDragGestureRecognizer(this,
                                                          DnDConstants.ACTION_COPY,
                                                          dgl);
         public Class getCompClass()
              return compClass;
    }Oh and here is ObjectFactory which simply instantiates Objects of a given class and sets their text to their classname (very crudely)...public class ObjectFactory
         public static Object instantiate(Class objectClass)
              Object o = null;
              try
                   o = objectClass.newInstance();
              catch (Exception e)
                   System.out.println("ObjectFactory#instantiate: " + e);
              String name = objectClass.getName();
              int lastDot = name.lastIndexOf('.');
              name = name.substring(lastDot + 1);
              if (o instanceof JLabel)
                   ((JLabel)o).setText(name);
              if (o instanceof JButton)
                   ((JButton)o).setText(name);
              if (o instanceof JTextComponent)
                   ((JTextComponent)o).setText(name);
              return o;
    }Two more classes required by this codepublic class ObjectTransferHandler extends TransferHandler {
         private static DataFlavor df;
          * Constructor for ObjectTransferHandler.
         public ObjectTransferHandler() {
              super();
              try {
                   df = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
              } catch (ClassNotFoundException e) {
                   Debug.trace(e.toString());
         public Transferable createTransferable(JComponent jC) {
              Transferable t = null;
              try {
                   t = new ObjectTransferable(((Dragable) jC).getCompClass());
              } catch (Exception e) {
                   Debug.trace(e.toString());
              return t;
         public int getSourceActions(JComponent c) {
              return DnDConstants.ACTION_MOVE;
         public boolean canImport(JComponent comp, DataFlavor[] flavors) {
              if (!(comp instanceof Dragable) && flavors[0].equals(df))
                   return true;
              return false;
         public boolean importData(JComponent comp, Transferable t) {
              JComponent c = null;
              try {
                   c = (JComponent) t.getTransferData(df);
              } catch (Exception e) {
                   Debug.trace(e.toString());
              comp.add(c);
              comp.validate();
              return true;
    public class ObjectTransferable implements Transferable {
         private static DataFlavor df = null;
         private Class objectClass;
         ObjectTransferable(Class objectClass) {
              try {
                   df = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
              } catch (ClassNotFoundException e) {
                   System.out.println("ObjectTransferable: " + e);
              this.objectClass = objectClass;
          * @see java.awt.datatransfer.Transferable#getTransferDataFlavors()
         public DataFlavor[] getTransferDataFlavors() {
              return new DataFlavor[] { df };
          * @see java.awt.datatransfer.Transferable#isDataFlavorSupported(DataFlavor)
         public boolean isDataFlavorSupported(DataFlavor testDF) {
              return testDF.equals(df);
          * @see java.awt.datatransfer.Transferable#getTransferData(DataFlavor)
         public Object getTransferData(DataFlavor arg0)
              throws UnsupportedFlavorException, IOException {
              return ObjectFactory.instantiate(objectClass);
    }And of course the test class:public class DragAndDropTest extends JFrame
         JPanel leftPanel = new JPanel();
         JPanel rightPanel = new JPanel();
         Container contentPane = getContentPane();
         Dragable dragableJLabel;
         Dragable dragableJButton;
         Dragable dragableJTextField;
         Dragable dragableJTextArea;
          * Constructor DragAndDropTest.
          * @param title
         public DragAndDropTest(String title)
              super(title);
              dragableJLabel = new Dragable(JLabel.class);
              dragableJButton = new Dragable(JButton.class);
              dragableJTextField = new Dragable(JTextField.class);
              dragableJTextArea = new Dragable(JTextArea.class);
              leftPanel.setBorder(new EtchedBorder());
              BoxLayout boxLay = new BoxLayout(leftPanel, BoxLayout.Y_AXIS);
              leftPanel.setLayout(boxLay);
              leftPanel.add(dragableJLabel);
              leftPanel.add(dragableJButton);
              leftPanel.add(dragableJTextField);
              leftPanel.add(dragableJTextArea);
              rightPanel.setPreferredSize(new Dimension(500,500));
              rightPanel.setBorder(new EtchedBorder());
              rightPanel.setTransferHandler(new ObjectTransferHandler());
              contentPane.setLayout(new BorderLayout());
              contentPane.add(leftPanel, "West");
              contentPane.add(rightPanel, "Center");
         public static void main(String[] args)
              JFrame frame = new DragAndDropTest("Drag and Drop Test");
              frame.pack();
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setVisible(true);
    }I wrote this code some time ago, so it won't be perfect but hopefully will give you some good ideas.
    Regards,
    Tim

  • Need help with accessing the program.

    I need help with accessing my adobe creative cloud on my windows 8.1 laptop. I have an account but do not have an app. I need this for my online classes. Please help!

    Link for Download & Install & Setup & Activation may help
    -Chat http://www.adobe.com/support/download-install/supportinfo/

  • Need help with basic program.....!

    I've to write a program that generates a random number, which the user has to try and guess, after each guess they're told whether it's too high or too low etc., I've gotten this far, however, the user has only 10 guesses.... In my program I've used a while loop and the user gets an infinite number of guesses, I know I'm supposed to use a for loop, but can't seem to get it to work properly. Also, when the user guesses the number, the program then has to print out how many guesses it took, and I have no idea how to get it to do this AT ALL!!! I'd really appreciate some help with this, thanks v. much!!!!

    I've to write a program that generates a random
    number, which the user has to try and guess, after
    each guess they're told whether it's too high or too
    low etc., I've gotten this far, however, the user has
    only 10 guesses.... In my program I've used a while
    loop and the user gets an infinite number of guesses,
    I know I'm supposed to use a for loop, but can't seem
    to get it to work properly. Also, when the user
    guesses the number, the program then has to print out
    how many guesses it took, and I have no idea how to
    get it to do this AT ALL!!! I'd really appreciate some
    help with this, thanks v. much!!!!Hey not every book covers every aspect of Java (if you haven't got a book and don't want to buy 1 i recommend an online tutorial) If u want the user to have an infinate number of guesses, use an infinate while loop. Put this in a file called app.java:
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class app extends Applet implements ActionListener
         JLabel lbl=new JLabel("Guess a number between 0 and 10:");
         JTextField txtfield=new JTextField(20);
         JButton button=new JButton("Guess...");
         JLabel lbl2=new JLabel();
         int randomnumber=Math.round((float)Math.random()*10);
         public void init()
              add(lbl);
              add(txtfield);
              add(button);
              button.addActionListener(this);
         public void actionPerformed (ActionEvent e)
              String s=new String("");
              s+=randomnumber;
              if (e.getSource().equals(button) && txtfield.getText().equals(s))
                   setBackground(Color.white);
                   setForeground(Color.black);
                   lbl2.setText("Got it!");
                   add(lbl2);
                   validate();
              else
                   setBackground(Color.white);
                   setForeground(Color.black);
                   if (Integer.parseInt(txtfield.getText())>randomnumber)
                   lbl2.setText("Too High!");
                   else
                   lbl2.setText("Too Low!");
                   add(lbl2);
                   validate();
    Then create a HTML document in the classes folder:
    <HTML>
    <HEAD>
    <TITLE>APPLET</TITLE>
    </HEAD>
    <BODY>
    <HR>
    <CENTER>
    <APPLET
         CODE=app.class
         WIDTH=400
         HEIGHT=200 >
    </APPLET>
    </CENTER>
    <HR>
    </BODY>
    </HTML>
    It will do what you wish. If you want to have more then 10 numbers to guess, for example 100, do this:
    int randomnumber=Math.round((float)Math.random()*100);
    Does that answer your question?

  • Help with a java program

    Hello. I'm posting in these forums because I really don't know where else to go. I have been trying for the past several days to figure out how to go about writing my program but to no avail. The project requires reading many lines each containing several different elements from a datafile named "DATA". A few examples of some lines from that file:
    Department number/Number of units received/Date on which the shipment arrived/Expiration date/Name of Object
    0 78 02/03/2001 02/12/2001 apples
    0 26 06/03/2001 06/10/2001 lemons
    3 62 03/06/2001 03/14/2001 hamburger
    What we have to do with this data is read all of it from the file, separate all the different elements, and based on input from the user, sort everything and print it out to the screen. If the user enters 03, the program will show everything that arrived and expired within the month of March, sorted by date.
    It is a pretty basic program, but my problem is that I have no idea how to go about reading in this data, putting it into a vector (probably the easiest method) or separating the different elements. I've gone to websites and looked through my textbooks but they didn't help much. If anyone has any resources that could help for writing such a program, or if anyone could offer help in writing the program, I would really appreciate it. I can also show what I've managed to write so far, or more details on how the program should work. Thanks in advance.
    Matt

    since im not a pro like some of the guys on here :),
    and believe me thiers people here, who could write your whole app in a hour.
    anyways my advice , would be to do a search on the forums for useing.bufferReader()
    i think you would need to read the file in with bufferreader then split up each line useing the stringTokenizer and then use some algorithm to compare
    the values and split them up into your vector arrays as needed.
    thier is also fileinputStream i think you can use that too.

  • Need Help with simple array program!

    Hi, I have just recently started how to use arrays[] in Java and I'm a bit confused and need help designing a program.
    What this program does, it reads in a range of letters specified by the user. The user then enters the letters (a, b or c) and stores these characters into an array, which the array's length is equal to the input range the user would enter at the start of the program. The program is then meant to find how many times (a,b and c) appears in the array and the Index it first appears at, then prints these results.
    Here is my Code for the program, hopefully this would make sense of what my program is suppose to do.
    import B102.*;
    class Letters
         static int GetSize()
              int size = 0;
              boolean err = true;
              while(err == true)
                   Screen.out.println("How Many Letters would you like to read in?");
                   size = Keybd.in.readInt();
                   err = Keybd.in.fail();
                   Keybd.in.clearError();
                   if(size <= 0)
                        err = true;
                        Screen.out.println("Invalid Input");
              return(size);
         static char[] ReadInput(int size)
              char input;
              char[] letter = new char[size];
              for(int start = 1; start <= size; start++)
                   System.out.println("Please enter a letter (a, b or c) ("+size+" max), enter # to stop:");
                   input = Keybd.in.readChar();
                   while((input != 'a') && (input != 'b') && (input != 'c') && (input != '#'))
                        Screen.out.println("Invalid Input");
                        System.out.println("Please enter a letter (a, b or c) ("+size+" max, enter # to stop:");
                        input = Keybd.in.readChar();
                                    while(input == '#')
                                                 start == size;
                                                 break;
                   for(int i = 0; i < letter.length; i++)
                        letter[i] = input;
              return(letter);
         static int CountA(char[] letter)
              int acount = 0;
              for(int i = 0; i < letter.length; i++)
                   if(letter[i] == 'a')
                        acount++;
              return(acount);
         static int CountB(char[] letter)
              int bcount = 0;
              for(int i = 0; i < letter.length; i++)
                   if(letter[i] == 'b')
                        bcount++;
              return(bcount);
         static int CountC(char[] letter)
              int ccount = 0;
              for(int i = 0; i < letter.length; i++)
                   if(letter[i] == 'c')
                        ccount++;
              return(ccount);
         static int SearchA(char[] letter)
              int ia;
              for(ia = 0; ia < letter.length; ia++)
                   if(letter[ia] == 'a')
                        return(ia);
              return(ia);
         static int SearchB(char[] letter)
              int ib;
              for(ib = 0; ib < letter.length; ib++)
                   if(letter[ib] == 'b')
                        return(ib);
              return(ib);
         static int SearchC(char[] letter)
              int ic;
              for(ic = 0; ic < letter.length; ic++)
                   if(letter[ic] == 'c')
                        return(ic);
              return(ic);
         static void PrintResult(char[] letter, int acount, int bcount, int ccount, int ia, int ib, int ic)
              if(ia <= 1)
                   System.out.println("There are "+acount+" a's found, first appearing at index "+ia);
              else
                   System.out.println("There are no a's found");
              if(ib <= 1)
                   System.out.println("There are "+bcount+" b's found, first appearing at index "+ib);
              else
                   System.out.println("There are no b's found");
              if(ic <= 1)
                   System.out.println("There are "+ccount+" c's found, first appearing at index "+ic);
              else
                   System.out.println("There are no c's found");
              return;
         public static void main(String args[])
              int size;
              char[] letter;
              int acount;
              int bcount;
              int ccount;
              int ia;
              int ib;
              int ic;
              size = GetSize();
              letter = ReadInput(size);
              acount = CountA(letter);
              bcount = CountB(letter);
              ccount = CountC(letter);
              ia = SearchA(letter);
              ib = SearchB(letter);
              ic = SearchC(letter);
              PrintResult(letter, acount, bcount, ccount, ia, ib, ic);
              return;
    }     Some errors i get with my program are:
    When reading in the letters to store into the array, I get the last letter I entered placed into the entire array. Also I believe my code to find the Index is incorrect.
    Example Testing: How many letters would you like to read? 3
    Enter letter (a, b or c) (# to quit): a
    Enter letter (a, b or c) (# to quit): b
    Enter letter (a, b or c) (# to quit): c
    It prints "There are no a's'" (there should be 1 a at index 0)
    "There are no b's" (there should be 1 b at index 1)
    and "There are 3 c's, first appearing at index 0" ( there should be 1 c at index 2)
    The last thing is that my code for when the user enters "#" that the input of letters would stop and the program would then continue over to the counting and searching part for the letters, my I believe is correct but I get the same problem as stated above where the program takes the character "#" and stores it into the entire array.
    Example Testing:How many letters would you like to read? 3
    Enter letter (a, b or c) (# to quit): a
    Enter letter (a, b or c) (# to quit): #
    It prints "There are no a's'" (should have been 1 a at index 0)
    "There are no b's"
    and "There are no c's"
    Can someone please help me??? or does anyone have a program simular to this they have done and would'nt mind showing me how it works?
    Thanks
    lou87.

    Without thinking too much...something like this
    for(int start = 0; start < size; start++) {
                System.out.println("Please enter a letter (a, b or c) ("+size+" max), enter # to stop:");
                input = Keybd.in.readChar();
                while((input != 'a') && (input != 'b') && (input != 'c') && (input != '#')) {
                    Screen.out.println("Invalid Input");
                    System.out.println("Please enter a letter (a, b or c) ("+size+" max, enter # to stop:");
                    input = Keybd.in.readChar();
                if(input == '#') {
                        break;
                letter[start] = input;
            }you dont even need to do start = size; coz with the break you go out of the for loop.

  • Help with Simple JAVA program

    I'm a complete novice with Java. I want to write a Java program to run on Windows 2000 servers to write a list of certain files in a directory into a *.txt file. I hope to add complexity once I have this basic part working. Here's the code I have so far:
    //this Java application finds poll* files
    public class FindPollApp
    //Create File Object
    File dir = new File("d:/jda/windss/poll");
    //List directory
    if(dir.isDirectory())
    String[] dirContents = dir.list();
    for (int i=0; i < dirContents.length; i++)
    System.out.println(dirContents);
    //Iterate through files
    I get the following errors:
    C:\JAVA>javac FindPollApp.java
    FindPollApp.java:9: illegal start of type
    if(dir.isDirectory())
    ^
    FindPollApp.java:18: <identifier> expected
    ^
    2 errors
    Thanks.

    I'm a complete novice with Java. I want to write a
    Java program to run on Windows 2000 servers to write
    a list of certain files in a directory into a *.txt
    file. I hope to add complexity once I have this
    basic part working. Here's the code I have so far:
    //this Java application finds poll* files
    public class FindPollApp
    //Create File Object
    File dir = new File("d:/jda/windss/poll");
    //List directory
    if(dir.isDirectory())
    String[] dirContents = dir.list();
    for (int i=0; i < dirContents.length; i++)
    System.out.println(dirContents);
    //Iterate through files
    I get the following errors:
    C:\JAVA>javac FindPollApp.java
    FindPollApp.java:9: illegal start of type
    if(dir.isDirectory())
    ^
    FindPollApp.java:18: <identifier> expected
    ^
    2 errors
    Thanks.
    You need to create a method and insert your if statement in there

  • Need help with spell checker program

    Hi
    I am writing a spell checker program and need help for a simple logic.I have "List" of correctly spelled words and a String array of wrong spelled words.How can I compare both and tell that for eg xyz word is not spelled correctly.

    BigDaddyLoveHandles wrote:
    To learn more about Map, take the collection tutorial: [http://java.sun.com/docs/books/tutorial/collections/index.html]
    (Actually, to me it sounds like you have a Set of correctly spelled words and another Set of words which may or may not be correctly spelled, and you want the difference...)That is what it sounds like to me also, and that is easy.
    JSG

  • Help with some Java Programs

    Hi all ..
    i am a new in Java and i need some help with my School Project ,,,
    Will you help me ??
    regards,
    Toota

    People here will answer questions and comment on your code, but don't ecpect them to debug your source nor do your homework for you.

Maybe you are looking for

  • Error code 1321 when I try to install update  in Windows 8.1

    I can find a solution for that error code on Adobe web site, however it only covers up to Win 7.  It says I need to update user permissions and I am not sure how to do it in Win 8.1 . Perhaps Adobe could add a "Update user privileges in  Win 8.1"  to

  • Animated content always in foreground. Indesign CS 5.5

    Hey, i got a huge problem. I am working on an ipad publication, viewing in adobe's content viewer for ipad. i have a lot of interaction going on in there. For example, if i wanna put a video file in one of my documents, or a scrollable content, or a

  • RESYNC CATALOG

    I'm looking at the following reference and a bit confused about the Full Resynchronization process http://docs.oracle.com/cd/B28359_01/backup.111/b28273/rcmsynta038.htm From one hand it says : "you run RESYNC CATALOG When You made changes to the phys

  • I want to display the website which i have designed using jsp in telugu....

    Hi, I want to display the website which i have designed using jsp,mysql in telugu.I have searched a number of articles but couldn't get sufficient information.I read articles on internationalise jsp based websites but they were about converting in ot

  • First look of Belle -Disappointed!

    Frankly, I am disappointed with Belle update. Some very good features for Symbian are changed. You can click on upper right corner to control many items in Symbian Anne like check message, battery mode, connection. The clock can be either a big digit