ActionListener code triggered twice - java

I made jbutton and added ActionListner to it but the code in public void actionPerformed(ActionEvent e){} exectues twice.It prints test twice,instead of just once.Here is my code
JButton testbut=new JButton("Test");
ListenForButton2 l=new ListenForButton2();
testbut.addActionListener(l);
private class ListenForButton2 implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == testbut){System.out.println("tEST");}
}
}
Here is complete code,in case this is no eneough.Looks like problem was adding two action listeners to my button."if (testbut.getActionListeners().length<1)) testbut.addActionListener(l); "fixed it.But can you find where i added two action listeneres to test button
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Arc2D;
import java.awt.geom.CubicCurve2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.QuadCurve2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Game extends JFrame {
JButton but1 = new JButton("MakeMoney");
JButton button1 = new JButton("Current money");
JButton testbut=new JButton("Make money");
int money = 0;
double currentMoney;
String moneyString = "";
String box1txt="Text for box one";
String[] boxtext={"Newspaper Delivery","Car wash","Pizza Delivery","Donut shop","Shrimp boat","Hockey team","Movie Studio","Bank","Oil Company"};
String[] prices={"60.00","720.00","8,640.00","103,680.00","1,244,160.00","14,929,920.00","179,159,040.00","2.149 billion","25.798 billion"};
public static void main(String[] args) {
new Game();
}
public Game() {
try {
this.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:/Users/TPC/workspace/ProjectMoney/Resources/backgroundForApp.png")))));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.setLayout(new BorderLayout());
button1.setContentAreaFilled(false);
ListenForButton lforButton = new ListenForButton();
but1.addActionListener(lforButton);
JPanel thePanel = new JPanel();
thePanel.add(button1);
thePanel.add(but1);
//thePanel.add(testbut);
this.setSize(1042, 617);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Project Money");
this.add(thePanel, BorderLayout.NORTH);
this.add(new DrawStuff(), BorderLayout.CENTER);
this.setResizable(true);
this.setVisible(true);
Sound sound1 = new Sound();
String sound = "file:C:/Users/TPC/Downloads/sound.wav";
sound1.playMusic(sound);
}
private class ListenForButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == but1) {
money += 10;
moneyString = Integer.toString(money);
button1.setText("$" + moneyString);
}
}
}
private class ListenForButton2 implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == testbut){System.out.println("tEST");}
}
}
private class DrawStuff extends JComponent {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D graph2 = (Graphics2D) g;
graph2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Shape drawRoundRec = new RoundRectangle2D.Double(170,40,250,66,45, 45);
//first num xpos,secound num ypost,third num sirina,fourht num duzina
int x1=170; int y1=40; int x2=250; int y2=66; int def=45;
Shape drawRoundRec2=new RoundRectangle2D.Double(x1,(y1+80),x2,y2,def,def);
Shape drawRoundRec3=new RoundRectangle2D.Double(x1,(y1+80+80),x2,y2,def,def);
Shape drawRoundRec4=new RoundRectangle2D.Double(x1,(y1+80+80+80),x2,y2,def,def);
Shape drawRoundRec5=new RoundRectangle2D.Double(x1,(y1+80+80+80+80),x2,y2,def,def);
Shape drawRoundRect6=new RoundRectangle2D.Double(x1+330,40,250,66,def, def);
Shape drawRoundRect7=new RoundRectangle2D.Double(x1+330,(y1+80),250,66,def, def);
Shape drawRoundRect8=new RoundRectangle2D.Double(x1+330,(y1+80+80),250,66,def, def);
Shape drawRoundRect9=new RoundRectangle2D.Double(x1+330,(y1+80+80+80),250,66,def, def);
Shape drawRoundRect10=new RoundRectangle2D.Double(x1+330,(y1+80+80+80+80),250,66,def, def);
graph2.setPaint(Color.BLACK);
graph2.setColor(Color.LIGHT_GRAY);
graph2.fill(drawRoundRec); graph2.fill(drawRoundRec2);
graph2.fill(drawRoundRec3); graph2.fill(drawRoundRec4); graph2.fill(drawRoundRec5); graph2.fill(drawRoundRect6);
graph2.fill(drawRoundRect7); graph2.fill(drawRoundRect8); graph2.fill(drawRoundRect9); graph2.fill(drawRoundRect10);
graph2.setPaint(Color.BLACK);
graph2.draw(drawRoundRec2); graph2.draw(drawRoundRec3); graph2.draw(drawRoundRec4);
graph2.draw(drawRoundRec5); graph2.draw(drawRoundRect6); graph2.draw(drawRoundRect7); graph2.draw(drawRoundRect8);
graph2.draw(drawRoundRect9); graph2.draw(drawRoundRect10);
Font font=new Font("Serif",Font.PLAIN,30);
g.setFont(font); g.drawString(box1txt,190,80); g.drawString(boxtext[0],190,150); g.drawString(boxtext[1],190,150+80); g.drawString(boxtext[2],190,150+90+70);
g.drawString(boxtext[3],190,150+90+70+80);
g.drawString(boxtext[4],520,80); g.drawString(boxtext[5],520,150); g.drawString(boxtext[6],520,150+80); g.drawString(boxtext[7],520,150+90+70);
g.drawString(boxtext[8],520,150+90+70+80);
g.drawString(prices[0],190,150+30); g.drawString(prices[1],190,150+80+30); g.drawString(prices[2],190,150+90+70+30);
g.drawString(prices[3],190,150+90+70+80+30);
g.drawString(prices[4],520,80+25); g.drawString(prices[5],520,150+30); g.drawString(prices[6],520,150+80+30); g.drawString(prices[7],520,150+90+70+30);
g.drawString(prices[8],520,150+90+70+80+30);
testbut.setLocation(180,70);
Dimension d = new Dimension(100,40);
testbut.setSize(d);
ListenForButton2 l=new ListenForButton2();
if (testbut.getActionListeners().length<1) testbut.addActionListener(l);
this.add(testbut);
}
}
}

