I am trying to create an X/O game and in that i am not able to call drawString() when user clicks on the required position.
I am able to display grid and take mouse co-ordinated where user clicks but i am not able to repaint "X" and "O" on that.
Please help.Thanks
Here is code snippet:
public class Tic_Tac_Toe extends JPanel
{
int xpos,ypos;
ArrayList xlist = new ArrayList();
ArrayList ylist = new ArrayList();
Point cursorPosition;
public static void main(String[] args)
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int x=0,y=0;
boolean win,mark;
Board b=new Board();
Tic_Tac_Toe t=new Tic_Tac_Toe();
t.dispFrame();
while(!b.isGridFull())
{
b.printboard();
System.out.println("Enter the desired character position:");
try
{
x=Integer.parseInt(br.readLine());
y=Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println("Exception is:");
}
mark=b.placeMark(x,y);
win=b.checkforwin();
if(b.flag==true)
{
System.out.println("Congratulations player with character "+b.CurrentPlayerMark+" has won");
break;
}
b.changePlayer();
}
if(b.flag==false)
System.out.println("The game has been drawn!!!");
}
public void dispFrame()
{
JFrame frame = new JFrame("My New Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(300, 300));
frame.setResizable(false);
JPanel panel=new JPanel()
{
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawLine(30,100,270,100);
g.drawLine(30,200,270,200);
g.drawLine(100,35,100,250);
g.drawLine(200,35,200,250);
for(int i = 0; i < xlist.size(); i ++)
{
Object a1=xlist.get(i);
Object b1=ylist.get(i);
int k=(Integer)a1;
int j=(Integer)b1;
g.drawString("X",k,j);
}
}
#Override
public void update(Graphics g)
{
paint(g);
if(Board.CurrentPlayerMark=='x')
g.drawString("X",xpos,ypos);
else if(Board.CurrentPlayerMark=='o')
g.drawString("O",xpos,ypos);
}
};
panel.addMouseListener(new MouseListener()
{
public char c;
#Override
public void mouseClicked(MouseEvent e)
{
c=Board.CurrentPlayerMark;
System.out.println(":MOUSE_CLICK_EVENT:");
cursorPosition = MouseInfo.getPointerInfo().getLocation();
xpos=cursorPosition.x;
ypos=cursorPosition.y;
xlist.add(xpos);
ylist.add(ypos);
Graphics g = getGraphics();
update(g);
repaint(); //Want to repaint here after user clicks on desired position in X/O grid
//Does update method is useful to call or not???
System.out.println("xlist: " + xlist +"ylist: " + ylist);
System.out.println("X: " + xpos + " Y: " + ypos);
System.out.println("CurrentPlayerMark is:"+c);
Board.changePlayer();
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
Related
I am currently working on a test project using windows and servers. I have it working so far (doing what's supposed to be doing), but the only problem is that the constructor is being called twice, making the code to display two similar windows. Help!
Here is my code:
(you can ignore the mouse listener parts, I don't really think that's the problem).
public class RummyClient implements Runnable{
public GUI gui = new GUI();
public static Servidor servidor;
public static void main(String[] args) throws UnknownHostException, IOException {
servidor = new Servidor(25565, "localhost");
new Thread(new RummyClient()).start();
}
#Override
public void run() {
while(true) {
gui.repaint();
}
}
public class GUI extends JFrame {
public int clickedX = 0;
public int clickedY = 0;
public String stage = "";
public boolean start = false;
public GUI() {
setTitle("Rummy");
setSize(1280, 720);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
Board board = new Board();
setContentPane(board);
getContentPane().setPreferredSize(new Dimension(1280, 720));
Move move = new Move();
addMouseMotionListener(move);
Click click = new Click();
addMouseListener(click);
pack();
stage = "start";
System.out.println("created");
}
public class Board extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
try {
Image board = ImageIO.read(new File("client/src/imgs/board.jpg")).getScaledInstance(1280, 720, java.awt.Image.SCALE_SMOOTH);
g.drawImage(board, 0, 0, this);
switch (stage) {
case "start":
Image playButtonNP = ImageIO.read(new File("client/src/imgs/play.png")).getScaledInstance(406, 220, java.awt.Image.SCALE_SMOOTH);
Image rummyTitle = ImageIO.read(new File("client/src/imgs/rummy.png")).getScaledInstance(526, 340, java.awt.Image.SCALE_SMOOTH);
g.drawImage(rummyTitle, 376, 0, this);
if (start){
g.drawImage(playButtonNP, 448, 360, this);
}
break;
}
} catch (Exception e) {
System.out.println("error!");
}
}
}
public class Move implements MouseMotionListener {
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
}
}
public class Click implements MouseListener{
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
clickedX = e.getX();
clickedY = e.getY();
}
#Override
public void mouseReleased(MouseEvent e) {
clickedX = 0;
clickedY = 0;
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
public void start() {
this.start = true;
}
}
static class Servidor extends RummyClient{
Socket s;
PrintWriter out;
Scanner in;
public Servidor(int port, String ip) throws UnknownHostException, IOException {
this.s = new Socket(ip, port);
this.out = new PrintWriter(s.getOutputStream());
this.in = new Scanner(s.getInputStream());
Thread input = new Thread(new Input());
input.start();
}
public void send(String text) {
out.println(text);
out.flush();
}
class Input implements Runnable {
#Override
public void run() {
while(true) {
String incoming = in.nextLine();
switch (incoming) {
case "ready":
gui.start();
break;
}
}
}
}
}
}
Trying to work on a networking project, where two or more users need to be able to paint in the same JFrame.
How would this be approached most realisticly, connecting the two PCs using their IPs, then create a real-time scenario for them to work in, OR, some kind of package system, where the users send what they've drawne recently, and then the other user can see what have just been send?
EDIT: Added my drawing class for context
public class CanvasFrame extends JPanel {
ArrayList<Point> location = new ArrayList<Point>();
JTextArea consoleOutput = new JTextArea(1,20);
public void addComponentToPane(Container pane) {
consoleOutput.setEditable(false);
}
public CanvasFrame() {
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
location.clear();
location.add(e.getPoint());
}
});
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
location.add(e.getPoint());
repaint();
}
});
setPreferredSize(new Dimension(800, 500));
setBackground(Color.WHITE);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(location.isEmpty()){
return;
}
Point p = location.get(0);
for (int i = 1; i < location.size(); i++) {
Point q = location.get(i);
g.drawLine(p.x, p.y, q.x, q.y);
p = q;
}
}
public static void main(String[] args) throws Exception {
InetAddress SERVERIP = InetAddress.getLocalHost();
Runnable runnable = new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Drawing with friends");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CanvasFrame(), BorderLayout.CENTER);
JTextArea IPadress = new JTextArea(1,20);
IPadress.setEditable(false);
IPadress.append("DEVICE IP: " + SERVERIP.getHostAddress());
frame.add(IPadress, BorderLayout.SOUTH);
frame.setSize(new Dimension(800,600));
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}
}
I'm creating a basic program that is to make a "life bar" that fills when you press the space bar, and when you get to the maximum, you win. Every second it decreases, so just spam the space bar to win. It's in attempt to test for a basic game throug java. My program is caught at this error, giving it a runtime error that I'm unfamiliar with. Here is my code:
import javax.swing.JOptionPane;
import javax.swing.*;
import java.util.*;
import static java.lang.System.*;
import static java.lang.Math.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*; //for files
public class clicker
{
public static void main(String args[])
{
new Clicker(); //Make a window
}
}
class Clicker extends Frame implements KeyListener, MouseListener
{
// global variables
private final static int SCHEIGHT=768,SCWIDTH=1024;
// direction constants
final static int N = 0,NE = 1,E = 2,SE = 3, S = 4, SW = 5, W = 6, NW =7,STILL = 8;
// movement change constants
final int X = 0,Y = 1,Z = 2;
final int TITLE = 30, STATUS = 40;
final static int size = 2;
Image myPic;
private boolean gameNotOver = true;
private boolean keyPressed = false;
private Image myScreen;
private int whichScreen;
private int numScreen;
private int timer;
private int amt;
public Clicker()
{
setSize(SCWIDTH,SCHEIGHT);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
this.setVisible(true);
gameLoop();
}
public void gameLoop()
{
do
{
if (keyPressed)
{
amt++;
out.println(keyPressed + " " +gameNotOver+" "+ "Time "+timer);
this.repaint();
keyPressed = false;
}
if(amt >= 450)
gameNotOver = false;
this.setVisible(true);
//this.repaint();
pause(30);
}
while (gameNotOver);
if(!gameNotOver)
{
pause(5000);
System.exit(0);
}
}
public int getAmt()
{
return amt;
}
public void paint(Graphics pen)
{
if(whichScreen==0)
{
pen.drawImage(myPic,100,200,506,279,this); //Draws the image
pen.setFont(new Font("Timesroman", Font.ITALIC, 50));
pen.drawString("Welcome to the Clicker Test", 200, 75);
pen.setFont(new Font("Timesroman", Font.ITALIC, 40));
pen.drawString("Created by Cody Coulter",150,150);
pen.setFont(new Font("Timesroman", Font.ITALIC, 25));
pause(2000); // 2000 final
whichScreen++;
}
else
{
myScreen =createImage(getSize().width,getSize().height);
Graphics o = myScreen.getGraphics();
doubleBuffer(o);
pen.drawImage(myScreen,0,0,this);
}
}
public void doubleBuffer(Graphics pen) // Draws the window
{
pause (500);
numScreen++;
if (numScreen > 0)
{
setBounds(0,0,SCWIDTH,SCHEIGHT);
Color HPRed = new Color(213, 0, 0);
pen.setColor(Color.BLACK);
setTitle("Clicker Test -- Cody Coulter."+
" To click, press the space bar");
pen.setFont(new Font("Timesroman",Font.PLAIN,48));
pen.drawString("Clicker Test ",350,75);
pen.setFont(new Font("TimesRoman",Font.BOLD,33));
pen.fillRect((SCWIDTH/4), (SCHEIGHT/3), 50, 500);
pen.setColor(HPRed);
pen.fillRect((SCWIDTH/4)-5, (SCHEIGHT/3)+5, 40, amt);
if(!gameNotOver)
{
if(amt > 100)
{
pen.setColor(HPRed);
pen.fillRect(SCWIDTH/4-75, SCHEIGHT/3, SCWIDTH/2+150, SCHEIGHT/3-60);
pen.setColor(Color.GRAY);
pen.fillRect(SCWIDTH/4-65, SCHEIGHT/3+10, SCWIDTH/2+130, SCHEIGHT/3-80);
pen.setColor(Color.YELLOW);
pen.setFont(new Font("Verdana", Font.BOLD, 40));
pen.drawString("You got it!", SCWIDTH/2-290, SCHEIGHT/2-20);
}
}
this.repaint();
}
}
public void keyPressed(KeyEvent e)
{
keyPressed = true;
setTitle(""+ KeyEvent.getKeyText(e.getKeyCode()));
System.out.println("hit + "+ KeyEvent.getKeyText(e.getKeyCode())+ " " + keyPressed);
switch(e.getKeyCode())
{
case KeyEvent.VK_SPACE: amt= amt + 4;
break;
}
}
public void mouseClicked(MouseEvent m)
{
}
public void mouseEntered(MouseEvent m)
{
}
public void mouseExited(MouseEvent m)
{
}
public void mousePressed(MouseEvent m)
{
}
public void mouseReleased(MouseEvent m)
{
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
public void update(Graphics G)
{
paint(G);
}
public static void pause (long r)
{
try
{
Thread.sleep(r);
}
catch (Exception e)
{
out.println(" sleep error " + e);
}
}
}
I'm new to this forum board, and I am most likely using arbitrary information to solve this particular problem, and am new to programming in general. Any insight, or how to narrow the question would be greatly appreciated.
Again, the error stated is "Exception in thread "main" java.lang.NoClassDefFoundError: clicker (wrong name: Clicker)
Thank You
public class clicker
{
public static void main(String args[])
{
new Clicker(); //Make a window
}
}
You're essentially declaring your class twice. Take the main function and put it in your other clicker class, and delete the lower case one.
class Clicker extends Frame implements KeyListener, MouseListener
{
public static void main(String args[])
{
new Clicker(); //Make a window
}
//.....rest of class.....
}
You main() method should be placed in the Clicker class.
So the solution is :
class Clicker extends Frame implements KeyListener, MouseListener
{
public static void main(String args[])
{
new Clicker(); // Make a window
}
...
}
Also, make sure that your file is named Clicker.java, to match your class's name.
public Clicker(){
setSize(SCWIDTH,SCHEIGHT);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
this.setVisible(true);
//ADD THIS
this.addKeyListener(this);
this.addMouseListener(this);
gameLoop();
}
I'm making a screenshot program so when you press the screenshot button, a JMessageDial pops up and prompts you with your image, it the tells you to drag your mouse and make a box around the area that you want to take a screenshot of. I can't seem to find how to get the image inside the box when the user clicks okay.
So what I need help with is getting the image inside of the rectangle the user "draws" with his mouse, and store that in a variable.
Here is the specific code:
public void selectArea(final BufferedImage screen) throws Exception {
final BufferedImage screenCopy = new BufferedImage(screen.getWidth(), screen.getHeight(), screen.getType());
final JLabel screenLabel = new JLabel(new ImageIcon(screenCopy));
JScrollPane screenScroll = new JScrollPane(screenLabel);
screenScroll.setPreferredSize(new Dimension((int)(screen.getWidth()/2), (int)(screen.getHeight()/2)));
JPanel panel = new JPanel(new BorderLayout());
panel.add(screenScroll, BorderLayout.CENTER);
final JLabel selectionLabel = new JLabel("Draw a rectangle");
panel.add(selectionLabel, BorderLayout.SOUTH);
repaint(screen, screenCopy);
screenLabel.repaint();
screenLabel.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent me) {
start = me.getPoint();
repaint(screen, screenCopy);
selectionLabel.setText("Start Point: " + start);
screenLabel.repaint();
}
#Override
public void mouseDragged(MouseEvent me) {
end = me.getPoint();
captureRect = new Rectangle(start, new Dimension(end.x-start.x, end.y-start.y));
try {
paintFinalImage(new BufferedImage((int)screenCopy.getGraphics().getClipBounds(captureRect).getWidth()+1,
(int)screenCopy.getGraphics().getClipBounds(captureRect).getHeight()+1, screen.getType()));
} catch (Exception e) {
e.printStackTrace();
}
repaint(screen, screenCopy);
screenLabel.repaint();
selectionLabel.setText("Rectangle: " + captureRect);
}
});
JOptionPane.showMessageDialog(null, panel, "Select your image", JOptionPane.OK_OPTION, new ImageIcon(""));
uploadImage(screenShot);
System.out.println("Final rectangle: " + screenCopy.getGraphics().getClipBounds(captureRect));
}
And this is the full class if you need it:
package com.screencapture;
import java.awt.*;
public class Main implements ActionListener, ItemListener, KeyListener, NativeKeyListener {
private final Image icon = Toolkit.getDefaultToolkit().getImage("./data/icon.gif");
private final TrayIcon trayIcon = new TrayIcon(icon, "Screen Snapper");
private JFrame frame;
private Rectangle captureRect;
private JComboBox<String> imageType;
private boolean hideWhenMinimized = false;
private final String API_KEY = "b84e430b4a65d16a6955358141f21a61";
private static Robot robot;
private BufferedImage screenShot;
private Point end;
private Point start;
public static void main(String[] args) throws Exception {
robot = new Robot();
new Main().start();
}
public void start() throws Exception {
GlobalScreen.getInstance().registerNativeHook();
GlobalScreen.getInstance().addNativeKeyListener(this);
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
frame = new JFrame("White power!");
frame.setPreferredSize(new Dimension(250, 250));
frame.getContentPane().setLayout(null);
frame.setIconImage(icon);
frame.addKeyListener(this);
frame.addWindowListener(new WindowListener() {
#Override
public void windowOpened(WindowEvent e) {}
#Override
public void windowClosing(WindowEvent e) {}
#Override
public void windowClosed(WindowEvent e) {}
#Override
public void windowIconified(WindowEvent e) {
if (hideWhenMinimized)
frame.setVisible(false);
}
#Override
public void windowDeiconified(WindowEvent e) {}
#Override
public void windowActivated(WindowEvent e) {}
#Override
public void windowDeactivated(WindowEvent e) {}
});
JLabel lblImageType = new JLabel("Image Format:");
lblImageType.setBounds(10, 11, 90, 14);
frame.getContentPane().add(lblImageType);
String[] imageTypes = {"PNG", "JPG"};
imageType = new JComboBox<String>(imageTypes);
imageType.setBounds(106, 8, 51, 20);
frame.getContentPane().add(imageType);
JButton btnTakeScreenShot = new JButton("ScreenShot");
btnTakeScreenShot.setBounds(24, 69, 115, 23);
frame.getContentPane().add(btnTakeScreenShot);
btnTakeScreenShot.addActionListener(this);
setTrayIcon();
frame.pack();
frame.setVisible(true);
}
public void setTrayIcon() throws AWTException {
CheckboxMenuItem startup = new CheckboxMenuItem("Run on start-up");
CheckboxMenuItem hide = new CheckboxMenuItem("Hide when minimized");
String[] popupMenuOptions = {"Open", "Exit"};
if (SystemTray.isSupported()) {
SystemTray tray = SystemTray.getSystemTray();
trayIcon.setImageAutoSize(true);
PopupMenu popupMenu = new PopupMenu();
for (String option : popupMenuOptions) {
if (option == "Exit") {
popupMenu.add(startup);
popupMenu.add(hide);
popupMenu.add(option);
} else {
popupMenu.add(option);
}
}
trayIcon.setPopupMenu(popupMenu);
popupMenu.addActionListener(this);
startup.addItemListener(this);
hide.addItemListener(this);
trayIcon.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.setVisible(true);
}
});
tray.add(trayIcon);
}
}
public void selectArea(final BufferedImage screen) throws Exception {
final BufferedImage screenCopy = new BufferedImage(screen.getWidth(), screen.getHeight(), screen.getType());
final JLabel screenLabel = new JLabel(new ImageIcon(screenCopy));
JScrollPane screenScroll = new JScrollPane(screenLabel);
screenScroll.setPreferredSize(new Dimension((int)(screen.getWidth()/2), (int)(screen.getHeight()/2)));
JPanel panel = new JPanel(new BorderLayout());
panel.add(screenScroll, BorderLayout.CENTER);
final JLabel selectionLabel = new JLabel("Draw a rectangle");
panel.add(selectionLabel, BorderLayout.SOUTH);
repaint(screen, screenCopy);
screenLabel.repaint();
screenLabel.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent me) {
start = me.getPoint();
repaint(screen, screenCopy);
selectionLabel.setText("Start Point: " + start);
screenLabel.repaint();
}
#Override
public void mouseDragged(MouseEvent me) {
end = me.getPoint();
captureRect = new Rectangle(start, new Dimension(end.x-start.x, end.y-start.y));
try {
paintFinalImage(new BufferedImage((int)screenCopy.getGraphics().getClipBounds(captureRect).getWidth()+1,
(int)screenCopy.getGraphics().getClipBounds(captureRect).getHeight()+1, screen.getType()));
} catch (Exception e) {
e.printStackTrace();
}
repaint(screen, screenCopy);
screenLabel.repaint();
selectionLabel.setText("Rectangle: " + captureRect);
}
});
JOptionPane.showMessageDialog(null, panel, "Select your image", JOptionPane.OK_OPTION, new ImageIcon(""));
uploadImage(screenShot);
System.out.println("Final rectangle: " + screenCopy.getGraphics().getClipBounds(captureRect));
}
public void paintFinalImage(BufferedImage image) throws Exception {
screenShot = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
Graphics2D g = screenShot.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
}
public void repaint(BufferedImage orig, BufferedImage copy) {
Graphics2D g = copy.createGraphics();
g.drawImage(orig, 0, 0, null);
if (captureRect != null) {
g.setColor(Color.BLACK);
g.draw(captureRect);
}
g.dispose();
}
public void uploadImage(BufferedImage image) throws Exception {
String IMGUR_POST_URI = "http://api.imgur.com/2/upload.xml";
String IMGUR_API_KEY = API_KEY;
String readLine = null;
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, imageType.getSelectedItem().toString(), outputStream);
URL url = new URL(IMGUR_POST_URI);
String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(Base64.encodeBase64String(outputStream.toByteArray()).toString(), "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(IMGUR_API_KEY, "UTF-8");
URLConnection urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data);
wr.flush();
InputStream inputStream;
if (((HttpURLConnection) urlConnection).getResponseCode() == 400) {
inputStream = ((HttpURLConnection) urlConnection).getErrorStream();
} else {
inputStream = urlConnection.getInputStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
readLine = line;
}
wr.close();
reader.close();
} catch(Exception e){
e.printStackTrace();
}
String URL = readLine.substring(readLine.indexOf("<original>") + 10, readLine.indexOf("</original>"));
System.out.println(URL);
Toolkit.getDefaultToolkit().beep();
StringSelection stringSelection = new StringSelection(URL);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
System.out.println(command);
if (command.equalsIgnoreCase("open")) {
frame.setVisible(true);
} else if (command.equalsIgnoreCase("exit")) {
System.exit(-1);
} else if (command.equalsIgnoreCase("screenshot")) {
try {
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
final BufferedImage screen = robot.createScreenCapture(new Rectangle(screenSize));
selectArea(screen);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
#Override
public void itemStateChanged(ItemEvent e) {
System.out.println(e.getItem() + ", " +e.getStateChange());
String itemChanged = e.getItem().toString();
if (itemChanged.equalsIgnoreCase("run on start-up")) {
//TODO
} else if (itemChanged.equalsIgnoreCase("hide when minimized")) {
if (e.getStateChange() == ItemEvent.DESELECTED) {
hideWhenMinimized = false;
} else if (e.getStateChange() == ItemEvent.SELECTED) {
hideWhenMinimized = true;
}
}
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println("KeyTyped: "+e.getKeyCode());
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void nativeKeyPressed(NativeKeyEvent e) {
}
#Override
public void nativeKeyReleased(NativeKeyEvent e) {
System.out.println("KeyReleased: "+e.getKeyCode());
System.out.println(KeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == 154) {
try {
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
final BufferedImage screen = robot.createScreenCapture(new Rectangle(screenSize));
selectArea(screen);
frame.setVisible(true);
} catch(Exception e1) {
e1.printStackTrace();
}
}
}
#Override
public void nativeKeyTyped(NativeKeyEvent e) {
}
}
I recommend that you simplify your problem to solve it. Create a small compilable and runnable program that doesn't have all the baggage of your current code, but whose only goal is to display an image, and let the user select a sub-portion of that image. Then if your attempt fails, you can post your attempt here, and we can actually both run it, and understand it, and hopefully then be able to fix it.
For example, here's a small bit of compilable and runnable code that uses a MouseListener to select a small section of an image. Perhaps you can get some ideas from it:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class ImagePlay extends JPanel {
public static final String IMAGE_PATH = "http://upload.wikimedia.org/wikipedia/" +
"commons/thumb/3/39/European_Common_Frog_Rana_temporaria.jpg/" +
"800px-European_Common_Frog_Rana_temporaria.jpg";
private static final Color RECT_COLOR = new Color(180, 180, 255);
private BufferedImage img = null;
Point p1 = null;
Point p2 = null;
public ImagePlay() {
URL imgUrl;
try {
imgUrl = new URL(IMAGE_PATH);
img = ImageIO.read(imgUrl );
ImageIcon icon = new ImageIcon(img);
JLabel label = new JLabel(icon) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
myLabelPaint(g);
}
};
setLayout(new BorderLayout());
add(new JScrollPane(label));
MouseAdapter mAdapter = new MyMouseAdapter();
label.addMouseListener(mAdapter);
label.addMouseMotionListener(mAdapter);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void myLabelPaint(Graphics g) {
if (p1 != null && p2 != null) {
int x = Math.min(p1.x, p2.x);
int y = Math.min(p1.y, p2.y);
int width = Math.abs(p1.x - p2.x);
int height = Math.abs(p1.y - p2.y);
g.setXORMode(Color.DARK_GRAY);
g.setColor(RECT_COLOR);
g.drawRect(x, y, width, height);
}
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
p1 = e.getPoint();
p2 = null;
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
p2 = e.getPoint();
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
p2 = e.getPoint();
repaint();
int x = Math.min(p1.x, p2.x);
int y = Math.min(p1.y, p2.y);
int width = Math.abs(p1.x - p2.x);
int height = Math.abs(p1.y - p2.y);
BufferedImage smlImg = img.getSubimage(x, y, width, height);
ImageIcon icon = new ImageIcon(smlImg);
JLabel label = new JLabel(icon);
JOptionPane.showMessageDialog(ImagePlay.this, label, "Selected Image",
JOptionPane.PLAIN_MESSAGE);
}
}
private static void createAndShowGui() {
ImagePlay mainPanel = new ImagePlay();
JFrame frame = new JFrame("ImagePlay");
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();
}
});
}
}
It uses a publicly available image obtained online, a MouseListener that's added to a JLabel, and the JLabel has its paintComponent(...) method overridden so as to show the guide lines from the MouseListener/Adapter. It creates the sub image via BufferedImage's getSubimage(...) method, and then it displays it in a JOptionPane, but it would be trivial to save the image if desired.
This gui should draw moving images on frame panel called "system". But first of all i need to make those objects. Here i'm trying to add them to an array and use that array in other classes. But array keeps being empty!
I guess the problem is in declaring(bottom of the code). There is no exception thrown because I let other classes to execute only when this array(Planetarium) is not empty(it should work like that, because other moves depends on planets created(those objects)). But if it is empty that means nothing is declared...
What should i do if I want to fill an array in the thread executed in event listener?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends Frame implements WindowListener,ActionListener {
cpWindow window1 = new cpWindow();
cmWindow window2 = new cmWindow();
Delete window3 = new Delete();
SolarSystem system = new SolarSystem(300,300);
Planet[] Planetarium = null; // using this to make an array
Moon[] Moonarium = null;
/**
* Frame for general window.
*/
public void createFrame0(){
JFrame f0 = new JFrame("Choose what you want to do");
f0.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f0.addWindowListener(this);
f0.setLayout(new GridLayout(3,1));
JButton cP = new JButton("Create a planet");
JButton cM = new JButton("Create a moon");
JButton Delete = new JButton("Annihilate a planet or moon");
f0.add(cP);
f0.add(cM);
f0.add(Delete);
cP.addActionListener(this);
cM.addActionListener(this);
Delete.addActionListener(this);
cP.setActionCommand("1");
cM.setActionCommand("2");
Delete.setActionCommand("3");
f0.pack();
f0.setVisible(true);
}
/**
* Frame for planet adding window.
*/
class cpWindow implements ActionListener,WindowListener{
JLabel name1 = new JLabel("Name");
JLabel color1 = new JLabel("Color");
JLabel diam1 = new JLabel("Diameter");
JLabel dist1 = new JLabel("Distance");
JLabel speed1 = new JLabel("Speed");
JTextField name2 = new JTextField();
JTextField color2 = new JTextField();
JTextField diam2 = new JTextField();
JTextField dist2 = new JTextField();
JTextField speed2 = new JTextField();
double distance;
int Speed;
double diameter;
public void createFrame1() {
JFrame f1 = new JFrame("Add planet");
f1.addWindowListener(this);
f1.setLayout(new GridLayout(6,2,5,5));
JButton mygt = new JButton("Create planet");
mygt.addActionListener(this);
name2.setText("belekoks");color2.setText("RED");diam2.setText("30");dist2.setText("60");spe ed2.setText("2");
f1.add(name1);f1.add(name2);f1.add(color1);f1.add(color2);f1.add(diam1);
f1.add(diam2);f1.add(dist1);f1.add(dist2);f1.add(speed1);f1.add(speed2);
f1.add(mygt);
f1.pack();
f1.setVisible(true);
}
public void createVariables(){
try {
distance = Double.parseDouble(dist2.getText());
Speed = Integer.parseInt(speed2.getText());
diameter = Double.parseDouble(diam2.getText());
}
catch(NumberFormatException i) {
}
Main.diametras = diameter;
Main.distancija = distance;
Main.greitis = Speed;
Main.vardas = name2.getText();
Main.spalva = color2.getText();
}
public void actionPerformed(ActionEvent e) {
createVariables();
new NewThread().start();
list.display();
}
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
}
/**
* Frame for moon adding window
*/
CheckboxGroup planets = new CheckboxGroup();
String which;
class cmWindow implements ActionListener,WindowListener, ItemListener{
JLabel name1 = new JLabel("Name");
JLabel color1 = new JLabel("Color");
JLabel diam1 = new JLabel("Diameter");
JLabel speed1 = new JLabel("Speed");
JTextField name2 = new JTextField();
JTextField color2 = new JTextField();
JTextField diam2 = new JTextField();
JTextField speed2 = new JTextField();
JLabel info = new JLabel("Which planet's moon it will be?");
JLabel corDist1 = new JLabel("Distance from centre of rotation");
JLabel corSpeed1 = new JLabel("Speed which moon centres");
JTextField corDist2 = new JTextField();
JTextField corSpeed2 = new JTextField();
int cordistance;
int corspeed;
public void createFrame1() {
JFrame f1 = new JFrame("Add moon");
f1.addWindowListener(this);
f1.setLayout(new GridLayout(8,2,5,5));
JButton mygt = new JButton("Create moon");
mygt.addActionListener(this);
for(int i=0;i<Planetarium.length;i++){
add(new Checkbox(Planetarium[i].nam,planets,false));
}
corDist2.setText("15");corSpeed2.setText("3");
f1.add(name1);f1.add(name2);f1.add(color1);f1.add(color2);
f1.add(diam1);f1.add(diam2);f1.add(speed1);f1.add(speed2);
f1.add(corDist1);f1.add(corDist2);f1.add(corSpeed1);f1.add(corSpeed2);
f1.add(mygt);
f1.pack();
f1.setVisible(true);
}
int Speed;
double diameter;
public void createVariables(){
try {
Speed = Integer.parseInt(speed2.getText());
diameter = Double.parseDouble(diam2.getText());
cordistance = Integer.parseInt(corDist2.getText());
corspeed = Integer.parseInt(corSpeed2.getText());
}
catch(NumberFormatException i) {}
Main.diametras = diameter;
Main.greitis = Speed;
Main.vardas = name2.getText();
Main.spalva = color2.getText();
Main.centGrt = corspeed;
Main.centAts = cordistance;
}
public void actionPerformed(ActionEvent e) {
createVariables();
new NewThread().start();
}
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
#Override
public void itemStateChanged(ItemEvent e) {
which = planets.getSelectedCheckbox().getLabel();
}
}
/**
* Deleting window
*/
class Delete implements ActionListener,WindowListener{
Checkbox[] checkB = new Checkbox[100];
public void createFrame2(){
JFrame f2 = new JFrame("Death Start");
f2.addWindowListener(this);
f2.setLayout(new GridLayout(6,2,5,5));
JButton Del = new JButton("Shoot it!");
Del.addActionListener(this);
JLabel[] planetName = new JLabel[100];
for(int i=0;i<Planetarium.length;i++){
planetName[i].setText(Planetarium[i].nam);
checkB[i].setLabel("This");
checkB[i].setState(false);
f2.add(planetName[i]);f2.add(checkB[i]);
}
}
public void actionPerformed(ActionEvent e) {
for(int i=0;i<Planetarium.length;i++){
if(checkB[i].getState()){
Planetarium[i] = null;
}
}
}
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
}
////////////////////////////////////////////////////////
public GUI() {
createFrame0();
}
public void actionPerformed(ActionEvent e) {
if ("1".equals(e.getActionCommand())) {this.window1.createFrame1();}
else if ("2".equals(e.getActionCommand()) & Planetarium != null) {this.window2.createFrame1();}
else if ("3".equals(e.getActionCommand()) & Planetarium != null) {this.window3.createFrame2();}
}
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
LinkedList list = new LinkedList();
class NewThread extends Thread {
Thread t;
NewThread() {
t = new Thread(this);
t.start();
}
public void run() {
Moon moon = null;
Planet planet = new Planet(Main.vardas,Main.distancija,Main.diametras,Main.spalva,Main.greitis);
if(Planetarium != null){
for(int i=0;i<Planetarium.length;i++){
if (which == Planetarium[i].nam){
moon = new Moon(Main.vardas,Planetarium[i].dist,Main.diametras,Main.spalva,Main.greitis,Main.centGrt,Main.centAts);
}
}}
int a=0,b=0;
int i = 0;
if (Main.centAts == 0){
Planetarium[i] = planet; //i guess problem is here
a++;
list.add(planet);
for(i=0; i <= i+1 0; i++) {
planet.move();
planet.drawOn(system);
system.finishedDrawing();
if (i==360){i=0;}
}
}
else{
Moonarium[i] = moon;
b++;
if(i==Main.greitis){
for(int l = 0; l <= l+1; l++) {
moon.move();
moon.drawOn(system);
system.finishedDrawing();
}}
}
}
}
}
EDIT: add linkedlist(still nothing after display) and moved declaration before infinite loop
You don't appear to have assigned these arrays anything so they should be null rather than empty.
The way you are using them a List might be better.
final List<Planet> planetarium = new ArrayList<Planet>();
planetarium.add(new Planet( .... ));
Planet p = planetarium.get(i);
for(Planet p: planetarium){
// something for each planet.
}
Note: you have to create an array before using it and you have know its length which is fixed. A list can have any length, but you still need to create it first.
Look at the loop before:
Planetarium[i] = planet;
It looks like it will loop infinitely
for(i=0; i >= 0; i++)
i will alway be >= 0.