I have written an applet in Java as a part of my programming class that takes a person's birthday and finds the day of the week on which they were born. As per the assignment specifications, we are to put this applet on our Amazon EC2 virtual servers as well.
Now, when the person is selected from a JTable, the program takes their information as well as the path to an image file also located in the JTable beside their info. So, for example, you could have the selection consisting of:
| John Doe | 17 | 02 | 2013 | /images/John.jpg |
When I run this on my local machine, everything works as expected - the date is calculated and the image is displayed. However, when I put it on my server, one of two things happens:
If I put the "display date" code before the "display image" code, then when I press the "Calculate" button, only the text displays and the image does not.
If I put the "display image" code before the "display date" code, nothing happens when I press the "Calculate" button.
What might be happening here? My images are still in the "images/Name.jpg" path, and I even tried using the entire path ("https://myUsername.course.ca/assignment/images/Name.jpg"). Neither works! Would there be any obvious reason for this odd behaviour?
/**
* Method that handles the user pressing the "Calculate" button
*/
private class btnCalculateHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
int result;
name = (String)table.getValueAt(table.getSelectedRow(), 0);
day = Integer.parseInt((String)table.getValueAt(table.getSelectedRow(), 1));
month = Integer.parseInt((String)table.getValueAt(table.getSelectedRow(), 2));
year = Integer.parseInt((String)table.getValueAt(table.getSelectedRow(), 3));
result = calculateDayOfWeek(day, month, year);
writeToFile();
ImageIcon imgPerson = new javax.swing.ImageIcon((String)table.getValueAt(table.getSelectedRow(), 4));
Image person = imgPerson.getImage();
Image personResized = person.getScaledInstance(75, 100, java.awt.Image.SCALE_SMOOTH);
ImageIcon imgPersonResized = new ImageIcon(personResized);
image.setIcon(imgPersonResized);
outputValue.setText(name + " was born on a " + days[result] + ".");
}
}
The first problem I see is this....
ImageIcon imgPerson = new javax.swing.ImageIcon((String)table.getValueAt(table.getSelectedRow(), 4))
ImageIcon(String) is used to specify a file name of the image. This should be used for loading images of a local disk, not a network path.
If the images are loaded relative to the to the applet, you would use Applet#getImage(URL, String) passing it a reference of Applet#getDocumentBase()
Something like getImage(getDocumentBase(), (String)table.getValueAt(table.getSelectedRow(), 4))
A better choice would be to use ImageIO. The main reason for this is that it won't use a background thread to load the image and will throw a IOException if something goes wrong, making it easier to diagnose any problems...
Something like...
BufferedImage image = ImageIO.read(new URL(getDocumentBase(), (String)table.getValueAt(table.getSelectedRow(), 4)));
Related
Basically, i'm using 2 images for a board game type of thing, and i change it from time to time,
So i need to be able to check if two has the same imageIcon.
For example if both uses "pirosfigura.png" from the resources folder.
public String malomcheck() {
String pirosicon=lblNewLabel.getIcon().toString();
String pirosfilenev = pirosicon.substring(pirosicon.lastIndexOf("/" ) + 1);
String iconfilenev = labelhely_1.getIcon().toString();
String filenev = iconfilenev.substring(iconfilenev.lastIndexOf("/" ) + 1);
if(filenev==pirosfilenev) {
lblJtkos.setText("piros malom.");
JOptionPane.showMessageDialog(null, "working");
return "lefutott";
}
return "notworking. very sad.";
}
By the way the return value of the getIcon().toString() is javax.swing.ImageIcon#cd7e8021
which is refers to the memory place i guess(?) so it's random with every run and for every image therefore it's seems unusable.
One way you can achieve this, is to keep your own mapping of ImageIcons to files, so that whenever you load an ImageIcon you store it in a Map as a key and its file or some symbolic name/enum as value. This way when you want to compare imIc1 and imIc2 you would write something like:
if (map.get(imIc1).equals(map.get(imIc2)) { ... }
or (if you have descriptive string values )
if (map.get(imIc1).equals("NOT_WORKING_ICON") { ... }
or (if you are using enum values )
if (map.get(imIc1) == NOT_WORKING_ICON ) { ... }
it's so weird for me that there is no method to get to the filepath the Jlabel is using for an image.
Makes perfect sense. A JLabel displays an Icon.
Why should a JLabel know or care about the file path?
You could implement the Icon interface yourself and do the custom painting for the Icon. So not all Icons will have a file path. Only an ImageIcon is created from a file.
The property for the file name belongs to the ImageIcon.
By the way the return value of the getIcon().toString() is javax.swing.ImageIcon#cd7e8021
Image piros=new ImageIcon(this.getClass().getResource("pirosfigura.png")).getImage();
celpont.setIcon(new ImageIcon(piros));
Look at the above code that you are using.
You area creating an Icon from an Image, so the file information is lost.
Instead you should just create the ImageIcon directly:
ImageIcon icon = new ImageIcon( this.getClass().getResource("pirosfigura.png") );
celpont.setIcon( icon );
System.out.println( celpont.getIcon() );
I believe the ImageIcon will then save the filename as the "description" for the ImageIcon. It appears the toString() will return the description.
I'm having trouble batch adding images to a JButton grid. I'm trying to use a for loop who's variable is used in the string name.
The names of the images are like:
32px-Shuffle001.png
32px-Shuffle821.png
etc.
Here's the part of the code that I'm trying to add in images with. The third setIcon works, but the first two don't. I'm confused on why this is.
Additionally, the image files are not consecutive numbers. For example, I have 001,002,003,004,005, but not 007,008, then continuing at 009,010. I'm trying to figure out a good way to make it skip to the next available image.
Overall, this code is for a match 3 puzzle solver, and this is a selection grid for icons to put on the puzzle grid, so I need to be able to call the correct image associated to a button ID.
for (int i = 0; i < 1000; i++) {
JButton selectionClicky = new JButton();
if (i < 10) {
selectionClicky.setIcon(new ImageIcon("src/img/32px-Shuffle" + "00"
+ i + ".png"));
}
if (i < 100){
selectionClicky.setIcon(new ImageIcon("src/img/32px-Shuffle"+ "0"
+ i + ".png"));
}
if (i < 1000){
selectionClicky.setIcon(new ImageIcon("src/img/32px-Shuffle"
+ i + ".png"));
}
selectionClicky.setFocusable(false);
selectionMainPanel.add(selectionClicky);
selectionButtonList.add(selectionClicky);
}
Don't ever use src in any path reference, this is a good indication that things will go wrong, instead use Class#getResource or Class#getResourceAsStream depending on your requirements.
Basically, the general idea would be to test if the resource actually existed before trying to load it, for example...
String path = String.format("/img/32px-Shuffle%03d", i);
URL resource = getClass().getResource(path);
if (resource != null) {
BufferedImage img = ImageIO.read(resource);
selectionClicky.setIcon(new ImageIcon(img));
}
Generally, ImageIO is preferred over using ImageIcon, mostly because ImageIO throws an IOException when the image can't be loaded for some reason (instead of failing silently) and won't return until the image is fully loaded
See Reading/Loading an Image for more details about ImageIO
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I know this question is probably asked a TON, but from what I understand it's pretty situational and nothing I've tried so far has worked.
I'm making a basic applet that simply needs to have an image and a simple function. Mine in particular gives a random quote of Dwight from "The Office" when a user hits the button (Later on their text input will have some sort of say in how the quote is determined).
My problem here though is the applet runs in my JGrasp, but doesn't run in the browser from a local file. The code is basically complete, but can anyone help me pinpoint where it's going wrong? I just don't really understand how it can work in my applet viewer but not my browser, it's odd. I tried switching over my SWING to AWT, but it didn't seem to help, so I used my older version.
I'm posting my code, HTML file and results from the java console when the applet failed. at the moment I'm still trying to figure out what exactly to print from the java console, but figured I'd post this regardless in the meantime. Thanks for any and all help!
// Imports
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
import java
public class AskDwight extends JApplet {
// initialize GUI components
private JPanel panel;
private JLabel questionLabel, responseLabel;
private JButton askButton;
private JTextField questionField;
// Constructor
public void init()
{
buildGUI();
// Add panel to content pane
add(panel);
}
// buildPanel method adds components to GUI
private void buildGUI()
{
questionLabel = new JLabel("Question :");
questionField = new JTextField(35);
askButton = new JButton("Ask!");
java.net.URL imageURL = AskDwight.class.getResource("dwight.PNG");
JLabel imageLabel = new JLabel();
imageLabel.setIcon(new ImageIcon(imageURL));
askButton.setPreferredSize(new Dimension(350, 30));
// Response label builder
responseLabel = new JLabel("");
responseLabel.setPreferredSize(new Dimension(350, 200));
responseLabel.setHorizontalAlignment(JLabel.CENTER);
responseLabel.setVerticalAlignment(JLabel.CENTER);
// Add an action listener to the button
askButton.addActionListener(new AskButtonListener());
// Create panels
panel = new JPanel(new FlowLayout());
// Add components to the panels
panel.add(questionLabel);
panel.add(questionField);
panel.add(askButton);
panel.add(imageLabel);
panel.add(responseLabel);
}
// Action Listener class for the ask button
private class AskButtonListener implements ActionListener
{
// Ask method exectutes when the button is clicked
public void actionPerformed(ActionEvent e)
{
String inputQuestion; // Holds user's input question
String[] response = new String[10]; // Holds Dwight's random responses
String randomResponse;
// Dwight Responses - contained in String array
response[0] = "<html>Fact: You can use the molten goose grease and save "
+ "it in the refrigerator.</html>";
response[1] = "<html>False: Bears do not eat beats.</html>";
response[2] = "<html>Question: Do you ever stop asking stupid questions?</html>";
response[3] = "<html>Fact: Bears can climb faster than they can run.</html>";
response[4] = "<html>What are you even asking? I order you to Cease and "
+ "desist right now, as third in command</html>.";
response[5] = "<html>You think that's funny? Millions suffer every year at "
+ "the expense of your jokes.</html>.";
response[6] = "<html>MICHAEL!";
response[7] = "<html>A day on Schrute's beet farm would shut your mouth.</html>";
response[8] = "<html>False: Nothing you say is important.</html>";
response[9] = "<html>I always keep concealed pepper spray just for an "
+ "occasion such as this.</html>";
// inputQuestion gets the user's entered string
inputQuestion = questionField.getText();
// When button is pressed, the following code will select
// a random response from the string array
Random rand = new Random();
randomResponse = response [rand.nextInt(response.length)];
responseLabel.setText(randomResponse);
}
}
}
Here's the HTML code
<HTML>
<HEAD>
<TITLE>Ask Dwight Schrute</TITLE>
</HEAD>
<BODY>
<applet code="AskDwight.class" width="420" height ="500">
</applet>
</BODY>
</HTML>
You've specified the programs class, but not provide the applications archive, this means that any call to Class#getResource is going to fail as the applet's classloader has no concept about where those resources might be stored, instead, consider trying something like...
<applet code = 'AskDwight'
archive = 'AskDwight.jar'
width = 420
height = 500>
</applet>
Assuming you've built the project into a Jar and have it deployed on the server...
It's been a (very) long time since I've done any applet program, so this might be slightly off...
Take a closer look at Deploying an Applet for more details
Updated based on feedback
If you can't use a Jar file then you'll need to use, something like Image img = getImage(getCodeBase(), "dwight.PNG"); to load the image...
The image will need to stored in the same location as your class files, for example, if AskDwight.class doesn't belong to a package, they would reside at the same location (on the drive). If AskDwight.class belonged to the com.foo.bar package, the image file would be in the directory above com
Hello there fellow stackers! I'm having a problem creating a proper save function for my game. The main problem I am having is capturing all of the data inside of my J text area named display. The display reflects what moves have been made so far in the game, and at the top of the display it says "Welcome to Togiz Kumalak".
My problem is that when I save the game, it only records the first line of text to the file instead of all lines.
an example is:
Welcome to Togiz Kumalak
Player 1 Cup 1
Player 2 Cup 3
and so on. When I save the file, only the top line will be shown.
Here is my current code for the save Listener.
class SaveListener implements ActionListener
{
String a = display.getText();
JFileChooser myChooser= new JFileChooser();
public void actionPerformed(ActionEvent event)
{
String fileName;
myChooser.setCurrentDirectory(new File("."));
myChooser.showSaveDialog(null);
fileName = myChooser.getSelectedFile().getPath();
try
{
OutputStream file = new FileOutputStream(fileName);
PrintStream printStream = new PrintStream(file);
printStream.print(a);
printStream.close();
/* Version 11, 23.1. Scroll pane and text area support when saving. */
}
catch(IOException e)
{
System.out.println("Problem making or writing to an output stream.");
System.out.println(e);
}
}
}
Use the write(...) method of the JTextArea API instead of trying to create your own method.
..having a problem creating a proper save function for my game
Given the word 'proper' (my emphasis) I have to point out that the proper way to save/load games is according to a 'game state model' as opposed to a 'game state model crudely translated to lines of text'.
That game state model might be saved a number of ways depending upon the complexity of the data, but should use very different serialization methods (with less work done encoding/decoding the data in our code) than this approach uses.
I have some experience with Android development and now I have decided to learn something new - developing for Kindle (NOT Android based Kindle Fire).
Amazon offers KDK + Personal Basis Profile 1.1.2 (JSR 217) as a platform.
My problem is, how to design UI. I do not have any experience with awt (just did som apps in java swing), but is doesn't seem to be a big issue, because it's quite simple... Main issue is with 'replacing' android's ListView.
I've tried to use component named KPages. I'm, however, not able to put anything else but KLabel into the pages model...
PageProvider pp = PageProviders.createKBoxLayoutProvider(KBoxLayout.PAGE_AXIS);
final KPages pages = new KPages(pp);
for (int i = 0; i < 40; i++) {
final KPanel listItem = new KPanel();
// listItem.add(new KLabelMultiline("label numero " + i + " is not very good, because it will be displayed over more than one line and 'pages' won't be able to deal with it"));
listItem.add(new KLabel("label numero " + i + " is very good, because it won't be displayed over more than one line and 'pages' will be able to deal with it"));
listItem.add(new KButton("read"));
listItem.add(new KButton("edit"));
pages.addItem(listItem);
}
context.getRootContainer().add(pages);
Sample code above shows my effort to list some items. KPages works well only when adding KLabel using pages.addItem(). Just inserting KLabelMultiline causes paging to mulfunction (instead of showing labels 0-12 it 'displays' 0-26 as in single line, but screen of kindle shows only 14-26). Trying to insert whole KPanel with label and 2 buttons results in listing the labels followed by one empty line for each item, without any button... displaying same KPanel outside pages works fine - I can see the label and both buttons...
I'm almost sure it's my fault for leaving something out, but thanks to really little information available on KDK, I'm not able to find it... Can anybody give me a hand? Thanks
Try overriding the getPreferredSize, getMinimumSize, and getMaximumSize calls to your constructor for KPanel. Set width and height to whatever your screen size is.
final KPanel listItem = new KPanel() {
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
public Dimension getMinimumSize() {
return new Dimension(width, height);
}
public Dimension getMaximumSize() {
return new Dimension(width, height);
}
};