WARNING Possible use of "Transverse_Mercator" projection outside its valid area - java

I am trying to combign tiff image and shapefile and want show it. For this, I am using GeoTiff and I am stuck that my tiff file is now being displayed. Shapefile is showing properly but tiff image, which is having only 1 band and grey scale index, is not being shown because of some reason. I am getting one warning message as below.
2016-08-04T12:43:06.456+0530 WARNING Possible use of "Transverse_Mercator" projection outside its valid area.
Latitude 180°00.0'S is out of range (±90°).
How can I remove this message?
My code is as below
private void displayLayers() throws Exception {
AbstractGridFormat format = GridFormatFinder.findFormat(this.getBlueMarble());
this.setGridCoverageReader(format.getReader(this.getBlueMarble()));
Style rgbStyle = this.createRGBStyle();
// connect to the shapefile
FileDataStore dataStore = FileDataStoreFinder.getDataStore(this.getBorderShape());
SimpleFeatureSource shapefileSource = dataStore.getFeatureSource();
Style shpStyle = SLD.createPolygonStyle(Color.BLUE, null, 0.0f);
MapContent map = new MapContent();
map.getViewport().setCoordinateReferenceSystem(
DefaultGeographicCRS.WGS84);
map.setTitle("Illegal Mining");
Layer rasterLayer = new GridReaderLayer(this.getGridCoverageReader(), rgbStyle);
map.addLayer(rasterLayer);
Layer shpLayer = new FeatureLayer(shapefileSource, shpStyle);
map.addLayer(shpLayer);
System.out.println("Trying to show on map...");
JMapPane mapPane = new JMapPane();
mapPane.setMapContent(map);
mapPane.setDisplayArea(shapefileSource.getBounds());
//mapPane.setDisplayArea(this.getGridCoverageReader().getOriginalEnvelope());
this.add(mapPane, BorderLayout.CENTER);
}
private Style createRGBStyle() {
GridCoverage2DReader reader = this.getGridCoverageReader();
StyleFactory sf = this.getStyleFactory();
GridCoverage2D cov = null;
try {
cov = reader.read(null);
} catch (IOException giveUp) {
throw new RuntimeException(giveUp);
}
// We need at least three bands to create an RGB style
int numBands = cov.getNumSampleDimensions();
System.out.println("numBands:"+numBands);
if (numBands < 3) {
System.out.println("Bands are less than 3");
//return null;
}
// Get the names of the bands
String[] sampleDimensionNames = new String[numBands];
for (int i = 0; i < numBands; i++) {
GridSampleDimension dim = cov.getSampleDimension(i);
sampleDimensionNames[i] = dim.getDescription().toString();
}
final int RED = 0, GREEN = 1, BLUE = 2;
int[] channelNum = { -1, -1, -1 };
Boolean greyflag=false;
// We examine the band names looking for "red...", "green...",
// "blue...".
// Note that the channel numbers we record are indexed from 1, not 0.
for (int i = 0; i < numBands; i++) {
String name = sampleDimensionNames[i].toLowerCase();
System.out.println("name :"+name);
if (name != null) {
if (name.matches("red.*")) {
channelNum[RED] = i + 1;
} else if (name.matches("green.*")) {
channelNum[GREEN] = i + 1;
} else if (name.matches("blue.*")) {
channelNum[BLUE] = i + 1;
}else if(name.matches("gray.*")){
System.out.println("What to do here");
channelNum[RED] = 1;
channelNum[GREEN] = 2;
channelNum[BLUE] = 3;
greyflag=true;
}
}
}
// If we didn't find named bands "red...", "green...", "blue..."
// we fall back to using the first three bands in order
if(greyflag==false){
if (channelNum[RED] < 0 || channelNum[GREEN] < 0
|| channelNum[BLUE] < 0) {
channelNum[RED] = 1;
channelNum[GREEN] = 2;
channelNum[BLUE] = 3;
}
}
// Now we create a RasterSymbolizer using the selected channels
SelectedChannelType[] sct = new SelectedChannelType[cov
.getNumSampleDimensions()];
ContrastEnhancement ce = sf.contrastEnhancement(this.ff.literal(1.0),
ContrastMethod.NORMALIZE);
for (int i = 0; i < numBands; i++) {
sct[i] = sf.createSelectedChannelType(
String.valueOf(channelNum[i]), ce);
System.out.println(String.valueOf(channelNum[i]));
}
RasterSymbolizer sym = sf.getDefaultRasterSymbolizer();
ChannelSelection sel =sf.channelSelection(sct[RED]);
if(numBands>1){
sel = sf.channelSelection(sct[RED], sct[GREEN],
sct[BLUE]);
}
sym.setChannelSelection(sel);
return SLD.wrapSymbolizers(sym);
}
I just pass two files as below code
public MapImagePanel() {
this.setLayout(new BorderLayout(0, 0));
this.setBackground(Color.BLUE);
this.setPreferredSize(new Dimension(720, 360));
this.setBlueMarble(new File("E:/tifffilename.TIFF"));
this.setBorderShape(new File("E:/shapefilename.shp"));
try {
this.displayLayers();
} catch (Exception e) {
e.printStackTrace();
}
}
This is how i use this class in main class
//see output in main method
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MapImagePanel panel = new MapImagePanel();
panel.setPreferredSize(new Dimension(1024,768));
panel.setVisible(true);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
frame.show();