Make sure to add your action listener just once.
You get the listeners count via testbut.getActionListeners().length .
Update - multiple calls
Within the paintComponent of the DrawStuff class which extends JComponent you are only adding the listener once. Same as for the first listener.
The difference is, the first is added within a constructor. While the paintComponent method of the JComponent which can be called multiples times.
As to how and when it is called, this answer might help you.

Related

Java -Repaint() not working when i want to call it

I wonder why the repiant() method is not working as intended. My Code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
public class RightPanel extends JPanel implements ActionListener{
JButton buttono;
JButton buttonu;
MyFrame frame;
ButtomPanel s;
public RightPanel(MyFrame frame){
super();
this.frame=frame;
s= new ButtomPanel(frame);
this.setPreferredSize(new Dimension((frame.getWidth()/3),frame.getHeight()));
setBackground(Color.green);
setLayout(new BorderLayout());
buttono = new JButton ("up");
buttonu = new JButton ("down");
buttono .addActionListener(this);
buttonu .addActionListener(this);
add(buttono , BorderLayout.NORTH);
add(buttonu , BorderLayout.SOUTH);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()==buttono) {
System.out.println("Up");
s.x=s.x+10;
s.repaint();
}
}
I want to Repaint following class:
import java.awt.Color;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ButtomPanel extends JPanel {
MyFrame frame;
BufferedImage image;
boolean geklickt=false;
public static int x=0;;
public ButtomPanel(MyFrame frame) {
super();
this.frame=frame;
this.setPreferredSize(new Dimension(((frame.getWidth()/3)*2),585));
setBackground(Color.blue);
java.net.URL resource = getClass().getResource("/resources/siegel.jpg");
try {
image = ImageIO.read(resource);
} catch (IOException e) {
e.printStackTrace();
}
setVisible(true);
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(image, 150+x, 150+x, 150, 150, null);}
}
}
I want to change with the ActionListener in the RightPanel Class the x from the BottomPanel Class and then repaint it, but it doesnt work. I can raise the x, but s.repaint() does not call the paint-Method.
s is never added to anything, so it will never be painted.
this.setPreferredSize(new Dimension((frame.getWidth()/3),frame.getHeight())); is a horribly bad idea. The window should be conforming to the size of the components, not the other way round. In fact, there's never really a good reason to expose MyFrame to the components this way, it provides these components control over MyFrame which they should never have.
java.net.URL resource = getClass().getResource("/resources/siegel.jpg");
try {
image = ImageIO.read(resource);
} catch (IOException e) {
e.printStackTrace();
}
is a bad idea. The class should be throwing the exception to those using it, so that they know something has gone wrong. Doing it this way not only consumes the error in a way which is difficult to trace, but also sets you up for a NullPointerException when you call g.drawImage(image, 150+x, 150+x, 150, 150, null)
Don't override paint
public void paint(Graphics g) {
super.paint(g);
g.drawImage(image, 150+x, 150+x, 150, 150, null);
}
prefer paintComponent instead. paint is actually a very complex method. See Painting in AWT and Swing and Performing Custom Painting for more details
public static int x=0; is a bad idea for a three reasons:
static is not your friend. What happens when you have more than one instance of ButtomPanel? Generally speaking, when you use static in this way, it's a red flag telling you that your design is wrong.
public is providing uncontrolled access to the property. This is generally discouraged and you could be preferring to use setters and getters to interact with the property.
JPanel already has a x property, which could make it confusing (ie if if someone used getX instead of x). Better to rename it to something like imageX of imageXOffset.
Runnable example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public final class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
JFrame frame = new JFrame();
frame.add(new RightPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public class RightPanel extends JPanel implements ActionListener {
JButton buttono;
JButton buttonu;
ButtomPanel s;
public RightPanel() throws IOException {
super();
s = new ButtomPanel();
setBackground(Color.green);
setLayout(new BorderLayout());
buttono = new JButton("up");
buttonu = new JButton("down");
buttono.addActionListener(this);
buttonu.addActionListener(this);
add(buttono, BorderLayout.NORTH);
add(buttonu, BorderLayout.SOUTH);
add(s);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttono) {
System.out.println("Up");
s.addToImageXOffset(10);
}
}
}
public class ButtomPanel extends JPanel {
private BufferedImage image;
private int imageXOffset = 0;
public ButtomPanel() throws IOException {
super();
setBackground(Color.blue);
image = ImageIO.read(getClass().getResource("/images/Heart.png"));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
public void addToImageXOffset(int delta) {
setImageXOffset(getImageXOffset() + delta);
}
public void setImageXOffset(int imageXOffset) {
this.imageXOffset = imageXOffset;
repaint();
}
public int getImageXOffset() {
return imageXOffset;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
g.drawImage(image, 150 + imageXOffset, 150 + imageXOffset, this);
}
}
}

