This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
java swing background image
drawing your own buffered image on frame
I am trying to add a back ground image to my frame, but nothing that I have done works.
I designed a slot machine consisting of several panels added to the container. Now, I am trying to add a nice background to the frame.
I tried using the paint method. But, since I am already using the paint method to paint the reel images, it is not working on the background.
I also tried adding a JLabel, but when I do it overwrites everything or get overwritten depending on how I call it. Following is my code; any help will be much appreciated:
import javax.swing.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import sun.audio.*;
public class SlotMachine extends JFrame {
private Container c = getContentPane();
private ImageIcon handleIcon = new ImageIcon("starWars/slot-handle.png");
private ImageIcon quitIcon = new ImageIcon("starWars/quit2.jpg");
private ImageIcon logoIcon = new ImageIcon("starWars/logo3.jpg");
private ImageIcon BG = new ImageIcon("space.jpg");
private JButton spin = new JButton("Spin", handleIcon);
private JButton quit = new JButton("Quit", quitIcon);
private JLabel logo = new JLabel(logoIcon);
private JLabel bankTotal = new JLabel("Empire Total");
private JLabel bankLabel = new JLabel("$1000.00");
private JLabel playerLabel = new JLabel("$1000.00");
private JLabel playerTotal = new JLabel("Rebellion Total");
private Font newFont = new Font("DialogInput",Font.ITALIC, 25);
private JPanel logoPanel = new JPanel(new BorderLayout());
private JPanel moneyPanel = new JPanel(new GridLayout(1, 3, 5, 5));
private JPanel imagePanel;
private JPanel mainPanel = new JPanel(new BorderLayout());
private JPanel bankPanel = new JPanel(new GridLayout(2, 1, 5, 5));
private JPanel playerPanel = new JPanel(new GridLayout(2, 1, 5, 5));
private JPanel panel = new JPanel(new FlowLayout());
private SlotMachine.ReelPanel reel1 = new SlotMachine.ReelPanel();
private SlotMachine.ReelPanel reel2 = new SlotMachine.ReelPanel();
private SlotMachine.ReelPanel reel3 = new SlotMachine.ReelPanel();
private AudioPlayer audioPlayer = AudioPlayer.player;
private AudioDataStream continuousMusic;
private AudioDataStream winMusic;
private AudioDataStream force;
private AudioDataStream force2;
//private AudioDataStream intro;
private ContinuousAudioDataStream audioLoop;
private static final int DELAY = 1000;
private static final double FUNDS = 1000.00;
private static final float PRICE = 1;
private int timerCounter = 0;
private double bank = FUNDS;
private double playerMoney = 1000.00;
private Timer timer = new Timer(DELAY, new SlotMachine.TimeHandler());
public SlotMachine() {
try {
FileInputStream inputStream = new FileInputStream(new File("cantina4.wav"));
AudioStream audioStream = new AudioStream(inputStream);
AudioData audioData = audioStream.getData();
continuousMusic = new AudioDataStream(audioData);
audioLoop = new ContinuousAudioDataStream(audioData);
inputStream = new FileInputStream(new File("Cheer.wav"));
audioStream = new AudioStream(inputStream);
audioData = audioStream.getData();
winMusic = new AudioDataStream(audioData);
inputStream = new FileInputStream(new File("forceNN.wav"));
audioStream = new AudioStream(inputStream);
audioData = audioStream.getData();
force = new AudioDataStream(audioData);
inputStream = new FileInputStream(new File("force2NN.wav"));
audioStream = new AudioStream(inputStream);
audioData = audioStream.getData();
force2 = new AudioDataStream(audioData);
} catch (Exception e) {
e.printStackTrace();
}
audioPlayer.start(force);
// Set the font
spin.setFont(newFont);
quit.setFont(newFont);
bankLabel.setFont(newFont);
bankTotal.setFont(newFont);
playerLabel.setFont(newFont);
playerTotal.setFont(newFont);
// implements start button
spin.setVerticalTextPosition(SwingConstants.BOTTOM);
spin.setHorizontalTextPosition(SwingConstants.CENTER);
spin.setBackground(Color.GREEN);
spin.setForeground(Color.WHITE);
spin.setPreferredSize(new Dimension(100, 370));
spin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
audioPlayer.stop(force);
audioPlayer.stop(force2);
timer.start();
reel1.startAnimation();
reel2.startAnimation();
reel3.startAnimation();
spin.setEnabled(false);
audioPlayer.start(audioLoop);
}
});
// implements quit button
quit.setBackground(Color.RED);
quit.setForeground(Color.WHITE);
quit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
spin.setEnabled(true);
reel1.stopAnimation();
reel2.stopAnimation();
reel3.stopAnimation();
timer.stop();
audioPlayer.stop(continuousMusic);
audioPlayer.stop(audioLoop);
audioPlayer.stop(winMusic);
timerCounter = 0;
audioPlayer.stop(force);
audioPlayer.start(force2);
imagePanel.repaint(); // without this call for repaint, if you press quit but then choose to cancel
// the curent image and the next image would sometimes overlap this repaint may change the images but they do not overlap.
if (JOptionPane.showConfirmDialog(SlotMachine.this,
"Are you sure you want to quit?", "Quit Option",
JOptionPane.OK_CANCEL_OPTION) == 0) {
audioPlayer.start(force2);
System.exit(0);
}
}
});
// create image panel
imagePanel = new JPanel(new GridLayout(1, 3, 15, 15));
imagePanel.setBackground(Color.WHITE);
imagePanel.add(reel1);
imagePanel.add(reel2);
imagePanel.add(reel3);
// create a panel to hold bank values
bankTotal.setForeground(Color.WHITE);
bankLabel.setForeground(Color.WHITE);
bankPanel.setBackground(Color.GRAY);
bankPanel.add(bankTotal);
bankPanel.add(bankLabel);
// panel to hold player values
playerTotal.setForeground(Color.WHITE);
playerLabel.setForeground(Color.WHITE);
playerPanel.setBackground(Color.GRAY);
playerPanel.add(playerTotal);
playerPanel.add(playerLabel);
// create a panel to add bank and player panels and quit button
//moneyPanel.setBackground(Color.BLACK);
moneyPanel.add(bankPanel);
moneyPanel.add(playerPanel);
moneyPanel.add(quit);
moneyPanel.setOpaque(false);
// this panel adds the reel panel and spin button
panel.setPreferredSize(new Dimension(650, 350));
//panel.setBackground(Color.BLACK);
panel.add(imagePanel);
panel.add(spin);
panel.setOpaque(false);
// create the logo panel
logoPanel.add(logo);
//logoPanel.setBackground(Color.BLACK);
logoPanel.setOpaque(false);
mainPanel.add(logoPanel, BorderLayout.NORTH);
mainPanel.add(panel, BorderLayout.CENTER);
mainPanel.add(moneyPanel, BorderLayout.SOUTH);
mainPanel.setOpaque(false);
//////////////////////////////////// background ???????????????????
/// I could just set backgroung black but i want to add a image
add(mainPanel, BorderLayout.CENTER);
setTitle("Slot Machine");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(950, 750);
setResizable(false);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
new SlotMachine();
}
public class ReelPanel extends JPanel {
private final static String IMAGE_NAME = "starWars/icon";
protected ImageIcon images[];
private int currentImage = 0;
private final int ANIMATION_DELAY = 150;
private final int TOTAL_IMAGES = 12;
private int width;
private int height;
private Timer animationTimer = new Timer(ANIMATION_DELAY, new SlotMachine.ReelPanel.TimerHandler());
private int index;
public ReelPanel() {
try {
images = new ImageIcon[TOTAL_IMAGES];
for (int count = 0; count < images.length; count++) {
images[ count] = new ImageIcon(IMAGE_NAME + (count + 1) + ".jpg");
}
width = images[ 1].getIconWidth();
height = images[ 1].getIconHeight();
currentImage = 0;
index = 0;
animationTimer.setInitialDelay(0);
} catch (Exception e) {
e.printStackTrace();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
images[ currentImage].paintIcon(this, g, 0, 0);
if (animationTimer.isRunning()) {
currentImage = (int) (Math.random() * TOTAL_IMAGES);
}
}
public void startAnimation() {
animationTimer.start();
}
public void stopAnimation() {
animationTimer.stop();
}
public int getIndex() {
return index;
}
public Dimension getMinimumSize() {
return getPreferredSize();
}
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
private class TimerHandler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
repaint();
index = currentImage;
}
}
}
private class TimeHandler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
audioPlayer.stop(winMusic);
++timerCounter;
if (timerCounter == 2) {
reel1.stopAnimation();
} else if (timerCounter == 3) {
reel2.stopAnimation();
} else if (timerCounter == 4) {
reel3.stopAnimation();
audioPlayer.stop(continuousMusic);
audioPlayer.stop(audioLoop);
timerCounter = 0;
timer.stop();
spin.setEnabled(true);
if (reel1.getIndex() == reel2.getIndex() && reel1.getIndex() == reel3.getIndex()) {
if (playerMoney > 0) {
playerMoney += bank;
} else {
playerMoney = bank;
}
bank = FUNDS;
winMusic.reset();
audioPlayer.start(winMusic);
} else {
bank += PRICE;
playerMoney -= PRICE;
}
bankLabel.setText("$" + bank + 0);
playerLabel.setText("$" + playerMoney + 0);
if (playerMoney <= 0) {
JOptionPane.showMessageDialog(SlotMachine.this,
"You are out of funds. GAME IS OVER", "Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
}
}
}
You can simply override paintComponent for your mainPanel and draw the background image in that method. You should choose the appropriate strategy for painting your image (stretch it, keep aspect ratio, repeat horizontally/vertically) but that should not be too hard.
Here is an example that stretches the image over the content pane.
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestBackgroundImage {
private static final String BACKHGROUND_IMAGE_URL = "http://cache2.allpostersimages.com/p/LRG/27/2740/AEPND00Z/affiches/blue-fiber-optic-wires-against-black-background.jpg";
protected void initUI() throws MalformedURLException {
JFrame frame = new JFrame(TestBackgroundImage.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final ImageIcon backgroundImage = new ImageIcon(new URL(BACKHGROUND_IMAGE_URL));
JPanel mainPanel = new JPanel(new BorderLayout()) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage.getImage(), 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width = Math.max(backgroundImage.getIconWidth(), size.width);
size.height = Math.max(backgroundImage.getIconHeight(), size.height);
return size;
}
};
mainPanel.add(new JButton("A button"), BorderLayout.WEST);
frame.add(mainPanel);
frame.setSize(400, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestBackgroundImage().initUI();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Set the layout of your main panel to BorderLayout
Create a JLabel and add it to you main panel
Set the image icon of the label using your background image
Set the layout of the label to what ever you want to use
Continue adding your components to the label as you normally would
An example can be found here
Related
I am very new to this community. I have tried to get up to speed on all rules before posting this question (as well as researching solutions). I apologize if I offended or broke any rules through ignorance. Please also excuse my awful code, I am still learning. Thank you for understanding!
EDIT: I have added additional information and tried different approaches to this issue I'm having. I have reworked part of the code below.
I am building a simple football game with a game field panel and control panel. The game field displays all of the player and tackles on the GUI. The control panel sets the difficulty of the game, starts the timer, and the type of quarterback. I ran into a road block where I have all of my code to compile correctly, but when calling set methods on the GameField class to update the score, it updates the variable but not the actual score through my JTextArea Score keeper.
I have instantiated the ControlPanel within the GameField class. I've also tested with a System.out.println() and it shows that it is indeed updating the variable. Is updating JTextArea allowed between classes?
GameField.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class GameField extends JPanel implements KeyListener {
ControlPanel cp = new ControlPanel();
// Game pieces
private JButton playerIcon = new JButton("RB");
private JButton tackleIcon1 = new JButton("LB");
private JButton tackleIcon2 = new JButton("LB");
private JButton fieldGoal = new JButton("FG");
// Player and Tackle locations
private int playerPositionX = 100;
private int playerPositionY = 500;
private int tackle1PositionX = 1200;
private int tackle1PositionY = 400;
private int tackle2PositionX = 1200;
private int tackle2PositionY = 600;
// Player variable speeds
private int playerSpeed = 20;
public GameField() {
setLayout(null);
setBackground(Color.green);
add(playerIcon);
playerIcon.setBounds(new Rectangle(getPlayerPositionX(), getPlayerPositionY(), 80, 30));
add(tackleIcon1);
tackleIcon1.setBounds(new Rectangle(getTackle1PositionX(), getTackle1PositionY(), 100, 50));
add(tackleIcon2);
tackleIcon2.setBounds(new Rectangle(getTackle2PositionX(), getTackle2PositionY(), 100, 50));
add(fieldGoal);
fieldGoal.setBounds(new Rectangle(1600, 100, 100, 800));
playerIsTackled();
setFocusable(true);
addKeyListener(this);
}
public void playerIsTackled() {
Rectangle playerRect = playerIcon.getBounds();
Rectangle tackle1Rect = tackleIcon1.getBounds();
Rectangle tackle2Rect = tackleIcon2.getBounds();
if (playerRect.intersects(tackle1Rect) || playerRect.intersects(tackle2Rect)) {
setPlayerPositionX(100);
setPlayerPositionY(500);
setTackle1PositionX(1200);
setTackle1PositionY(400);
setTackle2PositionX(1200);
setTackle2PositionY(600);
playerIcon.setBounds(getPlayerPositionX(), getPlayerPositionY(), 80, 30);
tackleIcon1.setBounds(getTackle1PositionX(), getTackle1PositionY(), 100, 50);
tackleIcon2.setBounds(getTackle2PositionX(), getTackle2PositionY(), 100, 50);
cp.setCurrentTackles(cp.getCurrentTackles() + 1);
System.out.println(cp.getCurrentTackles());
}
}
public void playerScored() {
Rectangle playerRect = playerIcon.getBounds();
Rectangle fieldGoalRect = fieldGoal.getBounds();
if (playerRect.intersects(fieldGoalRect)) {
setPlayerPositionX(100);
setPlayerPositionY(500);
setTackle1PositionX(1200);
setTackle1PositionY(400);
setTackle2PositionX(1200);
setTackle2PositionY(600);
playerIcon.setBounds(getPlayerPositionX(), getPlayerPositionY(), 80, 30);
tackleIcon1.setBounds(getTackle1PositionX(), getTackle1PositionY(), 100, 50);
tackleIcon2.setBounds(getTackle2PositionX(), getTackle2PositionY(), 100, 50);
cp.setCurrentScore(cp.getCurrentScore() + 1);
System.out.println(cp.getCurrentScore());
}
}
public void moveToPlayer() {
if (getTackle1PositionX() > getPlayerPositionX()) {
setTackle1PositionX(getTackle1PositionX() - 1);
} else {
setTackle1PositionX(getTackle1PositionX() + 1);
}
if (getTackle1PositionY() > getPlayerPositionY()) {
setTackle1PositionY(getTackle1PositionY() - 1);
} else {
setTackle1PositionY(getTackle1PositionY() + 1);
}
getTackleIcon1().setBounds(getTackle1PositionX(), getTackle1PositionY(), 100, 50);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
requestFocusInWindow();
playerIsTackled();
playerScored();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int k = e.getKeyCode();
if (k == e.VK_LEFT && getPlayerPositionX() > 0) {
setPlayerPositionX(getPlayerPositionX() - getPlayerSpeed());
}
if (k == e.VK_RIGHT && getPlayerPositionX() < 1703) {
setPlayerPositionX(getPlayerPositionX() + getPlayerSpeed());
}
if (k == e.VK_UP && getPlayerPositionY() > 0) {
setPlayerPositionY(getPlayerPositionY() - getPlayerSpeed());
}
if (k == e.VK_DOWN && getPlayerPositionY() < 1089) {
setPlayerPositionY(getPlayerPositionY() + getPlayerSpeed());
}
getPlayerIcon().setBounds(getPlayerPositionX(), getPlayerPositionY(), 80, 30);
}
Below is the ControlPanel.java. In the actionPerformed method, you can see I added a getScore().setText() method for updating the score. It correctly updates the score there if I replace the getCurrentScore() method with any integer.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Hashtable;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ControlPanel extends JPanel implements ActionListener, ChangeListener {
private JButton start;
private JButton stop;
private JSlider speed;
private JComboBox playerList;
private Timer tim;
private int delay = 1000;
private int i = 0;
private int currentScore = 0;
private int currentTackles = 0;
private JTextArea timer = new JTextArea("Timer: " + 0, 1, 6);
private JTextArea score = new JTextArea("Field Goals: " + currentScore + " Tackles: " + currentTackles, 1, 16);
private String[] playerStyle = {"Slow Runner", "Running Back", "All Star"};
public ControlPanel() {
super();
setBackground(Color.darkGray);
// Game controls
start = new JButton("Start");
stop = new JButton("Stop");
speed = new JSlider(JSlider.HORIZONTAL, 0, 2, 1);
playerList = new JComboBox(getPlayerStyle());
// Slider label
Hashtable labelTable = new Hashtable();
labelTable.put(new Integer(0), new JLabel("Slow"));
labelTable.put(new Integer(1), new JLabel("Normal"));
labelTable.put(new Integer(2), new JLabel("Fast"));
speed.setLabelTable(labelTable);
speed.setPaintLabels(true);
// Combo box dropdown
playerList.setSelectedIndex(1);
// Timer
tim = new Timer(getDelay(), this);
// Add methods
add(start);
add(stop);
add(timer);
add(speed);
add(score);
add(playerList);
// Event listeners
start.addActionListener(this);
stop.addActionListener(this);
speed.addChangeListener(this);
playerList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
String playerChoice = (String) cb.getSelectedItem();
playerList.setSelectedItem(playerChoice);
}
});
// Set focus to false on all game controls
start.setFocusable(false);
stop.setFocusable(false);
speed.setFocusable(false);
playerList.setFocusable(false);
}
#Override
public void actionPerformed(ActionEvent event) {
Object obj = event.getSource();
if (obj == getTim()) {
setI(getI() + 1);
getTimer().setText("Timer: " + getI());
getScore().setText("Field Goals: " + getCurrentScore() + " Tackles: " + getCurrentTackles());
}
if (obj == getStop()) {
getTim().stop();
}
if (obj == getStart()) {
getTim().start();
}
}
#Override
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
int currentSpeed = (int) source.getValue();
if (currentSpeed == 0) {
int delaySpeed = getTim().getDelay();
delaySpeed = (int) 2000;
getTim().setDelay(delaySpeed);
}
if (currentSpeed == 1) {
int delaySpeed = getTim().getDelay();
delaySpeed = (int) 1000;
getTim().setDelay(delaySpeed);
}
if (currentSpeed == 2) {
int delaySpeed = getTim().getDelay();
delaySpeed = (int) 500;
getTim().setDelay(delaySpeed);
}
}
MyJPanel.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyJPanel extends JPanel {
public MyJPanel() {
super();
setBackground(Color.gray);
setLayout(new BorderLayout());
ControlPanel gm = new ControlPanel();
GameField gf = new GameField();
add(gm, "North");
add(gf, "Center");
}
}
Thanks to #D.B. I have gotten my code to run as intended. Because I only intend to have two JPanels (Control Panel and Game Panel), I added the panels to pass as arguments to each other. After this, the code started working as intended. Thank you for pushing me into the right step! It was such a simple mistake. Special thanks to #DaveyDaveDave for motivating me to push harder!
Changes I made to my main JPanel object:
public class MyJPanel extends JPanel {
ControlPanel gm = new ControlPanel();
GameField gf = new GameField();
public MyJPanel() {
super();
setBackground(Color.gray);
setLayout(new BorderLayout());
add(gm, "North");
add(gf, "Center");
gf.setCp(gm);
gm.setGf(gf);
}
}
I am trying to implement a free hand drawing Java applet which allows user to draw something in canvas (canvas is not the priority, it could be anything else as long I can save the image after (need to save it, because I have to display it later in a different place after pressing a button, any other solutions are welcome)). I found a code, which allows me to draw, but now I am having a trouble with drawing inside the canvas... And I have already spent few days with no results on that. Here is the code I have by now and a description below it:
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.*;
import java.applet.*;
public class paintMozApplet extends Applet implements ActionListener
{
int xPressed,yPressed;
int xReleased,yReleased;
int xDragged,yDragged;
private GridLayout gL;
private JPanel buttons;
private JPanel panel;
private Button clear, createMoz;
private Label result_here;
private javax.swing.JPanel drawing;
private JPanel moz;
private Canvas canvas;
private draw draw;
public paintMozApplet()
{
draw = new draw();
gL = new GridLayout(1, 0);
buttons = new JPanel();
drawing = new JPanel();
moz = new JPanel();
canvas = new Canvas();
clear = new Button("clear");
createMoz = new Button("Create Moz");
buttons.add(clear);
buttons.add(createMoz);
result_here = new Label("Result here!");
moz.add(result_here);
drawing.add(canvas);
clear.addActionListener(this);
//canvas.add(draw);
//canvas.addMouseMotionListener(this);
canvas.setPreferredSize(new Dimension(200, 200));
canvas.setBackground(Color.green);
add(drawing);
add(buttons);
add(moz);
add(draw);
setPreferredSize(new Dimension(1000, 1000));
setSize(1000, 1000);
setLayout(gL);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==clear)
{
//setOpaque(false);
repaint();
}
}
}
class draw extends JFrame implements MouseListener, MouseMotionListener, ActionListener {
int xPressed,yPressed;
int xReleased,yReleased;
int xDragged,yDragged;
private JButton clear;
public draw()
{
setPreferredSize(new Dimension(1200, 500));
setBounds(0, 0, 480, 500);
clear=new JButton("CLEAR");
add(clear);
clear.setBounds(540, 5, 100, 25);
clear.addActionListener(this);
addMouseListener(this);
addMouseMotionListener(this);
}
protected void paintComponent(Graphics g)
{
g.drawLine(xPressed,yPressed,xDragged,yDragged);
xPressed=xDragged;
yPressed=yDragged;
}
#Override
public void mouseDragged(MouseEvent arg0) {
Graphics g = getGraphics();
g.drawLine(xPressed, yPressed, arg0.getX(), arg0.getY());
xDragged = arg0.getX();
yDragged = arg0.getY();
repaint();
}
#Override
public void mouseMoved(MouseEvent arg0) {
}
#Override
public void mouseClicked(MouseEvent arg0) {
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent arg0) {
xPressed = arg0.getX();
yPressed = arg0.getY();
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
So my idea is to create two classes where one is used to draw and other to create place where to draw and everything else. I have tried lots of things and now I am here and cant figure out, how to cal the draw class on my canvas so it will draw only there. Before I had everything in one class and called mouse events on my canvas. Result was that it drawed only when I clicked on canvas, but the actual drawing went also out of canvas if I did not let go of my mouse and dragged it out of canvas. Also it did not draw in canvas, but on the background of applet, at least it looked like that.
I really hope I explained my self understanding and I am sure, that this can be solved easily since there are lots of solutions online but I can't seem to find one that would work as I intend.
I suggest starting with this approach based around a BufferedImage as the painting surface..
import java.awt.*;
import java.awt.RenderingHints.Key;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
public class BasicPaint {
/** Reference to the original image. */
private BufferedImage originalImage;
/** Image used to make changes. */
private BufferedImage canvasImage;
/** The main GUI that might be added to a frame or applet. */
private JPanel gui;
/** The color to use when calling clear, text or other
* drawing functionality. */
private Color color = Color.WHITE;
/** General user messages. */
private JLabel output = new JLabel("You DooDoodle!");
private BufferedImage colorSample = new BufferedImage(
16,16,BufferedImage.TYPE_INT_RGB);
private JLabel imageLabel;
private int activeTool;
public static final int SELECTION_TOOL = 0;
public static final int DRAW_TOOL = 1;
public static final int TEXT_TOOL = 2;
private Point selectionStart;
private Rectangle selection;
private boolean dirty = false;
private Stroke stroke = new BasicStroke(
3,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND,1.7f);
private RenderingHints renderingHints;
public JComponent getGui() {
if (gui==null) {
Map<Key, Object> hintsMap = new HashMap<RenderingHints.Key,Object>();
hintsMap.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
hintsMap.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
hintsMap.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
renderingHints = new RenderingHints(hintsMap);
setImage(new BufferedImage(320,240,BufferedImage.TYPE_INT_RGB));
gui = new JPanel(new BorderLayout(4,4));
gui.setBorder(new EmptyBorder(5,3,5,3));
JPanel imageView = new JPanel(new GridBagLayout());
imageView.setPreferredSize(new Dimension(480,320));
imageLabel = new JLabel(new ImageIcon(canvasImage));
JScrollPane imageScroll = new JScrollPane(imageView);
imageView.add(imageLabel);
imageLabel.addMouseMotionListener(new ImageMouseMotionListener());
imageLabel.addMouseListener(new ImageMouseListener());
gui.add(imageScroll,BorderLayout.CENTER);
JToolBar tb = new JToolBar();
tb.setFloatable(false);
JButton colorButton = new JButton("Color");
colorButton.setMnemonic('o');
colorButton.setToolTipText("Choose a Color");
ActionListener colorListener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Color c = JColorChooser.showDialog(
gui, "Choose a color", color);
if (c!=null) {
setColor(c);
}
}
};
colorButton.addActionListener(colorListener);
colorButton.setIcon(new ImageIcon(colorSample));
tb.add(colorButton);
setColor(color);
final SpinnerNumberModel strokeModel =
new SpinnerNumberModel(3,1,16,1);
JSpinner strokeSize = new JSpinner(strokeModel);
ChangeListener strokeListener = new ChangeListener() {
#Override
public void stateChanged(ChangeEvent arg0) {
Object o = strokeModel.getValue();
Integer i = (Integer)o;
stroke = new BasicStroke(
i.intValue(),
BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND,
1.7f);
}
};
strokeSize.addChangeListener(strokeListener);
strokeSize.setMaximumSize(strokeSize.getPreferredSize());
JLabel strokeLabel = new JLabel("Stroke");
strokeLabel.setLabelFor(strokeSize);
strokeLabel.setDisplayedMnemonic('t');
tb.add(strokeLabel);
tb.add(strokeSize);
tb.addSeparator();
ActionListener clearListener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int result = JOptionPane.OK_OPTION;
if (dirty) {
result = JOptionPane.showConfirmDialog(
gui, "Erase the current painting?");
}
if (result==JOptionPane.OK_OPTION) {
clear(canvasImage);
}
}
};
JButton clearButton = new JButton("Clear");
tb.add(clearButton);
clearButton.addActionListener(clearListener);
gui.add(tb, BorderLayout.PAGE_START);
JToolBar tools = new JToolBar(JToolBar.VERTICAL);
tools.setFloatable(false);
JButton crop = new JButton("Crop");
final JRadioButton select = new JRadioButton("Select", true);
final JRadioButton draw = new JRadioButton("Draw");
final JRadioButton text = new JRadioButton("Text");
tools.add(crop);
tools.add(select);
tools.add(draw);
tools.add(text);
ButtonGroup bg = new ButtonGroup();
bg.add(select);
bg.add(text);
bg.add(draw);
ActionListener toolGroupListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource()==select) {
activeTool = SELECTION_TOOL;
} else if (ae.getSource()==draw) {
activeTool = DRAW_TOOL;
} else if (ae.getSource()==text) {
activeTool = TEXT_TOOL;
}
}
};
select.addActionListener(toolGroupListener);
draw.addActionListener(toolGroupListener);
text.addActionListener(toolGroupListener);
gui.add(tools, BorderLayout.LINE_END);
gui.add(output,BorderLayout.PAGE_END);
clear(colorSample);
clear(canvasImage);
}
return gui;
}
/** Clears the entire image area by painting it with the current color. */
public void clear(BufferedImage bi) {
Graphics2D g = bi.createGraphics();
g.setRenderingHints(renderingHints);
g.setColor(color);
g.fillRect(0, 0, bi.getWidth(), bi.getHeight());
g.dispose();
imageLabel.repaint();
}
public void setImage(BufferedImage image) {
this.originalImage = image;
int w = image.getWidth();
int h = image.getHeight();
canvasImage = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.drawImage(image, 0, 0, gui);
g.dispose();
selection = new Rectangle(0,0,w,h);
if (this.imageLabel!=null) {
imageLabel.setIcon(new ImageIcon(canvasImage));
this.imageLabel.repaint();
}
if (gui!=null) {
gui.invalidate();
}
}
/** Set the current painting color and refresh any elements needed. */
public void setColor(Color color) {
this.color = color;
clear(colorSample);
}
private JMenu getFileMenu(boolean webstart){
JMenu file = new JMenu("File");
file.setMnemonic('f');
JMenuItem newImageItem = new JMenuItem("New");
newImageItem.setMnemonic('n');
ActionListener newImage = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
BufferedImage bi = new BufferedImage(
360, 300, BufferedImage.TYPE_INT_ARGB);
clear(bi);
setImage(bi);
}
};
newImageItem.addActionListener(newImage);
file.add(newImageItem);
if (webstart) {
//TODO Add open/save functionality using JNLP API
} else {
//TODO Add save functionality using J2SE API
file.addSeparator();
ActionListener openListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (!dirty) {
JFileChooser ch = getFileChooser();
int result = ch.showOpenDialog(gui);
if (result==JFileChooser.APPROVE_OPTION ) {
try {
BufferedImage bi = ImageIO.read(
ch.getSelectedFile());
setImage(bi);
} catch (IOException e) {
showError(e);
e.printStackTrace();
}
}
} else {
// TODO
JOptionPane.showMessageDialog(
gui, "TODO - prompt save image..");
}
}
};
JMenuItem openItem = new JMenuItem("Open");
openItem.setMnemonic('o');
openItem.addActionListener(openListener);
file.add(openItem);
ActionListener saveListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser ch = getFileChooser();
int result = ch.showSaveDialog(gui);
if (result==JFileChooser.APPROVE_OPTION ) {
try {
File f = ch.getSelectedFile();
ImageIO.write(BasicPaint.this.canvasImage, "png", f);
BasicPaint.this.originalImage = BasicPaint.this.canvasImage;
dirty = false;
} catch (IOException ioe) {
showError(ioe);
ioe.printStackTrace();
}
}
}
};
JMenuItem saveItem = new JMenuItem("Save");
saveItem.addActionListener(saveListener);
saveItem.setMnemonic('s');
file.add(saveItem);
}
if (canExit()) {
ActionListener exit = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.exit(0);
}
};
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('x');
file.addSeparator();
exitItem.addActionListener(exit);
file.add(exitItem);
}
return file;
}
private void showError(Throwable t) {
JOptionPane.showMessageDialog(
gui,
t.getMessage(),
t.toString(),
JOptionPane.ERROR_MESSAGE);
}
JFileChooser chooser = null;
public JFileChooser getFileChooser() {
if (chooser==null) {
chooser = new JFileChooser();
FileFilter ff = new FileNameExtensionFilter("Image files", ImageIO.getReaderFileSuffixes());
chooser.setFileFilter(ff);
}
return chooser;
}
public boolean canExit() {
boolean canExit = false;
SecurityManager sm = System.getSecurityManager();
if (sm==null) {
canExit = true;
} else {
try {
sm.checkExit(0);
canExit = true;
} catch(Exception stayFalse) {
}
}
return canExit;
}
public JMenuBar getMenuBar(boolean webstart){
JMenuBar mb = new JMenuBar();
mb.add(this.getFileMenu(webstart));
return mb;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
// use default
}
BasicPaint bp = new BasicPaint();
JFrame f = new JFrame("DooDoodle!");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(bp.getGui());
f.setJMenuBar(bp.getMenuBar(false));
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
public void text(Point point) {
String text = JOptionPane.showInputDialog(gui, "Text to add", "Text");
if (text!=null) {
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.setColor(this.color);
g.setStroke(stroke);
int n = 0;
g.drawString(text,point.x,point.y);
g.dispose();
this.imageLabel.repaint();
}
}
public void draw(Point point) {
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.setColor(this.color);
g.setStroke(stroke);
int n = 0;
g.drawLine(point.x, point.y, point.x+n, point.y+n);
g.dispose();
this.imageLabel.repaint();
}
class ImageMouseListener extends MouseAdapter {
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
if (activeTool==BasicPaint.SELECTION_TOOL) {
selectionStart = arg0.getPoint();
} else if (activeTool==BasicPaint.DRAW_TOOL) {
// TODO
draw(arg0.getPoint());
} else if (activeTool==BasicPaint.TEXT_TOOL) {
// TODO
text(arg0.getPoint());
} else {
JOptionPane.showMessageDialog(
gui,
"Application error. :(",
"Error!",
JOptionPane.ERROR_MESSAGE);
}
}
#Override
public void mouseReleased(MouseEvent arg0) {
if (activeTool==BasicPaint.SELECTION_TOOL) {
selection = new Rectangle(
selectionStart.x,
selectionStart.y,
arg0.getPoint().x,
arg0.getPoint().y);
}
}
}
class ImageMouseMotionListener implements MouseMotionListener {
#Override
public void mouseDragged(MouseEvent arg0) {
reportPositionAndColor(arg0);
if (activeTool==BasicPaint.SELECTION_TOOL) {
selection = new Rectangle(
selectionStart.x,
selectionStart.y,
arg0.getPoint().x-selectionStart.x,
arg0.getPoint().y-selectionStart.y);
} else if (activeTool==BasicPaint.DRAW_TOOL) {
draw(arg0.getPoint());
}
}
#Override
public void mouseMoved(MouseEvent arg0) {
reportPositionAndColor(arg0);
}
}
private void reportPositionAndColor(MouseEvent me) {
String text = "";
if (activeTool==BasicPaint.SELECTION_TOOL) {
text += "Selection (X,Y:WxH): " +
(int)selection.getX() +
"," +
(int)selection.getY() +
":" +
(int)selection.getWidth() +
"x" +
(int)selection.getHeight();
} else {
text += "X,Y: " + (me.getPoint().x+1) + "," + (me.getPoint().y+1);
}
output.setText(text);
}
}
This source is very patchy.
It has many parts with // TODO
A dirty attribute is declared but never used in any meaningful way. ..
It is just something I hacked together today and thought should be shown before it hit the posting limit.
Oh, and don't go looking for any 'OO design' since I did not put any in. If there is any, it is only by accident. This code is intended to demonstrate what is possible and how to start doing it.
This program is asking the user to input the data of a circle. The following are included: the position of x, position of y, and the width and height of the circle.
So when I test this program, I enter the location and its size; and then I hit the draw button. The circle did not appear.
Here is my code!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Draw extends JFrame
{
private JButton draw;
private JTextField posOfX;
private JTextField posOfY;
private JTextField Jwidth;
private JTextField Jheight;
private ActionListener listener;
private JLabel JLx;
private JPanel drawingPanel;
private JLabel JLy;
private JLabel JLwidth;
private JLabel JLheight;
private JComponent component;
public int x =100 ;
public int y =100 ;
public int width = 100;
public int height = 100 ;
private JPanel panel;
public Draw()
{
listener = new actionPerform();
component = new drawCircle();
panel = new JPanel();
draw = new JButton ("Draw");
draw.addActionListener(listener);
posOfX = new JTextField( 15);
posOfY = new JTextField(15);
Jwidth = new JTextField(15);
Jheight = new JTextField(15);
JLx = new JLabel("X");
JLy = new JLabel("Y");
JLwidth = new JLabel("Width");
JLheight = new JLabel("Height");
panel.add(JLx);
panel.add(posOfX);
panel.add(JLy);
panel.add(posOfY);
panel.add(JLwidth);
panel.add(Jwidth);
panel.add(JLheight);
panel.add(Jheight);
panel.add(draw);
panel.add(component);
add(drawingPanel,BorderLayout.SOUTH);
add(panel,BorderLayout.NORTH);
}
class drawCircle extends JComponent
{
public void paintComponent(Graphics g)
{
g.drawOval(x,y,width,height);
}
}
class actionPerform implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
try{
if(e.getSource() == draw)
{
width = width + Integer.parseInt(Jwidth.getText());
height = height + Integer.parseInt(Jheight.getText());
x = Integer.parseInt(posOfX.getText()) + width;
y = Integer.parseInt(posOfY.getText())+ height;
Jwidth.setText("");
Jheight.setText("");
posOfX.setText("");
posOfY.setText("");
}
}
catch (Exception except)
{
Jwidth.setText("");
Jheight.setText("");
posOfX.setText("");
posOfY.setText("");
JOptionPane.showMessageDialog(null,"You should enter numbers only","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}
import java.awt.*;
import javax.swing.*;
public class DrawViewer
{
public static void main(String []args)
{
Draw d = new Draw();
d.setVisible(true);
d.setTitle("Draw circle");
d.setSize(1000,1000);
d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
When creating a new JComponent object without a layout manager, the width of its preferred size is initially 0 and its height 0, so it's not at all visible. To fix this, your drawCircle class should override the getPreferredSize method so that the component you add it to knows what its size should be. For example:
#Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
It is strongly encouraged that you use a layout manager of some sort, however, so that you won't end up with various problems such as the size of components being wrong.
I have multiple images representing players. Each image is stored in a label, which then is added to a JPanel. Then I simply add that JPanel to JFrame to display all players on the screen.
I have to mouse click on a location on screen and move the current player's label to that location.
I added a MouseListener event to every label, but I can't figure out how to focus on one label at a time, so that for example when I click my mouse on the window, current label moves to that location, and then the focus is set on another label, so that when I click again on screen different label moves.
For example:
// in main GUI
private JLabel activePiece = null;
private Player activePlayer = null;
// in JLabel's MouseListener
public void mousePressed(MouseEvent mEvt) {
JLabel currentPiece = (JLabel) mEvt.getSource();
if (activePlayer.holds(currentPiece)) {
// they've pressed on one of the current Player's pieces
activePiece = currentPiece;
}
}
// in main GUI's MouseListener
public void mousePressed(MouseEvent mEvt) {
if (activePlayer != null && activePiece != null) {
activePiece.setLocation(mEvt.getPoint());
activePlayer = //.... next active player;
revalidate();
repaint();
}
}
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.Border;
#SuppressWarnings("serial")
public class PlayerMover extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = 650;
private static final Border ACTIVE_BORDER = BorderFactory.createLineBorder(Color.RED);
private static final Border INACTIVE_BORDER = BorderFactory.createLineBorder(Color.BLUE.brighter());
private Player[] players = { new Player("John"), new Player("Bill"),
new Player("Boudreaux"), new Player("Thibodeaux") };
private int currentPlayerIndex = 0;
private Player currentPlayer = players[currentPlayerIndex];
private JTextField currentPlayerField = new JTextField(currentPlayer.getName(), 20);
private JLabel currentPiece = null;
private Random random = new Random();
public PlayerMover() {
currentPlayerField.setEditable(false);
JPanel northPanel = new JPanel();
northPanel.add(currentPlayerField);
JPanel gamePanel = new JPanel(null) {
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
};
PlayerLabelListener playerLabelListener = new PlayerLabelListener();
for (Player player : players) {
JLabel playerLabel = new JLabel(player.getName(), SwingConstants.CENTER);
int labelW = playerLabel.getPreferredSize().width + 10;
int labelH = playerLabel.getPreferredSize().height + 10;
playerLabel.setSize(new Dimension(labelW, labelH));
playerLabel.setOpaque(true);
playerLabel.setBorder(INACTIVE_BORDER);
int x = random.nextInt(PREF_W - playerLabel.getPreferredSize().width);
int y = random.nextInt(PREF_H - playerLabel.getPreferredSize().height);
playerLabel.setLocation(x, y);
player.setPlayerLabel(playerLabel);
playerLabel.addMouseListener(playerLabelListener);
playerLabel.addMouseMotionListener(playerLabelListener);
gamePanel.add(playerLabel);
}
currentPlayer.getPlayerLabel().setBorder(ACTIVE_BORDER);
setLayout(new BorderLayout());
add(northPanel, BorderLayout.NORTH);
add(gamePanel, BorderLayout.CENTER);
}
public void nextPlayer() {
currentPlayerIndex++;
currentPlayerIndex %= players.length;
currentPlayer = players[currentPlayerIndex];
currentPlayerField.setText(currentPlayer.getName());
currentPiece = null;
for (Player player : players) {
player.getPlayerLabel().setBorder(INACTIVE_BORDER);
}
currentPlayer.getPlayerLabel().setBorder(ACTIVE_BORDER);
}
private class PlayerLabelListener extends MouseAdapter {
private Point pressLoc;
#Override
public void mousePressed(MouseEvent evt) {
if (evt.getButton() != MouseEvent.BUTTON1) {
return;
}
JLabel pressedPiece = (JLabel) evt.getSource();
if (currentPlayer.holds(pressedPiece)) {
currentPiece = pressedPiece;
pressLoc = evt.getPoint();
}
}
#Override
public void mouseDragged(MouseEvent mEvt) {
if (currentPiece == null) {
return;
}
dragPiece(mEvt);
}
private void dragPiece(MouseEvent mEvt) {
Container cont = currentPiece.getParent();
int deltaX = mEvt.getLocationOnScreen().x - pressLoc.x - cont.getLocationOnScreen().x;
int deltaY = mEvt.getLocationOnScreen().y - pressLoc.y - cont.getLocationOnScreen().y;
currentPiece.setLocation(deltaX, deltaY);
cont.revalidate();
cont.repaint();
}
#Override
public void mouseReleased(MouseEvent mEvt) {
if (currentPiece == null) {
return;
}
dragPiece(mEvt);
nextPlayer();
}
}
private static void createAndShowGui() {
PlayerMover mainPanel = new PlayerMover();
JFrame frame = new JFrame("PlayerMover");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class Player {
private String name;
private JLabel playerLabel;
public Player(String name) {
this.name = name;
}
public boolean holds(JLabel label) {
return label == playerLabel;
}
public String getName() {
return name;
}
public JLabel getPlayerLabel() {
return playerLabel;
}
public void setPlayerLabel(JLabel playerLabel) {
this.playerLabel = playerLabel;
}
}
So I have the following code, and whenever I run the program it gives me an error. It all seems correct to me, but it isn't.
It is supposed to take the value of whatever is in the textfields and move the square to that position, and whenever the user enters a new value it is supposed to change the square to whatever the textfield says it should be. Can anybody fix this, or at least tell me whats wrong? Sorry about the code, it got even more screwed up when I started trying to debug it.
The error is
Exception in thread "main" java.lang.NullPointerException
at com.theDevCorner.Game$OptionPanel.<init>(Game.java:228)
at com.theDevCorner.Game$GridPane.<init>(Game.java:81)
at com.theDevCorner.Game.<init>(Game.java:35)
at com.theDevCorner.Game.main(Game.java:52)
Code
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Game extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private GridPane gridPane;
private DragPanel drag;
public boolean isMouseClicked = false;
public static JMenuBar bar = new JMenuBar();
public int gridY = 1;
public int gridX = 1;
public Game() {
setLayout(new BorderLayout());
OptionPanel options = new OptionPanel();
options.addActionListener(this);
add(options, BorderLayout.NORTH);
gridPane = new GridPane();
gridPane.setBorder(BorderFactory.createLineBorder(Color.white));
add(gridPane);
drag = new DragPanel(options);
drag.setBorder(BorderFactory.createLineBorder(Color.white));
drag.setBackground(new Color(100, 100, 125));
add(drag, BorderLayout.WEST);
}
public static void main(String args[]) {
Game game = new Game();
JFrame frame = new JFrame();
frame.setTitle("Game");
frame.setVisible(true);
frame.setAlwaysOnTop(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(game);
frame.pack();
frame.setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e);
if (e.getActionCommand().equalsIgnoreCase("grid")) {
gridPane.setGridOn(!gridPane.isGridOn());
}
if (e.getActionCommand().equalsIgnoreCase("square")) {
gridPane.setSqaureOn(!gridPane.isSquareOn());
}
if (e.getActionCommand().equalsIgnoreCase("vgrid")) {
gridPane.setVertOn(!gridPane.isVertOn());
}
}
public class GridPane extends JPanel {
public OptionPanel op = new OptionPanel();
private static final long serialVersionUID = 1L;
private boolean gridOn = false;
private boolean squareOn = false;
private boolean vertOn = false;
public int x = 0,y = 0,w = 0,h = 0;
public GridPane() {
setBackground(Color.BLACK);
}
public boolean isGridOn() {
return gridOn;
}
public boolean isSquareOn() {
return squareOn;
}
public boolean isVertOn() {
return vertOn;
}
public void setGridOn(boolean value) {
if (value != gridOn) {
this.gridOn = value;
repaint();
}
}
public void setVertOn(boolean value) {
if (value != vertOn) {
this.vertOn = value;
repaint();
}
}
public void setSqaureOn(boolean value) {
if (value != squareOn) {
this.squareOn = value;
repaint();
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Toolkit tk = Toolkit.getDefaultToolkit();
if (gridOn) {
System.out.println("Grid works");
g.setColor(Color.white);
for (int i = 0; i < tk.getScreenSize().height; i += 64) {
gridY++;
g.drawLine(0, (64 * gridY), tk.getScreenSize().width, (64 * gridY));
}
}
gridY = -1;
gridX = -1;
if (vertOn) {
System.out.println("vert grid works");
g.setColor(Color.white);
for (int ig = 0; ig < tk.getScreenSize().width; ig += 64) {
gridX++;
g.drawLine((64 * gridX), 0, (64 * gridX), tk.getScreenSize().height);
}
}
if (squareOn) {
System.out.println("Square works");
g.setColor(Color.red);
x = Integer.parseInt(op.squareX.getText());
y = Integer.parseInt(op.squareY.getText());
w = Integer.parseInt(op.squareW.getText());
h = Integer.parseInt(op.squareH.getText());
g.fillRect(x,y,w,h);
}
x = 0;
y = 0;
w = 64;
h = 64;
}
}
public class DragPanel extends JPanel {
OptionPanel op;
public DragPanel(OptionPanel op) {
this.op = op;
this.add(this.op.squareButton);
this.op.squareButton.setActionCommand("square");
}
public void addActionListener(ActionListener listener) {
System.out.println(listener);
this.op.squareButton.addActionListener(listener);
}
}
private static class Square {
}
private class OptionPanel extends JPanel {
public JButton grid;
public JButton vgrid;
public JButton squareButton;
public JTextField squareX;
public JTextField squareY;
public JTextField squareW;
public JTextField squareH;
public int x,y,w,h;
public Square square = new Square();
public OptionPanel() {
//Sets the stuff for the panel
setBackground(new Color(155, 0, 255));
setLayout(new GridBagLayout());
//end
//The Show Grid Button Stuff
grid = new JButton("Show Horizontal Grid");
grid.setActionCommand("grid");
//end
//The vertical grid
vgrid = new JButton("Show Vertical Grid");
vgrid.setActionCommand("vgrid");
//end
//The Square tool button stuff
squareButton = new JButton("Sqaure Tool");
//end
squareX = new JTextField(gridPane.x); //<----- THIS IS WHERE THE PROBLEM IS!!!!!
squareY = new JTextField("1",3);
squareW = new JTextField("1",3);
squareH = new JTextField("1",3);
//The gridbagConstraints things
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTH;
//kind of like padding
gbc.weighty = 1;
//sets the positions
gbc.gridx = 0;
gbc.gridy = 0;
//add it
add(grid, gbc);
//changes position for the second button
gbc.gridx = -1;
gbc.gridy = 0;
// adds it
add(vgrid, gbc);
//end
add(squareX, gbc);
add(squareY, gbc);
add(squareW, gbc);
add(squareH, gbc);
}
public void addActionListener(ActionListener listener) {
//adds action listeners
grid.addActionListener(listener);
vgrid.addActionListener(listener);
squareButton.addActionListener(listener);
squareX.addActionListener(listener);
squareY.addActionListener(listener);
squareW.addActionListener(listener);
squareH.addActionListener(listener);
}
}
Update
I need help with this portion of the code still:
squareX = new JTextField("0" + gridPane.x,3); //<----- THIS IS WHERE THE PROBLEM IS!!!!!
squareY = new JTextField("0" + gridPane.y,3);
squareW = new JTextField("0" + gridPane.w,3);
squareH = new JTextField("0" + gridPane.h,3);
It seems that the main errors are coming from when I try to do something like this...
OptionPanel options = new OptionPanel();
options.addActionListener(this);
add(options, BorderLayout.NORTH);
gridPane = new GridPane();
You create the OptionPanel before your create the GridPane, so the gridPane variable is null when your optionPanel tries to access that variable.
Create the gridPane before you create the OptionPanel
Your code should be
gridPane = new GridPane();
OptionPanel options = new OptionPanel();
options.addActionListener(this);
add(options, BorderLayout.NORTH);
gridPane.setBorder(BorderFactory.createLineBorder(Color.white));
add(gridPane);
You're first NullPointerException can be fixed by doing something like...
public Game() {
setLayout(new BorderLayout());
gridPane = new GridPane();
gridPane.setBorder(BorderFactory.createLineBorder(Color.white));
OptionPanel options = new OptionPanel();
options.addActionListener(this);
add(options, BorderLayout.NORTH);
add(gridPane);
drag = new DragPanel(options);
drag.setBorder(BorderFactory.createLineBorder(Color.white));
drag.setBackground(new Color(100, 100, 125));
add(drag, BorderLayout.WEST);
}
You're second NullPointerException is more tricky...
You have a cyclic dependency problem...
Class A is trying to create Class B, which is trying to create class C when class C depends on an instance of B...
To clarify...GridPane has an instance of OptionPane, but OptionPane is depended on the state of GridPane, which is null, because GridPane can't initalise until OptionPane has been initialised...confused yet...
You can solve this by using a lazy loading approach. That is, not try to insitate the OptionPane till you need it...
public class GridPane extends JPanel {
public OptionPanel op;
// Other variables...
// Other methods...
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Other paint code...
if (squareOn) {
if (op == null) {
op = new OptionPanel();
}
System.out.println("Square works");
g.setColor(Color.red);
x = Integer.parseInt(op.squareX.getText());
y = Integer.parseInt(op.squareY.getText());
w = Integer.parseInt(op.squareW.getText());
h = Integer.parseInt(op.squareH.getText());
g.fillRect(x, y, w, h);
}
}
}
How ever. I don't think this is going to achieve what you want in the long run, as the state of the OptionPane will be different between the classes...(GridPane and OptionPane won't share the same instance....)
A better solution would be to remove these direct dependencies, so that you can pass some the same reference of some kind of model between GridPane and OptionPane, which would allow it to act as the glue between them...