TLDR; add the following line to your program start up:
System.setProperty("org.geotools.referencing.forceXY", "true");
From GeoTools FAQ as computer programmers they knew that coordinates would be expressed as longitude,latitude pairs so they could use existing graphics code easily by treating them as a simple (x,y) pair. but for sequence like (x,y) or (y,x) they confused that is why this error is coming.

Related

How do you properly use PDPageContentStream::setTextRise?

Using PDFBox, given data notated like this: [G]Glory be to [D]God [Em]the [C]Father,\n[G]And to [A]Christ the [D]Son,, I am creating a guitar chord sheet like this:
My approach was to iterate through each character in the song and check the current index against the map.. whenever the map has an entry to that character index, we "jump" to the line above, write the chord, then jump back down.
The method setTextRise looked promising, but still processes the horizontal spacing incorrectly:
Here's an SSCCE (needs PDFBox libraries) that produces the PDF above:
public static void main(String[] args) {
try {
String extracted_text = "Capo 1\n\n1\n[G]Glory be to [D]God [Em]the [C]Father,\n[G]And to [A]Christ the [D]Son,\n[B7]Glory to the [Em]Holy [C]Spirit—\n[D-D7]Ever [ G]One.\n\n2\nAs we view the vast creation,\nPlanned with wondrous skill,\nSo our hearts would move to worship,\nAnd be still.\n\n3\nBut, our God, how great Thy yearning\nTo have sons who love\nIn the Son e’en now to praise Thee,\nLove to prove!\n\n4\n’Twas Thy thought in revelation,\nTo present to men\nSecrets of Thine own affections,\nTheirs to win.\n\n5\nSo in Christ, through His redemption\n(Vanquished evil powers!)\nThou hast brought, in new creation,\nWorshippers!\n\n6\nGlory be to God the Father,\nAnd to Christ the Son,\nGlory to the Holy Spirit—\nEver One.\n".replaceAll("\n", "\r");
String[] lines = extracted_text.split("\\r");
ArrayList<SongLine> songlines = new ArrayList<>();
for(String s : lines) {
LinkedHashMap<Integer, String> chords = new LinkedHashMap();
StringBuilder line = new StringBuilder();
StringBuilder currentchord = null;
int index = 0;
for(char c : s.toCharArray()) {
if(currentchord != null) {
if(c == ']') {
chords.put(index, currentchord.toString());
currentchord = null;
} else {
currentchord.append(c);
}
} else {
if(c == '[') {
currentchord = new StringBuilder();
} else {
line.append(c);
index++;
}
}
}
SongLine sl = new SongLine();
if(chords.size() > 0)
sl.char_index_to_chords = chords;
sl.line = line.toString();
songlines.add(sl);
}
try (PDDocument doc = new PDDocument()) {
PDPage page = new PDPage();
PDPageContentStream pcs = new PDPageContentStream(doc, page);
int firstLineX = 25;
int firstLineY = 700;
boolean first = true;
float leading = 14.5f;
pcs.beginText();
pcs.newLineAtOffset(firstLineX, firstLineY);
pcs.setFont(PDType1Font.TIMES_ROMAN, 12);
pcs.setLeading(leading);
for(SongLine line : songlines) {
if(line.char_index_to_chords != null)
System.out.println(line.char_index_to_chords.toString());
System.out.println(line.line);
if(!first) {
pcs.newLine();
}
first = false;
if(line.char_index_to_chords != null) {
pcs.newLine();
}
for(int i = 0; i < line.line.length(); i++) {
pcs.showText(String.valueOf(line.line.charAt(i)));
if(line.char_index_to_chords != null && line.char_index_to_chords.containsKey(i)) {
pcs.setTextRise(12);
pcs.showText(line.char_index_to_chords.get(i));
pcs.setTextRise(0);
}
}
}
pcs.endText();
pcs.close();
doc.addPage(page);
String path = "0001.pdf";
doc.save(path);
Desktop.getDesktop().open(new File(path));
}
} catch (Exception e) {
e.printStackTrace();
}
}
static class SongLine {
Map<Integer, String> char_index_to_chords;
String line;
}
What would you do in PDFBox to create the text aligned with chords (like in the first image)?
I got it. The answer was not setTextRise, rather newLineAtOffset while using getStringWidth to calculate font size:
for(SongLine line : songlines) {
if(!first) {
pcs.newLine();
}
first = false;
if(line.char_index_to_chords != null) {
float offset = 0;
for(Entry<Integer, String> entry : line.char_index_to_chords.entrySet()) {
float offsetX = font.getStringWidth(line.char_index_to_leading_lyrics.get(entry.getKey())) / (float)1000 * fontSize;
pcs.newLineAtOffset(offsetX, 0);
offset += offsetX;
pcs.showText(entry.getValue());
}
pcs.newLineAtOffset(-offset, -leading);
}
pcs.showText(line.line);
}

