Jan 30, 2014 Membuat Form Menu Utama Netbeans Agung Sulistyanto. Unsubscribe from Agung Sulistyanto? Cara Membuat Database Rental Mobil Dengan Netbeans 8.1 - Duration: 2:01:38.
Active5 months ago
I am creating a menu based program in java using switch case.here are 4 cases:
- add record
- delete record
- update record
- Exit
I added break after each case but, what I want to do is to terminate the program when user enter case no 4 so what to do in this case ?
Abhijit KumbharAbhijit Kumbhar4213 gold badges12 silver badges34 bronze badges
8 Answers
Please don't use
System.exit
. It's like trying to use a chainsaw to slice a tomato. It's a blunt tool that might be useful for emergency situations, but not for normal situations like you're trying to write.There are a couple better approaches: (1) If you put your loop in a method, where the method's only purpose is to read the user's input and perform the desired functions, you can
return
from that method:Now, whatever program calls
mainMenu()
has an opportunity to do some cleanup, print a 'goodbye' message, ask the user if they want to back up their files before exiting, etc. You can't do that with System.exit
.Another mechanism, besides
return
, is to use break
to exit the loop. Since break
also breaks out of a switch
, you'll need a loop label:Or (as Riddhesh Sanghvi suggested) you can put a condition in the
while
loop instead of breaking out of it. His answer used a condition based on the option
; another idiom I've used a lot is to set up a boolean
for the purpose:Or:
So you have a lot of options, all better than
ajbajbSystem.exit
.27.4k3 gold badges40 silver badges67 bronze badges
If you do not wish to choose either
Why to put
Riddhesh SanghviRiddhesh Sanghvireturn
or System.exit(ExitCode)
then put the termination condition in while loop as shown below. Why to put
while(true)
and then put return
or System.exit
insteadexploit the boolean check of the while loop to exit it.1,0741 gold badge8 silver badges20 bronze badges
You can use
System.exit()
for this purpose.System.exit(int status)
Terminates the currently running Java Virtual Machine.
Bruno CaceiroBruno Caceiro5,0191 gold badge15 silver badges35 bronze badges
return OR System.exit(ExitCode) if you want to exit directly.
Shubham ChaurasiaShubham Chaurasia1,3152 gold badges11 silver badges19 bronze badges
In case no 4, add:
Usually,
status >= 0
indicates that the program terminated correctly and status < 0
indicates an abnormal termination. I think you should use:status
serves as errorCode. You can assign whatever value you want. If your program contains many exit points, you can assign different errorCodes to them. You can return the errorCode to the environment which called the application. Through this errorCode, you can trace which System.exit() caused the program to terminate.WololoWololo
Your particular
burglarhobbitburglarhobbitcase
in your switch
statement would be:1,0871 gold badge12 silver badges29 bronze badges
Whenever You want to Exit out of the Switch case it is always better to use a do-while loop because that gives the user an advantage of running the Program again if he wants to update, delete or add Multiple records as in your Program
Wherever you want to add the Code for adding,deleting and updating the records you can call the Methods also which are defined outside the Switch Case and the Program should run just fine
Radhesh KhannaRadhesh Khanna
RJSoni13RJSoni13
Not the answer you're looking for? Browse other questions tagged java or ask your own question.
By Craig Conover and Marina Sum, updated: September 1, 2006 |
Since this article was published in late June, we have received a host of excellent comments from readers, hence this update. In particular, thanks to Geertjan Wielenga of the NetBeans IDE team for his valuable input. |
The tool for generating reports is an essential component of all enterprise systems and arguably the most valuable one in an application. One such popular, open-source, and Java technology-based tool is JasperReports. Rather than being a standalone product, JasperReports is a framework that you can integrate into your application.
JasperReports ably handles the most common reporting needsthose for relational database applications. The relational database management system (RDBMS) is not the only data storage format available, however. JasperReports' flexibility shines with its customizable datasource API: Whether your data is stored as XML files, in an LDAP repository, accessible through POJOs, or in a proprietary format, JasperReports can handle your reporting needs.
This article describes how to integrate the JasperReports library into the NetBeans 5.5 IDE (henceforth, NetBeans) so that you can develop your report-integration software with the NetBeans code-complete and lookup capabilities of Javadoc tools and then compile and run your code. In addition, the article shows you how to work with a simple Hello Report World! example template and Java application to generate an actual report. Lastly, you learn how to enhance the report template to produce a report by retrieving the data from an RDBMS.
Note: Even though NetBeans does not include a report designer for creating complex templates for JasperReports, you can do so with other third-party, rich-client Java tools. (See the JasperSoft and JasperReports SourceForge sites.) We suggest that you follow the procedures in this article to manually develop a report template to become familiar with its basic XML elements. The steps for many common formatting tasks are far from being intuitive.
If you are already familiar with JasperReports, this article serves as a refresher course. Those new to JasperReports can use this article as a first-step tutorial.
Note: The procedures in this article pertain to the NetBeans UI on the Windows and Solaris operating systems. For Macintosh users, the menus and keyboard shortcuts may differ.
- | Downloading and Installing the Framework |
- | Integrating Compilation, Code-Complete, and Documentation Capabilities |
- | Defining the Template's File Extension |
- | Generating Reports |
- | Summary |
- | Reference |
Downloading and Installing the Framework
First, download the JasperReports v1.2.5 framework, which includes the source files, bits, documentation, and examples. Select the package
jasperreports-1.2.5- project.zip
and expand it to a directory of your choice.Note: When this article was first published in late June, JasperReports 1.2.3 was the latest release. If a new release is available, it might very well work with the code in this article. However, we make no guarantees of such compatibility. If you use a newer release, be prepared to adjust the code as required as a result of the JasperReports API modifications.
Integrating Compilation, Code-Complete, and Documentation Capabilities
Next, integrate the source files, bits, and documentation into NetBeans:
Note: The directories and files in the procedures that follow are under the base JasperReports directory, named
jasperreports-1.2.5
by default, in which the sources and bits reside.- Start NetBeans.
Important: Ensure thatjavac
is on yourPATH
environment variable. - Choose Tools > Library Manager to open the Library Manager dialog box.
- Click New Library and, in the New Library dialog box, type
JasperReports-1.2.5
in the Library Name field. Choose Class Libraries from the Library Type drop-down list. Click OK. See Figure 1.Figure 1: Creating a New Library - In the Classpath tab, add the
jasperreports-1.2.5.jar
file from the JasperReportsdist
directory and add the following five files from thelib
directory:commons-beanutils-1.5.jar
commons-collections-2.1.jar
commons-digester-1.7.jar
commons-logging-1.0.2.jar
commons-javaflow-20060411.jar
Note: This example uses only a minimal number of JAR files. If you continue to use more advanced features of the JasperReports framework, you might need to add more JAR files to this new library entry. - In the Sources tab, add the JasperReports
src
directory. - In the Javadoc tab, add the JasperReports
api
directory, which is underdocs
. - Click OK to close Library Manager.
JasperReports report templates are simply XML files with the file extension
.jrxml
. In the following procedure, you define this file extension in NetBeans, which then recognizes .jrxml
files as XML files. Accordingly, NetBeans displays all the XML syntax color coding for those files and you can take advantage of the XML code-complete capability in the IDE.To define the file extension:
- Choose Tools > Options to open the Options dialog box.
- Click Advanced Options.
- Under the IDE Configuration node, expand System and then Object Types.
- Scroll down and select XML Objectsnot XML Schemas. Click the (...) button for the Extensions and MIME Types property to open the customizer editor.
- Type
jrxml
in the Item field and click Add. See Figure 2. - Close the editor and the Options dialog box.
Now, when you open a JasperReports report template (a
.jrxml
file), NetBeans recognizes it as an XML file so that the content uses the XML color-coded syntax and code-complete capability.Generating Reports
You're now ready to create a simple Java application that reads a JasperReports template and generates a report with the framework.
Adding JasperReports to a New Project
First, create a Java application project and add JasperReports as a new library:
- Choose File > New Project for the New Project wizard and then select General under Categories and Java Application under Projects.
- Name the project JasperReportsDemoApp and accept all the default settings.
- Right-click the JasperReportsDemoApp project node and choose Properties from the context menu.
The Project Properties dialog box is displayed. - In the Categories list, select Libraries and click Add Library.
The Add Library dialog box is displayed. - Select JasperReports-1.2.5 under Libraries and click Add Library. See Figure 3. Figure 3: Adding the JasperReports-1.2.5 Library
- Click OK to close the Project Properties dialog box.
Specifying Template and Report Locations
Next, create the directories in which to save your templates and to place the generated reports. Under the JasperReportsDemoApp project's root folder, create a directory named
report
and then create two subdirectories under report
: templates
and results
.- In the Files tab, right-click the JasperReportsDemoApp folder and choose File > New Folder > File from the context menu. (If the Files tab is not visible, choose Window > Files.)
The New File dialog box is displayed. - Choose Other under Categories and Folder under File types. See Figure 4.
Creating a Template
Next, create a template:
- In the Files tab, right-click the templates folder and choose File > File/Folder from the context menu. (If the Files tab is not visible, choose Window > Files.)
The New File dialog box is displayed. - Select Other under Categories and Empty File under File types.
- Add the following content to the empty
HelloReportWorld.jrxml
file. - Open the
Main
class file, which NetBeans created along with a package when you first created the Java project. - In the
main
method of the class, insert the following code underpublic void main(String[] args)
, not the constructorpublic Main()
.
The NetBeans Java editor reports many code errors. As a resolution, import the proper classes with the Fix Imports operation. Either right-click in the editor and choose Fix Imports from the context menu or, with the focus in the editor, type Alt-Shift-F. NetBeans then inserts all the necessaryimport
statements into your class and the error messages will disappear. - Place your cursor just after the dot after
JasperCompileManager
in the first line in thetry
block to test the NetBeans code-completion capability with the JasperReports library. - Press Control+space bar to invoke the code-complete drop-down list.
NetBeans displays a list of choices according to the context of your cursor location. This list automatically appears as you type in code and pause for a moment. To configure the properties of the code-completion prompt, choose Tools > Options for the Options dialog box and then click Editor on the left.
At this point, try the built-in NetBeans Javadoc indexing for JasperReports: Rightclick
JasperCompileManager
and choose Show Javadoc from the context menu. NetBeans launches a browser that shows the Javadoc documentation for that class.Here is an explanation of the JasperReports framework in the preceding code fragment:
JasperCompileManager.compileReport
ThecompileReport
method takes the JasperReports XML template and compiles it into byte code format (a JasperReports instance), which you can serialize to disk as a.jasper
file. You can reuse the compiled templates to generate reports without compiling them unless you've changed the template source. This is similar to the difference between a.jsp
file and its compiled servlet class counterpart.JasperFillManager.fillReport
ThefillReport
method takes the compiled report (the JasperReports instance), a few user-defined custom parameters, and a JasperReports datasource (an empty instancemore on that later), and fills the report instance with the parameters and data, if any. In this simple static Hello Report World! example, the method fills in nothing but returns an instance ofJasperPrint
instead.
TheJasperPrint
instance is an object representation of the completed report. Now all you have to do is instruct JasperReports to write it to disk in the desired and supported formats.JasperExportManager.exportReportToHtmlFile
TheexportReport
method takes theJasperPrint
instance and a destination file path and creates an HTML file with the report content. Besides HTML, the JasperReports framework supports exporting to PDF, XML, CSV (comma-separated values), XLS, RTF, and text file formats. You can also create custom file formats for export with the extensible JasperReports API.JasperExportManager.viewReport
TheviewReport
method displays the generated report in the built-in JasperReport Viewer. This is an optional but handy display that enables you to quickly see how a report looks without opening the generated files.
Performing a Test Run
Now do a test run to see what the report looks like:
- Run the
Main
class, which compiles the changes automatically. Right-click theMain.java
file in the project tree or in the editor and choose Run File from the context menu. Alternatively, press F6.
The image is displayed in the Jasper Viewer. See Figure 5.Figure 5: Hello Report World! Report - View the results and then manually view the content of
report/results/HelloReportWorld.html
by right-clicking the file name and choosing View from the context menu.
The content is displayed in the default browser.
Note: You can programmatically display the HTML report in the default browser. Also, you can add a couple lines of code to produce a report in PDF or any of the other output formats supported by JasperReports. Generating reports in those other formats may require that you add JAR libraries from JasperReports to the JasperReports library you created in NetBeans. We leave you to explore those possibilities; they are outside the scope of this article.
Enhancing the Template
As enhancements, format the template,
HelloReportWorld.jrxml
, with its title, author, date and other details:- Add the following parameter declarations (shown in bold) above the
<detail>
section. - Add a
<title>
section (shown in bold) between the<parameter>
and<detail>
sections. - Add the code (shown in bold) to the
main
method of theMain
class. - With the focus in the editor window of the
Main
class, press F6 to compile and run the class.
An enhanced report with a title, header, and date is displayed. See Figure 6. - Add the
Customer_ID, NAME, CITY,
andSTATE queryString
andfield
declarations (shown in bold) between the<parameter>
and<title>
sections to the template,HelloReportWorld.jrxml
.
ThequeryString
declaration defines the SQL query to retrieve data for the report.
Note: The order of the template sections is important. A wrong order produces parsing errors and the error message is not intuitive. When you add thequeryString
andfield
sections, be sure to insert them after theparameter
section. In other words, the correct order for the sections isparameter
,queryString
, andfield
. - Add a
<columnHeader>
section (shown in bold) between the<title>
and<detail>
sections. - Replace the
<detail>
section with the one shown in bold, which integrates the newly declared fields that will line up with the columns in the<columnHeader>
section.
Adding the Java DB Driver Library
Next, add the Java DB database library to your project:
- Start the Java DB database by choosing Tools > Java DB Database > Start Java DB Server.
- Add the Java DB driver library to the Java project:
- Under the JasperReportsDemoApp project node in the Projects tab, right-click the Libraries node and choose Add Library from the context menu.
The Add Libraries dialog box is displayed. - Choose Java DB Driver and click Add Library. See Figure 7.
Figure 7: Adding the Database Library - Under the JasperReportsDemoApp project node in the Projects tab, right-click the Libraries node and choose Add Library from the context menu.
- Replace the
try
andcatch
blocks in themain
method of theMain
class with the following code. - Fix the imports. Either right-click in the editor and choose Fix Imports from the context menu or, with the focus in the editor, type Alt-Shift-F.
Generating the Report
Finally, generate the report with the content from the database. With the focus in the editor window of the
Caveat: If your application throws
Main
class, press F6 to compile and run the report. Caveat: If your application throws
ClassNotFoundException
, add the following as the first line in the try
code block:Summary
The preceding is just a simple example of a report you can create when you integrate JasperReports into the NetBeans IDE. The JasperReports API supports numerous capabilities with which you can create more complex reports in many types of file formats. For example, you can format the JasperReports XML templates to match your company's look and feel and incorporate cascading style sheets to centralize formatting updates.
Many JasperReports designers are available that ease the process of creating complex templates. For details, see the GUI Tools site on the JasperReports SourceForge site.
References
- NetBeans 5.5
- JasperReports