User Interface in java - java

I am trying to design a UI for tic tac toe in java but I don't understand why is their a 5th row in the UI.I want to have four rows where bottom three rows would serve as buttons for Board of tictactoe and top row would be used as display toshow important messages to the users . I have attached the code and a snapshot of the UI.
//code
package TicTacToe;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TicTacToeUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
JPanel[] row = new JPanel[4];
JButton[] button = new JButton[9];
String[] buttonString = {" "," "," ",
" "," "," ",
" "," "," "};
Dimension displayDimension = new Dimension(290, 45);
Dimension regularDimension = new Dimension(90, 90);
JTextArea display = new JTextArea(2, 20);
Font font = new Font("Times new Roman", Font.BOLD, 14);
public TicTacToeUI(){
super("TicTacToe");
setDesign();
setSize(350, 500);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(5,5);
setLayout(grid);
FlowLayout f1 = new FlowLayout(FlowLayout.CENTER);
FlowLayout f2 = new FlowLayout(FlowLayout.CENTER,1,1);//gap in cells
for(int i = 0; i < 4; i++ )
row[i] = new JPanel();
row[0].setLayout(f1);
for(int i = 1; i < 4; i++)
row[i].setLayout(f2);
for(int i = 0; i < 9; i++) {
button[i] = new JButton();
button[i].setText(buttonString[i]);
button[i].setBackground(Color.black);
button[i].setFont(font);
button[i].addActionListener(this);
}
display.setFont(font);
display.setEditable(false);
display.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
display.setPreferredSize(displayDimension);
for(int i = 0; i < 9; i++)
button[i].setPreferredSize(regularDimension);
row[0].add(display);
add(row[0]);
for(int i=1,k=0;i<4&&k<9;i++){
for(int j=0;j<3;j++){
row[i].add(button[k]);
k++;
}
add(row[i]);
}
setVisible(true);
}
public final void setDesign() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e) {
}
}
public static void main(String[] args) {
TicTacToeUI obj = new TicTacToeUI();
}
#Override
public void actionPerformed(ActionEvent ae) {
// TODO Auto-generated method stub
int x,y;
if(ae.getSource()==button[0]){
x=0;
y=0;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[1]){
x=0;
y=1;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[2]){
x=0;
y=2;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[3]){
x=1;
y=0;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[4]){
x=1;
y=1;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[5]){
x=1;
y=2;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[6]){
x=2;
y=0;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[7]){
x=2;
y=1;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[8]){
x=2;
y=2;
display.setText("x = " + x + "y = " + y);
}
}
}

Well, I'm not sure if I understand your question, because the problem you have is in this line:
GridLayout grid = new GridLayout(5,5);
I you want to have 4 rows then just change it to:
GridLayout grid = new GridLayout(4,5);
Hope it helps.

Related

Why I can't get medium level for math questions to appear?