rsps where to find background image

I am developing an rsps and cant seem to find where to find the background image
i found the loading screen but cant find the background image any ideas on what to search?
loading screen code
try {
for (int i = 1; i <= 3; i++) {
if (!new File(signlink.findcachedir() + "load" + i + ".png").exists()) {
String url = "";
switch (i) {
case 1:
url = "http://Morytania.org/load1.png";
break;
case 2:
url = "http://Morytania.org/load2.png";
break;
case 3:
url = "http://Morytania.org/load3.png";
break;
}
HttpDownloadUtility.downloadFile(url, signlink.findcachedir());
}
loadingSprites[i - 1] = Toolkit.getDefaultToolkit()
.getImage(signlink.findcachedir() + "load" + i + ".png");
}
super.graphics.drawImage(loadingSprites[0], 0, 0, null);
super.graphics.drawImage(loadingSprites[1], 5, clientHeight - 35, null);
} catch (Exception e) {
e.printStackTrace();
}
It would appear that you're using revision 317 of the RuneScape client. In the older versions of the engine, such as the one you're using, the background is, by default, loaded from the game cache.
Inside of archive 0, there is a file labelled "title". Inside of that file, you may find the actual background ("title.dat") as the login box ("titlebox.dat") and buttons ("titlebutton.dat"). These files are simply JPEG images.
The background itself is stored as a 383x503 image that is then mirrored in-engine to create the full image. See createTitleBackground(). An excerpt of the code can be found below.
public void createTitleBackground() throws IOException {
Image24 image = new Image24(archiveTitle.read("title.dat"), this);
...
// Flips the title background horizontally
int[] tmp = new int[image.width];
for (int y = 0; y < image.height; y++) {
for (int x = 0; x < image.width; x++) {
tmp[x] = image.pixels[(image.width - x - 1) + (image.width * y)];
}
System.arraycopy(tmp, 0, image.pixels, image.width * y, image.width);
}
...
}
The code above is then called in the load() method:
archiveTitle = loadArchive(1, "title screen", "title", archiveChecksum[1], 25);
fontPlain11 = new BitmapFont(archiveTitle, "p11_full", false);
fontPlain12 = new BitmapFont(archiveTitle, "p12_full", false);
fontBold12 = new BitmapFont(archiveTitle, "b12_full", false);
fontQuill8 = new BitmapFont(archiveTitle, "q8_full", true);
createTitleBackground();
createTitleImages();

How to use androd Maps Bounds which adapts with Bottom Sheet

In my project I have a method that draws a route inside of map and create a bounds for this route, the problem is, I need to create this bounds with the bottom sheet and not the entire screen!
First I open the Bottom Sheet:
private void openBottom(){
if(latLngs != null){
if(bottomSheetBehavior.getState() != BottomSheetBehavior.STATE_EXPANDED){
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
bottomSheetBehavior.setPeekHeight(300);
}
}
}
And then Draw and the bounds!
private void drawnNewRoute() {
if(polyline == null){
LatLngBounds.Builder builder = new LatLngBounds.Builder();
po = new PolylineOptions();
for(int i = 0, tam = latLngs.size(); i < tam; i++){
po.add(latLngs.get(i));
builder.include(latLngs.get(i));
}
String data = new Gson().toJson(latLngs);
po.color(Color.BLACK).width(10);
polyline = mMap.addPolyline(po);
ArrayList<LatLng> latlang = new ArrayList<>();
latlang.add(latLngs.get(0));
latlang.add(latLngs.get(latLngs.size() -1));
mMarkerNewPosition = mMap.addMarker(new MarkerOptions().position(finalLocaltion).title(finalLocationName));
mMarkerNewPosition.showInfoWindow();
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 120));
location_display_incl.setVisibility(View.GONE);
stopLocation();
InicialAddressTxt.setText(InicialAddress);
double finalLat = latLngs.get(latLngs.size() -1).latitude;
double finalLong = latLngs.get(latLngs.size() -1).longitude;
try {
ADRS = getAddress(finalLat,finalLong);
} catch (IOException e) {
e.printStackTrace();
}
FinalAddressTxt.setText(finalLocationName);
String finalComp = ADRS.getLocality() + "," + address.getAdminArea();
FinalComplement.setText(finalComp);
//zoomToCoverAllMarkersInMap(latlang);
}
else{
polyline.setPoints(latLngs);
}
}
But it keeps getting the whole screen and not just the "available" part of it!

