This question already has answers here:
Newline in JLabel
(6 answers)
Is there a "word wrap" property for JLabel?
(7 answers)
Closed 9 years ago.
This may seem like a stupid question but I'm unable to do it; I use a scanner to read a file then using a while loop I input the text into a string which I then put onto a JLabel. However, the text is displayed in one very long horizontal line, how to I make it so that all the text appear normally like paragraphs as in the original text file?
The code:
class howToPlay implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
JFrame htp = new JFrame();
htp.setSize(300, 100);
htp.setLocationRelativeTo(null);
Scanner fileStream = null;
try {
fileStream = new Scanner(new File("text/howtoplay.txt"));
} catch (FileNotFoundException e1) {
System.out.println("File not found");
e1.printStackTrace();
}
String file = "";
while(fileStream.hasNextLine())file += fileStream.nextLine();
JLabel howToPlay = new JLabel(file);
htp.add(howToPlay);
htp.setVisible(true);
}
}
This is the text in the file, which is rules of how to play a game:
The Object of the Game is to move your pieces until they are all in one connected group. Diagonals are considered to be connected. However, there are certain rules that need be followed:
-White moves first
-Each turn, the player to move moves one of his pieces, in a straight line, exactly as many squares as there are pieces of -either color
anywhere along the line of movement. (These are the Lines of Action).
-You may jump over your own pieces.
-You may not jump over your opponents pieces, but you can capture them by landing on them.
-If one player is reduced by captures to a single piece, that is a win for the captured player.
-If a move simultaneously creates a win for both the player moving and the opponent, the player moving wins. There are actually quite a few
Unusual endgames which are at least theoretically possible.
Any help is appreciated.
Maybe try out this :)
Looks weird, but work fine for me.
You can use HTML formatting: prefix .setText() with:
<html>
and you will be able to use HTML code in your JLabel. Example:
label.setText("<html>First line<br>Second line");
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++;
}
}
.
.
Well, I decided to edit everything. So, the code goes like this:
public void actionPerformed(ActionEvent e) {
if (!uiCreator.getTextArea().getText().equalsIgnoreCase("Beggining text")) {
JOptionPane.showMessageDialog(null, "You must have main method first", "Error",
JOptionPane.ERROR_MESSAGE);
} else {
n = Integer.valueOf(JOptionPane.showInputDialog("..."));
l = Integer.valueOf(JOptionPane.showInputDialog("..."));
uiCreator.getTextArea()
.setText("Beggining text with few additions");
On the code above, I made it to check if JTextArea contains text that is needed and if it doesn't it will show an error message. If it does it will set a text with few more words.
Now. I also have more JButtons. So if one is clicked, it will also do the same thing. Check the text and if it meets all conditions, set new modified text. But, now, my problem comes here. I have this:
public void actionPerformed(ActionEvent e) {
if (!uiCreator.getTextArea().getText()
.equalsIgnoreCase("Beggining text with few additions")) {
JOptionPane.showMessageDialog(null, "Error, you don't have main or JFrame inside main", "Error",
JOptionPane.ERROR_MESSAGE);
} else {
uiCreator.getTextArea()
.setText("Beggining text with even more additions");
}
Which checks if JTextArea had "Beggining text with few additions" and if it did, change the text to Beggining text with even more additions. I have few more buttons that do the same thing. Now, I would like to know a way to let setText(some text) method be used regardless is there Beggining text with few additions or Beggining text with even more additions.
Don't use setText(...) to keep replacing all the text.
Instead you can use methods like:
replaceSelection(...);
getDocument().insertString(...);
to change part of the text or insert new text.
I'm a complete beginner in Java programming and I'm interested to learn more about its concepts.
Recently, I've been given an exercise which instructs me to display two versions of a picture. The picture to be displayed is provided in the form of a data file of 40,000 digits that are arranged in rows (although there is no marker between rows) and it starts from the top of the picture. So the first digit represents the top left corner of the picture and the last is the bottom right.
Basically, what the exercise wants me to construct a program that plots a dot in one of two colours for each digit. If the digit is in the range 0 to 3 the output should be one colour and for digits in the range 4 to 9 the dot should be in the other colour.
I understand I have to use arrays and also loops to perform this. I'm familiar with the fillEllipse, drawEllipse, drawRectangle and fillRectangle but this exercise is nothing I've attempted before.
Any hints on how to make this work? Your help would be greatly appreciated.
As a hint, rather than a complete solution, I would suggest looking into creating a java.awt.image.BufferedImage, and then set the colors of the individual pixels using the setRGB() method. You would then display this image using drawImage() on your Graphics object.
All what you need is how to read the digits from the file and put it into two dimension array
check this tutorial for how to read a file
Then you have to draw each pixel on a fram or a Panel
check this Java basic graphics tutorial
I hope this could help!
use Scanner to read the data like :
Scanner sc = new Scanner(new File("path_to_your_digits_file"));
int[][] digits= new int [200][200];
String line;
while(sc.hasNext()){//this means there is still a line to go
line = sc.nextLine();
//split the line and fill the array . or read char by char ,
// i dont know how your file looks like, it's just some simple string manipulation here
}
int x;
BufferedImage img = new BufferedImage(200,200,BufferedImage.TYPR_INT_RGB);
for(int i=0;i<200;i++){
for(int j=0;i<200;j++){
if(digits[i][j]>0 && digits[i][j]<=3){
x=//some color code;
}else{
x=//some other color code;
} //not sure about this loop , again idk the structure of your file;
img.setRGB(i,j,x);
}
}
JLabel lbl = new JLabel();
lbl.setSize(200,200);
ImageIcon ico=new ImageIcon(img);
lbl.setIcone(ico);
lbl.setVisible(true);
JFrame frame = new Jframe();
frame.setSize(500,500);
frame.add(lbl);
frame.setVisible(true);
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.