import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import javax.swing.border.*;
import java.awt.event.*;
public class MATHfighter extends JFrame implements ActionListener
{
Border border = new LineBorder(Color.WHITE, 3, true);
Border unborder = new LineBorder(Color.BLACK, 1, true);
Container c = getContentPane();
JPanel gameText = new JPanel();
JPanel gameMenu = new JPanel();
JTextField answer = new JTextField(12);
JTextField result = new JTextField(12);
JButton bAnswer = new JButton("Answer");
JButton bNext = new JButton("Next");
JButton bExit = new JButton("Exit");
int score = 0;
JLabel mathQuestion = new JLabel();
JLabel startText = new JLabel(">");
JLabel startText1 = new JLabel(">");
Font headlineFont = new Font("Comic Sans MS",Font.BOLD, 15);
int typeQ;
int number1;
int number2;
int number3;
int life_point = 200;
int player_lp = 200;
int r = 0;
int g = 204;
int b = 0;
int r1 = 0;
int g1 = 204;
int b1 = 0;
public MATHfighter()
{
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c.setBackground(Color.BLACK);
textGame();
menuGame();
bAnswer.addActionListener(this);
bNext.addActionListener(this);
bExit.addActionListener(this);
}
public void textGame()
{
gameText.setLayout(null);
gameText.setBorder(border);
gameText.setBounds(10,410,290,140);
gameText.setVisible(true);
gameText.setBackground(Color.BLACK);
gameText.add(startText);
gameText.add(startText1);
startText.setForeground(Color.WHITE);
startText1.setForeground(Color.WHITE);
startText.setFont(headlineFont);
startText1.setFont(headlineFont);
add(gameText);
randomMath();
}
public void menuGame()
{
gameMenu.setLayout(null);
gameMenu.setBorder(border);
gameMenu.setBounds(305,410,290,140);
gameMenu.setVisible(true);
gameMenu.setBackground(Color.BLACK);
add(gameMenu);
gameMenu.add(bAnswer);
bAnswer.setBorder(border);
bAnswer.setBackground(Color.BLACK);
bAnswer.setFont(headlineFont);
bAnswer.setForeground(Color.WHITE);
bAnswer.setBounds(10,10,130,50);
gameMenu.add(bNext);
bNext.setBorder(border);
bNext.setBackground(Color.BLACK);
bNext.setFont(headlineFont);
bNext.setForeground(Color.WHITE);
bNext.setBounds(150,10,130,50);
bNext.setEnabled(false);
gameMenu.add(bExit);
bExit.setBorder(border);
bExit.setBackground(Color.BLACK);
bExit.setFont(headlineFont);
bExit.setForeground(Color.WHITE);
bExit.setBounds(150,70,130,50);
}
public void randomMath()
{
typeQ = (int) (Math.random() * 4) + 1;
number1 = (int) (Math.random() * 10) + 10;
number2 = (int) (Math.random() * 10) + 10;
number3 = (int) (Math.random() * 10) + 10;
mathQuestion.setFont(headlineFont);
mathQuestion.setBounds(10,10,290,15);
mathQuestion.setForeground(Color.WHITE);
gameText.add(mathQuestion);
answer.setFont(headlineFont);
answer.setBorder(unborder);
answer.setBackground(Color.BLACK);
answer.setForeground(Color.WHITE);
startText.setBounds(10,35,20,20);
answer.setBounds(25,35,250,20);
gameText.add(answer);
result.setFont(headlineFont);
result.setBorder(unborder);
result.setBackground(Color.BLACK);
result.setForeground(Color.WHITE);
result.setBounds(25,65,250,20);
result.setEditable(false);
startText1.setBounds(10,65,20,20);
gameText.add(result);
if((life_point<=200)&&(life_point>100))
{
if(typeQ==1)
{
mathQuestion.setText("> What is " + number1 + " + " + number2 + " ?");
}
else if(typeQ==2)
{
mathQuestion.setText("> What is " + number1 + " - " + number2 + " ?");
}
else if(typeQ==3)
{
mathQuestion.setText("> What is " + number1 + " * " + number2 + " ?");
}
else if(typeQ==4)
{
mathQuestion.setText("> What is " + number1*number2 + " / " + number2 + " ?");
}
}
else if(life_point<=100)
{
if(typeQ==1)
{
mathQuestion.setText("> What is " + number1 + " * " + number2 + " + " + number3 + " ?");
}
else if(typeQ==2)
{
mathQuestion.setText("> What is " + number1 + " * " + number2 + " - " + number3 + " ?");
}
else if(typeQ==3)
{
mathQuestion.setText("> What is " + number1*number2 + " / " + number2 + " + " + number3 + " ?");
}
else if(typeQ==4)
{
mathQuestion.setText("> What is " + number1*number2 + " / " + number2 + " - " + number3 + " ?");
}
}
}
public void paint(Graphics gr)
{
Color c1 = new Color(r, g, b);
Color c2 = new Color(r1, g1, b1);
super.paint(gr);
gr.setColor(c1);
gr.fillRect(212, 40, life_point, 30);
gr.setColor(c2);
gr.fillRect(212, 400, player_lp, 30);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==bAnswer)
{
try
{
int kotae = Integer.parseInt(answer.getText());
if((life_point<=200)&&(life_point>100))
{
if(typeQ==1)
{
if ((number1 + number2) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1 + number2) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==2)
{
if ((number1 - number2) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1 - number2) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==3)
{
if ((number1 * number2) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1 * number2) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==4)
{
if ((number1*number2 / number2) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1*number2 / number2) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
}
if(life_point<=100)
{
if(typeQ==1)
{
if ((number1 * number2 + number3) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
//bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1 * number2 + number3) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==2)
{
if ((number1 * number2 - number3) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
//bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1 * number2 - number3) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==3)
{
if ((number1*number2 / number2 + number3) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
//bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1*number2 / number2 + number3) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==4)
{
if ((number1*number2 / number2 - number3) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
//bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1*number2 / number2 - number3) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"<html><font face='Comic Sans MS' size='3'>INTEGER ONLY, KIDDO");
}
}
else if(e.getSource()==bNext)
{
typeQ = (int) (Math.random() * 4) + 1;
number1 = (int) (Math.random() * 10) + 10;
number2 = (int) (Math.random() * 10) + 10;
result.setText("");
answer.setText("");
answer.setEditable(true);
bNext.setEnabled(false);
bAnswer.setEnabled(true);
if(typeQ==1)
{
mathQuestion.setText("> What is " + number1 + " + " + number2 + " ?");
}
else if(typeQ==2)
{
mathQuestion.setText("> What is " + number1 + " - " + number2 + " ?");
}
else if(typeQ==3)
{
mathQuestion.setText("> What is " + number1 + " * " + number2 + " ?");
}
else if(typeQ==4)
{
mathQuestion.setText("> What is " + number1*number2 + " / " + number2 + " ?");
}
}
else
{
System.exit(0);
}
}
public static void main(String[] args)
{
MATHfighter fight = new MATHfighter();
fight.setSize(625,600);
fight.setVisible(true);
}
}
This is the continuation from my last question and I did change while loop to if-else, thank you to others who helped me.
My new problems are that I want a bunch of middle level questions to appear when enemy life point become 100 and below but the problem is my GUI became like this after I answered the fifth question:
there is a chance that my mathQuestion.setText are not working after I used these code:
else if(life_point<=100)
{
if(typeQ==1)
{
mathQuestion.setText("> What is " + number1 + " * " + number2 + " + " + number3 + " ?");
}
else if(typeQ==2)
{
mathQuestion.setText("> What is " + number1 + " * " + number2 + " - " + number3 + " ?");
}
else if(typeQ==3)
{
mathQuestion.setText("> What is " + number1*number2 + " / " + number2 + " + " + number3 + " ?");
}
else if(typeQ==4)
{
mathQuestion.setText("> What is " + number1*number2 + " / " + number2 + " - " + number3 + " ?");
}
}
and
if(life_point<=100)
{
if(typeQ==1)
{
if ((number1 * number2 + number3) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
//bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1 * number2 + number3) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==2)
{
if ((number1 * number2 - number3) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
//bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1 * number2 - number3) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==3)
{
if ((number1*number2 / number2 + number3) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
//bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1*number2 / number2 + number3) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
else if(typeQ==4)
{
if ((number1*number2 / number2 - number3) != kotae)
{
result.setText("" + String.format("%s","Incorrect"));
//bNext.setEnabled(false);
player_lp = player_lp - 20;
if(player_lp == 100)
{
r1=204;
}
else if(player_lp == 40)
{
g1=0;
}
repaint();
}
else if ((number1*number2 / number2 - number3) == kotae)
{
result.setText("" + String.format("%s","Correct"));
answer.setEditable(false);
bNext.setEnabled(true);
bAnswer.setEnabled(false);
life_point = life_point - 20;
if(life_point == 100)
{
r=204;
}
else if(life_point == 40)
{
g=0;
}
repaint();
}
}
I really hope that someone can help me about these problem
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the Laying Out Components Within a Container and the Performing Custom Painting sections.
The code provided in the question is typical of beginner Java programmers. All of the code is contained in one class. Almost all of the variables are class variables. Some of the variables are poorly named. Code is copied over and over with minor changes.
Swing layout managers are not used. Null layouts and absolute positioning are used instead. The makes for a brittle GUI that's hard to maintain and understand. I wonder how much effort it took to calculate all of the Swing component offsets?
So, let's see what we can do to improve this code. Here's the GUI I came up with.
Explanation
Breaking up the code into an application model, a view, and multiple ActionListeners helps me to separate my concerns and focus on one part of the application at a time.
Model
The first thing I did was create an application model class, the MathFighterModel class
The MathFighterModel class is a plain Java getter/setter class. It turned out that the class only needed three class variables; the answer to the current math problem, the number of enemy life points, and the number of player life points.
The creation of a math equation is contained in the generateRandomMathQuestion method. I calculate the correct answer and build the question String in the same method. This way, it's much easier to visually verify that the actual calculation matches the question String.
By the way, the code is doing integer division when it divides.
The rest of the class is getters and setters. The original code didn't include a check for either the enemy or player getting to zero life points. I didn't include the check either.
View
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
I used a JFrame. I did not extend a JFrame. The only reason you extend a Swing component, or any Java class, is to override one or more of the class methods. The JFrame has a default BorderLayout, which I used to place two JPanels.
I created four JPanels; a drawing JPanel for the health bars, a control JPanel, an entry JPanel, and a button JPanel. This allows me to separate my concerns and focus on one small part of the GUI at a time.
I create the drawing JPanel in a separate class. I extend JPanel because I override the paintComponent method. I call the super.paintComponent in the first line of the method to maintain the Swing paint chain.
I calculate the bar colors in the drawing JPanel. I also centered the bar drawings in the drawing JPanel. Finally, I added the life points number to the center of the bars.
The control JPanel is a container that holds the entry JPanel and the button JPanel. I used a FlowLayout to put the two JPanels side by side.
The entry JPanel contains the entry and display Swing components. I used a GridBagLayout to layout the ">" and the display and entry Swing components. Yes, the GridBagLayout looks complicated, but it's the easiest way to create a form with labels in one column and the entry fields in another column.
The button JPanel contains the JButtons. I used a GridLayout to arrange the JButtons. Yes, I had to put a dummy JLabel in column 1, row 2 to make the layout work.
Using Swing layout managers makes the GUI more flexible and allows for the easier addition of Swing components. Just maximize the GUI to see what happens.
Controller
I created three ActionListeners for the three JButtons. It's much easier to manage separate ActionListeners than one complicated ActionListener.
I used lambda expressions for the next button and exit button because they were simple ActionListeners. A lambda expression creates an anonymous ActionListener class under the covers.
I left the answer button ActionListener as an internal method to the view class. You can see how simple the method is, after creating an application model and view.
Code
Here's the complete runnable code. I made all the additional classes inner classes so I could post the code as one block. You should separate these classes into separate files.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
public class MathFighter implements ActionListener, Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new MathFighter());
}
private final DrawingPanel drawingPanel;
private JFrame frame;
private JLabel mathQuestionLabel, responseLabel;
private JTextField answerField;
private final MathFighterModel model;
public MathFighter() {
this.model = new MathFighterModel();
this.drawingPanel = new DrawingPanel(model);
}
#Override
public void run() {
frame = new JFrame("Math Fighter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(drawingPanel, BorderLayout.CENTER);
frame.add(createControlPanel(), BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createControlPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBackground(Color.BLACK);
panel.add(createEntryPanel());
panel.add(createButtonPanel());
return panel;
}
private JPanel createEntryPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBackground(Color.BLACK);
panel.setPreferredSize(new Dimension(300, 150));
Border outsideBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
Border insideBorder = BorderFactory.createLineBorder(Color.WHITE, 3);
panel.setBorder(BorderFactory.createCompoundBorder(outsideBorder,
insideBorder));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 1;
gbc.insets = new Insets(10, 10, 10, 0);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.0;
panel.add(createLabel(">"), gbc);
gbc.gridx++;
gbc.weightx = 1.0;
mathQuestionLabel = createLabel(" ");
panel.add(mathQuestionLabel, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.weightx = 0.0;
panel.add(createLabel(">"), gbc);
gbc.gridx++;
gbc.weightx = 1.0;
answerField = new JTextField(12);
answerField.setFont(getHeadlineFont());
answerField.setBorder(BorderFactory.createEmptyBorder(0, -8, 0, 0));
answerField.setBackground(Color.BLACK);
answerField.setForeground(Color.WHITE);
panel.add(answerField, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.weightx = 0.0;
panel.add(createLabel(">"), gbc);
gbc.gridx++;
gbc.weightx = 1.0;
responseLabel = createLabel(" ");
panel.add(responseLabel, gbc);
updateEntryPanel();
return panel;
}
private JLabel createLabel(String labelText) {
JLabel label = new JLabel(labelText);
label.setBackground(Color.BLACK);
label.setForeground(Color.WHITE);
label.setFont(getHeadlineFont());
return label;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new GridLayout(0, 2, 10, 10));
panel.setBackground(Color.BLACK);
panel.setPreferredSize(new Dimension(300, 150));
Border outsideBorder = BorderFactory.createEmptyBorder(5, 0, 5, 5);
Border insideBorder = BorderFactory.createLineBorder(Color.WHITE, 3);
Border marginBorder = BorderFactory.createEmptyBorder(10, 10, 10, 10);
Border compoundBorder = BorderFactory.createCompoundBorder(insideBorder,
marginBorder);
panel.setBorder(BorderFactory.createCompoundBorder(outsideBorder,
compoundBorder));
JButton answerButton = createButton("Answer", insideBorder);
answerButton.addActionListener(this);
panel.add(answerButton);
JButton nextButton = createButton("Next", insideBorder);
nextButton.addActionListener(event -> {
updateEntryPanel();
});
panel.add(nextButton);
panel.add(new JLabel(" "));
JButton exitButton = createButton("Exit", insideBorder);
exitButton.addActionListener(event -> {
frame.dispose();
System.exit(0);
});
panel.add(exitButton);
return panel;
}
private JButton createButton(String buttonText, Border insideBorder) {
JButton button = new JButton(buttonText);
button.setBorder(insideBorder);
button.setBackground(Color.BLACK);
button.setFont(getHeadlineFont());
button.setForeground(Color.WHITE);
return button;
}
private Font getHeadlineFont() {
return new Font("Comic Sans MS", Font.BOLD, 16);
}
public void updateEntryPanel() {
mathQuestionLabel.setText(model.generateRandomMathQuestion());
answerField.setText(" ");
answerField.requestFocusInWindow();
responseLabel.setText(" ");
}
public void repaint() {
drawingPanel.repaint();
}
#Override
public void actionPerformed(ActionEvent event) {
try {
int userAnswer = Integer.valueOf(answerField.getText().trim());
if (model.isAnswerCorrect(userAnswer)) {
responseLabel.setText("Correct");
model.incrementPlayerLife(20);
} else {
responseLabel.setText("Incorrect, try another answer");
model.incrementPlayerLife(-20);
}
answerField.requestFocusInWindow();
repaint();
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(frame,
"<html><font face='Comic Sans MS' size='3'>INTEGER ONLY, KIDDO");
}
}
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = 1L;
private final MathFighterModel model;
public DrawingPanel(MathFighterModel model) {
this.model = model;
this.setBackground(Color.BLACK);
this.setPreferredSize(new Dimension(400, 300));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setFont(getHeadlineFont());
int width = getWidth();
int height = getHeight();
int margin = 20;
int barHeight = 30;
int enemyLifePoints = model.getEnemyLifePoints();
g2d.setColor(calculateBarColor(enemyLifePoints));
int x = (width - enemyLifePoints) / 2;
int y = margin;
g2d.fillRect(x, y, enemyLifePoints, barHeight);
drawString(g2d, x, y, enemyLifePoints, barHeight);
int playerLifePoints = model.getPlayerLifePoints();
g2d.setColor(calculateBarColor(playerLifePoints));
x = (width - playerLifePoints) / 2;
y = height - margin - barHeight;
g2d.fillRect(x, y, playerLifePoints, barHeight);
drawString(g2d, x, y, playerLifePoints, barHeight);
}
private void drawString(Graphics2D g2d, int x, int y, int width,
int height) {
String lifePointString = Integer.toString(width);
FontMetrics fm = g2d.getFontMetrics();
Rectangle2D r = fm.getStringBounds(lifePointString, g2d);
int a = (width - (int) r.getWidth()) / 2 + x;
int b = (height - (int) r.getHeight()) / 2 + fm.getAscent() + y;
g2d.setColor(Color.BLACK);
g2d.drawString(lifePointString, a, b);
}
private Color calculateBarColor(int lifePoints) {
int red = 0;
int green = 204;
int blue = 0;
if (lifePoints <= 100) {
red = 204;
if (lifePoints <= 40) {
green = 0;
}
}
return new Color(red, green, blue);
}
private Font getHeadlineFont() {
return new Font("Comic Sans MS", Font.BOLD, 16);
}
}
public class MathFighterModel {
private int answer, enemyLifePoints, playerLifePoints;
public MathFighterModel() {
this.enemyLifePoints = 200;
this.playerLifePoints = 200;
}
public String generateRandomMathQuestion() {
String questionString = "";
int questionType = (int) (Math.random() * 4) + 1;
int number1 = (int) (Math.random() * 10) + 10;
int number2 = (int) (Math.random() * 10) + 10;
int number3 = (int) (Math.random() * 10) + 10;
if (playerLifePoints > 100) {
if (questionType == 1) {
this.answer = number1 + number2;
questionString = "What is " + number1 + " + " + number2
+ " ?";
} else if (questionType == 2) {
this.answer = number1 - number2;
questionString = "What is " + number1 + " - " + number2
+ " ?";
} else if (questionType == 3) {
this.answer = number1 * number2;
questionString = "What is " + number1 + " X " + number2
+ " ?";
} else if (questionType == 4) {
this.answer = number1 * number2 / number3;
questionString = "What is " + number1 + " X " + number2
+ " / " + number3 + " ?";
}
} else {
if (questionType == 1) {
this.answer = number1 * number2 + number3;
questionString = "What is " + number1 + " X " + number2
+ " + " + number3 + " ?";
} else if (questionType == 2) {
this.answer = number1 * number2 - number3;
questionString = "What is " + number1 + " X " + number2
+ " + " + number3 + " ?";
} else if (questionType == 3) {
this.answer = (number1 * number2) / (number2 + number3);
questionString = "What is (" + number1 + " x " + number2
+ ") / (" + number2 + " + " + number3 + ") ?";
} else if (questionType == 4) {
this.answer = (number1 * number2) / (number2 - number3);
questionString = "What is (" + number1 + " x " + number2
+ ") / (" + number2 + " - " + number3 + ") ?";
}
}
return questionString;
}
public void incrementPlayerLife(int increment) {
this.playerLifePoints += increment;
this.enemyLifePoints -= increment;
}
public boolean isAnswerCorrect(int userAnswer) {
return userAnswer == answer;
}
public int getEnemyLifePoints() {
return enemyLifePoints;
}
public int getPlayerLifePoints() {
return playerLifePoints;
}
}
}

Nullpointerexception and NumberFormatException java GUI [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to make a GUI of a calculator which solves Parallel and Perpendicular Equations. It works when the GUI is not implemented but when I implement the GUI there are errors coming out such as nullpointerexception and numberformatexception. please do help me in resolving this.
import java.awt.*;
public class SuntayProjGUI {
JFrame frame;
private JTextField Ax;
private JTextField By;
private JTextField C;
private JTextField slopeLine;
private JTextField yintLine;
BigDecimal xCoefficient, yCoefficient, b, slope1, slope2, yIntercept1, yIntercept2, xCoord, yCoord; // declaration. Obvious naman na 'to
/**
* Launch the application.
* #param args
* #wbp.parser.entryPoint
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SuntayProjGUI window = new SuntayProjGUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* #wbp.parser.entryPoint
*/
public SuntayProjGUI(){
initialize();
}
public void initialize(){
frame = new JFrame();
frame.getContentPane().setBackground(Color.PINK);
frame.getContentPane().setLayout(null);
Ax = new JTextField();
Ax.setBounds(46, 142, 116, 22);
frame.getContentPane().add(Ax);
Ax.setColumns(10);
By = new JTextField();
By.setBounds(46, 191, 116, 22);
frame.getContentPane().add(By);
By.setColumns(10);
C = new JTextField();
C.setBounds(46, 191, 116, 22);
frame.getContentPane().add(C);
C.setColumns(10);
JLabel lblPleaseChooseWhat = new JLabel("Please choose what inputs this calculator will receive");
lblPleaseChooseWhat.setBounds(12, 44, 302, 16);
frame.getContentPane().add(lblPleaseChooseWhat);
JComboBox comboBox = new JComboBox();
comboBox.setBounds(22, 76, 147, 22);
comboBox.addItem("Line with Y-intercept");
comboBox.addItem("Line with Point");
frame.getContentPane().add(comboBox);
//Computations
xCoefficient = new BigDecimal(Ax.getText());
yCoefficient = new BigDecimal(By.getText());
b = new BigDecimal(C.getText());
slope1 = getSlope(xCoefficient, yCoefficient);
yIntercept1 = getYIntercept(yCoefficient, b);
JLabel lblA = new JLabel("A :");
lblA.setBounds(12, 148, 36, 16);
frame.getContentPane().add(lblA);
JLabel lblB = new JLabel("B:");
lblB.setBounds(12, 194, 56, 16);
frame.getContentPane().add(lblB);
JLabel lblC = new JLabel("C:");
lblC.setBounds(12, 240, 56, 16);
frame.getContentPane().add(lblC);
C = new JTextField();
C.setBounds(46, 237, 116, 22);
frame.getContentPane().add(C);
C.setColumns(10);
JLabel lblLineAx = new JLabel("Line: Ax + By = C");
lblLineAx.setBounds(12, 111, 137, 16);
frame.getContentPane().add(lblLineAx);
JButton btnEnter = new JButton("Enter");
btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
if(comboBox.equals("Line with Y-intercept")){
Line_with_yint lwy = new Line_with_yint();
lwy.frame.setVisible(true);
}
else if(comboBox.equals("Line with Point")){
Line_with_point lwp = new Line_with_point();
lwp.frame.setVisible(true);
}
}
});
btnEnter.setBounds(217, 383, 97, 25);
frame.getContentPane().add(btnEnter);
JLabel lblSlopeOfThe = new JLabel("Slope of the Line: ");
lblSlopeOfThe.setBounds(12, 291, 114, 16);
frame.getContentPane().add(lblSlopeOfThe);
slopeLine = new JTextField();
slopeLine.setEnabled(false);
slopeLine.setEditable(false);
slopeLine.setBounds(151, 288, 116, 22);
frame.getContentPane().add(slopeLine);
slopeLine.setColumns(10);
slopeLine.setText(slope1.toString());
JLabel lblYinterceptOfThe = new JLabel("Y-Intercept of the Line:");
lblYinterceptOfThe.setBounds(12, 332, 137, 16);
frame.getContentPane().add(lblYinterceptOfThe);
yintLine = new JTextField();
yintLine.setEnabled(false);
yintLine.setEditable(false);
yintLine.setBounds(151, 329, 116, 22);
frame.getContentPane().add(yintLine);
yintLine.setColumns(10);
yintLine.setText(yIntercept1.toString());
JButton btnCalculate = new JButton("Calculate");
btnCalculate.setBounds(217, 236, 97, 25);
frame.getContentPane().add(btnCalculate);
}
public static BigDecimal getSlope(BigDecimal x, BigDecimal y)
{
y = y.multiply(new BigDecimal(-1)); // yung pagmultiply sa -1 yung pagtranspose ng Ax + By = C -> By = -Ax + C
y = x.divide(y, 4, RoundingMode.CEILING); // eto yung pagdivide nung coefficient ni y sa both sides ng equation -> y = -Ax/B + C/B
return y;
}
public static BigDecimal getReciprocalSlope(BigDecimal x, BigDecimal y)
{
y = y.divide(x, 4, RoundingMode.CEILING).multiply(new BigDecimal(-1)); // eto yung reciprocal. obviously. balaiktarin lang. kung kanina
return y;
}
public static BigDecimal getYIntercept(BigDecimal y, BigDecimal b)
{
b = b.divide(y, 4, RoundingMode.CEILING); // yung pagkuha ng y-intercept similar dun sa getSlope pero ang difference since walang transposition, divide lang.
return b;
}
public static void getGEandSE(BigDecimal slope, BigDecimal xCoord, BigDecimal yCoord, BigDecimal yIntercept, BigDecimal x, BigDecimal y)
{
BigDecimal parallelA, parallelB, parallelC, perpendicularA, perpendicularB, perpendicularC;
if (x.compareTo(BigDecimal.ZERO) < 0) // itong part na 'to, kapag yung divisor (kasi diba either si y or x yung divisor, kapag slope na normal, si y, kapag nirereciprocate for perpendicular, si x diba.) negative, gagawing positive since lagi namang positive kapag nagdidivide both sides diba
x = x.multiply(new BigDecimal(-1));
if (y.compareTo(BigDecimal.ZERO) < 0)
y = y.multiply(new BigDecimal(-1));
if (yIntercept == null)
{
yCoord = yCoord.multiply(new BigDecimal(-1));
xCoord = xCoord.multiply(new BigDecimal(-1));
parallelA = slope.multiply(y).multiply(new BigDecimal(-1)); // eto yung diba kapag points ang given, y - y1 = m(x - x1). Yung coefficient ni x kasi si parallelA tapos transpose kaya may -1 tapos para mawala yung fraction, mumultiply by y. Gets naman kung bakit diba? Dito nagaganap yung -mx + y - y1 = mx1
parallelC = (xCoord.multiply(slope).multiply(new BigDecimal(-1))).add(yCoord).multiply(y); // kapag si C naman, diba y - y1 = m(x - x1) dito nagaganap yung didistribute si M tsaka ttranspose sa kabila. From y -y1 = m(x - x1) -> y - y1 + mx1 = mx
perpendicularA = getReciprocalSlope(x, y).multiply(x).multiply(new BigDecimal(-1)); // same principle lang, difference lang neto yung imbis na slope yung mumultiply, yung reciprocal nya (yung function dun na reciprocalSlope)
perpendicularC = (xCoord.multiply(getReciprocalSlope(x, y).multiply(new BigDecimal(-1))).add(yCoord)).multiply(x);
if (parallelC.compareTo(BigDecimal.ZERO) > 0)
System.out.println("Parallel Line GE: " + parallelA + "x + " + y + "y + " + parallelC + " = 0");
else
System.out.println("Parallel Line GE: " + parallelA + "x + " + y + "y - " + parallelC.multiply(new BigDecimal(-1)) + " = 0");
System.out.println("Parallel Line SE: " + parallelA + "x + " + y + "y = " + parallelC);
if (perpendicularC.compareTo(BigDecimal.ZERO) > 0)
System.out.println("Perpendicular Line GE: " + perpendicularA + "x + " + x + "y + " + perpendicularC + " = 0");
else
System.out.println("Perpendicular Line GE: " + perpendicularA + "x + " + x + "y - " + perpendicularC.multiply(new BigDecimal(-1)) + " = 0");
System.out.println("Perpendicular Line SE: " + perpendicularA + "x + " + x + "y = " + perpendicularC.multiply(new BigDecimal(-1)));
}
else
{
parallelA = slope.multiply(new BigDecimal(-1)).multiply(y); // gets mo na siguro 'to. Kung ano nasa notes mo at yung pagkakahawig nya sa nasa taas ganun din
parallelC = yIntercept.multiply(new BigDecimal(-1)).multiply(y);
perpendicularA = getReciprocalSlope(x, y).multiply(new BigDecimal(-1)).multiply(x);
perpendicularC = yIntercept.multiply(new BigDecimal(-1)).multiply(x);
if (parallelC.compareTo(BigDecimal.ZERO) > 0)
System.out.println("Parallel Line GE: " + parallelA + "x + " + y + "y + " + parallelC + " = 0");
else
System.out.println("Parallel Line GE: " + parallelA + "x + " + y + "y - " + parallelC.multiply(new BigDecimal(-1)) + " = 0");
System.out.println("Parallel Line SE: " + parallelA + "x + " + y + "y = " + parallelC.multiply(new BigDecimal(-1)));
if (perpendicularC.compareTo(BigDecimal.ZERO) > 0)
System.out.println("Perpendicular Line GE: " + perpendicularA + "x + " + x + "y + " + perpendicularC + " = 0");
else
System.out.println("Perpendicular Line GE: " + perpendicularA + "x + " + x + "y - " + perpendicularC.multiply(new BigDecimal(-1)) + " = 0");
System.out.println("Perpendicular Line SE: " + perpendicularA + "x + " + x + "y = " + perpendicularC);
}
}
}
and when I try to run this, there are errors:
java.lang.NumberFormatException
at java.math.BigDecimal.<init>(BigDecimal.java:596)
at java.math.BigDecimal.<init>(BigDecimal.java:383)
at java.math.BigDecimal.<init>(BigDecimal.java:806)
at SuntayProjGUI.initialize(SuntayProjGUI.java:83)
at SuntayProjGUI.<init>(SuntayProjGUI.java:47)
at SuntayProjGUI$1.run(SuntayProjGUI.java:34)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
thank you for answering
You'r trying to get a text from a text box which should be empty after initializing.
Therefore you'r calling new BigDecimal("") which will throw an NumberFormatException.
The NullpointerException will probably get thrown because new BigDecimal failed to create an Object.
You need to do the computations after the fields got filled.
EDIT:
Also it looks like C hasn't been initialized at this point of code.
xCoefficient = new BigDecimal(Ax.getText());
yCoefficient = new BigDecimal(By.getText());
b = new BigDecimal(C.getText());
EDIT2: You could move everything which should only be done after entering values into a method and call this method via a button.
#Nordiii already explained the reason behind your problem. So, i am not repeating it.
The computation part of your code should be in actionPerformed method of your Calculate Button.
EDIT:
btnCalculate.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
xCoefficient = new BigDecimal(Ax.getText());
yCoefficient = new BigDecimal(By.getText());
b = new BigDecimal(C.getText());
slope1 = getSlope(xCoefficient, yCoefficient);
yIntercept1 = getYIntercept(yCoefficient, b);
slopeLine.setText(slope1.toString());
yintLine.setText(yIntercept1.toString());
}
});
Also set default frame size
frame.setBounds(100, 100, 468, 369);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Return value does not change - java

My parameter value doesn't seem to change after I pass it through, edit it and return it - It remains the same.
Can I have some help on where I am doing wrongly? I'm creating a simple gun class program. The problem occurs in my reload method. When I reload the bullets to the gun, the bulletsRemaining in the gun becomes the maximum capacity, but the ammo value doesn't decrease.
public class Gun {
String name;
String sound;
int minDamage;
int maxDamage;
int shotsPerSecond;
int capacity;
int bulletsRemaining;
public Gun(String name, String sound, int minDamage, int maxDamage, int shotsPerSecond, int capacity, int bulletsRemaining) {
this.name = name;
this.sound = sound;
this.minDamage = minDamage;
this.maxDamage = maxDamage;
this.shotsPerSecond = shotsPerSecond;
this.capacity = capacity;
this.bulletsRemaining = bulletsRemaining;
}
public void fire() {
Random rnd = new Random();
int totalDamage = 0;
for(int x = 0; x<shotsPerSecond; x++)
{
int damage = rnd.nextInt(maxDamage) + 1;
System.out.print(sound + "(" + damage + ")");
totalDamage += damage;
}
System.out.println(" --> " + totalDamage + " Dmg/Sec ");
}
public void fireAtWill() {
Random rnd = new Random();
int totalDamage = 0;
while(bulletsRemaining > 0) {
for(int x = 0; x<shotsPerSecond; x++)
{
int damage = rnd.nextInt(maxDamage) + 1;
System.out.print(sound + "(" + damage + ")");
totalDamage += damage;
bulletsRemaining--;
if(bulletsRemaining == 0)
break;
}
System.out.println(" --> " + totalDamage + " Dmg/Sec ");
totalDamage = 0;
}
}
public int reload(int ammo) {
//System.out.println();
//System.out.println("Bullets remaining: " + bulletsRemaining);
//System.out.println("Ammo remaining: " + ammo);
//System.out.println("Reloading " + name);
int bulletsReload = capacity - bulletsRemaining; //Amount of bullets to be loaded to gun
ammo = ammo -= bulletsReload;
bulletsRemaining = bulletsRemaining += bulletsReload; //Fill bulletsRemaining to the max again after reloading
return ammo;
}
public void supressiveFire(int ammo) {
Random rnd = new Random();
int totalDamage = 0;
while(ammo != 0) {
while(bulletsRemaining > 0) {
for(int x = 0; x<shotsPerSecond; x++)
{
int damage = rnd.nextInt(maxDamage) + 1;
System.out.print(sound + "(" + damage + ")");
totalDamage += damage;
bulletsRemaining--;
}
System.out.println(" --> " + totalDamage + " Dmg/Sec ");
totalDamage = 0;
if(bulletsRemaining == 0)
reload(ammo);
}
}
if(ammo == 0)
System.out.println("Out of ammunition)");
}
public static void main(String[] args) {
// TODO code application logic here
int ammo = 5;
Gun g1 = new Gun("MK16", "Bang!", 10,15,5,5,5);
g1.fire();
g1.reload(ammo);
System.out.println("Ammo left: " + ammo);
System.out.println("Bullets left: " + g1.bulletsRemaining);
}
}
Expected output:
Ammo: 0
Bullets Remaining: 5
Output I received:
Ammo: 5
Bullets Remaining: 5
You should assign it back like below.
ammo = g1.reload(ammo);
in the main
public static void main(String[] args) {
// TODO code application logic here
int ammo = 5;
Gun g1 = new Gun("MK16", "Bang!", 10,15,5,5,5);
g1.fire();
ammo = g1.reload(ammo);
System.out.println("Ammo left: " + ammo);
System.out.println("Bullets left: " + g1.bulletsRemaining);
}

Drops being cleared, but still dropping

So I am making a plugin, and everything works so far.
The only problem I have is that the chestplate lore wipes, and items sometimes drop twice, one with broken durability and the same stats. Any help is appreciated
package me.impatheimpaler.mmo;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.entity.Skeleton;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
public class Mobdrops extends JavaPlugin implements Listener {
public List<String> t1h = new ArrayList<String>();
public List<String> t1c = new ArrayList<String>();
public List<String> t1l = new ArrayList<String>();
public List<String> t1b = new ArrayList<String>();
public List<String> t1s = new ArrayList<String>();
public static me.impatheimpaler.mmo.Main plugin;
public Mobdrops(Main main) {
plugin = main;
}
#EventHandler
public void onDeath(EntityDeathEvent e) {
Skeleton s = (Skeleton) e.getEntity();
if (!(e.getEntity() instanceof Player)) {
e.getDrops().clear();
e.setDroppedExp(0);
}
if ((e.getEntity() instanceof Skeleton)) {
Skeleton sk = (Skeleton)e.getEntity();
if (sk.getCustomName() == null) {
return;
}
}
Random random = new Random();
int rarity = random.nextInt(3) + 1;
int chestdrop = random.nextInt(20) + 1;
int legsdrop = random.nextInt(17) + 1;
int helmdrop = random.nextInt(6) + 1;
int bootsdrop = random.nextInt(11) + 1;
int swordDrop = random.nextInt(15) + 1;
if (helmdrop == 3) {
ItemStack t1helm = new ItemStack(Material.LEATHER_HELMET);
ItemMeta t1helmMeta = t1helm.getItemMeta();
t1helmMeta.setDisplayName(ChatColor.WHITE + "Renegade's Torn Helmet");
if (rarity == 3) {
int hp = random.nextInt(20) + 33;
t1h.add(ChatColor.RED + "HP: +" + hp);
t1h.add(ChatColor.GOLD + "Legendary");
}
if (rarity == 2) {
int hp = random.nextInt(10) + 20;
t1h.add(ChatColor.RED + "HP: +" + hp);
t1h.add(ChatColor.AQUA + "Normal");
}
if (rarity == 1) {
int hp = random.nextInt(15) + 6;
t1h.add(ChatColor.RED + "HP: +" + hp);
t1h.add(ChatColor.GRAY + "Poor");
}
t1helmMeta.setLore(t1h);
t1helm.setItemMeta(t1helmMeta);
s.getEquipment().setHelmet(t1helm);
e.getDrops().add(t1helm);
t1h.clear();
}
if (chestdrop == 7) {
ItemStack t1chest = new ItemStack(Material.LEATHER_CHESTPLATE);
ItemMeta t1chestMeta = t1chest.getItemMeta();
t1chestMeta.setDisplayName(ChatColor.WHITE + "Renegade's Torn Chestplate");
if (rarity == 3) {
int hp = random.nextInt(20) + 72;
t1c.add(ChatColor.RED + "HP: +" + hp);
t1c.add(ChatColor.GOLD + "Legendary");
}
if (rarity == 2) {
int hp = random.nextInt(30) + 33;
t1c.add(ChatColor.RED + "HP: +" + hp);
t1c.add(ChatColor.AQUA + "Normal");
}
if (rarity == 1) {
int hp = random.nextInt(10) + 20;
t1c.add(ChatColor.RED + "HP: +" + hp);
t1c.add(ChatColor.GRAY + "Poor");
}
t1chestMeta.setLore(t1c);
t1chest.setItemMeta(t1chestMeta);
s.getEquipment().setChestplate(t1chest);
e.getDrops().add(t1chest);
t1c.clear();
}
if (legsdrop == 2) {
ItemStack t1legs = new ItemStack(Material.LEATHER_LEGGINGS);
ItemMeta t1legsMeta = t1legs.getItemMeta();
t1legsMeta.setDisplayName(ChatColor.WHITE + "Renegade's Torn Leggings");
if (rarity == 3) {
int hp = random.nextInt(20) + 61;
t1l.add(ChatColor.RED + "HP: +" + hp);
t1l.add(ChatColor.YELLOW + "Legendary");
}
if (rarity == 2) {
int hp = random.nextInt(20) + 33;
t1l.add(ChatColor.RED + "HP: +" + hp);
t1l.add(ChatColor.AQUA + "Normal");
}
if (rarity == 1) {
int hp = random.nextInt(10) + 10;
t1l.add(ChatColor.RED + "HP: +" + hp);
t1l.add(ChatColor.GRAY + "Poor");
}
t1legsMeta.setLore(t1l);
t1legs.setItemMeta(t1legsMeta);
s.getEquipment().setLeggings(t1legs);
e.getDrops().add(t1legs);
t1l.clear();
}
if (bootsdrop == 1) {
ItemStack t1boots = new ItemStack(Material.LEATHER_BOOTS);
ItemMeta t1bootsMeta = t1boots.getItemMeta();
t1bootsMeta.setDisplayName(ChatColor.WHITE + "Renegade's Torn Boots");
if (rarity == 3) {
int hp = random.nextInt(20) + 23;
t1b.add(ChatColor.RED + "HP: +" + hp);
t1b.add(ChatColor.YELLOW + "Legendary");
}
if (rarity == 2) {
int hp = random.nextInt(10) + 10;
t1b.add(ChatColor.RED + "HP: +" + hp);
t1b.add(ChatColor.AQUA + "Normal");
}
if (rarity == 1) {
int hp = random.nextInt(5) + 6;
t1b.add(ChatColor.RED + "HP: +" + hp);
t1b.add(ChatColor.GRAY + "Poor");
}
t1bootsMeta.setLore(t1b);
t1boots.setItemMeta(t1bootsMeta);
s.getEquipment().setBoots(t1boots);
e.getDrops().add(t1boots);
t1b.clear();
}
if (swordDrop == 3) {
ItemStack t1sword = new ItemStack(Material.WOOD_SWORD);
ItemMeta t1swordMeta = t1sword.getItemMeta();
if (rarity == 3) {
int min = random.nextInt(20) + 11;
int max = random.nextInt(20) + 21;
t1s.add(ChatColor.RED + "DMG: " + min + " - " + max);
t1s.add(ChatColor.YELLOW + "Legendary");
}
if (rarity == 2) {
int max = random.nextInt(10) + 21;
int min = random.nextInt(10) + 11;
t1s.add(ChatColor.RED + "DMG: " + min + " - " + max);
t1s.add(ChatColor.AQUA + "Normal");
}
if (rarity == 1) {
int min = random.nextInt(5) + 6;
int max = random.nextInt(10) + 11;
t1s.add(ChatColor.RED + "DMG: " + min + " - " + max);
t1s.add(ChatColor.GRAY + "Poor");
}
t1swordMeta.setLore(t1s);
t1sword.setItemMeta(t1swordMeta);
s.getEquipment().setItemInHand(t1sword);
e.getDrops().add(t1sword);
t1s.clear();
}
}
}
There are quite a few issues here, but I think the reason you are seeing duplicate items is because you are adding it to both the drop list as well as an equipment slot. When a mob has an item equipped it has a small chance of dropping that item. So essentially you are adding the item twice and occasionally one extra is dropping. Also, code formatting and readability is huge if you ever want to expand on this.
I don't normally do this, but I wanted to help you out. I'm doing this in notepad so please bare with any small errors. If there are any small mistakes let me know so I can update the code accordingly.
package me.impatheimpaler.mmo;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.entity.Skeleton;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
public class Mobdrops extends JavaPlugin implements Listener {
public static me.impatheimpaler.mmo.Main plugin;
public Mobdrops(Main main) {
plugin = main;
}
private ItemStack AddArmorToDropList(EntityDeathEvent e, Material oMaterial, String strItemName, int intRarity, int T3Random, int T3Bonus, int T2Random, int T2Bonus, int T1Random, int T1Bonus) {
ItemStack oItemStack = new ItemStack(oMaterial);
ItemMeta oItemMeta = oItemStack.getItemMeta();
oItemMeta.setDisplayName(strItemName);
List<String> arrItemLore = new ArrayList<String>(); //Always use descriptive variable names
Random random = new Random();
if (intRarity == 3) {
arrItemLore.add(ChatColor.RED + "HP: +" + (random.nextInt(T3Random) + T3Bonus));
arrItemLore.add(ChatColor.GOLD + "Legendary");
}
else if (intRarity == 2) {
arrItemLore.add(ChatColor.RED + "HP: +" + ()random.nextInt(T2Random) + T2Bonus);
arrItemLore.add(ChatColor.AQUA + "Normal");
}
else { //Always use a final else to catch all exceptions
arrItemLore.add(ChatColor.RED + "HP: +" + (random.nextInt(T1Random) + T1Bonus));
arrItemLore.add(ChatColor.GRAY + "Poor");
}
oItemMeta.setLore(arrItemLore);
oItemStack.setItemMeta(oItemMeta);
e.getDrops().add(oItemStack);
}
private void AddWeaponToDropList(EntityDeathEvent e, Material oMaterial, String strItemName, int intRarity, int T3MinDmg, int T3MaxDmg, int T2MinDmg, int T2MaxDmg, int T1MinDmg, int T1MaxDmg) {
ItemStack oItemStack = new ItemStack(oMaterial);
ItemMeta oItemMeta = oItemStack.getItemMeta();
oItemMeta.setDisplayName(strItemName);
List<String> arrItemLore = new ArrayList<String>(); //Always use descriptive variable names
Random random = new Random();
if (intRarity == 3) {
arrItemLore.add(ChatColor.RED + "DMG: " + T3MinDmg + " - " + T3MaxDmg);
arrItemLore.add(ChatColor.GOLD + "Legendary");
}
else if (intRarity == 2) {
arrItemLore.add(ChatColor.RED + "DMG: " + T2MinDmg + " - " + T2MaxDmg);
arrItemLore.add(ChatColor.AQUA + "Normal");
}
else { //Always use a final else to catch all exceptions
arrItemLore.add(ChatColor.RED + "DMG: " + T1MinDmg + " - " + T1MaxDmg);
arrItemLore.add(ChatColor.GRAY + "Poor");
}
oItemMeta.setLore(arrItemLore);
oItemStack.setItemMeta(oItemMeta);
e.getDrops().add(oItemStack);
}
#EventHandler
public void onDeath(EntityDeathEvent e) {
Skeleton oSkeleton = null; //Never do a direct cast without being sure that the entity is what you think it is
if (!(e.getEntity() instanceof Player)) { //Clear items and exp dropped
e.getDrops().clear();
e.setDroppedExp(0);
}
if (e.getEntity() instanceof Skeleton) {
if (oSkeleton.getCustomName() != null) {
oSkeleton = (Skeleton) e.getEntity(); //Set oSkeleton value
}
}
if (oSkeleton != null) {
Random random = new Random();
int intRarity = random.nextInt(3) + 1;
if ((random.nextInt(6) + 1) == 3) {
AddArmorToDropList(e, Material.LEATHER_HELMET, ChatColor.WHITE + "Renegade's Torn Helmet", intRarity, 20, 33, 10, 20, 15, 6);
}
if ((random.nextInt(20) + 1) == 7) {
AddArmorToDropList(e, Material.LEATHER_CHESTPLATE, ChatColor.WHITE + "Renegade's Torn Chestplate", intRarity, 20, 72, 30, 33, 10, 20);
}
if ((random.nextInt(17) + 1) == 2) {
AddArmorToDropList(e, Material.LEATHER_LEGGINGS, ChatColor.WHITE + "Renegade's Torn Leggings", intRarity, 20, 61, 20, 33, 10, 10);
}
if ((random.nextInt(11) + 1) == 1) {
AddArmorToDropList(e, Material.LEATHER_BOOTS, ChatColor.WHITE + "Renegade's Torn Boots", intRarity, 20, 23, 10, 10, 5, 6);
}
if ((random.nextInt(15) + 1) == 3) {
int intT3Min = random.nextInt(20) + 11;
int intT3Max = random.nextInt(20) + 21;
int intT2Min = random.nextInt(10) + 11;
int intT2Max = random.nextInt(10) + 21;
int intT1Min = random.nextInt(5) + 6;
int intT1Max = random.nextInt(10) + 11;
AddWeaponToDropList(e, Material.WOOD_SWORD, ChatColor.WHITE + "RGAMinecraft's Sword", intRarity, intT3Min, intT2Max, intT2Min, intT3Max, intT1Min, intT1Max);
}
}
}
}

Yahtzee - Java - Error

I am trying to do a Yahtzee program. I start with trying to get the card pairs to work out before I continue with rest.
public class PlayEngine {
public PlayEngine(){}
public int evaluate(int[] dicePoints){
double dice1 = Math.random()*6+1;
int diceint1 = (int) dice1;
double dice2 = Math.random()*6+1;
int diceint2 = (int) dice2;
double dice3 = Math.random()*6+1;
int diceint3 = (int) dice3;
double dice4 = Math.random()*6+1;
int diceint4 = (int) dice4;
double dice5 = Math.random()*6+1;
int diceint5 = (int) dice5;
/* int[] dicePoints = {dice1, dice2, dice3, dice4, dice5}; */
int par = 0;
if(dice1==dice2 || dice1==dice3 || dice1==dice4 || dice1==dice5 || dice2==dice3 || dice2==dice4 || dice2==dice5 || dice3==dice4 || dice3==dice5 || dice4==dice5)
{
par = 1;
return par;
} else {
return par;
}
} //dicePoints
} //PlayEngine
When I run this, I get no errors. I only get up the "No main methods..", and that is how it should be.
When I try to run the program we got from school to test if the score:
import javax.swing.*;
import java.util.*;
public class TestScore {
public static void main(String[] args) {
int[] dicePoints = new int[5];
int[] playPoints = new int[15];
PlayEngine player = new PlayEngine ();
String[] kategori = {"Ettor ",
"Tvåor ",
"Treor ",
"Fyror ",
"Femmor ",
"Sexor ",
"Par ",
"Två Par ",
"Triss ",
"Fyrtal ",
"Liten stege ",
"Stor stege ",
"Kåk ",
"Chans ",
"Yatzy "};
String indata, utdata;
while(true) {
indata = JOptionPane.showInputDialog("Ange tärningarnas värden: ");
if (indata == null) // Avsluta genom att trycka Cancel
break;
StringTokenizer ordSeparator = new StringTokenizer(indata, " ,\t");
if (ordSeparator.countTokens() == 5) {
int index = 0;
while(ordSeparator.hasMoreTokens() && index < 5) {
String ettOrd = ordSeparator.nextToken();
dicePoints[index] = Integer.parseInt(ettOrd);;
index = index + 1;
}
playPoints = player.evaluate(dicePoints);
utdata = "Tärningarnas värden: ";
for (int i = 0; i < dicePoints.length; i = i + 1)
utdata = utdata + dicePoints[i] + " ";
utdata = utdata + "\n";
for (int i = 0; i <playPoints.length; i = i + 1) {
utdata = utdata + kategori[i] + playPoints[i] + "\n";
}
JOptionPane.showMessageDialog(null, utdata);
}
else
JOptionPane.showMessageDialog(null, "Du har angivt felaktigt antal värden!!!");
}
}//main
} //TestScore
I get this error:
TestScore.java:36: error: incompatible types: int cannot be converted to int[]
playPoints = player.evaluate(dicePoints);
^
How come? What is wrong?
Updated code:
import javax.swing.*;
import java.util.*;
public class TestScore {
public static void main(String[] args) {
int[] dicePoints = new int[5];
int playPoints;
PlayEngine player = new PlayEngine ();
String[] kategori = {"Ettor ",
"Tvåor ",
"Treor ",
"Fyror ",
"Femmor ",
"Sexor ",
"Par ",
"Två Par ",
"Triss ",
"Fyrtal ",
"Liten stege ",
"Stor stege ",
"Kåk ",
"Chans ",
"Yatzy "};
String indata, utdata;
while(true) {
indata = JOptionPane.showInputDialog("Ange tärningarnas värden: ");
if (indata == null) // Avsluta genom att trycka Cancel
break;
StringTokenizer ordSeparator = new StringTokenizer(indata, " ,\t");
if (ordSeparator.countTokens() == 5) {
int index = 0;
while(ordSeparator.hasMoreTokens() && index < 5) {
String ettOrd = ordSeparator.nextToken();
dicePoints[index] = Integer.parseInt(ettOrd);;
index = index + 1;
}
playPoints = player.evaluate(dicePoints);
utdata = "Tärningarnas värden: ";
for (int i = 0; i < dicePoints.length; i = i + 1)
utdata = utdata + dicePoints[i] + " ";
utdata = utdata + "\n";
for (int i = 0; i <playPoints.length; i = i + 1) {
utdata = utdata + kategori[i] + player.evaluate(dicePoints) + "\n";
}
JOptionPane.showMessageDialog(null, utdata);
}
else
JOptionPane.showMessageDialog(null, "Du har angivt felaktigt antal värden!!!");
}
}//main
} //TestScore
evaluate method return int (defined as public int evaluate(int[] dicePoints){) and not int[]. You are trying to save value returned from evaluate method as an array here:
playPoints = player.evaluate(dicePoints);
as you defined playPoints variable as int[] playPoints = new int[15];
Change it to int playPoints;

Categories

Resources