Why does key listener works only once if I trigger the action setVisible(true) / action setVisible(false)?

I'm trying to display a Jpanel that is added into a Jframe,for making this is i created a variable that turns on or off when ENTER is pressed, I even tried to make a counter that counts times Enter is pressed but it stops working after one call, but if i remove the setVisible(); part the counter keeps being incremented. Please help.I leave the code here:
package test;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import game.Component;
public class Panel {
public boolean chat=Listener.chat;
public static void main(String[]args) {
JFrame frame = new JFrame();
frame.setTitle("Finestra di test per il gioco");
frame.setResizable(false);
frame.getContentPane().setBackground(Color.CYAN);
Dimension di = new Dimension(500,30);
frame.setBounds(0, 0, 500, 500);
frame.setResizable(false);
JPanel chatLayer=new JPanel();
chatLayer.setBounds(0, 0, 500, 500);
chatLayer.setBackground(Color.GREEN);
JTextField barra_chat=new JTextField();
barra_chat.setPreferredSize(di);
chatLayer.add(barra_chat);
frame.add(chatLayer);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Listener li=new Listener(chatLayer);
barra_chat.addKeyListener(li);
frame.validate();
frame.setVisible(true);
}
}
package test;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
import test.Component;
public class Listener implements KeyListener{
int x=0;
JPanel pan = new JPanel();
public static boolean chat=true;
public Listener(JPanel pan) {
this.pan=pan;
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int key=e.getKeyCode();
switch(key) {
case KeyEvent.VK_ENTER:
if(!chat) {
pan.setVisible(true);
chat=true;
System.out.println(chat);
x+=1;
System.out.println(x);
}else {
pan.setVisible(false);
chat=false;
System.out.println(chat);
x+=1;
System.out.println(x);
}
break;
}
}
#Override
public void keyReleased(KeyEvent e) {
}
}

