GUI is showing up blank. No Errors during compiling - java

I tried to run my code and it went through without any issues, but the GUI is showing a blank when I run it. This is the main class for my project, I have several other subclasses. I've looked over it several times to figure out what's wrong and I can't seem to. Did I use setVisible incorrectly? The project 3 class should generate a GUI which allows the user to input the type of shape they want, the color of the shape, and the fill type of the shape.
public class Project3 extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel shapeType, fillType, color, Width, Height, xCoordinate, yCoordinate;
JTextField xCoor, yCoor, jWidth, jHeight;
JPanel left, right, down;
String shapetoDraw, shapeColor, filltype;
Rectangular rect;
Oval ov;
Drawing drawing= new Drawing();
Project3(){
setTitle("Geometric Drawing");
setLayout(null);
setSize(600,500);
left = new JPanel(new GridLayout(2,2,10,10));
right = new JPanel(new GridLayout(0, 2));
right.setBorder(BorderFactory.createTitledBorder("Shape Drawing"));
down = new JPanel(new GridLayout(2,2,10,10));
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
shapeType = new JLabel("Shape Type");
fillType = new JLabel("Fill Type");
color = new JLabel("Color");
Width = new JLabel("Width");
Height = new JLabel("Height");
xCoordinate = new JLabel("x coordinate");
yCoordinate = new JLabel("y coordinate");
xCoor = new JTextField(10);
yCoor = new JTextField(10);
jWidth = new JTextField(10);
jHeight = new JTextField(10);
left.add(shapeType);
String[] shape = {"Rectangle","Oval"};
JComboBox<String> shapeCombo = new JComboBox<String>(shape);
left.add(color);
String[] colors = {"Black", "Red", "Orange","Yellow","Green","Blue","Magenta"};
JComboBox<String> colorCombo = new JComboBox<String>(colors);
left.add(fillType);
String[] fill = {"Hollow", "Solid"};
JComboBox<String> filltypeCombo = new JComboBox<String>(fill);
left.add(Width);
left.add(jWidth);
left.add(Height);
left.add(jHeight);
left.add(xCoordinate);
left.add(xCoor);
left.add(yCoordinate);
left.add(yCoor);
JButton drawButton = new JButton("Draw");
drawButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapetoDraw=shapeCombo.getSelectedItem().toString();
shapeColor=colorCombo.getSelectedItem().toString();
filltype=filltypeCombo.getSelectedItem().toString();
drawing.drawShape(shapetoDraw, shapeColor, filltype);
}});
down.add(drawButton);
}
public static void main(String[] args) {
Project3 mainFrame = new Project3();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}
public void paint(Graphics g) {
super.paintComponents(g);
//g.setFont(new Font("Times", Font.BOLD, 12));
//g.drawString(Integer.toString(Shape.getNoOfShapes()),10, 30);
//rect.draw(g);
}}

Related

Java Swing GridLayout Change Grid Sizes

