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);
}
}
Related
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
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);
}}
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);
}
}
}
Please can someone help me, I'm trying to make a seat reservation part for my cinema ticket system assignment ... so the problem is i want the text of the button to show in the text area when selected and not show only the specific text when deselected .. but when i deselect a button the whole text area is cleared.
For e.g. when I select C1, C2, C3 - it shows in the text area correctly, but if I want to deselect C3, the text area must now show only C1 & C2. Instead, it clears the whole text area!
Can anyone spot the problem in the logic?
import java.awt.*;
import static java.awt.Color.blue;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.Border;
public class Cw_Test2 extends JFrame {
JButton btn_payment,btn_reset;
JButton buttons;
JTextField t1,t2;
public static void main(String[] args) {
// TODO code application logic here
new Cw_Test2();
}
public Cw_Test2()
{
Frame();
}
public void Frame()
{
this.setSize(1200,700); //width, height
this.setTitle("Seat Booking");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
Font myFont = new Font("Serif", Font.ITALIC | Font.BOLD, 6);
Font newFont = myFont.deriveFont(20F);
t1=new JTextField();
t1.setBounds(15, 240, 240,30);
JPanel thePanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
thePanel.setLayout(null);
JPanel ourPanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
//ourPanel.setBackground(Color.green);
Border ourBorder = BorderFactory.createLineBorder(blue , 2);
ourPanel.setBorder(ourBorder);
ourPanel.setLayout(null);
ourPanel.setBounds(50,90, 1100,420);
JPanel newPanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
//ourPanel.setBackground(Color.green);
Border newBorder = BorderFactory.createLineBorder(blue , 1);
newPanel.setBorder(newBorder);
newPanel.setLayout(null);
newPanel.setBounds(790,50, 270,340);
JLabel label1 = new JLabel( new ColorIcon(Color.GRAY, 400, 100) );
label1.setText( "SCREEN" );
label1.setHorizontalTextPosition(JLabel.CENTER);
label1.setVerticalTextPosition(JLabel.CENTER);
label1.setBounds(130,50, 400,30);
JLabel label2 = new JLabel(" CINEMA TICKET MACHINE ");
label2.setBounds(250,50,400,30);
label2.setFont(newFont);
JLabel label3 = new JLabel("Please Select Your Seat");
label3.setBounds(270,10,500,30);
label3.setFont(newFont);
JLabel label4 = new JLabel("Selected Seats:");
label4.setBounds(20,10,200,30);
label4.setFont(newFont);
btn_payment=new JButton("PROCEED TO PAY");
btn_payment.setBounds(35,290,200,30);
JLabel label6 = new JLabel("Center Stall");
label6.setBounds(285,172,200,30);
JPanel seatPane, seatPane1, seatPane2, seatPane3, seatPane4, seatPane5;
JToggleButton[] seat2 = new JToggleButton[8];
JTextArea chosen = new JTextArea();
chosen.setEditable(false);
chosen.setLineWrap(true);
chosen.setBounds(20, 60, 200, 100);
// Center Seats
seatPane1 = new JPanel();
seatPane1.setBounds(200,200,250,65);
seatPane1.setLayout(new FlowLayout());
for(int x=0; x<8; x++){
seat2[x] = new JToggleButton("C"+(x+1));
seatPane1.add(seat2[x]);
seat2[x].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
AbstractButton abstractButton = (AbstractButton) ev.getSource();
boolean selected = abstractButton.getModel().isSelected();
for(int x=0; x<8; x++){
if(seat2[x]==ev.getSource()){
if(selected){
chosen.append(seat2[x].getText()+",");
}else{
chosen.setText(seat2[x].getText().replace(seat2[x].getText(),""));
}
}
}
}
});
}
newPanel.add(chosen);
ourPanel.add(seatPane1);
ourPanel.add(label6);
thePanel.add(label2);
ourPanel.add(label3);
ourPanel.add(label1);
newPanel.add(btn_payment);
newPanel.add(label4);
ourPanel.add(newPanel);
thePanel.add(ourPanel);
add(thePanel);
setResizable(false);
this.setVisible(true);
}
public static class ColorIcon implements Icon
{
private Color color;
private int width;
private int height;
public ColorIcon(Color color, int width, int height)
{
this.color = color;
this.width = width;
this.height = height;
}
public int getIconWidth()
{
return width;
}
public int getIconHeight()
{
return height;
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
g.setColor(color);
g.fillRect(x, y, width, height);
}
}
When any seat is selected or deselected, this code iterates an array of seats (in the method showSelectedSeats()) and updates the text area to show the seats that are selected.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CinemaTicketMachine {
private JComponent ui = null;
private JToggleButton[] seats = new JToggleButton[80];
private JTextArea selectedSeats = new JTextArea(3, 40);
CinemaTicketMachine() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
selectedSeats.setLineWrap(true);
selectedSeats.setWrapStyleWord(true);
selectedSeats.setEditable(false);
ui.add(new JScrollPane(selectedSeats), BorderLayout.PAGE_END);
JPanel cinemaFloor = new JPanel(new BorderLayout(40, 0));
cinemaFloor.setBorder(new TitledBorder("Available Seats"));
ui.add(cinemaFloor, BorderLayout.CENTER);
JPanel leftStall = new JPanel(new GridLayout(0, 2, 2, 2));
JPanel centerStall = new JPanel(new GridLayout(0, 4, 2, 2));
JPanel rightStall = new JPanel(new GridLayout(0, 2, 2, 2));
cinemaFloor.add(leftStall, BorderLayout.WEST);
cinemaFloor.add(centerStall, BorderLayout.CENTER);
cinemaFloor.add(rightStall, BorderLayout.EAST);
ActionListener seatSelectionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showSelectedSeats();
}
};
for (int ii=0; ii <seats.length; ii++) {
JToggleButton tb = new JToggleButton("S-" + (ii+1));
tb.addActionListener(seatSelectionListener);
seats[ii] = tb;
int colIndex = ii%8;
if (colIndex<2) {
leftStall.add(tb);
} else if (colIndex<6) {
centerStall.add(tb);
} else {
rightStall.add(tb);
}
}
}
private void showSelectedSeats() {
StringBuilder sb = new StringBuilder();
for (int ii=0; ii<seats.length; ii++) {
JToggleButton tb = seats[ii];
if (tb.isSelected()) {
sb.append(tb.getText());
sb.append(", ");
}
}
String s = sb.toString();
if (s.length()>0) {
s = s.substring(0, s.length()-2);
}
selectedSeats.setText(s);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
CinemaTicketMachine o = new CinemaTicketMachine();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
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!