Problems with Graphics drawImage

I've been hunting through past StackOverflow posts and trying to figure out why my image won't display.
I know that the ImageIO is fine since I can run getWidth() on my BufferedImage and it returns the correct width.
Here is my Graphic class, followed by my main class.
(I'm sorry for trashy code, I'm new to this.)
Code in Graphic class:
package blackjack;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Graphic extends JPanel implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
public JFrame frame = new JFrame("Game Window");
public JPanel layout = new JPanel(new BorderLayout());
public JPanel menu = new JPanel();
public JPanel playing = new JPanel(new BorderLayout());
public JPanel game = new JPanel();
public BufferedImage cardArray[] = new BufferedImage[52];
public void begin() {
//starting menu
}
public void playersTurn() {
menu.add(playing);
Font font = new Font("",Font.PLAIN, 24);
JPanel btnHolder = new JPanel();
JLabel play = new JLabel("Playing:");
JLabel or = new JLabel(" or ");
JLabel question = new JLabel(" ? ");
question.setFont(font);
or.setFont(font);
play.setFont(font);
JButton hit = new JButton("Hit");
JButton stand = new JButton("Stand");
hit.addActionListener(this);
stand.addActionListener(this);
playing.add(play, BorderLayout.WEST);
playing.add(btnHolder, BorderLayout.CENTER);
btnHolder.add(hit);
btnHolder.add(or);
btnHolder.add(stand);
btnHolder.add(question);
}
public void gui() {
//main gui
Dimension imageD = new Dimension(71,96);
Dimension menuD = new Dimension(900,120);
menu.setBorder(BorderFactory.createLineBorder(Color.black));
menu.setPreferredSize(menuD);
JPanel titlePanel = new JPanel();
JLabel title = new JLabel("BlackJack");
title.setFont(new Font("", Font.PLAIN, 14));
titlePanel.add(title);
Graphic gr = new Graphic();
gr.setPreferredSize(imageD);
//adding
frame.add(layout);
layout.add(menu, BorderLayout.SOUTH);
layout.add(titlePanel, BorderLayout.NORTH);
layout.add(gr, BorderLayout.CENTER);
//frame settings
frame.setSize(900, 650);
frame.setResizable(false);
frame.setVisible(true);
}
public void buildPathArray() {
for(int i = 1; i<=52; i++){
BufferedImage im = null;
try {
im = ImageIO.read(new File(Blackjack.getInstallDir() + Blackjack.s + "src" + Blackjack.s + "cardpngs"+ Blackjack.s + (100+i)+".png"));
} catch (IOException e) {
e.printStackTrace();
}
cardArray[i-1]= im;
//System.out.println(Blackjack.getInstallDir() + "\\src\\cardpngs\\" + (100+i)+".png");
}
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Hit")) {
} else if(e.getActionCommand().equals("Stand")) {
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//g.setColor(Color.GREEN);
//g.fillOval(20, 20, 20, 20);
g.drawImage(cardArray[0], 0, 0, this);
}
}
Code in my main class:
package blackjack;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Blackjack {
public static String installDir = "";
public static String s = "";
public static void main(String[] args) {
Path currentRelativePath = Paths.get("");
installDir = currentRelativePath.toAbsolutePath().toString();
s = System.getProperty("file.separator");
Graphic gr = new Graphic();
gr.buildPathArray();
gr.gui();
//System.out.println(installDir);
//g.playersTurn();
}
public static String getInstallDir() {
return installDir;
}
}
The output is this:
You're creating one instance of Graphic in your Blackjack class...
public class Blackjack {
public static String installDir = "";
public static String s = "";
public static void main(String[] args) {
//...
Graphic gr = new Graphic();
gr.buildPathArray();
gr.gui();
}
And another in your Graphic class
public void gui() {
//...
Graphic gr = new Graphic();
gr.setPreferredSize(imageD);
//adding
//...
layout.add(gr, BorderLayout.CENTER);
//...
}
But you only initialise the images, using buildPathArray of the instance in you BlackBelt class, which is not what is actually displayed on the screen...
As a general rule of thumb, you shouldn't be creating an instance of JFrame from within another component with the express purpose of display that component. Your Graphic component is also trying to do too much. Instead, I would have a Game class, maybe, which pulled the title, menu and Graphic components together and then put that onto an instance of JFrame
The main reason for this is, is your Graphic class is trying to do too much. It should be solely responsible for display the cards and managing them. The Game class should manage the other UI elements and be responsible for ensuring that the UI meets the current state of the game "model", taking in user input (and listening to events from the other UI elements) and updating the model and responding to events that the model creates, a little more like...
BlackJack...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class BlackJack {
public static void main(String[] args) {
new BlackJack();
}
public BlackJack() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Game());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Game extends JPanel {
private JPanel menu;
private Graphic graphic;
public Game() {
menu = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(900, 120);
}
};
menu.setBorder(BorderFactory.createLineBorder(Color.black));
JPanel titlePanel = new JPanel();
JLabel title = new JLabel("BlackJack");
title.setFont(new Font("", Font.PLAIN, 14));
titlePanel.add(title);
Graphic gr = new Graphic();
gr.buildPathArray();
setLayout(new BorderLayout());
add(menu, BorderLayout.SOUTH);
add(titlePanel, BorderLayout.NORTH);
add(gr, BorderLayout.CENTER);
}
}
}
Graphic...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Graphic extends JPanel {
private static final long serialVersionUID = 1L;
public BufferedImage cardArray[] = new BufferedImage[52];
public void begin() {
//starting menu
}
public void playersTurn() {
// All of this belongs in Game
}
#Override
public Dimension getPreferredSize() {
return new Dimension(71,96);
}
public void buildPathArray() {
for (int i = 1; i <= 52; i++) {
BufferedImage im = null;
try {
im = ImageIO.read(new File(Blackjack.getInstallDir() + Blackjack.s + "src" + Blackjack.s + "cardpngs" + Blackjack.s + (100 + i) + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
cardArray[i - 1] = im;
//System.out.println(Blackjack.getInstallDir() + "\\src\\cardpngs\\" + (100+i)+".png");
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//g.setColor(Color.GREEN);
//g.fillOval(20, 20, 20, 20);
g.drawImage(cardArray[0], 0, 0, this);
}
}
You might also want to have a look at Model-View-Controller.

GUI Application that allows the user to choose the shape and color of a drawing

I need to create a program that allows the user to select a color from a list of checkboxes, red and blue, and then a shape from a
list of radio buttons, square or circle. When the “Draw” button is pressed the selected
shape and color are drawn. If both red and blue are chosen, the shape is drawn in purple.
should look like the following picture:
This is about as far i've gotten, stumped as to how to create the circle and print it when that option is chosen. Also how do I reorganize the labels and buttons?
any help is appreciated
import java.awt.GridBagLayout;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Shapes
{
public static JFrame window = new JFrame("Shapes");
public static JPanel panel = new JPanel(new GridBagLayout());
public static void main(String[] args)
{
window.setBounds(0, 0,300, 300);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(panel);
MApp m = new MApp();
m.setBounds(100,100,100,100);
window.add(m);
Draw d = new Draw(panel) ;
d.setBounds(0, 0, window.getWidth(), 90);
window.add(d);
window.setVisible(true);
}
}
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JPanel;
public class MApp extends JPanel implements MouseListener
{
private boolean clicked;
private Rectangle r;
public MApp()
{
clicked = false;
r = new Rectangle(15, 15, 50, 50);
addMouseListener(this);
}
public void paintComponent(Graphics g)
{
if(clicked)
{
g.setColor(Color.BLUE);
}
else
{
g.setColor(Color.RED);
}
g.fillRect((int)r.getX(), (int)r.getY(),
(int)r.getWidth(), (int)r.getHeight());
}
public void mouseClicked (MouseEvent e)
{
Point p = new Point(e.getX(),e.getY());
if(r.contains(p))
{
clicked = !clicked;
}
repaint();
}
public void Circle()
{
g.fillOval(0, 0, s, s);
}
public void mousePressed (MouseEvent evnt) {}
public void mouseReleased (MouseEvent evnt) {}
public void mouseEntered (MouseEvent evnt) {}
public void mouseExited (MouseEvent evnt) {}
}
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class Draw extends JPanel implements ActionListener
{
JTextField tfInfo;
JLabel lblColor, lblShapes;
JCheckBox cbRed, cbBlue;
ButtonGroup shapes;
JRadioButton rbCircle, rbSquare;
JButton btnSubmit;
public Draw(JPanel panel)
{
GridBagConstraints c = new GridBagConstraints();
tfInfo = new JTextField("Color", 15);
tfInfo = new JTextField("Shapes", 50);
lblColor = new JLabel("Colors:");
cbRed = new JCheckBox("Red");
cbBlue = new JCheckBox("Blue");
lblShapes = new JLabel("Shapes:");
shapes = new ButtonGroup();
rbCircle = new JRadioButton("Circle");
rbSquare = new JRadioButton("Square");
btnSubmit = new JButton("Draw");
btnSubmit.addActionListener(this);
this.setBackground(Color.WHITE);
add(lblColor);
add(cbRed);
add(cbBlue);
add(lblShapes);
add(rbCircle);
add(rbSquare);
add(btnSubmit);
shapes.add(rbCircle);
shapes.add(rbSquare);
}
public void actionPerformed(ActionEvent a)
{
if(a.getSource() == btnSubmit)
{
if(cbRed.isSelected()&&cbBlue.isSelected())
{
if(rbCircle.isSelected())
{
}
else if(rbSquare.isSelected())
{
}
}
else if(cbRed.isSelected())
{
if(rbCircle.isSelected())
{
}
else if(rbSquare.isSelected())
{
}
}
else if(cbBlue.isSelected())
{
if(rbCircle.isSelected())
{
}
}
else if(rbSquare.isSelected())
{
}
}
repaint();
}
}
Start by separating your "management" code from you "painting" code
You should have a single class that only handles the painting of the shape, nothing else, it just does what it's told.
You should then have a second class which takes input from the user and when they press the Draw button, it tells the "paint" class what it should be paint, for example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DrawStuff extends JFrame {
public static void main(String[] args) {
new DrawStuff();
}
public DrawStuff() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ControlPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ControlPane extends JPanel {
private JRadioButton circle;
private JRadioButton square;
private DrawPane drawPane;
public ControlPane() {
setLayout(new GridBagLayout());
ButtonGroup bg = new ButtonGroup();
circle = new JRadioButton("Circle");
square = new JRadioButton("Square");
bg.add(circle);
bg.add(square);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
JPanel shape = new JPanel();
shape.add(circle);
shape.add(square);
add(shape, gbc);
JButton draw = new JButton("Draw");
draw.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (circle.isSelected()) {
drawPane.setDrawableShape(DrawableShape.CIRCLE);
} else if (square.isSelected()) {
drawPane.setDrawableShape(DrawableShape.SQUARE);
}
}
});
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(draw, gbc);
drawPane = new DrawPane();
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = gbc.BOTH;
add(drawPane, gbc);
}
}
public enum DrawableShape {
CIRCLE,
SQUARE
}
public class DrawPane extends JPanel {
private DrawableShape drawableShape;
public DrawPane() {
}
public void setDrawableShape(DrawableShape drawableShape) {
this.drawableShape = drawableShape;
repaint();
}
public DrawableShape getDrawableShape() {
return drawableShape;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
DrawableShape shape = getDrawableShape();
if (shape != null) {
int width = getWidth() - 20;
int height = getHeight() - 20;
int size = Math.min(width, height);
int x = (getWidth() - size) / 2;
int y = (getHeight() - size) / 2;
if (shape == DrawableShape.CIRCLE) {
g2d.fillOval(x, y, size, size);
} else if (shape == DrawableShape.SQUARE) {
g2d.fillRect(x, y, size, size);
}
}
g2d.dispose();
}
}
}
I'll leave you to add in the color management.
Have a closer look at:
How to Use Buttons, Check Boxes, and Radio Buttons
How to Write an Action Listeners
Painting in AWT and Swing
Performing Custom Painting
2D Graphics
for more details

Drawing using Graphics in Java

I have a Graphics question. I'm trying to draw an image in a Frame and I'm having some issue. I want to know what's the best approach to successfully do what I want to do.
I will show my 3 classes. The Main class create the Menu. Once Matchmaking button is press, it create the Board object and call Main.draw to paint all it's component (only Board for now). The picture only sometime appear so it make me realise my code isn't probably setup the right way. THANKS!!!
MAIN CLASS
import java.awt.Graphics;
public class Main
{
public static Board theBoard;
public static void main(String[] args)
{
new Menu("Main Menu").setVisible(true);
}
public static void draw(Graphics painter)
{
theBoard.draw(painter);
}
}
MENU CLASS
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Menu extends JFrame implements ActionListener
{
//Jpanel
JPanel pnlButton = new JPanel();
//Buttons
JButton btnMatchmaking = new JButton("Matchmaking");
JButton btnExit = new JButton("Exit");
JButton btnProfile = new JButton("Profile");
JButton btnOption = new JButton("Options");
public Menu(String s)
{
super("Bu$ted: " + s);
btnExit.addActionListener(this);
btnMatchmaking.addActionListener(this);
//JPanel setting
pnlButton.add(btnMatchmaking);
pnlButton.add(btnProfile);
pnlButton.add(btnOption);
pnlButton.add(btnExit);
pnlButton.setVisible(true);
//The winddow options
super.setLocation(0,0); //A remplacer par des dimension variables
super.setSize(600, 500); //A remplacer par des dimension variables
super.setResizable(false);
super.setVisible(true);
super.add(pnlButton);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//Handle action events.
//#param evt
#Override
public void actionPerformed(ActionEvent evt)
{
if(evt.getSource() == btnMatchmaking)
{
super.remove(pnlButton);
Main.theBoard = new Board("TestBoard");
super.add(Main.theBoard);
super.setSize(Main.theBoard.boardSize);
Main.draw(super.getGraphics());
}
if(evt.getSource() == btnExit)
{
System.exit(0);
}
}
}
BOARD CLASS
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class Board extends JPanel
{
BufferedImage boardImage;
int width;
int height;
Dimension boardSize;
public Board (String boardName)
{
boardImage = loadBoard(boardName);
width=boardImage.getWidth();
height=boardImage.getHeight();
boardSize = new Dimension(width,height);
this.setVisible(true);
System.out.println("The board is setup.");
}
private BufferedImage loadBoard (String boardName)
{
BufferedImage img = null;
try
{
img = ImageIO.read(new File("Components/"+boardName+".png"));
}
catch (IOException e)
{
System.out.println("The board image couldn't be loaded.");
}
return img;
}
public void draw(Graphics painter)
{
painter.drawImage(boardImage, 0, 0, null);
System.out.println("The board image was painted.");
}
}
The recommended approach is to override the paintComponent of your Board class and let the paint system handel it...
See Painting in AWT and Swing and Perfoming Custom Painting for more details

Categories