Reputation: 39
I need help because I am trying to code a game in Java. I was stopped in my tracks when I found out that it would not draw a string to the JFrame. I have tried several methods of getting around this and done lots of research but found nothing. This is the code:- Oregon (Main Class):
package com.lojana.oregon.client;
import java.awt.*;
import javax.swing.*;
import com.lojana.oregon.src.Desktop;
import com.lojana.oregon.src.Keyboard;
import com.lojana.oregon.src.Mouse;
import com.lojana.oregon.src.Paint;
public class Oregon extends JFrame {
private static final long serialVersionUID = 1L;
// Currently unused but there will be a use for it in the future
public Desktop desktop;
public String TITLE = "Oregon";
public Oregon() {
/* Window code */
setTitle(TITLE);
setSize(640, 640);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
/* Extra code for Window */
addKeyListener(new Keyboard());
addMouseListener(new Mouse());
}
public void paint(Graphics g) {
Paint.paint(g);
}
}
GuiButton (Painting Class):
package com.lojana.oregon.src;
import java.awt.*;
public class GuiButton {
public GuiButton(Graphics g, String text, Font font, int coordX, int coordY,
int textX, int textY, int width, int height) {
Color border = Color.gray;
Color fill = Color.white;
Color textColor = Color.black;
Stroke borderSize = new BasicStroke(8);
g.setColor(border);
((Graphics2D) g).setStroke(borderSize);
g.drawRect(coordX, coordY, width, height);
g.setColor(fill);
g.fillRect(coordX, coordY, width, height);
g.setColor(textColor);
g.setFont(font);
g.drawString(text, textX, textY);
}
}
GuiMainMenu (The file that uses the GuiButton file):
package com.lojana.oregon.src;
import java.awt.*;
public class GuiMainMenu {
public static void paint(Graphics g) {
new GuiButton(g, "Start Game", new Font("Arial", Font.BOLD, 20), 60, 80, 20, 20, 240, 40);
}
}
If you know how to fix it, please comment. Thank you so much :)
Upvotes: 1
Views: 2566
Reputation: 17784
Swing programs are supposed to override paintComponent(Graphics g)
instead of paint(Graphics g)
and directly to the JFrame
. See this article for details:
http://java.sun.com/products/jfc/tsc/articles/painting/
In addition it would be better to override the paintComponent
of a JPanel
that is added to the (content pane of) JFrame
instead of the JFrame
itself, because you want to draw into this content pane. See this tutorial for details:
http://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html
Upvotes: 5