Java Applet and Console - java

I'm new in building Java applets
I want to show what it's display in my console in the Java applet, I know you should use the paint method, but I don't know how to call it in the code.
public void paint(Graphics g) {
//Draw a rectangle width=250, height=100
g.drawRect(0,0,250,100);
//Set the color to blue
g.setColor(Color.blue);
//Write the message to the web page
g.drawString("Running",10,50);
This is what I currently have, the whole program it's made to run from the console in
System.out.println(x)
is there anyway to call something like
paint(x)
to show the same on the applet as is show on the console? Plus I need it to refresh constantly.

You don't have a call to the superclass method. Put
super.paint(g);
before anything else.
If you want to display a message on the applet at the same time as on the console, you need to have a method that calls repaint();. The way I would set this up is to have an Arraylist of Strings. When you want something written to the applet output, you add the new String to the ArrayList, then call repaint(). Then, in paint(),
ArrayList<String> ar = new ArrayList();
public void paint(Graphics g) {
super.paint();
//Draw a rectangle width=250, height=100
g.drawRect(0,0,250,100);
//Set the color to blue
g.setColor(Color.blue);
//Write the message to the web page
for(int i = 0; i<ar.size(); i++)
g.drawString(ar.get(i), 10, 50); }
If you want a function that does this, you might write it like so
public void appletOut.println(String str){
ar.add(str);
repaint();
}
Finally, I question whether this route is really best for what you are trying to accomplish. I would suggest researching text fields and scrollbars and seeing if that might fit your parameters better.

Related

Using drawLine Function in Other Function

I'm creating a game where I need to draw some lines and dots. I have a general function called paintDot (check code below) and I want to call it in a different function. I don't know how to call it, any help?
public void paintDot (Graphics g, int x, int y)
{
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillOval(x,y,15,15);
}
This is the other function/method where I need to call the drawing function:
ATM the coordinates are just hardcoded so I know it's working correctly.
As you can see, I'm calling the paintDot method with bad arguements. Don't know what argument should be placed at Graphics g
private void gameWindow (int dif)
{
this.removeAll();
areaImage = new JPanel ();
//distance between points = 75
//point grid = 7*6
areaImage.setBounds(50,50,675,600);
areaImage.setBackground(Color.WHITE);
areaImage.setBorder(BorderFactory.createLineBorder(Color.black));
add(areaImage);
answer = new JTextField();
answer.setBounds(835,200,150,50);
answer.setBorder(BorderFactory.createLineBorder(Color.black));
answer.setHorizontalAlignment(JTextField.CENTER);
answer.setFont(new Font("Verdana", Font.BOLD, 20));
add(answer);
info= new JLabel ("Write your answer here:");
info.setBounds(830,155,250,50);
info.setFont(new Font("Verdana", Font.BOLD, 12));
add(info);
checkAnswer = new JButton ("Check Answer");
checkAnswer.setBounds(835,310,150,50);
checkAnswer.addActionListener(this);
add(checkAnswer);
next = new JButton ("Next");
next.setBounds(835,410,150,50);
next.addActionListener(this);
add(next);
end = new JButton ("End Game");
end.setBounds(835,510,150,50);
end.addActionListener(this);
add(end);
revalidate();
repaint();
int x = 75,y=75;
for(int num=0;num<6;num++)
{
for(int xx=0; x<7;xx++)
{
paintDot (areaImage,x,y); // here is the problem
x=x*2;
}
y=y*2;
}
}
I have a general function called paintDot (check code below) and I want to call it in a different function
You can't.
Painting can only be done in the paintComponent() method.
You should NEVER be invoking paintComponent() directly.
All painting code MUST be in the paintComponent() method.
If you want to paint 7 dots. Then that painting code MUST be in the paintComponent() method which means the looping code would be in the paintComponent() method and then you invoke the paintDot(...) method from withing the loop. The painting of the dots must be done EVERY time Swing determines the component needs to be repainted.
You have asked several questions on this topic and the answer is always the same. Read the tutorial link you have been given and follow the examples. The tutorial draws a square, but the concept would be similar for drawing 7 dots.
So once again, read the tutorial, download the code and play with the working example. Start by changing the tutorial code to draw 7 dots. Once you understand how that works, then you add the logic to your real code.
The tutorial link is give to you for a reason. If there is something you don't understand in the tutorial, then ask a question, but don't post code that looks nothing like the example from the tutorial and wonder why it doesn't work!
You have this for:
for(int xx=0; x<7;xx++)
where you have an index called xx and you try to do a cycle. The problem is that you test for x < 7 instead of xx < 7 and since x is greater than 7, you will never get into the for.
You could extend JPanel and overwrite the drawing functions, such as the paintComponent(Graphics g) (Thanks camickr) or paintAll(Graphics g) (I believe) method.
You might also want to add a JLabel with a BufferedImage using createGraphics()
Please note if you are trying to make a full-fledged game, you would need a game loop and other stuff, which is NOT fun without a library.
This is not an attempt in shameless self-promotion, it's a suggestion.
IF you need a game loop, canvases, multiple screens and stuff,
a library could be the way to go.
I made the library j2D to make 2D games.

Graphics2D reset Screen?

I have a Game Tutorial that I followed, that paints String's on the Screen using Graphics2D. It works like a star, but the only problem is that I don't undertstand why.
I call draw(graphics) in a game loop and it works fine. I use an int, named currentChoice to keep track of which letter should be Red and which should be Black.
Well, I call the method Draw in a loop. I just don't understand how does the graphics clear the previous string it drew. I mean, I call the method constantly, and it keeps on Drawing string's on the window, and its 'clearing' the other ones (if you get what i'm saying).
Basicly, I just don't undertstant how it's clearing the screen (NOTE: I am super new to this sort of thing)
CODE (I call this in a loop and it works):
public void draw(Graphics2D graphics) {
bg.draw(graphics);
graphics.setColor(titleColor);
graphics.setFont(titleFont);
graphics.drawString("Peache's Revenge", 50, 70);
graphics.setFont(font);
for (int i = 0; i < options.length; i++) {
if (i == currentChoice) {
graphics.setColor(Color.RED);
} else {
graphics.setColor(Color.BLACK);
}
graphics.drawString(options[i], 145, 140 + i * 15);
}
}
Assuming the Graphics context does not change (ie is the same for each call), then, unless the background is cleared, content will continue to be painted ontop of it.
From you comments, bg.draw is drawing the background, over the top of whatever was previously painted, meaning that anything that was previously painted will now be covered by the background, thus requiring the text to be re-generated.

blackberry - bring field to the front within NegativeMarginVerticalFieldManager

I'm stuck with a problem of bringing a field to the front as it's drawing, has anyone countered a problem like this before?
In plain words, the problem is that I'm using NegativeMarginVerticalFieldManager from the Advanced UI samples, I use it to display a highlighted text under each panel button, the text should go in front of the content under the panel, but now it's going in the back of it.
So, does any one know how to make it appear in the front?
The order of paint is different. Could you override paint in your fields and check order of painting?
Unfortunately there z-order is connected to order how fields were added to manager and I don't know how to change it.
What you could do - override paint in manager and call paint for children in your needed order:
public class MyManager extends NegativeMarginVerticalFieldManager {
protected void paint(Graphics g) {
for (int i = 1; i < getFieldCount(); i++) {
paintChild(getField(i), g);
}
if (getFieldCount() > 0)
paintChild(getField(0), g);
}
}
This is hack - I'm painting first field after all other.

Why is my background Glitching after repainting?

I have a program selection tool that i made. it opens a JFrame with 17 buttons, 15 of which are customizable, and they get their text from a .txt document located in the C: drive. when i click the assign button, it opens a JFileChooser to select a file to open when the button is clicked. You then select a button to change, and then type the text you want displayed by the button. After that the program rewrites the .txt file and updates the buttons. here is the code for updating:
public static void restart() {
start.assignButtonActions();
start.assignButtonText();
start.paint(graphics);
}
public void assignButtonActions() {
/**
* assign button actions
*/
for (int i = 0; i < buttonAction.length; i++) {
buttonAction[i] = io.readSpecificFromHD("C:\\ButtonActions.txt", i
+ 1 + actionButton.length);
}
}
public void assignButtonText() {
for (int i = 0; i < actionButton.length; i++) {
/**
* set button text
*/
actionButton[i].setText(io.readSpecificFromHD(
"C:\\ButtonActions.txt", i + 1));
}
}
public void paint(Graphics g) {
g.drawImage(getImage("files/background.png"), 0, 0, FRAMEWIDTH,
FRAMEHEIGHT, null);
refresh();
}
public void refresh() {
graphics.drawImage(getImage("files/background.png"), 0, 0, FRAMEWIDTH,
FRAMEHEIGHT, null);
for (int i = 0; i < actionButton.length; i++) {
actionButton[i].repaint();
}
assignButton.repaint();
helpButton.repaint();
}
Thats all the code that is required for this question i believe. The problem is, after the method restart() is called, the background is there, with a white square around the buttons, with it being white inside the square. not really a major problem, but really incredibly annoying and pretty unprofessional. At first i thought it was that the buttons were resizing after the background is painted, so i made it so that the refresh runs twice each time its called. didnt help one bit.
EDIT:
I fixed the problem. I took hovercraft's answer and modified what i learned a little bit. all i had to do was modify the restart() method to:
public static void restart() {
start.assignButtonActions();
start.assignButtonText();
start.repaint();
}
because the repaint(); repaint the whole component which was what hovercraft said. Thank you a ton everyone! hope this helps future questions.
You appear to be handling your Swing graphics incorrectly by calling paint(...) directly and trying to use a Graphics object outside of a JComponent's paintComponent(...) method. Don't do this, as all the Swing graphics tutorials will tell you (if you've not gone through some of them yet, you will want to do this soon). Instead do all graphics within a JComponent's (such as a JPanel's) paintComponent(...), call the super's method first, and use the Graphics object provided by the JVM in the paintComponent's method parameter.
Edit
Tutorial links:
The introductory tutorial is here: Lesson: Performing Custom Painting.
The advanced tutorial is here: Painting in AWT and Swing.
I'm thinking that you'll have to re-write most of your graphics code. Changes you should make:
Draw only in a JPanel or other JComponent-derived class, not in a JFrame or other top-level window.
Draw in your class's paintComponent(...) method.
Place an #Override annotation just above your paintComponent(...) method to be sure that you are in fact overriding the super method.
Call the super's paintComponent(...) as the first line (usually) of your paintComponent(...) override method.
Use the Graphics object passed into this method by the JVM.
Do not use a Graphics object obtained by calling getGraphics() on a component (with rare exceptions).
Do not give your class a Graphics field and try to store the Graphics object in it. The Graphics objects given by the JVM do not persist and will quickly become null or non-usable.
Do not call paint(...) or paintComponent(...) directly yourself (with rare exceptions -- and your current code does not qualify as one of the exceptions, trust me).
You will likely not need to call repaint() on your JButtons

Dynamic amount of images printed on JPanel

I have a stickynote png image and I want to basically at runtime, grab the data in the database and then print out as many images onto the JPanel as there are records in the database, then print text over each png so there is a sticky note type of look and feel.
My problem is when I loop through and try to create images, do I need a separate image object reference for each one or can I reuse the same image object in the loop? This code would be in paintComponent in a class extending JPanel. I feel like I am thinking about this all wrong...
for example for(i=0;i<recordCount; i++
{
Image image = new ImageIcon("mysticky.png").getImage
}
My problem is that I think that this will overwrite each new image put on the Jpanel. What is the best way to do this? Thanks!
You need just one image.
Use:
ImageIcon image = new ImageIcon("mysticky.png");
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(ImagePanelImage nextim : backgroundImages) {
g.drawImage(image.getImage(), 0, 0, image.getIconWidth(), image.getIconHeight(), this);
}
}
You may want to search the web for the concept of 'background image' in java.

Categories