I'm trying to create a program that lists movies in a Netflix style to learn Front-End coding.
How I want it to look in the end:
My guess is that every movie is a button component with an image a name label and a release year label.
I'm struggling to recreate this look. This is how it looks when I try it:
The navigationbar in my image is at the page start of a border layout. Below the navigationbar the movie container is in the center of the border layout.
My idea was creating a GridLayout and then create a button for each movie and adding it to the GridLayout.
You can recreate this with this code:
public class Main {
private static JFrame frame;
public static void main(String[] args) throws HeadlessException {
frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setBackground(new Color(32, 32, 32));
JPanel navigationPanel = createNavigationBar();
frame.add(navigationPanel, BorderLayout.PAGE_START);
JPanel moviePanel = createMoviePanel();
frame.add(moviePanel, BorderLayout.CENTER);
frame.setPreferredSize(new Dimension(1920, 1080));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Example App");
frame.pack();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
public static JPanel createMoviePanel() {
JPanel moviePanel = new JPanel();
GridLayout layout = new GridLayout(0, 10);
layout.setHgap(3);
layout.setVgap(3);
moviePanel.setLayout(layout);
moviePanel.setBackground(new Color(32, 32, 32));
ArrayList<String> exampleList = new ArrayList<>();
// Add stuff to the example list
for(int i = 0; i < 120; i++) {
exampleList.add(Integer.toString(i));
}
final File root = new File("");
for(final String movie : exampleList) {
JLabel picLabel = new JLabel();
try {
File imageFile = new File(root.getAbsolutePath() + "\\src\\images\\" + "imageName.jpg"); // Try to find the cover image
if(imageFile.exists()) {
BufferedImage movieCover = ImageIO.read(imageFile);
picLabel = new JLabel(new ImageIcon(movieCover));
} else {
BufferedImage movieCover = ImageIO.read(new File(root.getAbsolutePath() + "\\src\\images\\temp.jpg")); // Get a temp image
picLabel = new JLabel(new ImageIcon(movieCover));
}
} catch (IOException e) {
e.printStackTrace();
}
JLabel movieName = new JLabel("New Movie");
movieName.setForeground(Color.WHITE);;
JButton movieButton = new JButton();
movieButton.setLayout(new GridLayout(0, 1));
//movieButton.setContentAreaFilled(false);
//movieButton.setBorderPainted(false);
//movieButton.setFocusPainted(false);
movieButton.add(picLabel);
movieButton.add(movieName);
moviePanel.add(movieButton);
}
return moviePanel;
}
public static JPanel createNavigationBar() {
JPanel navBar = new JPanel();
navBar.setLayout(new FlowLayout(FlowLayout.LEFT, 30, 20));
navBar.setBackground(new Color(25, 25, 25));
JButton homeButton = new JButton("Home");
homeButton.setContentAreaFilled(false);
homeButton.setBorderPainted(false);
homeButton.setFocusPainted(false);
JButton movieButton = new JButton("Movies");
movieButton.setContentAreaFilled(false);
movieButton.setBorderPainted(false);
movieButton.setFocusPainted(false);
// Add all the buttons to the navbar
navBar.add(homeButton);
navBar.add(movieButton);
return navBar;
}
}
I noticed that the GridLayout always tries to fit everything onto the window.
All that's needed is a properly configured JButton in a GridLayout.
E.G.
public static JPanel createMoviePanel() {
JPanel movieLibraryPanel = new JPanel(new GridLayout(0, 10, 3, 3));
movieLibraryPanel.setBackground(new Color(132, 132, 132));
int m = 5;
BufferedImage image = new BufferedImage(9 * m, 16 * m, BufferedImage.TYPE_INT_RGB);
for (int ii = 1; ii < 21; ii++) {
JButton picButton = new JButton("Mov " + ii, new ImageIcon(image));
picButton.setMargin(new Insets(0,0,0,0));
picButton.setForeground(Color.WHITE);
picButton.setContentAreaFilled(false);
picButton.setHorizontalTextPosition(JButton.CENTER);
picButton.setVerticalTextPosition(JButton.BOTTOM);
movieLibraryPanel.add(picButton);
}
return movieLibraryPanel;
}
Here is a complete source for the above with a tweak to put the year on a new line. It uses HTML in the JButton to break the button text into two lines.
The input focus is on the first button, whereas the mouse hovers over the '2009' movie:
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
class MovieGrid {
MovieGrid() {
JFrame f = new JFrame("Movie Grid");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.add(createMoviePanel());
f.pack();
f.setVisible(true);
}
public static JPanel createMoviePanel() {
JPanel movieLibraryPanel = new JPanel(new GridLayout(0, 10, 3, 3));
movieLibraryPanel.setBackground(new Color(132, 132, 132));
int m = 5;
BufferedImage image = new BufferedImage(
9 * m, 16 * m, BufferedImage.TYPE_INT_RGB);
for (int ii = 2001; ii < 2021; ii++) {
JButton picButton = new JButton(
"<html>Movie<br>" + ii, new ImageIcon(image));
picButton.setMargin(new Insets(0,0,0,0));
picButton.setForeground(Color.WHITE);
picButton.setContentAreaFilled(false);
picButton.setHorizontalTextPosition(JButton.CENTER);
picButton.setVerticalTextPosition(JButton.BOTTOM);
movieLibraryPanel.add(picButton);
}
return movieLibraryPanel;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new MovieGrid();
}
};
SwingUtilities.invokeLater(r);
}
}
Same idea's from Andrew Thompson answer but with some minor text alignment changes and hover effect
final class Testing
{
public static void main(String[] args)
{
JFrame frame=new JFrame("NEFLIX");
frame.setContentPane(new GridDisplay());
frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static final class GridDisplay extends JPanel implements ActionListener
{
private GridDisplay()
{
super(new GridLayout(0,5,20,20));
setBackground(new Color(0,0,0,255));
BufferedImage image=new BufferedImage(150,200,BufferedImage.TYPE_INT_RGB);
Graphics2D g2d=(Graphics2D)image.getGraphics();
g2d.setColor(Color.BLUE);
g2d.fillRect(0,0,image.getWidth(),image.getHeight());
HoverPainter painter=new HoverPainter();
for(int i=0;i<10;i++)
{
TVShowCard card=new TVShowCard(image,"Show "+i,"199"+i);
card.addMouseListener(painter);
add(card);
}
}
//highlight only on hover
private final class HoverPainter extends MouseAdapter
{
#Override
public void mouseExited(MouseEvent e) {
((TVShowCard)e.getSource()).setBorderPainted(false);
}
#Override
public void mouseEntered(MouseEvent e) {
((TVShowCard)e.getSource()).setBorderPainted(true);
}
}
private final class TVShowCard extends JButton
{
private TVShowCard(BufferedImage preview,String name,String year)
{
super();
setContentAreaFilled(false);
setBackground(new Color(0,0,0,0));
setFocusPainted(false);
setBorderPainted(false);
//I didn't use image icon & text horizontal alignment because the text always horizontally centered aligned but from the expected output it was left so created 2 labels for the job
setLayout(new GridBagLayout());
addIcon(preview);
addLabel(name,year);
addActionListener(GridDisplay.this);
}
private void addIcon(BufferedImage preview)
{
JLabel icon=new JLabel();
icon.setIcon(new ImageIcon(preview));
add(icon,new GridBagConstraints(0,0,1,1,1.0f,0.0f,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(0,0,0,0),0,0));
}
private void addLabel(String name,String year)
{
JLabel label=new JLabel("<html><body>"+name+"<br>"+year+"</body></html>");
label.setForeground(Color.white);
label.setBackground(new Color(0,0,0,0));
add(label,new GridBagConstraints(0,1,1,1,1.0f,1.0f,GridBagConstraints.SOUTHWEST,GridBagConstraints.NONE,new Insets(5,0,0,0),0,0));
}
}
#Override
public void actionPerformed(ActionEvent e)
{
TVShowCard card=(TVShowCard)e.getSource();
//do stuff with it
}
}
}

I want to use a variable outside of "public void actionPerformed(ActionEvent e) {}"

I need to create a GUI and enter the height and width there, click on the button and a new window will start with these heights and widths. Аt the moment I have variable values width and height ​​which are set in public void actionPerformed(ActionEvent e) {} and I want to use them to transfer the values ​​for a new window. I came to the conclusion that it is necessary either to pull values ​​from the JTextField itself or the way that I want to implement
public class Form extends JFrame implements Runnable {
//private int w= 1280;
//private int h=768;
public int wt;
public int ht;
public void Okno() {
JFrame win1 = new JFrame("Evolution.IO");
win1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win1.setLayout(new BorderLayout());
win1.setSize(470, 400);
JPanel pane = new JPanel();
pane.setLayout(new FlowLayout());
JTextField txtField = new JTextField(5);
JTextField txtField2 = new JTextField(5);
JLabel weightL = new JLabel("Weight: ");
JLabel highL = new JLabel("High: ");
pane.add(weightL);
pane.add(txtField);
pane.add(highL);
pane.add(txtField2);
JButton btn = new JButton("Начать симуляцию");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
wt = Integer.parseInt(txtField.getText());
ht = Integer.parseInt(txtField2.getText());
if (!(txtField==null)) {
Form f = new Form();
new Thread(f).start();
win1.getDefaultCloseOperation();
}
}
});
pane.add(btn);
win1.add(pane);
win1.setLocationRelativeTo(null);
win1.setVisible(true);
}
//THIS DOESNT WORK#
// public int w1() {
// return this.wt;
// }
// public int h1() {
// return this.ht;
// }
private final int FRAMES_TOTAL = 100000;
private final int SKIP_FRAMES = 10;
private final Color BG = new Color(200, 200, 200, 255);
private final Color BLUE = new Color(150, 160, 255, 255);
private final Color RED = new Color(255, 100, 120, 255);
private BufferedImage buf = new BufferedImage(w1(), h1(), BufferedImage.TYPE_INT_RGB);
private BufferedImage img = new BufferedImage(w1(), h1(), BufferedImage.TYPE_INT_RGB);
private BufferedImage graph = new BufferedImage(w1(), h1(), BufferedImage.TYPE_INT_ARGB);
//no longer needed