JSwing, how do I make a Jtable render prior to starting another action?

I've got and action listener for my buttons on a normal Jpanel, when I click the button its supposed to bring up a contact window, and then send each of them a text 1 by 1. It brings up a window and stays blank until after the text messages have been sent out, even though here in my action listener it clearly requires the window to be brought up first.
else if (ae.getActionCommand() == "Initiate Recall") {
int doneCheck = 0;
if (doneCheck == 0){
oh.ViewAllMembers();
doneCheck = 1;
}
if (doneCheck == 1){
try {
oh.doRecall();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here is my do Recall Method
public void doRecall() throws Exception {
String customMessage = getMessage();
boolean programOpen = true;
Member con = new Member();
Object data[][] = new Object[v.size()][8];
k = 0;
for (int j = 0; j < v.size(); j++) {
con = (Member) v.elementAt(k);
data[j][0] = con.getFName();
data[j][1] = con.getLName();
data[j][2] = con.getNname();
data[j][3] = con.getEMail();
data[j][4] = con.getAddress();
data[j][5] = con.getPhoneNo();
data[j][6] = con.getresponse();
data[j][7] = con.getBday();
try {
String myPasscode = "*******";
String myUsername = "*******";
String toPhoneNumber = con.getPhoneNo();
customMessage = customMessage.replaceAll("\\s+", "+");
System.out.println(customMessage);
String requestUrl = ("http://cloud.fowiz.com/api/message_http_api.php?username=******&phonenumber=+"
+ toPhoneNumber + "&message=" + customMessage + "&passcode=******");
URL url = new URL(requestUrl);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
System.out.println(uc.getResponseMessage());
String reply = uc.getResponseMessage();
if (reply.equalsIgnoreCase("ok")) {
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
k++;
}
k = 0;
for (int j = 0; j < v.size(); j++) {
con = (Member) v.elementAt(k);
boolean phoneCheck = false;
while (phoneCheck != true) {
mR2 = new MailReader();
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username = "*********#gmail.com";// change
// accordingly
String password = "*******";// change accordingly
MailReader.check(host, mailStoreType, username, password);
if (MailReader.searchForPhone(con.getPhoneNo()) == true) {
System.out.println("IT WORKED");
phoneCheck = true;
}
}
}
}
and here is my view contact method
public void ViewAllMembers() {
newFrame = new JFrame("All Members In The Roster");
newFrame.setSize(600, 300);
newFrame.setIconImage(img);
Member con = new Member();
String columnNames[] = { "First Name", "Last Name", "Nickname",
"E Mail Address", "Address", "Phone No.", "response", "B'day" };
Object data[][] = new Object[v.size()][8];
for (int j = 0; j < v.size(); j++) {
con = (Member) v.elementAt(k);
data[j][0] = con.getFName();
data[j][1] = con.getLName();
data[j][2] = con.getNname();
data[j][3] = con.getEMail();
data[j][4] = con.getAddress();
data[j][5] = con.getPhoneNo();
data[j][6] = con.getresponse();
data[j][7] = con.getBday();
k++;
}
k = 0;
JTable abtable = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane(abtable);
abtable.setPreferredScrollableViewportSize(new Dimension(500, 370));
JPanel pane = new JPanel();
JLabel label = new JLabel("Members Currently In The Recall Roster");
pane.add(label);
newFrame.getContentPane().add(pane, BorderLayout.SOUTH);
newFrame.getContentPane().add(scrollPane, BorderLayout.CENTER);
newFrame.setLocation(screenWidth / 4, screenHeight / 4);
newFrame.show();
}
Problems:
else if (ae.getActionCommand() == "Initiate Recall") {
Don't use == to compare Strings. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of
if (fu == "bar") {
// do something
}
do,
if ("bar".equals(fu)) {
// do something
}
or,
if ("bar".equalsIgnoreCase(fu)) {
// do something
}
Next:
int doneCheck = 0;
if (doneCheck == 0){
oh.ViewAllMembers();
I'm guessing this is a long running bit of code -- you never tell us what this does (??). If so, it's putting your complete Swing GUI to sleep making it unresponsive. perhaps it needs to run on a background thread.
doneCheck = 1;
}
if (doneCheck == 1){
try {
oh.doRecall();
}
Does oh.doRecall() show your JTable? If so, or if not, you're not explaining your code well to us but seem to be assuming that we can understand code and concepts not shown. Reality check: we can't.
Edit
Your doRecall() code should be called in a background thread, such as with a SwingWorker (Google Concurrency in Swing), because it is tying up the Swing event thread, preventing your other code from showing. This is your major problem, and the tutorial will help you learn how to fix it.
You seem to be showing multiple JFrames, a common Swing newbie mistake that you'll want to fix. If you need to show a dependent window, show a dialog such as a JDialog, or don't show a sub window and swap views with a CardLayout.
Again, don't use == to compare Strings.
Don't call deprecated methods such as JFrame#show(). They're deprecated for a reason, and the Java API will tell you about the alternatives that you should use.
Something like....
if ("Initiate Recall".equalsIgnoreCase(ae.getActionCommand())) {
// viewAllMembers method name should begin with a lower-case letter
oh.viewAllMembers();
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
oh.doRecall();
return null;
}
#Override
protected void done() {
try {
get();
} catch (InterruptedException | ExecutionException e) {
// do something with any exceptions here
e.printStackTrace();
}
}
};
worker.execute();
}

Change java applet to java application

I have an applet that runs a GUI. I want to call this GUI from my other program. I know that I need to turn this applet into an application. I have an init() and a actionPerformed(ActionEvent ae). How can I do it?
My code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class survey extends Applet implements ActionListener
{
private TextField question;
private Button enter, start;
int count = 0;
int a = 0;
int b = 0;
int c = 0;
int d = 0;
String text, input;
private Label intro1, intro2, intro3;
private Label qone1, qone2, qone3, qone4, qone5, qone6, qone7, qone8, qone9, qone10, qone11, qone12;
private Label qtwo1, qtwo2, qtwo3, qtwo4, qtwo5, qtwo6, qtwo7, qtwo8, qtwo9, qtwo10, qtwo11, qtwo12;
private Label qthree1, qthree2, qthree3, qthree4, qthree5, qthree6, qthree7, qthree8, qthree9, qthree10, qthree11, qthree12;
private Label qfour1, qfour2, qfour3, qfour4, qfour5, qfour6, qfour7, qfour8, qfour9, qfour10, qfour11, qfour12;
private Label qfive1, qfive2, qfive3, qfive4, qfive5, qfive6, qfive7, qfive8, qfive9, qfive10, qfive11, qfive12;
private Label qsix1, qsix2, qsix3, qsix4, qsix5, qsix6, qsix7, qsix8, qsix9, qsix10, qsix11, qsix12;
private Label qseven1, qseven2, qseven3, qseven4, qseven5, qseven6, qseven7, qseven8, qseven9, qseven10, qseven11, qseven12;
private Label qeight1, qeight2, qeight3, qeight4, qeight5, qeight6, qeight7, qeight8, qeight9, qeight10, qeight11, qeight12;
private Label qnine1, qnine2, qnine3, qnine4, qnine5, qnine6, qnine7, qnine8, qnine9, qnine10, qnine11, qnine12;
private Label qten1, qten2, qten3, qten4, qten5, qten6, qten7, qten8, qten9, qten10, qten11, qten12;
private Label qeleven1, qeleven2, qeleven3, qeleven4, qeleven5, qeleven6,
private Label finish1, finish2, finish3;
public void init()
{
setLayout(null);
start = new Button ("Start");
question = new TextField(10);
enter = new Button ("Enter");
if (count == 0)
{
setBackground( Color.yellow);
intro1 = new Label("Target Advertising", Label.CENTER);
intro1.setFont(new Font("Times-Roman", Font.BOLD, 16));
intro2 = new Label("Welcome to this questionnaire. First, we would like to know more about your personal preferences.");
intro3 = new Label("For each question, Input a rating between 0-9 (zero = least interested, 9 = most interested) in the text box. Click enter for next question.");
add(intro1);
add(intro2);
add(intro3);
intro1.setBounds(0,0,800,20);
intro2.setBounds(15,20,800,20);
intro3.setBounds(15,40,800,20);
add(start);
start.setBounds(370,60,70,23);
start.addActionListener(this);
}
if(count == 1)
{
setBackground( Color.yellow );
qone1 = new Label("Question 1", Label.LEFT);
qone1.setFont(new Font("Times-Roman", Font.BOLD, 16));
qone2 = new Label("How much do you like action movies?");
qone3 = new Label("0");
qone4 = new Label("1");
qone5 = new Label("2");
qone6 = new Label("3");
qone7 = new Label("4");
qone8 = new Label("5");
qone9 = new Label("6");
qone10 = new Label("7");
qone11 = new Label("8");
qone12 = new Label("9");
add(qone1);
add(qone2);
add(qone3);
add(qone4);
add(qone5);
add(qone6);
add(qone7);
add(qone8);
add(qone9);
add(qone10);
add(qone11);
add(qone12);
qone1.setBounds(15,0,800,20);
qone2.setBounds(15,20,800,15);
qone3.setBounds(15,60,800,15);
qone4.setBounds(15,80,800,15);
qone5.setBounds(15,100,800,15);
qone6.setBounds(15,120,800,15);
qone7.setBounds(15,140,800,15);
qone8.setBounds(15,160,800,15);
qone9.setBounds(15,180,800,15);
qone10.setBounds(15,200,800,15);
qone11.setBounds(15,220,800,15);
qone12.setBounds(15,240,800,15);
add(question);
add(enter);
question.setBounds(15,260,70,15);
enter.setBounds(90,260,110,23);
question.addActionListener(this);
enter.addActionListener(this);
}
if (count == 2)
{
qtwo1 = new Label("Question 2", Label.LEFT);
qtwo1.setFont(new Font("Times-Roman", Font.BOLD, 16));
qtwo2 = new Label("How much do you like Science Fiction?");
qtwo3 = new Label("0");
qtwo4 = new Label("1");
qtwo5 = new Label("2");
qtwo6 = new Label("3");
qtwo7 = new Label("4");
qtwo8 = new Label("5");
qtwo9 = new Label("6");
qtwo10 = new Label("7");
qtwo11 = new Label("8");
qtwo12 = new Label("9");
add(qtwo1);
add(qtwo2);
add(qtwo3);
add(qtwo4);
add(qtwo5);
add(qtwo6);
add(qtwo7);
add(qtwo8);
add(qtwo9);
add(qtwo10);
add(qtwo11);
add(qtwo12);
qtwo1.setBounds(15,0,800,20);
qtwo2.setBounds(15,20,800,15);
qtwo3.setBounds(15,60,800,15);
qtwo4.setBounds(15,80,800,15);
qtwo5.setBounds(15,100,800,15);
qtwo6.setBounds(15,120,800,15);
qtwo7.setBounds(15,140,800,15);
qtwo8.setBounds(15,160,800,15);
qtwo9.setBounds(15,180,800,15);
qtwo10.setBounds(15,200,800,15);
qtwo11.setBounds(15,220,800,15);
qtwo12.setBounds(15,240,800,15);
add(question);
add(enter);
question.setBounds(15,260,70,15);
enter.setBounds(90,260,110,23);
question.addActionListener(this);
enter.addActionListener(this);
}
if(count == 3)
{
qthree1 = new Label("Question 3", Label.LEFT);
qthree1.setFont(new Font("Times-Roman", Font.BOLD, 16));
qthree2 = new Label("How much do you like comedy?");
qthree3 = new Label("0");
qthree4 = new Label("1");
qthree5 = new Label("2");
qthree6 = new Label("3");
qthree7 = new Label("4");
qthree8 = new Label("5");
qthree9 = new Label("6");
qthree10 = new Label("7");
qthree11 = new Label("8");
qthree12 = new Label("9");
add(qthree1);
add(qthree2);
add(qthree3);
add(qthree4);
add(qthree5);
add(qthree6);
add(qthree7);
add(qthree8);
add(qthree9);
add(qthree10);
add(qthree11);
add(qthree12);
qthree1.setBounds(15,0,800,20);
qthree2.setBounds(15,20,800,15);
qthree3.setBounds(15,60,800,15);
qthree4.setBounds(15,80,800,15);
qthree5.setBounds(15,100,800,15);
qthree6.setBounds(15,120,800,15);
qthree7.setBounds(15,140,800,15);
qthree8.setBounds(15,160,800,15);
qthree9.setBounds(15,180,800,15);
qthree10.setBounds(15,200,800,15);
qthree11.setBounds(15,220,800,15);
qthree12.setBounds(15,240,800,15);
add(question);
add(enter);
question.setBounds(15,260,70,15);
enter.setBounds(90,260,110,23);
question.addActionListener(this);
enter.addActionListener(this);
}
if(count == 4)
{
qfour1 = new Label("Question 4", Label.LEFT);
qfour1.setFont(new Font("Times-Roman", Font.BOLD, 16));
qfour2 = new Label("How much do you like luxary cars?");
qfour3 = new Label("0");
qfour4 = new Label("1");
qfour5 = new Label("2");
qfour6 = new Label("3");
qfour7 = new Label("4");
qfour8 = new Label("5");
qfour9 = new Label("6");
qfour10 = new Label("7");
qfour11 = new Label("8");
qfour12 = new Label("9");
add(qfour1);
add(qfour2);
add(qfour3);
add(qfour4);
add(qfour5);
add(qfour6);
add(qfour7);
add(qfour8);
add(qfour9);
add(qfour10);
add(qfour11);
add(qfour12);
qfour1.setBounds(15,0,800,20);
qfour2.setBounds(15,20,800,15);
qfour3.setBounds(15,60,800,15);
qfour4.setBounds(15,80,800,15);
qfour5.setBounds(15,100,800,15);
qfour6.setBounds(15,120,800,15);
qfour7.setBounds(15,140,800,15);
qfour8.setBounds(15,160,800,15);
qfour9.setBounds(15,180,800,15);
qfour10.setBounds(15,200,800,15);
qfour11.setBounds(15,220,800,15);
qfour12.setBounds(15,240,800,15);
add(question);
add(enter);
question.setBounds(15,260,70,15);
enter.setBounds(90,260,110,23);
question.addActionListener(this);
enter.addActionListener(this);
}
if(count == 5)
{
qfive1 = new Label("Question 5", Label.LEFT);
qfive1.setFont(new Font("Times-Roman", Font.BOLD, 16));
qfive2 = new Label("How much do you like trucks?");
qfive3 = new Label("0");
qfive4 = new Label("1");
qfive5 = new Label("2");
qfive6 = new Label("3");
qfive7 = new Label("4");
qfive8 = new Label("5");
qfive9 = new Label("6");
qfive10 = new Label("7");
qfive11 = new Label("8");
qfive12 = new Label("9");
add(qfive1);
add(qfive2);
add(qfive3);
add(qfive4);
add(qfive5);
add(qfive6);
add(qfive7);
add(qfive8);
add(qfive9);
add(qfive10);
add(qfive11);
add(qfive12);
qfive1.setBounds(15,0,800,20);
qfive2.setBounds(15,20,800,15);
qfive3.setBounds(15,60,800,15);
qfive4.setBounds(15,80,800,15);
qfive5.setBounds(15,100,800,15);
qfive6.setBounds(15,120,800,15);
qfive7.setBounds(15,140,800,15);
qfive8.setBounds(15,160,800,15);
qfive9.setBounds(15,180,800,15);
qfive10.setBounds(15,200,800,15);
qfive11.setBounds(15,220,800,15);
qfive12.setBounds(15,240,800,15);
add(question);
add(enter);
question.setBounds(15,260,70,15);
enter.setBounds(90,260,110,23);
question.addActionListener(this);
enter.addActionListener(this);
}
if(count == 7)
{
finish1 = new Label("Thank You." , Label.CENTER);
finish1.setFont(new Font("Times-Roman", Font.BOLD, 50));
finish2 = new Label("Questionnaire Completed.", Label.CENTER);
finish2.setFont(new Font("Times-Roman", Font.BOLD, 50));
add(finish1);
add(finish2);
finish1.setBounds(0,200,800,60);
finish2.setBounds(0,300,800,60);
}
}
public void actionPerformed(ActionEvent ae)
{
String button = ae.getActionCommand();
text = question.getText();
b = 0;
c = 0;
if (count == 6)
{
input = text.toUpperCase();
remove(enter);
remove(question);
question.setText("");
remove(qsix1);
remove(qsix2);
remove(qsix3);
remove(qsix4);
remove(qsix5);
remove(qsix6);
remove(qsix7);
remove(qsix8);
remove(qsix9);
remove(qsix10);
remove(qsix11);
remove(qsix12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("OL"))
{
b = 1;
count = 7;
init();
}
else
{
b = 2;
count = 7;
init();
}
}
if (count == 5)
{
input = text.toUpperCase();
remove(enter);
remove(question);
question.setText("");
remove(qfive1);
remove(qfive2);
remove(qfive3);
remove(qfive4);
remove(qfive5);
remove(qfive6);
remove(qfive7);
remove(qfive8);
remove(qfive9);
remove(qfive10);
remove(qfive11);
remove(qfive12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("BR"))
{
b = 1;
count = 6;
init();
}
else
{
b = 2;
count = 6;
init();
}
}
if (count == 4)
{
input = text.toLowerCase();
remove(enter);
remove(question);
question.setText("");
remove(qfour1);
remove(qfour2);
remove(qfour3);
remove(qfour4);
remove(qfour5);
remove(qfour6);
remove(qfour7);
remove(qfour8);
remove(qfour9);
remove(qfour10);
remove(qfour11);
remove(qfour12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("no"))
{
b = 1;
count = 5;
init();
}
else
{
b = 2;
count = 5;
init();
}
}
if (count == 3)
{
input = text.toLowerCase();
remove(enter);
remove(question);
question.setText("");
remove(qthree1);
remove(qthree2);
remove(qthree3);
remove(qthree4);
remove(qthree5);
remove(qthree6);
remove(qthree7);
remove(qthree8);
remove(qthree9);
remove(qthree10);
remove(qthree11);
remove(qthree12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("black"))
{
b = 1;
count = 4;
init();
}
else
{
b = 2;
count = 4;
init();
}
}
if (count == 2)
{
input = text.toLowerCase();
remove(enter);
remove(question);
question.setText("");
remove(qtwo1);
remove(qtwo2);
remove(qtwo3);
remove(qtwo4);
remove(qtwo5);
remove(qtwo6);
remove(qtwo7);
remove(qtwo8);
remove(qtwo9);
remove(qtwo10);
remove(qtwo11);
remove(qtwo12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("yes"))
{
b = 1;
count = 3;
init();
}
else
{
b = 2;
count = 3;
init();
}
}
if (count == 1)
{
input = text.toUpperCase();
remove(enter);
remove(question);
question.setText("");
remove(qone1);
remove(qone2);
remove(qone3);
remove(qone4);
remove(qone5);
remove(qone6);
remove(qone7);
remove(qone8);
remove(qone9);
remove(qone10);
remove(qone11);
remove(qone12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("i"))
{
b = 1;
count = 2;
init();
}
else
{
b = 1;
count = 2;
init();
}
}
if (count == 0)
{
remove(intro1);
remove(intro2);
remove(intro3);
remove(start);
count = 1;
init();
}
this.validate();
}
}
In all honesty, you need to re-write your program from scratch so that you can incorporate OOP techniques, arrays, collections, and other advantages that Java has to offer. I recommend:
First of all since your code displays a series of questions and prompts for response, don't hard-code the questions in the code but make them part of the data. Have your program read in a text file that holds the questions. This will allow you to change questions or add questions without altering code.
Create a non-GUI Question class that holds questions and user responses and that is used by the GUI as its "model".
Create an ArrayList of Question objects.
For your GUI, code to the JPanel, not the applet or the JFrame. This will give you the option of using your GUI in a JFrame or a JApplet, or even a JDialog or embedded in another JPanel should you so desire.
If you will need to swap display panels, consider using CardLayout for this purpose.
If however all you'll be doing is changing the text of the question, then display the question text in a JLabel and when you want to change it, call setText(...) on the JLabel passing in the new question's text.
Use the user-friendly layout managers to ease your work of laying out components in the GUI.
Your current code has a lot of unnecessary redundencies. Use of arrays and collections such as ArrayLists will remove many of these redudancies and make debugging and upgrading much easier.
As others have stated and as I stated in my earlier comment, you should move up to the Swing library as it is much more flexible and robust than the AWT gui library that you are currently using. The Swing tutorials will show you what you need to know to create beautiful Swing programs.
Just add a main() method, make a Frame for your applet, add the applet to the frame, and call the applet's init() and start() methods. See my Mandelbrot.java for an example: http://unixshell.jcomeau.com/src/java/com/jcomeau/Mandelbrot.java
One advantage of this approach is that it can be used with any existing applet, to allow it to function as either an applet or application. Use a JFrame if you're using Swing components, otherwise it should work pretty nearly the same.
In general, you'll want to change all the non swing components to swing components. For events, they're roughly the same for both applets and swing applications. Hope it helps.
I'm not sure what you are asking, but if you want it inside a window all you need to do is this:
public Object[] startNewSurvey()
{
java.awt.Frame f = new java.awt.Frame("You're title here.");
f.setSize(new Dimension(<Width>, <Height>));
f.setResizable(false);
survey s = new survey();
s.init();
f.add(s);
f.setVisible(true);
return new Object[] { f, s };
}
That will just instance a brand new frame and put another new instance of your survey class in that frame, then display it. It also returns a 2 sized Object[] array containing the new Frame and survey instances made. Hope that helps.
https://way2java.com/applets/applet-to-application/
Following are the changes to be made from Applet to Application
Delete the statement "import java.applet" package
Replace extends Applet with Frame
Replace the init() method with constructor
Check the layout (for Applet, the default layout is FlowLayout and for Frame, it is BorderLayout)
Add setXXX() methods like setSize() etc.
Add the main() method
HTML is not required (delete it)

Categories

Resources