I'm just getting back into Java programming and long story short, I made an Applet without knowing those can only run in browsers so I tried to change to code so I could put it in a runnable .Jar, but when I run my code it doesn't do anything.
public static void main(String args[])
{
setBackground(Color.black); //Sets the background to black.
Font myFont = new Font("Arial", Font.PLAIN, 14); //Makes "myFont" a font that is plain.
setFont(myFont); //Sets the font to "myFont"..
}
private static void setFont(Font myFont) {
}
private static void setBackground(Color black) {
}
public void paint(java.awt.Graphics g) {
g.setColor(Color.blue); //Sets anything in "paint" to be in blue.
int xArray[] = {20, 110, 200, 200, 110, 20, 20}; //This line, and the line below are the cords for the bowtie.
int yArray[] = {20, 45, 20, 100, 65, 100, 20};
g.drawPolygon(xArray, yArray, 7); //Draws the bowtie.
g.drawString("Bow ties are no longer cool.", 20, 150); //Writes the text.
}
}
The code is only doing what you tell it to:
The main method will run of course.
It then calls setFont, setBackground, both methods of which do nothing since you've written them to do nothing
And then the main method and the program ends.
A paint(...) method will have no effect if it is not overriding the paint method of a Swing component, which yours is not.
Better to override the paintComponent method of a Swing component, which the tutorials will tell you all about.
I'm surprised that you're expecting it to do more. If you want a GUI to actually show, then get most of your code out of the static realm and into the class or instance realm, have your code extend JPanel, override its paintComponent, and put your JPanel in a JFrame in your main method. Most important, read the tutorials as they will show you the best path for this. You can find links to the Swing tutorials and other Swing resources here: Swing Info
For example,
import java.awt.*;
import javax.swing.*;
public class SwingExample extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = 300;
public SwingExample() {
setBackground(Color.black); //Sets the background to black.
Font myFont = new Font("Arial", Font.PLAIN, 14); //Makes "myFont" a font that is plain.
setFont(myFont); //Sets the font to "myFont"..
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.blue); //Sets anything in "paint" to be in blue.
int xArray[] = {20, 110, 200, 200, 110, 20, 20}; //This line, and the line below are the cords for the bowtie.
int yArray[] = {20, 45, 20, 100, 65, 100, 20};
g.drawPolygon(xArray, yArray, 7); //Draws the bowtie.
g.drawString("Bow ties are no longer cool.", 20, 150); //Writes the text.
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
SwingExample mainPanel = new SwingExample();
JFrame frame = new JFrame("SwingExample");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Related
I am currently working on a simple pong-like game, but I got stucked with positioning the rectangle.
I want to change it's Y position to be at the half of the actual panel's height.
package com.game;
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("gEngine");
Player playerOne = new Player(frame);
Player playerTwo = new Player(frame);
}
}
package com.game;
import javax.swing.*;
import java.awt.*;
public class Player {
public Player(JFrame frame) {
MyPanel panel = new MyPanel();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.BLACK);
frame.setSize(1280, 720);
frame.setVisible(true);
}
}
class MyPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(50, 60, 20, 120);
}
}
Your code has a lot of "problems". I suggest you to find some kind of tutorials or something. You frame.setVisible(true) and stuff inside Player's class constructor. Do you realize that every time you create a Player object, all these things will be applied to the JFrame? Is this necessary? Maybe you should do them only once. Also in order to paint the compnent according to its position according size, you can do g.fillRect(50, getHeight() / 2, 20, 120);
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame("gEngine");
Player playerOne = new Player();
Player playerTwo = new Player();
// Set the proper layout manager
frame.setLayout(new GridLayout());
frame.add(playerOne.getMyPanel());
frame.add(playerTwo.getMyPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.BLACK);
frame.setSize(1280, 720);
frame.setVisible(true);
}
public static class Player {
private JPanel myPanel;
public Player() {
this.myPanel = new MyPanel();
}
public JPanel getMyPanel() {
return myPanel;
}
}
static class MyPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
// let the component be painted "natural"
super.paintComponent(g);
// Do custom painting
g.setColor(Color.WHITE);
g.fillRect(50, getHeight() / 2, 20, 120);
}
}
}
Edit (based on comment):
The background is the default one because GridLayout splits the screen into 2 panels (in the middle of the frame). Even the frame has BLACK background, these 2 panels cover it. So the background you see is from the panels, and not from the frame. In order to change it you will have to change the background of the panels (and make them non-transparent):
static class MyPanel extends JPanel {
public MyPanel() {
super();
setOpaque(true);
setBackground(Color.BLACK);
}
#Override
public void paintComponent(Graphics g) {
// let the component be painted "natural"
super.paintComponent(g);
// Do custom painting
g.setColor(Color.WHITE);
g.fillRect(50, getHeight() / 2, 20, 120);
}
}
What I am trying to achieve is that the program would draw a line in the middle of the frame as soon as the user has clicked draw. But sadly nothing is happening other than "frame 3" is disappearing. Any ideas about how I could fix the problem?
Here is the method:
Windowj is my frame. Frame3 is the previous frame please don't worry about it.
public static void graf() {
frame3.setVisible(false);
windowj.setSize(400, 500);
windowj.setLocationRelativeTo(null);
windowj.setResizable(false);
windowj.setLayout(null);
windowj.setVisible(true);
windowj.setTitle("Graphs");
windowj.setDefaultCloseOperation(EXIT_ON_CLOSE);
xinwindow.setBounds(30,40, 90, 40);
yinwindow.setBounds(100,100,90,40);
thefunction.setBounds(200,300,90,40);
draw.setBounds(300,200,90,40 );
windowj.add(xinwindow);
windowj.add(yinwindow);
windowj.add(thefunction);
windowj.add(draw);
c.setPreferredSize(new Dimension(300,200));
draw.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
windowj.add(c);
c.revalidate();
c.repaint();
}
And here is the paintcomponent method:
private static Component c = new JComponent() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine(50, 0, 70 , 100);
}
};
Any help would be appreciated, and please try to keep it simple, I am a beginner. :)
I will assume you use windowj as your JFrame and that what will happen when you click draw button your use windowj.setVisible(false) and that will make your window disappear
so remove it
2nd thing is you need to put your Component in windowj as windowj.add(c); in your draw ActionListener at actionPerformed before c.revalidate();
and here a little code that I wrote to understand what I mean:
public class DrawLine {
private JFrame windowj = new JFrame();
private JButton draw = new JButton();
private static int width = 640, height = 480;
private static JComponent c = new JComponent() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine((width/2) - 1, 0, (width/2) +1 , height);
}
};
public DrawLine() {
windowj.setDefaultCloseOperation(windowj.EXIT_ON_CLOSE);
windowj.setSize(width, height);
windowj.setLayout(new FlowLayout());
windowj.setResizable(false);
windowj.setLocationRelativeTo(null);
windowj.setVisible(true);
draw = new JButton("Draw");
draw.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//i don't know why you set windowj(windowj) false but that will close your window
//windowj.setVisible(false);
//add component to windowj(windowj)
windowj.add(c);
c.revalidate();
c.repaint();
}
});
c.setPreferredSize(new Dimension(width, height-100));
windowj.add(draw);
}
public static void main(String[] args) {
new DrawLine();
}
}
Here is the modified code:
private JFrame frame3, windowj;
private JPanel xinwindow, yinwindow,thefunction;
private JButton draw;
private static Component c = new JComponent() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine(50, 0, 70 , 100);
}
};
public DrawLine() {
xinwindow = new JPanel();
yinwindow = new JPanel();
thefunction = new JPanel();
draw = new JButton("Draw");
//i ignored frame3 as you said so just ignore my implementation here
frame3 = new JFrame();
frame3.setVisible(false);
windowj = new JFrame();
windowj.setSize(400, 500);
windowj.setLocationRelativeTo(null);
windowj.setResizable(false);
windowj.setLayout(null);
windowj.setVisible(true);
windowj.setTitle("Graphs");
windowj.setDefaultCloseOperation(EXIT_ON_CLOSE);
/*i used setBackground(Color.anycolor); to make it easier for me to know where
your window is in your frame*/
xinwindow.setBackground(Color.RED);
xinwindow.setBounds(30,40, 90, 40);
yinwindow.setBackground(Color.yellow);
yinwindow.setBounds(100,100,90,40);
thefunction.setBounds(200,300,90,40);
thefunction.setBackground(Color.green);
draw.setBounds(300,200,90,40 );
windowj.add(xinwindow);
windowj.add(yinwindow);
windowj.add(thefunction);
windowj.add(draw);
//here use setBonds instead of setPreferredSize
c.setBounds(100, 200, 200, 200);
draw.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
windowj.add(c);
c.revalidate();
c.repaint();
}
});
}
public static void main(String[] args) {
new DrawLine();
}
hope that solve your problem.
I have to do a little Game in Java Swing for school. I created some gifs for it and wanted to put them in and I did, but the problem is that the gifs flicker sometimes. I really can't find anything on the Internet and honestly I don't even know where to start to look exactly.
My code:
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class Chicken extends JFrame {
private int canvasWidth = 560;
private int canvasHeight = 480;
private Color sideGreen = new Color(14, 37, 14);
private Color gapGreen = new Color(56, 148, 56);
private Color edgeGreen = new Color(49, 129, 49);
private Image chicken;
private Image cookie;
private DrawCanvas canvas;
public Chicken() {
canvas = new DrawCanvas();
canvas.setPreferredSize(new Dimension(canvasWidth, canvasHeight));
try {
addImages();
} catch (Exception ex) {
ex.printStackTrace();
}
Container cp = getContentPane();
cp.add(canvas);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setTitle("Chicken");
pack();
setVisible(true);
}
private class DrawCanvas extends JPanel {
#Override
public void update(Graphics g) {
paintComponent(g);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
setDoubleBuffered(true);
setBackground(Color.BLACK);
g2.setColor(sideGreen);
g2.fillRect(0, 0, 80, canvasHeight);
g2.fillRect(canvasWidth - 80, 0, 80, 480);
g2.setColor(gapGreen);
g2.fillRect(80, 0, 400, 100);
g2.fillRect(80, canvasHeight - 100, 400, 100);
g2.setColor(edgeGreen);
g2.fillRect(80, 80, 400, 20);
g2.fillRect(80, canvasHeight - 100, 400, 20);
g2.drawImage(cookie, 85, 5, this);
g2.drawImage(chicken, 150, 120, this);
}
}
private void addImages() throws Exception {
ImageIcon iconCookie = new ImageIcon(new URL("https://i.stack.imgur.com/1PcWC.gif"));
Image cookieimage = iconCookie.getImage();
Image newimg = cookieimage.getScaledInstance(70, 70, Image.SCALE_DEFAULT);
iconCookie = new ImageIcon(newimg);
ImageIcon iconChicken = new ImageIcon(new URL("https://i.stack.imgur.com/qJA7G.gif"));
Image chickenimage = iconChicken.getImage();
Image newimgc = chickenimage.getScaledInstance(250, 250, Image.SCALE_DEFAULT);
iconChicken = new ImageIcon(newimgc);
chicken = iconChicken.getImage();
cookie = iconCookie.getImage();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Chicken());
}
}
Is there something wrong in the code? Or is there another way to do it and I've just done it wrong? The gifs should be fine, I've created them myself and they look fine when I view them from my PC.
Chicken
Cookie
Edit
Found out that the chicken isn't flickering when I remove the cookie, but I don't know why.
Remove setDoubleBuffered(true); from paintComponent. Probably temptative code. You could call it in the constructor, but by default double buffering is on. Move setBackground(Color.BLACK); to the constructor.
Then remove the update method.
You normally do not need to call super.paintComponent();. Comment it out, and try to see a change.
You might do setContentPane(canvas).
Should there still be a problem, then it is due to the inner workings of gif handling.
So, I need to make the stick-man movable by a user-input. When the user clicks on a part (Head, hands, feet and posterior) and he should move, and have no idea how to go about this..
If possible, there also needs to be a confine around the character, likely rectangular, so that there is a limit to how far each part can be pulled.
See below for my code;
// Created by Charlie Carr - (28/11/17 - /11/17)
import java.awt.*;
import java.applet.Applet;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
//Imports complete
//Suppress warning about undeclared static final serialVersionUID field in VS Code
#SuppressWarnings("serial")
public class Animator extends JPanel {
public static class AnimatorWindow extends JPanel {
public void paint(Graphics page) {
setBackground(Color.gray);
setForeground(Color.white);
super.paintComponent(page);
page.drawString("Stickmen Animation Station", 150, 15);
//draw the head
//x1, y1, x2, y2
page.drawOval(90, 60, 20, 20);
// draw the body
page.drawLine(100, 80, 100, 110);
// draw the hands
page.drawLine(100, 90, 80, 105);
page.drawLine(100, 90, 120, 105);
//draw the legs, he hasn't a leg to stand on..
page.drawLine(100, 110, 85, 135);
page.drawLine(100, 110, 115, 135);
}
}
public static void main(String[] args) {
AnimatorWindow displayPanel = new AnimatorWindow();
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(displayPanel, BorderLayout.CENTER);
//declare window size
int x = 480;
int y = 240;
JFrame window = new JFrame("GUI");
window.setContentPane(content);
window.setSize(x, y);
window.setLocation(101, 101);
window.setVisible(true);
}
}
Use MouseListenerto deal with mouse events.
Also, you should override the paintComponent() method instead of paint(), because paint() also paints the border and other stuff.
public static class AnimatorWindow extends JPanel implements MouseListener{
public AnimatorWindow(){
setBackground(Color.gray);
setForeground(Color.white);
//add the listener
addMouseListener(this);
}
public void paintComponent(Graphics page) {
super.paintComponent(page);
//You should not alter the Graphics object passed in
Graphics2D g = (Graphics2D) page.create();
//draw your stuff with g
g.drawString("Stickmen Animation Station", 150, 15);
.......
//finish
g.dispose();
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseClicked(MouseEvent e){
//implement your clicking here
//Use e.getX() and e.getY() to get the click position
}
}
For more on swing events, check this site
EDIT: Your problem also includes animation, and you can use a javax.swing.Timer to do that.
Im trying to make an application that will change the state of a traffic light in the click of a button.
My code: Main
import javax.swing.*;
public class PP416
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Traffic light");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TrafficPanel());
frame.pack();
frame.setVisible(true);
}
}
JPanel Class:
import javax.swing.*;
import java.awt.*;
import java.awt.Event;
public class TrafficPanel extends JPanel
{
private JButton button;
private int indicator = 0; // Light is off
public TrafficPanel()
{
button = new JButton("Change");
this.add(button);
}
public void paint(Graphics g)
{
if (indicator == 0)
{
g.drawOval(30, 40, 30, 30);
g.drawOval(30, 70, 30, 30);
g.drawOval(30, 100, 30, 30);
}
}
}
the button just not appearing , just the ovalls.
anyone can help me with this?
Don't override paint but rather paintComponent and Most important, call the super's method. Your lack of a super call may be preventing your JPanel from drawing its child components well.
e.g.,
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (indicator == 0) {
g.drawOval(30, 40, 30, 30);
g.drawOval(30, 70, 30, 30);
g.drawOval(30, 100, 30, 30);
}
}