I am making a simple clicker type game. The problem is, my JPanel is ignoring the Swing Timer I have set to it to update every second and is instead updating every millisecond on it's own, even if I remove the timer. Repaint is not called anywhere except the timer's listener, so the JPanel is repainting itself without my instruction, does anyone know why this would be happening?
public GameGUI() {
sectors.add(new Sector());
add(recourseMonitor);
recourseMonitor.setOpaque(false);
recourseMonitor.setFocusable(false);
add(buyHShip);
buyHShip.setToolTipText("Extracts Hydrogren directly from the core of a star.");
buyHShip.addActionListener(this);
add(buyCShip);
buyCShip.setToolTipText("Extracts Carbon from indigenous lifeforms.");
buyCShip.addActionListener(this);
add(buyIShip);
add(buyUShip);
buyUShip.setToolTipText("Extracts Uranium from nuclear waste leftovers.");
buyUShip.addActionListener(this);
buyIShip.setToolTipText("Strip mines nearby planets for Iron.");
buyIShip.addActionListener(this);
add(buyAShip);
buyAShip.setToolTipText("Collects Antimatter from the fabric of the universe.");
buyAShip.addActionListener(this);
add(buyCookieShip);
buyCookieShip.setToolTipText("Rips holes in the space-time continuum to "
+ "bring back cookies from an ancient civilization.");
buyCookieShip.addActionListener(this);
add(buyTShip);
buyTShip.addActionListener(this);
add(cashButton);
cashButton.addActionListener(this);
add(sellHplus);
sellHplus.addActionListener(this);
add(sellCplus);
sellCplus.addActionListener(this);
add(sellIplus);
sellIplus.addActionListener(this);
add(sellUplus);
sellUplus.addActionListener(this);
add(sellAplus);
sellAplus.addActionListener(this);
add(sellCookieplus);
sellCookieplus.addActionListener(this);
add(sellHminus);
sellHminus.addActionListener(this);
add(sellCminus);
sellCminus.addActionListener(this);
add(sellIminus);
sellIminus.addActionListener(this);
add(sellUminus);
sellUminus.addActionListener(this);
add(sellAminus);
sellAminus.addActionListener(this);
add(sellCookieminus);
sellCookieminus.addActionListener(this);
add(hBeingSold);
add(cBeingSold);
add(iBeingSold);
add(uBeingSold);
add(aBeingSold);
add(cookiesBeingSold);
if (debug == true) {
add(testButton);
testButton.addActionListener(this);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
buyHShip.setText("[" + sectors.get(0).getStation().gethShip() + "] "
+ "Buy Hydrogen Extractor: " + hPrice);
buyCShip.setText("[" + sectors.get(0).getStation().getcShip() + "] "
+ "Buy Carbon Miner: " + cPrice);
buyUShip.setText("[" + sectors.get(0).getStation().getuShip() + "] "
+ "Buy Uranium Miner: " + uPrice);
buyIShip.setText("[" + sectors.get(0).getStation().getiShip() + "] "
+ "Buy Iron Miner: " + iPrice);
buyAShip.setText("[" + sectors.get(0).getStation().getaShip() + "] "
+ "Buy Antimatter Collector: " + aPrice);
buyCookieShip.setText("[" + sectors.get(0).getStation().getcChip() + "] "
+ "Buy Cookie Drone: " + cookiePrice);
buyTShip.setText("[" + sectors.get(0).getStation().gettShip() + "] "
+ "Buy Trading Ship: " + tradePrice);
hBeingSold.setText("Hydrogen being sold: " + tradeH);
cBeingSold.setText("Carbon being sold: " + tradeC);
iBeingSold.setText("Iron being sold: " + tradeI);
uBeingSold.setText("Uranium being sold: " + tradeU);
aBeingSold.setText("Antimatter being sold: " + tradeA);
cookiesBeingSold.setText("Cookies being sold: " + tradeCookie);
recourseMonitor.setText("Space Cash: " + spaceCash
+ "\nEnergy: " + energy
+ "\nHydrogen: " + hydrogen
+ "\nCarbon: " + carbon
+ "\nUranium: " + uranium
+ "\nIron: " + iron
+ "\nAntimatter: " + antimatter
+ "\nCookies: " + cookies);
drawItems(g);
playGame();
}
public void drawItems(Graphics g) {
super.paintComponent(g);
recourseMonitor.setLocation(5, 0);
buyHShip.setLocation(getWidth() - buyHShip.getWidth(), 0);
buyCShip.setLocation(getWidth() - buyCShip.getWidth(), buyCShip.getHeight() * 2);
buyIShip.setLocation(getWidth() - buyIShip.getWidth(), buyIShip.getHeight() * 4);
buyUShip.setLocation(getWidth() - buyUShip.getWidth(), buyUShip.getHeight() * 6);
buyAShip.setLocation(getWidth() - buyAShip.getWidth(), buyAShip.getHeight() * 8);
buyCookieShip.setLocation(getWidth() - buyCookieShip.getWidth(), buyCookieShip.getHeight() * 10);
buyTShip.setLocation(getWidth() - buyTShip.getWidth(), buyTShip.getHeight() * 12);
cashButton.setLocation(getWidth() / 2 - cashButton.getWidth() / 2, 10);
testButton.setLocation(getWidth() / 2 - testButton.getWidth() / 2, testButton.getHeight() + 20);
sellHplus.setLocation(5, 200);
hBeingSold.setLocation(sellHplus.getWidth() + 20, 200);
sellHminus.setLocation(sellHplus.getWidth() + hBeingSold.getWidth() + 40, 200);
sellCplus.setLocation(5, 250);
cBeingSold.setLocation(sellCplus.getWidth() + 20, 250);
sellCminus.setLocation(sellCplus.getWidth() + cBeingSold.getWidth() + 40, 250);
sellIplus.setLocation(5, 300);
iBeingSold.setLocation(sellIplus.getWidth() + 20, 300);
sellIminus.setLocation(sellIplus.getWidth() + iBeingSold.getWidth() + 40, 300);
sellUplus.setLocation(5, 350);
uBeingSold.setLocation(sellUplus.getWidth() + 20, 350);
sellUminus.setLocation(sellUplus.getWidth() + uBeingSold.getWidth() + 40, 350);
sellAplus.setLocation(5, 400);
aBeingSold.setLocation(sellAplus.getWidth() + 20, 400);
sellAminus.setLocation(sellAplus.getWidth() + aBeingSold.getWidth() + 40, 400);
sellCookieplus.setLocation(5, 450);
cookiesBeingSold.setLocation(sellCookieplus.getWidth() + 20, 450);
sellCookieminus.setLocation(sellCookieplus.getWidth() + cookiesBeingSold.getWidth() + 40, 450);
}
public void playGame() {
for (int i = 0; i < sectors.size(); i++) {
hIncome = sectors.get(i).getStation().gethShip() - tradeH;
cIncome = sectors.get(i).getStation().getcShip() - tradeC;
iIncome = sectors.get(i).getStation().getiShip() - tradeI;
uIncome = sectors.get(i).getStation().getuShip() - tradeU;
aIncome = sectors.get(i).getStation().getaShip() - tradeA;
cookieIncome = sectors.get(i).getStation().getcChip() - tradeCookie;
cashIncome = (tradeH * 5) + (tradeC * 20) + (tradeI * 100)
+ (tradeU * 500) + (tradeA * 1500) + (tradeCookie * 5000);
}
for (int i = 0; i < sectors.size(); i++) {
spaceCash += cashIncome;
energy += energyIncome;
hydrogen += hIncome;
carbon += cIncome;
iron += iIncome;
uranium += uIncome;
antimatter += aIncome;
cookies += cookieIncome;
}
}
There's the code (excluding the action listener and initialization of variables and buttons).
Painting methods are for painting only:
Don't invoke methods like setText(....)
Don't invoke methods like setLocation()
Changing properties on a component will cause the component to be repainted which may cause an infinite loop.
Don't invoke super.paintComponent() in the drawItems() method. You should never invoke a painting method directly except to invoke super.paintComponent() in the paintComponent() method.
The playGame() method should not be invoked from the paintComponent() method. Again that is logic for your game. That code should be invoked from your Timer that controls the game.
Related
I am using the PDFBox to extract the character coordinates from the read PDF. However, I can't identify the unit of measurement of the value returned by the getXDirAdj () and getYDirAdj () methods?
#Override
protected void processTextPosition(TextPosition text) {
String tChar = text.getCharacter();
System.out.println("String[" + text.getXDirAdj() + ","
+ text.getYDirAdj() + " fs=" + text.getFontSize() + " xscale="
+ text.getXScale() + " height=" + text.getHeightDir() + " space="
+ text.getWidthOfSpace() + " width="
+ text.getWidthDirAdj() + "]" + text.getCharacter());
}
1 unit = 1/72 inch
"how to obtain the rotation of the character read": from the ExtractText.java tool:
static int getAngle(TextPosition text)
{
Matrix m = text.getTextMatrix().clone();
m.concatenate(text.getFont().getFontMatrix());
return (int) Math.round(Math.toDegrees(Math.atan2(m.getShearY(), m.getScaleY())));
}
I would like to apologize in advance I am new to java and don't know very much so stick with me please. I would like to know how to get my character attributes from one ActionListener method in one class to another ActionListener method in another class. I would like to get the inputs from the user about player1 in one class and then use them in the other class. Please help, and I appreciate your time.
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
if(event.getSource() == create){
Character player1 = new Character( Integer.parseInt(strength.getText()), Integer.parseInt(defense.getText()), Integer.parseInt(health.getText()) , Integer.parseInt(dexterity.getText()));
player1.name = name.getText();
JOptionPane.showMessageDialog(this, "\nName: " + player1.name + "\nHealth: " + player1.health + "\nStrength: " + player1.strength + "\nDefense: " + player1.defense + "\nDexterity: " + player1.dexterity);
dispose();//To close the current window
GameWindow gwindow = new GameWindow();
gwindow.setVisible(true);//Open the new window
}
put into
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
Character Goblin = new Character(10, 3, 6, 10);
Character Witch = new Character(2, 7, 3, 20);
Character Zombie = new Character(5, 5, 5, 15);
int damage;
if (event.getSource() == right) {
label1.setText("You have encountered a goblin!");
label2.setText("Do you wish to fight or flee?");
fight.setVisible(true);
flee.setVisible(true);
}
if(event.getSource() == fight) {
System.out.println(player1 + " VS. " + Goblin.name);
while(player1.isAlive() && Goblin.isAlive()){
// player 1 attack
damage = player1.attack(Goblin);
System.out.println(player1.name + " hits " + Goblin.name + " for " + damage + " damage.");
// player 2 attack
damage = Goblin.attack(player1);
System.out.println(Goblin.name + " hits " + player1.name + " for " + damage + " damage.\n");
}
// Check to see who won
if( player1.isAlive()){
System.out.println(player1.name + " wins!");
}
else{
System.out.println("You have perished");
}
}
}
Declare Player1 as public Static member
So it's Value can;t be changed.
and You can use player1 Through the object of that particular Class.
Class First{
//Declare That Character object as a static public here
//Player1;
}
Class Second{
//First Create Object Of that class....
First f = new First(//Parameter For Constructor);
f.Player1;
}
Change your GameWindow constructor like this.
class GameWindow extends JFrame implements ActionListener{
private Character player1;
public GameWindow(Character player1){
this.player1 = player1;
}
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
Character Goblin = new Character(10, 3, 6, 10);
Character Witch = new Character(2, 7, 3, 20);
Character Zombie = new Character(5, 5, 5, 15);
int damage;
if (event.getSource() == right) {
label1.setText("You have encountered a goblin!");
label2.setText("Do you wish to fight or flee?");
fight.setVisible(true);
flee.setVisible(true);
}
if(event.getSource() == fight) {
System.out.println(player1 + " VS. " + Goblin.name);
while(player1.isAlive() && Goblin.isAlive()){
// player 1 attack
damage = player1.attack(Goblin);
System.out.println(player1.name + " hits " + Goblin.name + " for " + damage + " damage.");
// player 2 attack
damage = Goblin.attack(player1);
System.out.println(Goblin.name + " hits " + player1.name + " for " + damage + " damage.\n");
}
// Check to see who won
if( player1.isAlive()){
System.out.println(player1.name + " wins!");
}
else{
System.out.println("You have perished");
}
}
}
}
And pass parameter to new contructor.
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
if(event.getSource() == create){
Character player1 = new Character( Integer.parseInt(strength.getText()), Integer.parseInt(defense.getText()), Integer.parseInt(health.getText()) , Integer.parseInt(dexterity.getText()));
player1.name = name.getText();
JOptionPane.showMessageDialog(this, "\nName: " + player1.name + "\nHealth: " + player1.health + "\nStrength: " + player1.strength + "\nDefense: " + player1.defense + "\nDexterity: " + player1.dexterity);
dispose();//To close the current window
GameWindow gwindow = new GameWindow(player1);
gwindow.setVisible(true);//Open the new window
}
I need the currentStockLevel for another void Method in java, is there any possibility to get it?
I think no, because of void right?
public void receive (int currentStock)
{
String outLine;
if (currentStockLevel > 0)
outLine = productCode;
{
outLine = ". Current Stock: " + currentStockLevel;
outLine += " Current Stock changed from " + currentStockLevel;
currentStockLevel += currentStock;
outLine += " to " + currentStockLevel;
int storeCost = wholeSalePrice * currentStockLevel;
System.out.println (productCode + ":" + " Received " + currentStockLevel + "." + " Store Cost " + "$" + storeCost + "." + " New stock level: " + currentStockLevel);
}
I'm having a problem! I'm making an app with multiple panels. I'm using Card Layout and I don't have this problem with changing to the other panels. I have a JButton (in a panel called optionsPanel) that should first change to the panel "panelCargando" (which has two JLabel, one with text and the other with a squared animated GIF (72x72)) and then looks after some info using Twitter4J that is showed in another JPanel called tweetsPanel. The problem is that when I press the button, it doesn't hide the other panels and make "panelCargando" visible, it keeps the options panel in the front and when it finishes looking for the info, it puts both panels together. Here's the code that I'm using in the ActionListener of the JButton:
btnNewButton_2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
mainPanel.setVisible(false);
optionsPanel.setVisible(false);
tweetsPanel.setVisible(false);
panelCargando.setVisible(true);
long lCursor = -1;
IDs friendsIDs;
try
{
friendsIDs = twitter.getFriendsIDs(twitter.getId(), lCursor);
System.out.println(twitter.showUser(twitter.getId()).getName());
do
{
for (long i : friendsIDs.getIDs())
{
if(textArea.getText().isEmpty())
{
textArea.setText(textArea.getText() + "ID de usuario: " + i +
"\nNombre de usuario: #" + twitter.showUser(i).getScreenName() +
"\nNombre: " + twitter.showUser(i).getName() +
"\nDescripción: " + twitter.showUser(i).getDescription() +
"\nImagen de perfil: " + twitter.showUser(i).getProfileImageURLHttps() +
"\nSigue a " + twitter.showUser(i).getFriendsCount() + " usuarios" +
"\nTiene " + twitter.showUser(i).getFollowersCount() + " seguidores\n");
}
else
{
textArea.setText(textArea.getText() + "\nID de usuario: " + i +
"\nNombre de usuario: #" + twitter.showUser(i).getScreenName() +
"\nNombre: " + twitter.showUser(i).getName() +
"\nDescripción: " + twitter.showUser(i).getDescription() +
"\nImagen de perfil: " + twitter.showUser(i).getProfileImageURLHttps() +
"\nSigue a " + twitter.showUser(i).getFriendsCount() + " usuarios" +
"\nTiene " + twitter.showUser(i).getFollowersCount() + " seguidores\n");
}
}
}
while(friendsIDs.hasNext());
frame.setTitle("Información sobre seguidores de " + twitter.showUser(twitter.getId()).getName() + " - BISmart");
panelCargando.setVisible(false);
tweetsPanel.setVisible(true);
tweetsPanel.setFocusable(true);
tweetsPanel.requestFocusInWindow();
So, finally I see the "tweetsPanel" panel with the textArea and the "panelCargando" in the front. In that code that I put here, I changed it and added "panelCargando.setVisible(false)", but this way I can't see it at all.
Can anyone help me with this? If it's not clear please let me know! Thank you all!
EDIT
Now the code is this one, but I keep having problems with the same. Even if I do "layout.show(frame.getContentPane(), "panelCargando")", the panel doesn't show. I added this:
layout = new CardLayout(0,0);
frame.getContentPane().setLayout(layout);
frame.getContentPane().add(splashPanel, "splashPanel");
frame.getContentPane().add(newTweetPanel, "newTweetPanel");
frame.getContentPane().add(mainPanel, "mainPanel");
frame.getContentPane().add(tweetsPanel, "tweetsPanel");
frame.getContentPane().add(optionsPanel,"optionsPanel");
frame.getContentPane().add(panelCargando, "panelCargando");
And the actionPerformed looks like this:
public void actionPerformed(ActionEvent arg0)
{
layout.show(frame.getContentPane(), "panelCargando");
long lCursor = -1;
IDs friendsIDs;
try
{
friendsIDs = twitter.getFriendsIDs(twitter.getId(), lCursor);
System.out.println(twitter.showUser(twitter.getId()).getName());
do
{
for (long i : friendsIDs.getIDs())
{
if(textArea.getText().isEmpty())
{
textArea.setText(textArea.getText() + "ID de usuario: " + i +
"\nNombre de usuario: #" + twitter.showUser(i).getScreenName() +
"\nNombre: " + twitter.showUser(i).getName() +
"\nDescripción: " + twitter.showUser(i).getDescription() +
"\nImagen de perfil: " + twitter.showUser(i).getProfileImageURLHttps() +
"\nSigue a " + twitter.showUser(i).getFriendsCount() + " usuarios" +
"\nTiene " + twitter.showUser(i).getFollowersCount() + " seguidores\n");
}
else
{
textArea.setText(textArea.getText() + "\nID de usuario: " + i +
"\nNombre de usuario: #" + twitter.showUser(i).getScreenName() +
"\nNombre: " + twitter.showUser(i).getName() +
"\nDescripción: " + twitter.showUser(i).getDescription() +
"\nImagen de perfil: " + twitter.showUser(i).getProfileImageURLHttps() +
"\nSigue a " + twitter.showUser(i).getFriendsCount() + " usuarios" +
"\nTiene " + twitter.showUser(i).getFollowersCount() + " seguidores\n");
}
}
}
while(friendsIDs.hasNext());
frame.setTitle("Información sobre seguidores de " + twitter.showUser(twitter.getId()).getName() + " - BISmart");
layout.show(frame.getContentPane(), "tweetsPanel");
}
I am not sure what I am doing wrong to get my frame to change when I have the user input data and press enter to adjust the string that was set to display on the frame. I am just going to include the code that I feel is applicable since the whole code is pretty long, but if someone would like to see more of something, let me know and I can post more. Thank you for the help!
//adds the Flower data to the Array and list
ActionListener flowerAddAction = new ActionListener(){
#Override
public void actionPerformed(ActionEvent flowerAddAction){
if(flowerAddAction.getActionCommand().equals("Enter")){
Name = NameTxt2.getText();
Colors = ColorTxt2.getText();
Smell = SmellTxt.getText();
ID = (int) IDCmbo.getSelectedItem();
if(((String) ThornCmbo.getSelectedItem()).equals("Yes"))
Thorns = true;
else
Thorns = false;
plants[count] = new Flower(Name, ID, Colors, Smell, Thorns);
displayEntered.setText(displayArray);
count++;
frame.repaint();
frameB.setVisible(false);
}
}
};
enterFlrData.addActionListener(flowerAddAction);
this code above is to add the action to when the user presses enter after inputting data into the textFields and ComboBoxes. Below creates a long string of an array that is created by the input. (If anyone has a better way of displaying an array on a JLabel I'd love to know because I know this is a little sloppy.
//create a string of all values for the array
displayArray = " ";
String displayArraytemp = " ";
for(int n = 0; n < 25; n++){
if(plants[n] != null){
if(plants[n] instanceof Flower){
displayArraytemp = (n + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Flower)plants[n]).getColor() + ", " + ((Flower)plants[n]).getSmell() + ", Thorny: " + ((Flower)plants[n]).getThorns() + "/n");
}
else if(plants[n] instanceof Fungus){
displayArraytemp = (n + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Fungus)plants[n]).getColor() + ", Poisonous: " + ((Fungus)plants[n]).getPoisonous() + "/n");
}
else if(plants[n] instanceof Weed){
displayArraytemp = (n + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Weed)plants[n]).getColor() + ", Edible: " + ((Weed)plants[n]).getEdible() + ", Medicinal: " + ((Weed)plants[n]).getMedicinal() + ", Poisonous: " + ((Weed)plants[n]).getPoisonous() + "/n");
}
else if(plants[n] instanceof Herb){
displayArraytemp = (n + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Herb)plants[n]).getColor() + ", " + ((Herb)plants[n]).getFlavor() + ", Medicinal: " + ((Herb)plants[n]).getMedicinal() + ", Poisonous: " + ((Herb)plants[n]).getSeasonal() + "/n");
}
displayArray += (displayArraytemp + "/n");
}
}
Below is showing the rest creating the label and includes the main method.
final JPanel p2Base = new JPanel();
displayEntered = new JLabel(displayArray);
//entire constant GUI put together
p2Base.setLayout(new BorderLayout(10,10));
p2Base.add(menuBar, BorderLayout.NORTH);
p2Base.add(p1Right, BorderLayout.EAST);
p2Base.add(displayEntered, BorderLayout.WEST);
public static void main(String[] args) {
frame = new GUI();
frame.setTitle("Plant Database");
frame.setSize(900,700);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
This looks suspicious to me:
flowerAddAction.getActionCommand().equals("Enter")
If you want this ActionListener respond to pressing the enter button then this will fail since the actionCommand String will not be "Enter". I'm not even sure what it will be, and don't really care, since I usually use ActionListener's for each component and so usually don't test the actionCommand String.
As for your messy array code, consider instead giving your flowers a decent toString() method or method of a similar idea that returns a useful String that can be displayed. That way you can get rid of all of those instanceof operations and have much simpler smaller code.
Edit
I should just shut up and read the API. The action command of a JTextField is the text it contains, unless you set it explicitly.
import java.awt.event.*;
import javax.swing.*;
public class EnterActionCommand {
public static void main(String[] args) {
JTextField field1 = new JTextField(10);
JTextField field2 = new JTextField(10);
// **** set the action command explicitly for field2 ****
field2.setActionCommand("Field 2");
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.printf("action command: \"%s\"%n", e.getActionCommand());
}
};
field1.addActionListener(actionListener);
field2.addActionListener(actionListener);
JPanel panel = new JPanel();
panel.add(new JLabel("Field 1:"));
panel.add(field1);
panel.add(new JLabel("Field 2:"));
panel.add(field2);
JOptionPane.showMessageDialog(null, panel);
}
}