Paint a parabola using JTextField values in Java

The program consists of drawing a parabola using the values from the A, B and C jtextfields every time the button is pressed:
It also has to be on two separate classes, the View which displays the menu and the Controller which takes the inputs from the first class and paints the parabola.
My actual code:
public static void main(String[] args) {
JFrame frame = new JFrame("Parabola");
frame.getContentPane().setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(50, 50));
JLabel labelA = new JLabel();
labelA.setText("a");
JTextField textA = new JTextField("0",3);
JLabel labelB = new JLabel();
labelB.setText("b");
JTextField textB = new JTextField("0",3);
JLabel labelC = new JLabel();
labelC.setText("c");
JTextField textC = new JTextField("0",3);
JButton draw = new JButton();
draw.setText("Draw");
draw.addActionListener( new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
textA.getText();
textB.getText();
textC.getText();
}
});
panel1.add(labelA);
panel1.add(textA);
panel1.add(labelB);
panel1.add(textB);
panel1.add(labelC);
panel1.add(textC);
panel1.add(draw);
JPanel panel2 = new JPanel(){
double a=2, b=1, c=0;
public void section (Graphics g){
g.setColor(Color.blue);
g.drawLine(200,0,200,400);
g.drawLine(0,200,400,200);
for (int x=0; x<=400; x= x +40){
g.drawLine(x,195,x,205);
}
for (int y=0; y<=400; y=y+40){
g.drawLine(195,y,205,y);
}
}
public void graphic(Graphics g) {
g.setColor(Color.red);
for (double x=-100;x<=100;x = x+0.1){
double y = a * x * x + b * x + c;
int X = (int)Math.round(200 + x*20);
int Y = (int)Math.round(200 - y*20);
g.fillOval(X-2,Y-2,4,4);
}
}
public void paint (Graphics g){
section(g);
graphic(g);
}
};
panel2.setBackground(Color.WHITE);
frame.getContentPane().add(panel1, BorderLayout.PAGE_START);
frame.getContentPane().add(panel2, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.setSize(420,490);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
I`ve managed to do it in one class without the textfields working and have no idea how to separate the graphic into another class so it can do the operations and send them back to the view class again.
Solved it:
Class View
public class View extends JFrame {
public View() {
JFrame frame = new JFrame("Equation");
frame.getContentPane().setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(50, 50));
JLabel labelA = new JLabel();
labelA.setText("a");
JTextField textA = new JTextField("0",3);
JLabel labelB = new JLabel();
labelB.setText("b");
JTextField textB = new JTextField("0",3);
JLabel labelC = new JLabel();
labelC.setText("c");
JTextField textC = new JTextField("0",3);
JButton draw = new JButton();
draw.setText("Draw");
draw.addActionListener( new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
Controller.a = Double.parseDouble(textA.getText());
Controller.b = Double.parseDouble(textB.getText());
Controller.c = Double.parseDouble(textC.getText());
repaint();
frame.pack();
frame.setSize(420,490);
}
});
panel1.add(labelA);
panel1.add(textA);
panel1.add(labelB);
panel1.add(textB);
panel1.add(labelC);
panel1.add(textC);
panel1.add(draw);
JPanel panel2 = new JPanel(){
public void paint(Graphics g){
super.paint(g);
Controller.grid(g);
Controller.Graphic1(g);
}
};
panel2.setBackground(Color.WHITE);
frame.getContentPane().add(panel1, BorderLayout.PAGE_START);
frame.getContentPane().add(panel2, BorderLayout.CENTER);
frame.setVisible(true);
frame.setSize(420,490);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
View frame = new View();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Class Controller
public class Controller {
static double a=2, b=1, c=0;
public static void grid (Graphics g){
g.setColor(Color.blue);
g.drawLine(200,0,200,400);
g.drawLine(0,200,400,200);
for (int x=0; x<=400; x= x +40){
g.drawLine(x,195,x,205);
}
for (int y=0; y<=400; y=y+40){
g.drawLine(195,y,205,y);
}
}
public static void Graphic1(Graphics g) {
g.setColor(Color.red);
for (double x=-100;x<=100;x = x+0.1){
double y = a * x * x + b * x + c;
int X = (int)Math.round(200 + x*20);
int Y = (int)Math.round(200 - y*20);
g.fillOval(X-2,Y-2,4,4);
}
}
}

Trying to understand how Timer object works - JAVA SWING

I declare a Timer object at the start of my code, initialize it when a JButton is clicked but i can't stop it no matter what i do.
In my code i'm trying to stop the timer when the button print is clicked but it doesn't work.
Here's my Window.java class :
public class Window extends JFrame{
Panel pan = new Panel();
JPanel container, north,south, west;
public JButton ip,print,cancel,start,ok;
JTextArea timeStep;
JLabel legend;
double time=0;
double temperature=0.0;
Timer chrono;
public static void main(String[] args) {
new Window();
}
public Window()
{
System.out.println("je suis là");
this.setSize(1000,400);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setTitle("Assignment2 - CPU temperature");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container = new JPanel(new BorderLayout());
north = new JPanel();
north.setLayout(new BorderLayout());
ip = new JButton ("New");
north.add(ip, BorderLayout.WEST);
print = new JButton ("Print");
north.add(print,BorderLayout.EAST);
JPanel centerPanel = new JPanel();
centerPanel.add(new JLabel("Time Step (in s): "));
timeStep = new JTextArea("0.1",1,5);
centerPanel.add(timeStep);
start = new JButton("OK");
ListenForButton lForButton = new ListenForButton();
start.addActionListener(lForButton);
ip.addActionListener(lForButton);
centerPanel.add(start);
north.add(centerPanel, BorderLayout.CENTER);
south = new JPanel();
legend = new JLabel("Legends are here");
south.add(legend);
west = new JPanel();
JLabel temp = new JLabel("°C");
west.add(temp);
container.add(north, BorderLayout.NORTH);
container.add(west,BorderLayout.WEST);
container.add(pan, BorderLayout.CENTER);
container.add(south, BorderLayout.SOUTH);
this.setContentPane(container);
this.setVisible(true);
}
private class ListenForButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==start)
{
time=Double.parseDouble(timeStep.getText());
System.out.println(time);
chrono = new Timer((int)(1000*time),pan);
chrono.start();
}
if(e.getSource()==ip)
{
JPanel options = new JPanel();
JLabel address = new JLabel("IP Address:");
JTextField address_t = new JTextField(15);
JLabel port = new JLabel("Port:");
JTextField port_t = new JTextField(5);
options.add(address);
options.add(address_t);
options.add(port);
options.add(port_t);
int result = JOptionPane.showConfirmDialog(null, options, "Please Enter an IP Address and the port wanted", JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION)
{
System.out.println(address_t.getText());
System.out.println(port_t.getText());
}
}
if(e.getSource()==print)
{
chrono.stop();
}
}
}
}
And here's my Panel.java class:
public class Panel extends JPanel implements ActionListener {
int rand;
int lastrand=0;
ArrayList<Integer> randL = new ArrayList<>();
ArrayList<Integer> tL = new ArrayList<>();
int lastT = 0;
Color red = new Color(255,0,0);
Color green = new Color(0,150,0);
Color blue = new Color (0,0,150);
Color yellow = new Color (150,150,0);
int max=0;
int min=0;
int i,k,inc = 0,j;
int total,degr,moyenne;
public Panel()
{
super();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(1.8f));
g2.drawLine(20, 20, 20, this.getHeight()-50);
g2.drawLine(20, this.getHeight()-50, this.getWidth()-50, this.getHeight()-50);
g2.drawLine(20, 20, 15, 35);
g2.drawLine(20, 20, 25, 35);
g2.drawLine(this.getWidth()-50, this.getHeight()-50, this.getWidth()-65, this.getHeight()-45);
g2.drawLine(this.getWidth()-50, this.getHeight()-50, this.getWidth()-65, this.getHeight()-55);
if(!randL.isEmpty()){
g2.setColor(green);
g2.drawLine(15, this.getHeight()-50-max, this.getWidth()-50,this.getHeight()-50-max);
g2.setColor(blue);
g2.drawLine(15, this.getHeight()-50-min, this.getWidth()-50,this.getHeight()-50-min);
g2.setColor(yellow);
g2.drawLine(15, this.getHeight()-50-moyenne, this.getWidth()-50,this.getHeight()-50-moyenne);
}
for(i = 0; i<tL.size(); i++){
int temp = randL.get(i);
int t = tL.get(i);
g2.setColor(red);
g2.drawLine(20+t, this.getHeight()-50-temp, 20+t, this.getHeight()-50);
// Ellipse2D circle = new Ellipse2D.Double();
//circle.setFrameFromCenter(20+t, this.getHeight()-50, 20+t+2, this.getHeight()-52);
}
for(j=0;j<5;j++)
{
inc=inc+40;
g2.setColor(new Color(0,0,0));
g2.drawLine(18, this.getHeight()-50-inc, 22, this.getHeight()-50-inc);
}
inc=0;
}
#Override
public void actionPerformed(ActionEvent e) {
rand = (int)(50+((Math.random() * (80))));
lastT += 60;
randL.add(rand);
tL.add(lastT);
Object obj = Collections.max(randL);
max = (int) obj;
Object obj2 = Collections.min(randL);
min = (int) obj2;
if(!randL.isEmpty()) {
degr = randL.get(k);
total += degr;
moyenne=total/randL.size();
//System.out.println(moyenne);
}
k++;
if(randL.size()>=15)
{
randL.removeAll(randL);
tL.removeAll(tL);
//System.out.println(randL);
lastT = 0;
k=0;
degr=0;
total=0;
moyenne=0;
}
repaint();
}
}
Sorry this work is really messy, but if you succeed in finding the solution i'll thank you ! :D
Cheers!

How to add moving sprites to JFrame

I'm trying to add sprites to a JFrame that move or 'fidget' in place(meaning they just move up a pixel and then down a pixel), almost like the Pokemon sprites in your party menu move, but just with a single sprite. I got the code to work when I was just running it as a JApplet, but my larger game is built in a JFrame with multiple JPanels. When I tried to incorporate the working code into my larger game, it stopped working. Any help would be greatly appreciated. This is not for school, just my own personal game.
This begins the JApplet that works.
public class SpriteAnimation extends JApplet{
private static final long serialVersionUID = 1L;
public static final int WIDTH = 150;
public static final int HEIGHT = 50;
private PaintSurface canvas;
public void init(){
this.setSize(WIDTH, HEIGHT);
canvas = new PaintSurface();
this.add(canvas, BorderLayout.CENTER);
Timer t = new Timer(250, e -> {canvas.repaint();});
t.start();
}
}
public class PaintSurface extends JComponent{
private static final long serialVersionUID = 1L;
ArrayList<Sprite> sprites = new ArrayList<Sprite>();
public PaintSurface(){
sprites.add(new Hero(0));
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
doDrawing(g);
Toolkit.getDefaultToolkit().sync();
}
public void doDrawing(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for(Sprite h : sprites){
g2.drawImage(h.getImage(), h.getX(), h.getY(), null);
h.move();
}
}
}
public class Sprite {
private int x, y, fidget;
private Image image;
boolean flip = true;
public Sprite(String s, int fidget, int startingX) {
this.fidget = fidget;
ImageIcon icon = new ImageIcon(s);
image = icon.getImage();
x = startingX; y = 15;
}
public void move() {
y = 10;
if(!flip){
y += fidget;
flip = !flip;
}
else{
y -= fidget;
flip = !flip;
}
}
public Image getImage(){
return image;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
}
public class Hero extends Sprite {
private int startingX;
public Hero(int x){
super("Hero.png", 1, x);
this.startingX = x;
}
public int getStartingX() {
return startingX;
}
public void setStartingX(int startingX) {
this.startingX = startingX;
}
}
This is where I'd like to add the working Sprites to(Specifically the battlefield JPanel).
public class BattleFrame extends JFrame {
private static final long serialVersionUID = 1L;
static ArrayList<JButton> buttonsActions = new ArrayList<JButton>();
static ArrayList<JButton> buttonsConfirmation = new ArrayList<JButton>();
static ArrayList<JButton> buttonsAlly = new ArrayList<JButton>();
static ArrayList<JButton> buttonsEnemy = new ArrayList<JButton>();
static ArrayList<ArrayList<JButton>> buttons = new ArrayList<ArrayList<JButton>>();
static Box boxAllies = Box.createVerticalBox();
static int movesLeft = 3;
static JScrollPane logs;
static JTextArea log;
public BattleFrame(){
this.setSize(1200, 700);
this.setTitle("The Last Battle");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
JPanel battleField = new JPanel();
battleField.setBorder(BorderFactory.createTitledBorder("Battle Field"));
battleField.setLayout(new BorderLayout());
JPanel allies = new JPanel();
allies.setBorder(BorderFactory.createTitledBorder("Armies of Light"));
boxAllies.add(new JLabel("Moves left: " + movesLeft));
JButton channellers = new JButton("Channellers");
channellers.setName("Channellers"); buttonsAlly.add(channellers);
channellers.addActionListener(e -> ButtonClick.clicked(channellers));
JButton archers = new JButton("Archers");
archers.setName("Archers"); buttonsAlly.add(archers);
archers.addActionListener(e -> ButtonClick.clicked(archers));
JButton infantry = new JButton("Infantry");
infantry.setName("Infantry"); buttonsAlly.add(infantry);
infantry.addActionListener(e -> ButtonClick.clicked(infantry));
boxAllies.add(Box.createVerticalStrut(150)); boxAllies.add(channellers);
boxAllies.add(Box.createVerticalStrut(40)); boxAllies.add(infantry);
boxAllies.add(Box.createVerticalStrut(40)); boxAllies.add(archers);
boxAllies.add(Box.createVerticalStrut(40));
allies.add(boxAllies);
JPanel enemies = new JPanel();
enemies.setBorder(BorderFactory.createTitledBorder("The Shadow"));
Box boxEnemies = Box.createVerticalBox();
JButton enemyChannellers = new JButton("Dreadlords");
enemyChannellers.setName("Dreadlords"); buttonsEnemy.add(enemyChannellers);
enemyChannellers.addActionListener(e -> ButtonClick.clicked(enemyChannellers));
JButton enemyArchers = new JButton("Enemy Archers");
enemyArchers.setName("Enemy Archers"); buttonsEnemy.add(enemyArchers);
enemyArchers.addActionListener(e -> ButtonClick.clicked(enemyArchers));
JButton enemyInfantry = new JButton("Enemy Infantry");
enemyInfantry.setName("Enemy Infantry"); buttonsEnemy.add(enemyInfantry);
enemyInfantry.addActionListener(e -> ButtonClick.clicked(enemyInfantry));
boxEnemies.add(Box.createVerticalStrut(150)); boxEnemies.add(enemyChannellers);
boxEnemies.add(Box.createVerticalStrut(40)); boxEnemies.add(enemyInfantry);
boxEnemies.add(Box.createVerticalStrut(40)); boxEnemies.add(enemyArchers);
boxEnemies.add(Box.createVerticalStrut(40));
enemies.add(boxEnemies);
JPanel messagePanel = new JPanel();
Box boxMessage = Box.createHorizontalBox();
log = new JTextArea("This is where battle updates will appear.", 36, 32);
logs = new JScrollPane(log, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
log.setWrapStyleWord(true);
log.setAlignmentY(20); log.setEditable(false);
logs.setSize(log.getWidth(), log.getHeight());
boxMessage.add(logs); boxMessage.add(Box.createVerticalStrut(100));
messagePanel.add(boxMessage);
JPanel actionPanel = new JPanel();
actionPanel.setBorder(BorderFactory.createTitledBorder("Available Actions"));
Box boxActions = Box.createHorizontalBox();
JButton newUnit = new JButton("New Unit");
newUnit.setName("new"); buttonsActions.add(newUnit);
newUnit.addActionListener(e -> ButtonClick.clicked(newUnit));
JButton attack = new JButton("Attack");
attack.setName("attack"); buttonsActions.add(attack);
attack.addActionListener(e -> ButtonClick.clicked(attack));
JButton train = new JButton("Train");
train.setName("train"); buttonsActions.add(train);
train.addActionListener(e -> ButtonClick.clicked(train));
JButton heal = new JButton("Heal");
heal.setName("heal"); buttonsActions.add(heal);
heal.addActionListener(e -> ButtonClick.clicked(heal));
JButton rest = new JButton("Rest");
rest.setName("rest"); buttonsActions.add(rest);
rest.addActionListener(e -> ButtonClick.clicked(rest));
JButton status = new JButton("Status Report");
status.setName("status"); buttonsActions.add(status);
status.addActionListener(e -> ButtonClick.clicked(status));
JButton cancel = new JButton("Cancel");
cancel.setName("cancel"); buttonsActions.add(cancel);
cancel.addActionListener(e -> ButtonClick.clicked(cancel));
boxActions.add(newUnit); boxActions.add(Box.createHorizontalStrut(40));
boxActions.add(attack); boxActions.add(Box.createHorizontalStrut(40));
boxActions.add(train); boxActions.add(Box.createHorizontalStrut(40));
boxActions.add(rest); boxActions.add(Box.createHorizontalStrut(40));
boxActions.add(heal); boxActions.add(Box.createHorizontalStrut(40));
boxActions.add(status); boxActions.add(Box.createHorizontalStrut(40));
boxActions.add(cancel);
actionPanel.add(boxActions);
JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, enemies, messagePanel);
buttons.add(buttonsAlly);
buttons.add(buttonsActions);
buttons.add(buttonsEnemy);
this.add(actionPanel, BorderLayout.SOUTH);
this.add(allies, BorderLayout.WEST);
this.add(pane, BorderLayout.EAST);
this.add(battleField, BorderLayout.CENTER);
this.setVisible(true);
}
}

Categories