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
Related
This question already has answers here:
Java - checking if parseInt throws exception
(8 answers)
Closed 1 year ago.
So I tried to look a bit in forums and StackOverflow but nothing worked for me I need when enter is pressed to stop my code this is my code `
JFrame f;
JTextField I;
// JButton
JToggleButton b;
// label to display text
JLabel l;
f = new JFrame("AutoClicker");
i = new JTextField("100");
// create a label to display text
l = new JLabel("clicks/seconds");
// create a new buttons
b = new JToggleButton("Start");
// create a panel to add buttons
JPanel p = new JPanel();
// add buttons and textfield to panel
p.add(b);
p.add(i);
p.add(l);
// setbackground of panel
p.setBackground(Color.red);
// add panel to frame
f.add(p);
// set the size of frame
f.setSize(280, 80);
f.setVisible(true);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int jml = Integer.parseInt(i.getText());
if(jml < 50)
{
jml = 50;
}
AutoClicker(jml);
}
});
}
static void AutoClicker(int jml)
{
while(true)
{
try{
Robot r = new Robot();
int button = InputEvent.BUTTON1_DOWN_MASK;
r.mousePress(button);
Thread.sleep(jml);
r.mouseRelease(button);
Thread.sleep(jml);
}
catch(Exception e){
e.printStackTrace();
System.out.println("not good");
}
}
}
}`
I tried to add a KeyListener but it did not work.
I don't understand why it doesn't work so if you can just help me know why it doesn't work it would be much apreciated.
KeyListener isn't going to solve the problem of the fact that you are simply not handling the potential of Integer.parseInt to throw an exception - I mean, how can it convert "" or "This is not a number" to an int. In those cases it throws an exception
The JavaDocs clearly state
Throws:NumberFormatException - if the string does not contain a
parsable integer.
Go back and have a look at the original error you were getting from your previous question on this exact topic
java.lang.NumberFormatException: For input string: "Enter"
It's telling you exactly what the problem is - the text "Enter" can not be converted to an int value.
YOU have to handle this possibility. No offence, but this is honestly basic Java 101. See Catching and Handling Exceptions
Another option which "might" help is to use a formatted text field
You also don't seem to have a firm grip on the concept of what a "event driven environment" is or what the potential risk of what doing something like while (true) will do if executed within the context of the Event Dispatching Thread. This makes me think you've got yourself in over all head.
You're going to want to learn about Concurrency in Swing as AutoClicker should never be called within the context of the Event Dispatching Thread, which is going to lead you another area of complexity, concurrency and all the joys that brings.
Updated
Wow, you changed the title. Maybe a better description of the problem you're trying to solve would have a gotten a better answer. In short, you can't, not natively in Java anyway. The only way you can detect keyboard input out side of the app is using native integration, JNA/JNI. Plenty of examples about, for example
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 6 years ago.
Improve this question
I am writing a quiz app, where you get marks as you answer the correct questions and your score increases, and I have to use if statements. Please does any one know how to use a value in an if statement in another if statement! I'm kinda confused about it and its hooking me up at work here....Thanks for the help!... here is a little code example;
int x = 3;
String xy = Integer.toString(x);
int y = 0;
String yy = Integer.toString(y);
JButton one = new JButton ("Quest 1");
one.addActionListener (new ActionListener (){
public void actionPerformed(ActionEvent p) {
JFrame ex = new JFrame ();
ex.setTitle("Question 1);
ex.setSize(400, 400);
ex.setLayout(new FlowLayout());
ex.setBackground(Color.WHITE);
JLabel ey = new JLabel ("What is the capital of Japan?);
Font tan = new Font ("Script MT Bold", Font.BOLD, 18);
ey.setFont(tan);
ey.setForeground(Color.BLACK);
ex.add(ey, BorderLayout.NORTH);
JButton answ = new JButton("submit");
JTextField g = new JTextField (10);
g.setFont(tan);
String ans = "Tokyo";
String merit = "Correct";
String flop = "wrong";
String mer = merit + ans;
String flip = flop + ans;
answ.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent p) {
if (g.getText.equals("Tokyo") {
JOptionPane.showMessageDialog(null, mer);
one.setText(xy);
}
else {
JOptionPane.showMessageDialog(null,flip);
one.setText(yy);
}
//In my next Action Listener, I would love to
//pick the score from the previous listener....and add to the next score....
//So that we have something like ....
//x(updated from previous listener) + x
ex.add(g, BorderLayout.SOUTH);
}
});
}
});
The only problem I can guess at in the code supplied is that you're testing if a JTextField's text contains a specific String, "Tokyo" in your GUI creational code. This is code that runs at GUI creation and before the user has had any chance to enter data. To fix this, the if test should be within some listener, perhaps a JButton's ActionListener. Otherwise I have no idea what you mean by if within an if.
Edit
Regarding your new information:
I am writing a quiz app, where you get marks as you answer the correct questions and your score increases, and I have to use if statements.
You need to completely re-design your code as you're hard coding your code logic within the GUI, making for a very rigid, huge, and difficult to enhance program (as you're finding out) since the code logic must change as the state of the program changes.
Instead you should split out your program logic, the "model" from the GUI, the "view", and try to create them and test them independently, something similar to (or equal to) a "Model-View-Controller" or "MVC" program design. Start with the model, the "guts" of the program and create your non-GUI Question class, one with instance fields, methods, and any other supporting classes. Once this has been tested and debugged, then try to create a GUI or view class that can use this model and display its state. You might also want to create a "Controller" class with listeners that help connect the view to the model.
For example, if your quiz is to be a multiple-choice type of program, then consider:
A Question class that contains the question String, possible answer Strings and the correct answer String.
Give it a public boolean test(String testString) that returns true if the correct answer String is passed into it.
Allow the Question class to randomize the order of the possible answer Strings, likely held in an ArrayList.
Then create a Quiz class that holds an ArrayList of Questions.
Then create a GUI to display these.
I generally create GUI's that are geared to create JPanels, not JFrames for increased flexibility and then create the JFrame when needed.
Create a QuestionPanel that displays the question String and the randomized possible answer Strings.
Display the possible answers as JRadioButtons with a ButtonGroup to limit the selection to one.
etc....
You'll also want a class to read from a text file data for each question, and load that data into the Quiz class.
You'll also want a mechanism to grade.
Please make all required variables as class level variables instead of declaring it in actionlistner method. Class level variables will be visible in all methods so no need to pass those. Declare score variable as class level.
public class ClassTest {
int score=0;
public void acgionlistner1(Event ev)
{
if(ans.equals(userinput))
{
score++;
}
}
public void acgionlistner2(Event ev)
{
if(ans.equals(userinput))
{
score++;
}
}
.
.
I'm writing a program in java language and I want to make some changes in one part of my JOptionPane.showInputDialog. My dialog is this :
JOptionPane.showInputDialog("Total Amount Deposited:\t\t" +
totalAmount + "\n Enter Coin Value \n" + "(Enter 1 to stop)");
and I want to make the part that is saying (Enter 1 to stop) a little bit smaller than the other parts.
I'm beginner in java language (roughly 2 months :D) and don't have any other experience. so, please keep your answers simple. thanks in advance.
A JOptionPane will display the text in a JLabel, which supports basic HTML. So you will need to wrap your text string in HTML, then you can use different fonts, colors or whatever.
Simple example:
String text = "<html>Normal text <b>and bold text</b></html>";
JOptionPane.showInputDialog(text);
You can also use Font.pointSize() or Font.size() from java.awt.Font.
Create a String = "the text"
put in a label pa
use setFont();
Quick example :
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Test extends JFrame {
public static void main(String[] args)
{
String a = "(enter 1 to stop)";
JLabel pa = new JLabel();
JFrame fr = new JFrame();
fr.setSize(200,200);
pa.setText(a);
pa.setFont(pa.getFont().deriveFont(11.0f)); //change the font size from here
fr.add(pa);
fr.setVisible(true);
}
}
For JDK 8.x, I find the following works to enlarge the font size of most portions of the built-in JOptionPane.showInputDialog, especially buttons, textboxes and comboboxes.
It is mostly generic, except for the two parts I want to be bold font.
It even allows for exceptions (think of it as an "all except" strategy) when you want to enlarge 99% of the pieces of an input dialog, except for one or two pieces.
Sorry for the bad formatting, but the "Code Sample" tool messed up everything and I don't have time to fix it.
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.swing.*;
/**
* Changes the font size used in JOptionPane.showInputDialogs to make them more
* ADA section 508 compliant by making the text size larger, which is very nice
* for older people and anyone else with vision problems.
*
* #param fontSize
* - size of the font in pixels
*/
private static void makeDialogsEasierToSee(int fontSize)
{
// This next one is very strange; but, without it,
// any subsequent attempt to set InternalFrame.titleFont will
// be ignored, so resist the temptation to remove it.
JDialog.setDefaultLookAndFeelDecorated(true);
// define normal and bold fonts that we will use to override the defaults
Font normalFont = new Font(Font.MONOSPACED, Font.PLAIN, fontSize);
Font boldFont = normalFont.deriveFont(Font.BOLD);
// get a list of objects that we can try to adjust font size and style for
List<Map.Entry<Object, Object>> entries = new ArrayList<>(UIManager.getLookAndFeelDefaults().entrySet());
// System.out.println(entries.size());
// remove anything that does NOT involve font selection
entries.removeIf(filter -> filter.getKey().toString().indexOf(".font") == -1);
// System.out.println(entries.size());
// Define a list of font sections of the screen that we do NOT want to
// enlarge/bold.
// The following is specific to jKarel so we do not obscure the display of
// "beeper piles" on the maps.
List<String> exempt = Arrays.asList("Panel.font");
// remove anything on the exempt list
entries.removeIf(filter -> exempt.contains(filter.getKey().toString()));
// System.out.println(entries.size());
// optional: sort the final list
Collections.sort(entries, Comparator.comparing(e -> Objects.toString(e.getKey())));
// apply normal font to all font objects that survived the filters
for (Map.Entry<Object, Object> entry : entries)
{
String key = entry.getKey().toString();
// System.out.println(key);
UIManager.put(key, normalFont);
}
UIManager.put("Label.font", boldFont);
UIManager.put("InternalFrame.titleFont", boldFont);
}
You basically have two straightforward options - Switch to JDialog or use HTML.
JOptionPane is intended for simple messages or interaction with the users. JDialog is a better choice if you want to break out of the canned use cases, and as you get more complex you will probably eventually have to switch to it.
To meet your immediate use case, you can send in an html message. The rules are:
You must begin and end with <html></html> tags. Put them in the middle and nothing happens.
You must remove all "\n"'s in your code. They don't work in html
anyway and the JPanel tries to use each line, as defined by \n's as a
separate html doc. Switch to
int totalAmount = 345; //for testing
String message = "<html>"
+ "Total Amount Deposited: " + totalAmount
+ "<br> Enter Coin Value "
+ "<br><span style='font-size:10'>(Enter 1 to stop)</span>"
+ "</html>";
JOptionPane.showInputDialog(message);
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)));
I'm having more "I'm hopeless at programming" problems.
I have a piece of code which uses StringBuilder to display elements of an array in a text panel of a GUI when the program starts. Here's the StringBuilder code:
// memory tab
StringBuilder mList = new StringBuilder();
memLocList = new Memory[MEM_LOCATIONS];
mem = new Memory();
for (int i = 0; i < memLocList.length; i++) {
memLocList[i] = mem;
memLocList[i].setOpCode(00);
mList.append(String.format("%10s %04x %10s %6s", "Address: ", i,
"Value: ", memLocList[i].getOpCode()));
mList.append("\n");
}
JComponent memTab = makeTextPanel(mList.toString());
tabs.addTab("Memory", new JScrollPane(memTab));
}
protected JComponent makeTextPanel(String t) {
text = t;
JPanel panel = new JPanel(false);
JTextPane filler = new JTextPane();
filler.setFont(new Font("Courier", Font.PLAIN, 14));
filler.setText(text);
filler.setAlignmentX(LEFT_ALIGNMENT);
panel.setLayout(new GridLayout(1, 1));
panel.add(filler);
return panel;
}
The GUI also has a text entry panel where a String of hex values can be entered.
On clicking a button, the user is prompted for another value, which corresponds to the position in the array where the first hex value should be inserted.
Once these values have been entered, I'd like the display to be updated / refreshed to reflect this but am unsure of how to go about it.
I found this question here, which is similar but I'm not sure if implementing Observer/Observable pattern is the right way to proceed, and even if it is, how I'd go about it:
Best Way to Constantly Update GUI Elements
My initial approach was to add an "updateDisplay()" method, which I could call after processing the button click and re-call the makeTextPanel method:
public void updateDisplay() {
makeTextPanel(text);
}
I thought this might refresh it but it has no effect of the display.
Any help appreciated.
You hold your array in a model class, and you allow other classes to "listen" to this by giving this class a SwingPropertyChangeSupport object as well as an addPropertyChangeListener(...) method. Then give the array a setXXX(...) method, and in that method fire the SwingPropertyChangeSupport object after updating the array. There are examples of just this sort of thing on this site, some written by me.
For example: here, here, here, ...
By the way, I'm not surprised that your call to makeTextPanel(text) doesn't work. It creates a JPanel, but you don't appear to do anything with the JPanel that is returned from the method. But nor should you. I don't think that creating new JPanels is the solution you want, but rather updating the Strings displayed by a component of some sort such as a JList or JTextArea using the listener framework that I've described above.
If any of this is confusing, please ask for clarification.