Dropdown option menu repeat same option - spring-mvc

This is what I implemented using spring-mvc. As I observed resultSet in ChildNameAccess.java works properly. As I put print statement here it print what I really need as the options. But dropdown box repeats the one result in the resultset object. Could anybody trace this and tell me what's wrong with my jsp please?
controller.java
#RequestMapping(value="/my_children", method = RequestMethod.GET)
public void viewMyChild(Model model) {
ChildNameAccess childNameDAO = new ChildNameAccess();
try{
java.util.List<Child> children = childNameDAO.getChildDataByMotherId("M-2");
model.addAttribute("children",children);
System.out.println(children);
}
catch (SQLException e) {
e.printStackTrace();
}
}
my_children.jsp
<div class="container-fluid bg-2 text-center">
<form:form method="get" >
<div class="div_box">
<select>
<option value="top" >Select child</option>
<c:forEach items="${children}" var="children">
<option value="" >${children.firstName} ${children.lastName}</option>
</c:forEach>
</select>
<br>
<div align ="justify">
<button type="button" onclick="location.href='/web/mother/my_child_details'" class="btn btn-success active">View Details</button>
</div>
</div>
</form:form>
ChildNameAccess.java
package com.emidwife.web.models.dataAccess;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.ArrayList;
import com.emidwife.web.models.entities.Child;
import com.emidwife.web.models.utilities.Database;
public class ChildNameAccess {
private Database connection = new Database();
Child child = new Child();
public List<Child> getChildDataByMotherId(String motherID) throws SQLException {
connection.openConnection();
List<Child> children = new ArrayList<Child>();
try{
ResultSet resultSet = connection.getData("SELECT * FROM childdetails WHERE MotherID=\'" + motherID + "\'");
while(resultSet.next()){
System.out.println(resultSet.getString("FirstName"));
child.setChildId(resultSet.getString("ChildID"));//database column -->ChildID
child.setMotherId(resultSet.getString("MotherID"));
child.setFirstName(resultSet.getString("FirstName"));
child.setLastName(resultSet.getString("LastName"));
System.out.println(children);
children.add(child);
System.out.println(children);
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally{
connection.closeConnection();
}
return children;
}
}

In your ChildNameAccess.java child is defined outside resultSet iteration, try creating new Child object inside the loop every time it loops. Because in Java strings are immutable, and you actually cannot change the value of a string. Means when you do child.setFirstName(resultSet.getString("FirstName"));
like wise original value of the firstName String is still in the memory and the other variables which are pointed to it haven't changed.
while(resultSet.next()){
Child child = new Child();
child.setChildId(resultSet.getString("ChildID"));//database column -->ChildID
child.setMotherId(resultSet.getString("MotherID"));
child.setFirstName(resultSet.getString("FirstName"));
System.out.println(resultSet.getString("FirstName"));
child.setLastName(resultSet.getString("LastName"));
children.add(child);
}

You need to create child object for each resultset row. You are not creating it. I have fixed it as follows.
package com.emidwife.web.models.dataAccess;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.ArrayList;
import com.emidwife.web.models.entities.Child;
import com.emidwife.web.models.utilities.Database;
public class ChildNameAccess {
private Database connection = new Database();
Child child = null;
public List<Child> getChildDataByMotherId(String motherID) throws SQLException {
connection.openConnection();
List<Child> children = new ArrayList<Child>();
try{
ResultSet resultSet = connection.getData("SELECT * FROM childdetails WHERE MotherID=\'" + motherID + "\'");
while(resultSet.next()){
child = new Child();
System.out.println(resultSet.getString("FirstName"));
child.setChildId(resultSet.getString("ChildID"));//database column -->ChildID
child.setMotherId(resultSet.getString("MotherID"));
child.setFirstName(resultSet.getString("FirstName"));
child.setLastName(resultSet.getString("LastName"));
System.out.println(children);
children.add(child);
System.out.println(children);
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally{
connection.closeConnection();
}
return children;
}}

Related

javafx combobox checkbox multiselect filtered

I have looked days on any ready solution for the subject of having TOGETHER in javafx (pure) :
Combobox
Multiselect of items through Checkboxes
Filter items by the "editable" part of the Combobox
I have had no luck finding what I was looking for so I have now a working solution taken from different separate solution... Thank you to all for this !
Now I would like to know if what I have done follows the best practices or not... It's working... but is it "ugly" solution ? Or would that be a sort of base anyone could use ?
I tied to comment as much as I could, and also kept the basic comment of the sources :
user:2436221 (Jonatan Stenbacka) --> https://stackoverflow.com/a/34609439/14021197
user:5844477 (Sai Dandem) --> https://stackoverflow.com/a/52471561/14021197
Thank you for your opinions, and suggestions...
Here is the working example :
package application;
import com.sun.javafx.scene.control.skin.ComboBoxListViewSkin;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Callback;
#SuppressWarnings ("restriction") // Only applies for PROTECTD library : com.sun.javafx.scene.control.skin.ComboBoxListViewSkin
public class MultiSelectFiltered2 extends Application {
// These 2 next fields are used in order to keep the FILTERED TEXT entered by user.
private String aFilterText = "";
private boolean isUserChangeText = true;
public void start(Stage stage) {
Text txt = new Text(); // A place where to expose the result of checked items.
HBox vbxRoot = new HBox(); // A basic root to order the GUI
ComboBox<ChbxItems> cb = new ComboBox<ChbxItems>() {
// This part is needed in order to NOT have the list hided when an item is selected...
// TODO --> Seems a little ugly to me since this part is the PROTECTED part !
protected javafx.scene.control.Skin<?> createDefaultSkin() {
return new ComboBoxListViewSkin<ChbxItems>(this) {
#Override
protected boolean isHideOnClickEnabled() {
return false;
}
};
}
};
cb.setEditable(true);
// Create a list with some dummy values.
ObservableList<ChbxItems> items = FXCollections.observableArrayList();
items.add(new ChbxItems("One"));
items.add(new ChbxItems("Two"));
items.add(new ChbxItems("Three"));
items.add(new ChbxItems("Four"));
items.add(new ChbxItems("Five"));
items.add(new ChbxItems("Six"));
items.add(new ChbxItems("Seven"));
items.add(new ChbxItems("Eight"));
items.add(new ChbxItems("Nine"));
items.add(new ChbxItems("Ten"));
// Create a FilteredList wrapping the ObservableList.
FilteredList<ChbxItems> filteredItems = new FilteredList<ChbxItems>(items, p -> true);
// Add a listener to the textProperty of the combo box editor. The
// listener will simply filter the list every time the input is changed
// as long as the user hasn't selected an item in the list.
cb.getEditor().textProperty().addListener((obs, oldValue, newValue) -> {
// This needs to run on the GUI thread to avoid the error described here:
// https://bugs.openjdk.java.net/browse/JDK-8081700.
Platform.runLater(() -> {
if (isUserChangeText) {
aFilterText = cb.getEditor().getText();
}
// If the no item in the list is selected or the selected item
// isn't equal to the current input, we re-filter the list.
filteredItems.setPredicate(item -> {
boolean isPartOfFilter = true;
// We return true for any items that starts with the
// same letters as the input. We use toUpperCase to
// avoid case sensitivity.
if (!item.getText().toUpperCase().startsWith(newValue.toUpperCase())) {
isPartOfFilter = false;
}
return isPartOfFilter;
});
isUserChangeText = true;
});
});
cb.setCellFactory(new Callback<ListView<ChbxItems>, ListCell<ChbxItems>>() {
#Override
public ListCell<ChbxItems> call(ListView<ChbxItems> param) {
return new ListCell<ChbxItems>() {
private CheckBox chbx = new CheckBox();
// This 'just open bracket' opens the newly CheckBox Class specifics
{
chbx.setOnAction(new EventHandler<ActionEvent>() {
// This VERY IMPORTANT part will effectively set the ChbxItems item
// The argument is never used, thus left as 'arg0'
#Override
public void handle(ActionEvent arg0) {
// This is where the usual update of the check box refreshes the editor' text of the parent combo box... we want to avoid this ;-)
isUserChangeText = false;
// The one line without which your check boxes are going to be checked depending on the position in the list... which changes when the list gets filtered.
getListView().getSelectionModel().select(getItem());
// Updating the exposed text from the list of checked items... This is added here to have a 'live' update.
txt.setText(updateListOfValuesChosen(items));
}
});
}
private BooleanProperty booleanProperty; //Will be used for binding... explained bellow.
#Override
protected void updateItem(ChbxItems item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
// Binding is used in order to link the checking (selecting) of the item, with the actual 'isSelected' field of the ChbxItems object.
if (booleanProperty != null) {
chbx.selectedProperty().unbindBidirectional(booleanProperty);
}
booleanProperty = item.isSelectedProperty();
chbx.selectedProperty().bindBidirectional(booleanProperty);
// This is the usual part for the look of the cell
setGraphic(chbx);
setText(item.getText() + "");
} else {
// Look of the cell, which has to be "reseted" if no item is attached (empty is true).
setGraphic(null);
setText("");
}
// Setting the 'editable' part of the combo box to what the USER wanted
// --> When 'onAction' of the check box, the 'behind the scene' update will refresh the combo box editor with the selected object reference otherwise.
cb.getEditor().setText(aFilterText);
cb.getEditor().positionCaret(aFilterText.length());
}
};
}
});
// Yes, it's the filtered items we want to show in the combo box...
// ...but we want to run through the original items to find out if they are checked or not.
cb.setItems(filteredItems);
// Some basic cosmetics
vbxRoot.setSpacing(15);
vbxRoot.setPadding(new Insets(25));
vbxRoot.setAlignment(Pos.TOP_LEFT);
// Adding the visual children to root VBOX
vbxRoot.getChildren().addAll(txt, cb);
// Ordinary Scene & Stage settings and initialization
Scene scene = new Scene(vbxRoot);
stage.setScene(scene);
stage.show();
}
// Just a method to expose the list of items checked...
// This is the result that will be probably the input for following code.
// -->
// If the class ChbxItems had a custom object rather than 'text' field,
// the resulting checked items from here could be a list of these custom objects --> VERY USEFUL
private String updateListOfValuesChosen(ObservableList<ChbxItems> items) {
StringBuilder sb = new StringBuilder();
items.stream().filter(ChbxItems::getIsSelected).forEach(cbitem -> {
sb.append(cbitem.getText()).append("\n");
});
return sb.toString();
}
// The CHECKBOX object, with 2 fields :
// - The boolean part (checked ot not)
// - The text part which is shown --> Could be a custom object with 'toString()' overridden ;-)
class ChbxItems {
private SimpleStringProperty text = new SimpleStringProperty();
private BooleanProperty isSelected = new SimpleBooleanProperty();
public ChbxItems(String sText) {
setText(sText);
}
public void setText(String text) {
this.text.set(text);
}
public String getText() {
return text.get();
}
public SimpleStringProperty textProperty() {
return text;
}
public void setIsSelected(boolean isSelected) {
this.isSelected.set(isSelected);
}
public boolean getIsSelected() {
return isSelected.get();
}
public BooleanProperty isSelectedProperty() {
return isSelected;
}
}
public static void main(String[] args) {
launch();
}
}

Populating the combobox from database

I want to build a ComboBox that is populated with data from database but it's not working.The Scene Builder is fine i made the fxid:comboBoxx and onAction:fillComboBox2 and its running,but i dont have any data,just blank.I dont know where is the problem,i tried everything i know.
public class FXMLController implements Initializable {
#FXML
private ComboBox comboBoxx;
final ObservableList options = FXCollections.observableArrayList();
public void initialize(URL url, ResourceBundle rb) {
}
public void fillComboBox2() {
String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=TestDB;integratedSecurity=true;";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(connectionUrl);
String query = "select artikulli from product_table";
PreparedStatement statement = con.prepareStatement(query);
ResultSet set = statement.executeQuery();
while(set.next()){
options.add(set.getString("artikulli"));
}
statement .close();
set.close();
} catch(ClassNotFoundException | SQLException ex) {
Logger.getLogger(JavaFXExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
There are a couple of things to address here. First of all, you are never actually telling your ComboBox where to find the data it's meant to display.
This is done using the comboBoxx.setItems() method. This is easy to do within the controller's initialize() method.
Also, you stated that you set the onAction property of the ComboBox to your fillComboBox2() method. This is not correct. Doing so will cause the fillComboBox2() method to be called every time you click on the dropdown for the ComboBox.
Instead, you should fill the ComboBox when loading the scene. So, remove the onAction definition from your FXML document.
Lastly, it would be a good idea to change that method entirely. In my updated code below, you'll see that I've changed it to a private method that returns a List<String>. We can use that List to populate the ComboBox.
Now, when the scene is being loaded, the comboBoxx.setItems() method is called, and the List<String> from the getData() method is used to populate it.
The code below also has some comments to help explain the flow.
THE CODE
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FXMLController {
// If you ComboBox is going to display Strings, you should define that datatype here
#FXML
private ComboBox<String> comboBoxx;
#FXML
private void initialize() {
// Within this initialize method, you can initialize the data for the ComboBox. I have changed the
// method from fillComboBox2() to getData(), which returns a List of Strings.
// We need to set the ComboBox to use that list.
comboBoxx.setItems(FXCollections.observableArrayList(getData()));
}
/**
* Here we will define the method that builds the List used by the ComboBox
*/
private List<String> getData() {
String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=TestDB;integratedSecurity=true;";
// Define the data you will be returning, in this case, a List of Strings for the ComboBox
List<String> options = new ArrayList<>();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(connectionUrl);
String query = "select artikulli from product_table";
PreparedStatement statement = con.prepareStatement(query);
ResultSet set = statement.executeQuery();
while (set.next()) {
options.add(set.getString("artikulli"));
}
statement.close();
set.close();
// Return the List
return options;
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
}

Javafx: Clearing a ResultSet for SQLite query so it won't keep previous results

I am taking the selected value in combobox 1 and using running a SQLite query based on that selection to populate combobox 2 using a result set. The query is fine but as it's the same resultset it keeps previous entries in the resultset.
Is there a way to clear the resultset each time to not pull through data I don't want?
Controller Class
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class UpdateInventoryController implements Initializable {
#FXML ComboBox brandOne;
#FXML ComboBox flavourOne;
String brandsInInventory;
String flavoursInInventory;
String selectedBrand = "";
private static Connection con;
#Override
public void initialize(URL location, ResourceBundle resources) {
populateBrandCombos();
brandOne.getSelectionModel().selectedItemProperty().addListener( (options, oldValue, newValue) -> {
selectedBrand = String.valueOf(newValue);
if (selectedBrand != "") {
populateFlavourCombos();
}
}
);
}
public void populateBrandCombos() {
try {
con = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\PengStation420\\IdeaProjects\\PengVapour\\PVIM.sqlite");
ResultSet rs = con.createStatement().executeQuery("SELECT " +
"DISTINCT Brand " +
"FROM Concentrates");
while (rs.next()) {
brandsInInventory = rs.getString("Brand");
brandOne.getItems().addAll(brandsInInventory);
brandTwo.getItems().addAll(brandsInInventory);
brandThree.getItems().addAll(brandsInInventory);
brandFour.getItems().addAll(brandsInInventory);
brandFive.getItems().addAll(brandsInInventory);
brandSix.getItems().addAll(brandsInInventory);
}
} catch (SQLException ex) {
Logger.getLogger(InventoryController.class.getName()).log(Level.SEVERE, null, ex);
}
}
#FXML
public void populateFlavourCombos() {
selectedBrand = brandOne.valueProperty().getValue().toString();
try {
con = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\PengStation420\\IdeaProjects\\PengVapour\\PVIM.sqlite");
ResultSet rs = stmt.executeQuery("SELECT " +
"DISTINCT Flavour " +
"FROM Concentrates " +
"WHERE Concentrates.Brand " +
"LIKE '%" + selectedBrand + "%'");
int rows = 0;
while (rs.next()) {
flavoursInInventory = rs.getString("Flavour");
flavourOne.getItems().addAll(flavoursInInventory);
rows++;
}
flavourOne.setVisibleRowCount(rows); // set new visibleRowCount value
} catch (SQLException ex) {
Logger.getLogger(InventoryController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Example Result:
Action 1: ComboBox 1 selection 1 pulls through 2 results. ComboBox 2 displays 2 reuslts.
Action 2: ComboBox 2 selection 2 pulls through 3 results. ComboBox displays Action 1 results and Action 2 results.
Desired result:
Action 1: ComboBox 1 selection 1 pulls through 2 results. ComboBox 2 displays 2 reuslts.
Action 2: ComboBox 2 selection 2 pulls through 3 results. ComboBox displays 3 results.
The results you are seeing happen because you never remove any items from the ComboBox.
You should clear the ComboBox each time to achieve this functionality.
Something similar to
flavourOne.getItems().clear();
This will remove all previous entries, and keep your basic functionality with flavourOne.getItems().add...

Alert in JAVA FX

I want to display an alert when a file already exists when trying to create the file with same name . I have not completed the code fully. I want to retrieve the button value Yes/No from the UI .
Code:
This is how the controller is coded.
package application;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
public class WarningController implements Initializable {
#FXML
public Button yes;
#FXML
public Button no;
public static String type;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
// TODO Auto-generated method stub
}
public String confirmSelection(ActionEvent event)throws IOException{
Button button = (Button) event.getSource();
type = button.getText();
if(type.equals("Yes")){
Stage stage = (Stage) yes.getScene().getWindow();
stage.close();
//System.out.println("Yes");
return type;
}
else{
//System.out.println("No");
Stage stage1 = (Stage) no.getScene().getWindow();
stage1.close();
return type;
}
}
/********************************************************************************/
public void writesheet(String[][] result,String ComboValue,String[] heading) throws IOException{
//Create blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet spreadsheet = workbook.createSheet( " Employee Info ");
//Create row object
XSSFRow row;
String[][] towrite=result;
int rows=towrite.length;
//int cols=towrite[0].length;
// System.out.println(rows +" "+ cols);
Map < String, Object[] > empinfo = new TreeMap < String, Object[] >();
empinfo.put("0", heading);
for(int i=1;i<=rows;i++){
empinfo.put( Integer.toString(i),towrite[i-1]);
}
//Iterate over data and write to sheet
Set < String > keyid = empinfo.keySet();
int rowid = 0;
for (String key : keyid)
{
row = spreadsheet.createRow(rowid++);
Object [] objectArr = empinfo.get(key);
int cellid = 0;
for (Object obj : objectArr)
{
Cell cell = row.createCell(cellid++);
//cell.setCellValue((String)obj);
cell.setCellValue(obj.toString());
}
}
//Write the workbook in file system
File f=new File(("C:\\"+ComboValue+".xlsx"));
if(f.exists()){
Stage primaryStage=new Stage();
Parent root=FXMLLoader.load(getClass().getResource("/application/Warning.fxml"));
Scene scene = new Scene(root,350,150);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
System.out.println(type);
}
FileOutputStream out = new FileOutputStream(f);
workbook.write(out);
out.close();
System.out.println(ComboValue+" "+"Excel document written successfully" );
workbook.close();
}
}
I want to use button value(stored in String type) in writesheet function. Now it is returning NULL.
Please suggest if there is any other way to show warning.I am using two fxml files and this is the second excel file.
[1]: http://i.stack.imgur.com/ZK6UC.jpg
Simply use the Alert class. It provides functionality for most yes/no dialogs that you ever need.
Alert alert = new Alert(AlertType.WARNING,
"File already exists. Do you want to override?",
ButtonType.YES, ButtonType.NO);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.YES){
// ... user chose YES
} else {
// ... user chose NO or closed the dialog
}
Also here is a good tutorial.
I usually make a method, and call it if certain conditions are not met.
Ex:
if(condition)
alert();
public void alert(){ //alert box
Alert alert = new Alert(AlertType.WARNING,"", ButtonType.YES, ButtonType.NO); //new alert object
alert.setTitle("Warning!"); //warning box title
alert.setHeaderText("WARNING!!!");// Header
alert.setContentText("File already exists. Overwrite?"); //Discription of warning
alert.getDialogPane().setPrefSize(200, 100); //sets size of alert box
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.YES){
// ... user chose YES
} else {
// ... user chose NO or closed the dialog
}
}
I grabbed some code from Jhonny007, credit to him.

importing error with import javax.imageio.ImageIO;

I am new to Java and are trying to display an image. I got code on the net but when trying it I get an error with the importing of " import javax.imageio.ImageIO;" The error message reads "javax.imageio.ImageIO" is either a misplace package name or a non-existing entity.
I have seen this on many samples but it does not work with me.
Is there any advice
mport java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Showmap extends Panel
{
BufferedImage img;
public Showmap ()
{
try
{
image = ImageIO.read (new File ("KNP.jpg"));
}
/*
catch (IOException e)
{
BufferedImage image;
public ShowImage() {
try {
System.out.println("Enter image name\n");
BufferedReader bf=new BufferedReader(new
InputStreamReader(System.in));
String imageName=bf.readLine();
File input = new File(imageName);
image = ImageIO.read(input);
}*/
catch (IOException e)
{
System.out.println ("Error:" + e.getMessage ());
}
}
public void paint (Graphics g)
{
g.drawImage (image, 0, 0, null);
}
static public void main (String args []) throws
Exception
{
JFrame frame = new JFrame ("Display image");
Panel panel = new Showmap ();
frame.getContentPane ().add (panel);
frame.setSize (500, 500);
frame.setVisible (true);
}
}
Thanks
Ivan
In your Project select:
Right Click on "JRE System Libary"
Select Properties
On Execution Enviroment select "J2SE-1.5(jre8)" or later; you should use the latest version of jre8
I was programming with "Ready to Program" and tried many options with out success. When I copied the same code to "JCreator" and run it fro there it was working fine. Seems "import javax.imageio.ImageIO;" is not working with "Ready to Program".

Resources