I took two open source games to learn how to overlay text onto one of the games from the other. however, whenever i try to transition one piece of code from the next all i get is exceptions. to make sure im drawing a string correct im using :
import java.awt.*;
public class charge{
Image buffer;
Graphics bufferg;
public void draw2(Graphics g2d){
g2d.setFont(new Font("Helvetica", Font.PLAIN, 13));
g2d.drawString("Most relationships seem so transitory", 20, 30);
}
}
can anyone tell me how im using graphics wrong?
Using the graphics class correctly is very tricky, especially if you're new to java. It's likely that the error your getting is a null pointer, because your g2d arg is probably null. One (preferred) way to draw text in java is to subclass the JPanel class and override the paint(Graphics) method so whenever the panel is drawn, it's drawn with text. Here's an example:
public class Test1 extends JFrame {
public Test1(){
TextPanel t = new TextPanel("Here's some text!");
getContentPane().add(t, BorderLayout.CENTER);
setMinimumSize(new Dimension(500, 500));
//Various JFrame initialization stuff.
//repaint() makes sure the text is immediately visible.
repaint();
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class TextPanel extends JPanel{
private String text;
public TextPanel(String t){
text = t;
}
//Called by swing whenever this or a parent component calls repaint()
#Override
public void paint(Graphics g){
g.setFont(new Font("Helvetica", Font.PLAIN, 13));
g.drawString(text, 20, 30);
}
}
public static void main(String[] args){
new Test1();
}
}
If you want to use the text for overlays then just make sure the background of the TextPanel is transparent and place it wherever you want to on the window.
Related
After making an instance in a previous frame, I'm trying to the background image on the next frame but as a result, I just saw the debugged result and found out that the paint method was not called. From what I know, the paint method is inherited by the JFrame class and with this logic, I've made it overrided. As I guess, the reason happen the logical error is from what I used the event handler and made the instance in the EventHandlerClass.
if(e.getActionCommand().equals(ButtonTo))
if(idString.equals("USER"))
{
{
if("1234".equals(pwSt))
{
System.out.println("Wellcome");
if(gs==null)
{
gs=new GameStart();
}
}
else
{
System.out.println("Confirm your password");
}
}
}
This is a code that If an action is performed it will make an instance(gs). After doing this, I noticed that the instance has been used as to make a new console frame.
class GameStart extends JFrame {
private Image screenImage;
private Graphics screenGraphic;
private Image introBackgroundImage;
private ImageIcon img;
GameStart()
{
JFrame jf=new JFrame("Game Set");
jf.setBounds(300, 300, 400, 200);
jf.setLayout(new BorderLayout());
JButton bt1=new JButton("Start");
JButton bt2=new JButton("Exit");
JPanel panel1=new JPanel();
panel1.add(bt1);panel1.add(bt2);
setContentPane(panel1);
jf.add(panel1, BorderLayout.SOUTH);
bt1.addActionListener(new Choice());
bt2.addActionListener(new Choice());
jf.setVisible(true);
img=new ImageIcon("./Images/backGroundImage.jpg");
System.out.println("1");
}
public void paint(Graphics g) {
screenImage=createImage(200, 200);
screenGraphic=screenImage.getGraphics();
screenDraw(screenGraphic);
g.drawImage(screenImage, 0, 0, null);
System.out.println("2");
}
public void screenDraw(Graphics g)
{
this.repaint();
System.out.println("3");
}
Now, With making a frame and some buttons, I expect to show all the numbers(1, 2, 3) that indicate the result but Just did number 1.
There are some errors in your code that I can see at first glance:
You're extending JFrame, but you're not adding any extra functionality to it, see: Extends JFrame vs. creating it inside the program. Instead, build your GUI towards the use of JPanels and override their paintComponent(...) method and not the paint(...) one.
You're breaking the paint-chain: After doing the above point, in paintComponent(), call super.paintComponent(...)
Maybe there are others but I'm currently busy and can't test your code, but the ones above should help with your issue.
I have nested a Jpanel within another JPanel. I want to refresh one of JPanels while not refreshing the other one. I have the following code, I can use the repaint() function however it will update all of the JPanels not just the one that I want (the Time JPanel).
How would I go about refreshing just the Time JPanel? Leaving the Weather JPanel untouched?
I would like to be able to do this from an external thread.
public class MainPanel extends JPanel{
public static JPanel TimePanel = new Time();
public static Weather WeatherPanel = new Weather();
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.BLACK);
this.setLayout(new FlowLayout(FlowLayout.LEADING, 0, 0));
TimePanel.setLocation(0, 0);
TimePanel.setSize(new Dimension(500, 300));
this.add(TimePanel);
WeatherPanel.setLocation(0,300);
WeatherPanel.setSize(new Dimension(100, 100));
this.add(WeatherPanel);
//repaint();//Just causes recursion
}
}
Your code is completely wrong. The paintComponent() method is used for painting with the Graphics object. You should NEVER add components to a panel or change the size, or change the location of a component in a painting method.
There is no need for you to override the paintComponent() method.
In the constructor of your class is where you create the child panels and add them to the main panel. Something like:
public class MainPanel extends JPanel
{
public JPanel timePanel = new Time();
public Weather teatherPanel = new Weather();
public MainPanel()
{
this.setBackground(Color.BLACK);
this.setLayout(new FlowLayout(FlowLayout.LEADING, 0, 0));
this.add(timePanel);
this.add(weatherPanel);
}
}
Notice how I also changed your variables:
you should not be using static
variable names start with a lower case character.
I suggest you start by reading the Swing Tutorial for Swing basics. You can check out the section on How To Use Panels for a working example.
I'm new to Java and I want to make a simple game where there are squares in a simple grid (something between a snake and a labyrinth). The number of squares doesn't change, only their color does.
I already programmed the objects I need for the game. Now I want to display the game.
I know how to create a JFrame, a JPanel and a JButton, which I will need, but I don't understand how to draw in a canvas.
I made a test class:
import javax.swing.*;
import java.awt.*;
public class Test extends Canvas {
public static void main (String[] arg) {
JFrame f=new JFrame();
f.setTitle("Title");
f.setSize(400,500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
JPanel pan=new JPanel(new FlowLayout());
pan.add(new JButton("hey"));
Test canvas=new Test();
Graphics g=canvas.getGraphics();
canvas.paint(g);
pan.add(canvas);
f.setContentPane(pan);
}
public Test() {
setBackground (Color.green);
setSize(300,300);
setVisible(true);
}
public void paint(Graphics g) {
Color c = g.getColor();
g.setColor(Color.RED);
g.fillRect(10,10,80,80);
g.setColor(Color.BLUE);
g.fillRect(150,50,80,80);
g.setColor(c);
}
}
When I run this, a windows is created, with the correct title , size and button, but there isn't anything else (no green background, no red or blue rectangle), and an error is detected :
Exception in thread "main" java.lang.NullPointerException
at Test.paint(Test.java:25)
at Test.main(Test.java:15)
What am I doing wrong ? Is there a better way to draw these squares ?
Thanks !
Comment these two lines
//Graphics g=canvas.getGraphics();
//canvas.paint(g);
And change the paint method as follows.
#Override
public void paint(Graphics g) {
super.paint(g);
Rest is all fine. Hope it helps you to progress.
i am trying for days to add a second window to my applet in which i want to draw mathematical graphs. Getting the second window is no problem, but i can't get the drawing to work. Maybe you can help me. This is my latest try:
import java.awt.*;
public class FFrame extends Frame{
public FFrame(){
Panel p = new MyPanel();
add(p);
}
private class MyPanel extends Panel {
protected void paintComponent(Graphics g) {
super.paintComponents(g);
g.setColor(Color.WHITE);
g.drawLine(10, 10, 100, 100);
}
};
}
I add this to my applet by creating a new FFrame-Object "f" and run f.show() in the init() method. I don't use swing, by the way.
I believe JViewport does work with JPanel, but when I build a new class that extends JPanel, it seem as if the JViewport is ignore by the program. I don't know if I do anything wrong, so this is the test I conduct and still get the same result:
public class panel extends JPanel
{
public panel()
{
super();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.BLUE);
g.drawString("Hello World", 50, 50);
g.setColor(Color.RED);
g.fillRect(50,50,100,100);
g.setColor(Color.BLACK);
g.fillOval(100, 100, 50, 50);
}
}
public class test extends JFrame
{
private panel p;
public void init()
{
this.setSize(1000, 1000);
this.setLayout(new BorderLayout());
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
p = new panel();
p.setOpaque(false);
JViewport v = new JViewport();
v.setViewSize(new Dimension(200,200));
v.setViewPosition(new Point(2000,2000));
v.setView(p);
this.add(v,BorderLayout.CENTER);
}
public test()
{
init();
}
public static void main(String[] args)
{
test t = new test();
}
}
It suppose to show part of the painted JPanel, but the JFrame window just display the whole JPanel. Therefore, I don't know if I did any wrong or JViewport is not built for this purpose. If it is the latter, then it would be great if anyone can suggest a workaround solution.
Thanks
The BorderLayout you're using is causing the viewport, which is placed in the center, to take the entire space inside the frame, since there are no other components in that layout. That's how the BorderLayout works.
Thus the viewport is also given a bigger size than defined (the size is overwritten by the layout manager). Since the panel doesn't have a fixed size either, it will also be resized.
In order to change that, either use a different layout manager or set a minimum/maximum size for the viewport and override getPreferredSize() for the panel.
As a side note: don't use lower case class names like panel.