Can not fill an array in thread - java

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.

Related

first Calculator GUI in Java Eclipse

hey guys I am having trouble with my subtraction button and my division button not working, not sure what i did wrong.. Let me know if you can guide me so I can correct my code! - Ben :)
enter code here
package week07_Ben_Calculator;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class AdvancedCalculatorGUI implements ActionListener {
JFrame frame;
JPanel butPanel;
JTextField res;
JTextField res2;
int oper = 0;
int currentCalc;
double last;
int memory = 0;
public static void main(String[] args) {
// Invocation
EventQueue.invokeLater(new Runnable() {
// Override run
#Override
public void run() {
// Call constructor
new AdvancedCalculatorGUI();
}
});
}
// Create GUI
public AdvancedCalculatorGUI() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Calculator");
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
// New text field
res = new JTextField();
res.setHorizontalAlignment(JTextField.RIGHT);
res.setEditable(false);
frame.add(res, BorderLayout.NORTH);
butPanel = new JPanel();
// 2nd text field
res2 = new JTextField();
res2.setHorizontalAlignment(JTextField.LEFT);
res2.setEditable(false);
frame.add(res2, BorderLayout.SOUTH);
// Create grid
butPanel.setLayout(new GridLayout(6, 3));
frame.add(butPanel, BorderLayout.CENTER);
// Add button
for (int i = 0; i < 10; i++) {
addButton(butPanel, String.valueOf(i));
}
//read button
JButton readButton = new JButton("Read");
readButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
memory = Integer.parseInt(res.getText());
res.setText("");
}
});
//store button
JButton storeButton = new JButton("Store");
storeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
res.setText(memory+"");
}
});
// Add button +
JButton additionButton = new JButton("+");
//additionButton.setActionCommand("+");
additionButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
oper = 1;
res2.setText(res2.getText()+"+");}
});
operAct additionAction = new operAct(1);
additionButton.addActionListener(additionAction);
// Subtract button
JButton subtractionButton = new JButton("-");
subtractionButton.setActionCommand("-");
subtractionButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
oper = 1;
res2.setText(res2.getText()+"-");}
});
operAct subtractionAction = new operAct(2);
subtractionButton.addActionListener(subtractionAction);
// Equal button
JButton eqButton = new JButton("=");
eqButton.setActionCommand("=");
eqButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
System.out.println(oper);
if (!res.getText().isEmpty()) {
int number = Integer.parseInt(res.getText());
if (oper == 1) {
int value = currentCalc + number;
last = value;
res.setText(Integer.toString(value));
res2.setText(res2.getText()+ "=" + Integer.toString(value));
} else if (oper == 2) {
int value = currentCalc - number;
last = value;
res.setText(Integer.toString(value));
res2.setText(res2.getText()+ "=" + Integer.toString(value));
} else if (oper == 3) {
int value = currentCalc * number;
last = value;
res.setText(Integer.toString(value));
res2.setText(res2.getText()+ "=" + Integer.toString(value));
} else if (oper == 4) {
if (number == 0)
res.setText("ERR");
double value = currentCalc / number;
last = value;
res.setText(Double.toString(value));
res2.setText(res2.getText()+ "=" + Double.toString(value));
}
}
}
});
// multiplication button
JButton mulButton = new JButton("*");
mulButton.setActionCommand("*");
mulButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
oper = 1;
res2.setText(res2.getText()+"*");}
});
operAct mulAction = new operAct(3);
mulButton.addActionListener(mulAction);
// division button
JButton divButton = new JButton("/");
divButton.setActionCommand("/");
divButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
oper = 1;
res2.setText(res2.getText()+"/");}
});
operAct divAction = new operAct(4);
divButton.addActionListener(divAction);
butPanel.add(additionButton);
butPanel.add(subtractionButton);
butPanel.add(eqButton);
butPanel.add(mulButton);
butPanel.add(divButton);
butPanel.add(readButton);
butPanel.add(storeButton);
frame.setVisible(true);
}
private void addButton(Container par, String nam) {
JButton b = new JButton(nam);
b.setActionCommand(nam);
b.addActionListener(this);
par.add(b);
}
#Override
public void actionPerformed(ActionEvent ev) {
String act = ev.getActionCommand();
res.setText(act);
System.out.println(ev);
res2.setText(res2.getText() + "" + act);
}
private class operAct implements ActionListener {
private int opt;
public operAct(int oper) {
opt = oper;
}
public void actionPerformed(ActionEvent ev) {
currentCalc = Integer.parseInt(res.getText());
oper = opt;
System.out.println(oper+" "+opt+" "+ currentCalc);
}
}
}
I have gone through your code; first I would suggest to make things simpler.
To make it simpler, first use getText() on the strings entry and then convert them into integers.
For both Input TextFields, distinctly save them in separate variables of respective data-types and then do whatever operations you need by defining their methods .
Instead of overriding the 'action performed method' every time, you can use the getAction Command. It will make your code more readable and you can find errors easier.

How to refactor a repetitive line of code java

I need to create a lot of buttons with information from an excel file, each button have different information but right now the method that creates the buttons is exceeding the 65535 bytes limit so I was thinking of refactoring the method that creates the buttons but I don't know if its possible considering each button is a little different than the previous one, here is an example of what im doing:
JRadioButton rdbtn1IOE1 = new JRadioButton("Cruzamiento con algún Cuerpo de Agua - Sí");
rdbtn1IOE1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IOE.set(0,0.8);
label_IOE.setText("IOE:"+(IOE.get(0)+IOE.get(1)+IOE.get(2)+IOE.get(3)+IOE.get(4)+IOE.get(5)+IOE.get(6)+IOE.get(7)+
IOE.get(8)+IOE.get(9)+IOE.get(10)+IOE.get(11)+IOE.get(12)+IOE.get(13)+IOE.get(14)+IOE.get(15)+IOE.get(16)+IOE.get(17)+
IOE.get(18)+IOE.get(19)+IOE.get(20)+IOE.get(21))+"% ");
}
});
JRadioButton rdbtn2IOE1 = new JRadioButton("Cruzamiento con algún Cuerpo de Agua - No");
rdbtn2IOE1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IOE.set(0,0.0);
label_IOE.setText("IOE:"+(IOE.get(0)+IOE.get(1)+IOE.get(2)+IOE.get(3)+IOE.get(4)+IOE.get(5)+IOE.get(6)+IOE.get(7)+
IOE.get(8)+IOE.get(9)+IOE.get(10)+IOE.get(11)+IOE.get(12)+IOE.get(13)+IOE.get(14)+IOE.get(15)+IOE.get(16)+IOE.get(17)+
IOE.get(18)+IOE.get(19)+IOE.get(20)+IOE.get(21))+"% ");
}
});
JRadioButton rdbtnNoDataIOE1 = new JRadioButton("No Data");
rdbtnNoDataIOE1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IOE.set(0,0.0);
label_IOE.setText("IOE:"+(IOE.get(0)+IOE.get(1)+IOE.get(2)+IOE.get(3)+IOE.get(4)+IOE.get(5)+IOE.get(6)+IOE.get(7)+
IOE.get(8)+IOE.get(9)+IOE.get(10)+IOE.get(11)+IOE.get(12)+IOE.get(13)+IOE.get(14)+IOE.get(15)+IOE.get(16)+IOE.get(17)+
IOE.get(18)+IOE.get(19)+IOE.get(20)+IOE.get(21))+"% ");
}
});
JRadioButton rdbtn1IOE2 = new JRadioButton("< 100 metros");
rdbtn1IOE2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IOE.set(1,0.1);
label_IOE.setText("IOE:"+(IOE.get(0)+IOE.get(1)+IOE.get(2)+IOE.get(3)+IOE.get(4)+IOE.get(5)+IOE.get(6)+IOE.get(7)+
IOE.get(8)+IOE.get(9)+IOE.get(10)+IOE.get(11)+IOE.get(12)+IOE.get(13)+IOE.get(14)+IOE.get(15)+IOE.get(16)+IOE.get(17)+
IOE.get(18)+IOE.get(19)+IOE.get(20)+IOE.get(21))+"% ");
}
});
JRadioButton rdbtnNoDataIOE2 = new JRadioButton("No Data");
rdbtnNoDataIOE2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IOE.set(1,0.0);
label_IOE.setText("IOE:"+(IOE.get(0)+IOE.get(1)+IOE.get(2)+IOE.get(3)+IOE.get(4)+IOE.get(5)+IOE.get(6)+IOE.get(7)+
IOE.get(8)+IOE.get(9)+IOE.get(10)+IOE.get(11)+IOE.get(12)+IOE.get(13)+IOE.get(14)+IOE.get(15)+IOE.get(16)+IOE.get(17)+
IOE.get(18)+IOE.get(19)+IOE.get(20)+IOE.get(21))+"% ");
}
});
JRadioButton rdbtn2IOE2 = new JRadioButton(">= 100 to <= 200 metros");
rdbtn2IOE2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IOE.set(1,0.05);
label_IOE.setText("IOE:"+(IOE.get(0)+IOE.get(1)+IOE.get(2)+IOE.get(3)+IOE.get(4)+IOE.get(5)+IOE.get(6)+IOE.get(7)+
IOE.get(8)+IOE.get(9)+IOE.get(10)+IOE.get(11)+IOE.get(12)+IOE.get(13)+IOE.get(14)+IOE.get(15)+IOE.get(16)+IOE.get(17)+
IOE.get(18)+IOE.get(19)+IOE.get(20)+IOE.get(21))+"% ");
}
});
I hope I explained this well, thank you in advance.
This looks to me like you could create a single ActionListener subclass, with a constructor that takes the two parameters that you are passing to IOE.set.
public class IOESetActionListener extends ActionListener {
private final int a;
private final double b;
public IOESetActionListener(int a, double b) {
this.a = a;
this.b = b;
}
public void actionPerformed(ActionEvent e) {
IOE.set(a, b);
final StringBuilder builder = new StirngBuilder("IOE:");
for (int i = 0; i < 22; ++i) {
builder.append(IOE.get(i));
}
label_IOE.setText(builder.append("% ").toString());
}
}
Then your buttons can just be (for example) rdbtn1IOE1.addActionListener(new IOESetActionListener(0,0.8));
Refactoring the code you have, either extend JRadioButton passing the "differences" to the constructor:
public class MyJRadioButton extends JRadioButton {
public MyJRadioButton(String title, final int x, final double y) {
super(title);
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IOE.set(x, y);
StringBuilder text = new StringBuilder("IOE:");
for (int i = 0; i < 22; i++)
text.append(IOE.get(i));
label_IOE.setText(text + "% ");
}
});
}
}
Then to use, for example:
JRadioButton rdbtnNoDataIOE1 = new MyJRadioButton("No Data", 0, 0.0);
Or if you prefer not to extend the component, here's a factory method version:
public static JRadioButton create(String title, final int x, final double y) {
JRadioButton button = JRadioButton(title);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IOE.set(x, y);
StringBuilder text = new StringBuilder("IOE:");
for (int i = 0; i < 22; i++)
text.append(IOE.get(i));
label_IOE.setText(text + "% ");
}
});
return button;
}
which you use like:
JRadioButton rdbtnNoDataIOE1 = create("No Data", 0, 0.0);

Java JTextfield focus

I made an application, which got quite alot textfields, which clear text on focus. When i run the application, the application works abolutely fine. Then, i made a menu, which give me a choice to open the application, or open the txt my FileWriter wrote. Now, when i run application using menu, it focuses on the first textfield. How do i make the menu run the application without focus on first textfield?? as i said, when i run application without menu, it doesnt focus.. hope u can help!
Best Regards, Oliver.
Menu:
public class menu extends JFrame{
private JFrame fr;
private JButton b1;
private JButton b2;
private JPanel pa;
public static void main(String[] args){
new menu();
}
public menu(){
gui();
}
public void gui(){
fr = new JFrame("menu");
fr.setVisible(true);
fr.setSize(200,63);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setLocationRelativeTo(null);
pa = new JPanel(new GridLayout(1,2));
b1 = new JButton("Infostore");
b2 = new JButton("log");
pa.add(b1);
pa.add(b2);
fr.add(pa);
Eventhandler eh = new Eventhandler();
b1.addActionListener(eh);
b2.addActionListener(eh);
}
private class Eventhandler implements ActionListener{
public void actionPerformed(ActionEvent event){
if(event.getSource()==b1){
IS is = new IS();
fr.setVisible(false);
}
if(event.getSource()==b2){
try{
Runtime.getRuntime().exec("C:\\Windows\\System32\\notepad C:\\Applications\\Infostore.txt");
}catch(IOException ex){
ex.printStackTrace();
}
System.exit(1);
}
}
}
}
Application:
public class IS extends JFrame{
private JLabel fname;
private JTextField name;
private JTextField lname;
private JLabel birth;
private JTextField date;
private JTextField month;
private JTextField year;
private JTextField age;
private JButton cont;
private JLabel lcon;
private JTextField email;
private JTextField numb;
String inumb;
int[] check = {0,0,0,0,0,0,0};
int sum=0;
private JPanel p;
private JFrame f;
public static void main(String[] args){
new IS();
}
public IS(){
gui();
}
public void gui(){
f = new JFrame("Infostore");
f.setVisible(true);
f.setSize(200,340);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
p = new JPanel();
fname = new JLabel("Name ");
name = new JTextField("Name",12);
lname = new JTextField("Last name",12);
birth = new JLabel("Birthday");
date = new JTextField("Date",12);
month = new JTextField("Month",12);
year = new JTextField("Year",12);
age = new JTextField("Your age",12);
lcon = new JLabel("Contact");
email = new JTextField("E-mail",12);
numb = new JTextField("Phone (optional)",12);
cont = new JButton("Store Information");
p.add(fname);
p.add(name);
p.add(lname);
p.add(birth);
p.add(date);
p.add(month);
p.add(year);
p.add(age);
p.add(lcon);
p.add(email);
p.add(numb);
p.add(cont);
f.add(p);
f.setVisible(true);
name.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jname = name.getText();
if(jname.equalsIgnoreCase("name")){
name.setText("");
}
}
public void focusLost(FocusEvent e) {
String jname = name.getText();
if(jname.equals("")){
name.setText("Name");
check[0] = 0;
}else{
check[0] = 1;
}
}});
lname.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jlname = lname.getText();
if(jlname.equalsIgnoreCase("last name")){
lname.setText("");
}
}
public void focusLost(FocusEvent e) {
String jlname = lname.getText();
if(jlname.equals("")){
lname.setText("Last name");
check[1] = 0;
}else{
check[1] = 1;
}
}});
date.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jdate = date.getText();
if(jdate.equalsIgnoreCase("date")){
date.setText("");
}
}
public void focusLost(FocusEvent e) {
String jdate = date.getText();
if(jdate.equals("")){
date.setText("Date");
check[2] = 0;
}else{
check[2] = 1;
}
}});
month.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jmonth = month.getText();
if(jmonth.equalsIgnoreCase("month")){
month.setText("");
}
}
public void focusLost(FocusEvent e) {
String jmonth = month.getText();
if(jmonth.equals("")){
month.setText("Month");
check[3] = 0;
}else{
check[3]=1;
}
}});
year.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jyear = year.getText();
if(jyear.equalsIgnoreCase("year")){
year.setText("");
}
}
public void focusLost(FocusEvent e) {
String jyear = year.getText();
if(jyear.equals("")){
year.setText("Year");
check[4] = 0;
}else{
check[4] = 1;
}
}});
age.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jage = age.getText();
if(jage.equalsIgnoreCase("your age")){
age.setText("");
}
}
public void focusLost(FocusEvent e) {
String jage = age.getText();
if(jage.equals("")){
age.setText("Your age");
check[5] = 0;
}else{
check[5] = 1;
}
}});
email.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jemail = email.getText();
if(jemail.equalsIgnoreCase("e-mail")){
email.setText("");
}
}
public void focusLost(FocusEvent e) {
String jemail = email.getText();
if(jemail.equals("")){
email.setText("E-mail");
check[6]=0;
}else{
check[6]=1;
}
}});
numb.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jnumb = numb.getText();
if(jnumb.equalsIgnoreCase("phone (optional)")){
numb.setText("");
}
}
public void focusLost(FocusEvent e) {
String jnumb = numb.getText();
if(jnumb.equals("")){
numb.setText("Phone (optional)");
}else{
}
}
});
eventh eh = new eventh();
cont.addActionListener(eh);
}
private class eventh implements ActionListener{
public void actionPerformed(ActionEvent event){
sum = check[0] + check[1] + check[2] + check[3] + check[4] + check[5] + check[6];
if(event.getSource()==cont&&sum==7){
String sname = name.getText();
String slname = lname.getText();
String sdate = date.getText();
String smonth = month.getText();
String syear = year.getText();
String sage = age.getText();
String semail = email.getText();
String snumb = numb.getText();
if(snumb.equalsIgnoreCase("Phone (optional)")){
numb.setText("");
}
String inumb = ("Phone: "+numb.getText());
String info = ("Name: "+sname+" "+slname+" "+"Birthday: "+sdate+"-"+smonth+"-"+syear+" "+" Age:"+sage+" "+"E-mail:"+" "+ semail+" "+inumb);
JOptionPane.showMessageDialog(null,info);
filewriter fw = new filewriter();
fw.setName(info);
fw.writeFile();
try{
Thread.sleep(150);
}catch(InterruptedException ex){
Thread.currentThread().interrupt();
}
System.exit(0);
}else{
JOptionPane.showMessageDialog(null,"Please fill out all fields");
}
}
}
}
You must force all the parents of the textfield to get focus, then we can set focus on the textfield
Java Textfield focus

How to randomly assign words in a Hangman game in JFrame?

So I am doing a Hang man game in Java for my Final Project in my Computer Science class. I have done the template for the Hang man (i.e. buttons and added the words needed). But I don't know how to draw the Hangman itself and how to randomly add the words (meaning so they will start guessing the words) to the program. What I am asking is how do I draw the Hangman if a letter was guessed wrong(or right, to write in the textfield). For the letters I have done JButtons because I think it would be easier, and added action listeners. I know the code is very long, but don't pay attention to the template, method Start is where I have my words and hints. Thank you in advance. Don't mind that I do not have a main method, I have a driver class that extends this class. (It was one of the requirements)
Solved!
package hangman;
import javax.swing.*;
import java.util.Random;
import java.util.Scanner;
import java.awt.event.*;
import java.awt.*;
public class Hangman extends JFrame
{
JPanel panel = new JPanel();
JButton restart = new JButton("Restart");
JButton a = new JButton("A"), b = new JButton("B"), c = new JButton("C"), d = new JButton("D"), ee = new JButton("E"), f = new JButton("F"),
g = new JButton("G"), h = new JButton("H"), i = new JButton("I"), j = new JButton("J"), k = new JButton("K"), l = new JButton("L"),
m = new JButton("M"), n = new JButton("N"), o = new JButton("O"), p = new JButton("P"), q = new JButton("Q"), r = new JButton("R"),
s = new JButton("S"), t = new JButton("T"), u = new JButton("U"), v = new JButton("V"), w = new JButton("W"), x = new JButton("X"),
y = new JButton("Y"), z = new JButton("Z");
JButton exit = new JButton("Exit");
JButton hint = new JButton("Hint");
JLabel title = new JLabel("Welcome to Hang Man! ");
JLabel hintWord = new JLabel("Click the Button to show a hint!");
Font font = new Font("Comic Sans MS", Font.ITALIC, 24);
JTextField theWord = new JTextField();
Font font1 = new Font("Comic Sans MS", Font.BOLD, 34);
public Hangman()
{
//Panel adding
panel.add(restart);
panel.add(theWord);
panel.add(hint);
panel.add(exit);
panel.add(title);
panel.add(hintWord);
panel.add(a);
panel.add(b);
panel.add(c);
panel.add(d);
panel.add(ee);
panel.add(f);
panel.add(g);
panel.add(h);
panel.add(j);
panel.add(k);
panel.add(l);
panel.add(m);
panel.add(n);
panel.add(o);
panel.add(p);
panel.add(q);
panel.add(r);
panel.add(s);
panel.add(t);
panel.add(u);
panel.add(v);
panel.add(w);
panel.add(x);
panel.add(y);
panel.add(z);
add(panel);
title.setFont(font);
// JFrame properties
setSize(1024, 700);
setTitle("Hangman");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
this.setLayout(null);
panel.setLayout(null);
//Adding to the panel
panel.add(restart);
panel.add(theWord);
panel.add(hint);
panel.add(exit);
panel.add(title);
panel.add(hintWord);
panel.add(a);
panel.add(b);
panel.add(c);
panel.add(d);
panel.add(ee);
panel.add(f);
panel.add(g);
panel.add(h);
panel.add(j);
panel.add(k);
panel.add(l);
panel.add(m);
panel.add(n);
panel.add(o);
panel.add(p);
panel.add(q);
panel.add(r);
panel.add(s);
panel.add(t);
panel.add(u);
panel.add(v);
panel.add(w);
panel.add(x);
panel.add(y);
panel.add(z);
add(panel);
// Positioning
restart.setLocation(25,25);
theWord.setLocation(100, 530);
theWord.setEnabled(false);
theWord.setSize(800, 100);
theWord.setHorizontalAlignment(theWord.CENTER);
theWord.setFont(font1);
theWord.setForeground(Color.RED);
hint.setLocation(600, 150);
exit.setLocation(900, 25);
title.setLocation(350, 25);
a.setLocation(600, 250);
b.setLocation(650, 250);
c.setLocation(700, 250);
d.setLocation(750, 250);
ee.setLocation(800, 250);
f.setLocation(850, 250);
g.setLocation(900, 250);
h.setLocation(950, 250);
j.setLocation(600, 280);
k.setLocation(650, 280);
l.setLocation(700, 280);
m.setLocation(750, 280);
n.setLocation(800, 280);
o.setLocation(850, 280);
p.setLocation(900, 280);
q.setLocation(950, 280);
r.setLocation(600, 310);
s.setLocation(650, 310);
t.setLocation(700, 310);
u.setLocation(750, 310);
v.setLocation(800, 310);
w.setLocation(850, 310);
x.setLocation(900, 310);
y.setLocation(950, 310);
z.setLocation(750, 340);
hintWord.setLocation(670, 150);
// Action Listeners
restart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
restartActionPerformed(e);
}
});
hint.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
hintActionPerformed(e);
}
});
exit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
exitActionPerformed(e);
}
});
a.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
aActionPerformed(e);
}
});
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
bActionPerformed(e);
}
});
c.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
cActionPerformed(e);
}
});
d.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dActionPerformed(e);
}
});
ee.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
eeActionPerformed(e);
}
});
f.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
fActionPerformed(e);
}
});
g.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
gActionPerformed(e);
}
});
h.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
hActionPerformed(e);
}
});
j.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
jActionPerformed(e);
}
});
k.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
kActionPerformed(e);
}
});
l.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
lActionPerformed(e);
}
});
m.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mActionPerformed(e);
}
});
n.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
nActionPerformed(e);
}
});
o.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
oActionPerformed(e);
}
});
p.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
pActionPerformed(e);
}
});
q.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
qActionPerformed(e);
}
});
r.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
rActionPerformed(e);
}
});
s.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
sActionPerformed(e);
}
});
t.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
tActionPerformed(e);
}
});
u.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
uActionPerformed(e);
}
});
v.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
vActionPerformed(e);
}
});
w.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
wActionPerformed(e);
}
});
x.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
xActionPerformed(e);
}
});
y.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
yActionPerformed(e);
}
});
z.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
zActionPerformed(e);
}
});
}
public void Start()
{
String words[] = new String[26];
String hints[] = new String[26];
// Words along with hints
words[0] = "president";
hints[0] = "Leader.";
words[1] = "exclamation";
hints[1] = "Shout out.";
words[2] = "statement";
hints[2] = "To say.";
words[3] = "television";
hints[3] = "You watch it.";
words[4] = "physics";
hints[4] = "Form of Science.";
words[5] = "algebra";
hints[5] = "Form of math.";
words[6] = "geometry";
hints[5] = "Form of math.";
words[7] = "difficult";
hints[7] = "Hard.";
words[8] = "extreme";
hints[8] = "Intense.";
words[9] = "procedure";
hints[9] = "Steps.";
words[10] = "ship";
hints[10] = "Big Boat.";
words[11] = "soldier";
hints[11] = "Army.";
words[12] = "lunch";
hints[12] = "Meal.";
words[13] = "hockey";
hints[13] = "Sports.";
words[14] = "tennis";
hints[14] = "Sports.";
words[15] = "soccer";
hints[15] = "Sports.";
words[16] = "football";
hints[16] = "Sports.";
words[17] = "basketball";
hints[17] = "Sports.";
words[18] = "bias";
hints[18] = "One sided.";
words[19] = "magazine";
hints[19] = "Form of book.";
words[20] = "computer";
hints[20] = "Microsoft.";
words[21] = "internet";
hints[21] = "World Wide Web.";
words[22] = "allegedly";
hints[22] = "Supposedly.";
words[23] = "system";
hints[23] = "Network.";
words[24] = "unison";
hints[24] = "As one.";
words[25] = "excited";
hints[25] = "Upbeat.";
}
// Action Listeners
public void restartActionPerformed(ActionEvent e)
{
a.setEnabled(true);
b.setEnabled(true);
c.setEnabled(true);
d.setEnabled(true);
ee.setEnabled(true);
f.setEnabled(true);
g.setEnabled(true);
h.setEnabled(true);
j.setEnabled(true);
k.setEnabled(true);
l.setEnabled(true);
m.setEnabled(true);
n.setEnabled(true);
o.setEnabled(true);
p.setEnabled(true);
q.setEnabled(true);
r.setEnabled(true);
s.setEnabled(true);
t.setEnabled(true);
u.setEnabled(true);
v.setEnabled(true);
w.setEnabled(true);
x.setEnabled(true);
y.setEnabled(true);
z.setEnabled(true);
hintWord.setText("Click the Button to show a hint!");
}
public void exitActionPerformed(ActionEvent e)
{
System.exit(0);
}
public void hintActionPerformed(ActionEvent e)
{
hintWord.setText("");
}
public void aActionPerformed(ActionEvent e)
{
a.setEnabled(false);
}
public void bActionPerformed(ActionEvent e)
{
b.setEnabled(false);
}
public void cActionPerformed(ActionEvent e)
{
c.setEnabled(false);
}
public void dActionPerformed(ActionEvent e)
{
d.setEnabled(false);
}
public void eeActionPerformed(ActionEvent e)
{
ee.setEnabled(false);
}
public void fActionPerformed(ActionEvent e)
{
f.setEnabled(false);
}
public void gActionPerformed(ActionEvent e)
{
g.setEnabled(false);
}
public void hActionPerformed(ActionEvent e)
{
h.setEnabled(false);
}
public void jActionPerformed(ActionEvent e)
{
j.setEnabled(false);
}
public void kActionPerformed(ActionEvent e)
{
k.setEnabled(false);
}
public void lActionPerformed(ActionEvent e)
{
l.setEnabled(false);
}
public void mActionPerformed(ActionEvent e)
{
m.setEnabled(false);
}
public void nActionPerformed(ActionEvent e)
{
n.setEnabled(false);
}
public void oActionPerformed(ActionEvent e)
{
o.setEnabled(false);
}
public void pActionPerformed(ActionEvent e)
{
p.setEnabled(false);
}
public void qActionPerformed(ActionEvent e)
{
q.setEnabled(false);
}
public void rActionPerformed(ActionEvent e)
{
r.setEnabled(false);
}
public void sActionPerformed(ActionEvent e)
{
s.setEnabled(false);
}
public void tActionPerformed(ActionEvent e)
{
t.setEnabled(false);
}
public void uActionPerformed(ActionEvent e)
{
u.setEnabled(false);
}
public void vActionPerformed(ActionEvent e)
{
v.setEnabled(false);
}
public void wActionPerformed(ActionEvent e)
{
w.setEnabled(false);
}
public void xActionPerformed(ActionEvent e)
{
x.setEnabled(false);
}
public void yActionPerformed(ActionEvent e)
{
y.setEnabled(false);
}
public void zActionPerformed(ActionEvent e)
{
z.setEnabled(false);
}
}
To draw the lines you could use drawline in the Graphics class.
g.drawLine(int x1, int y1, int x2, int y2);
Docs:
Draws a line, using the current color, between the points (x1, y1) and (x2, y2).
Write down the coordinates to a int array and loop thought that array for all cords.
int[] line1 = new int[]{x1,y1,x2,y2};
int[] line2 = new int[]{x3,y3,x4,y4};
If you wonder how to draw the head you can use drawPolygon
int[] head = new int[]{x,y};
final int headSize = 50; //width and height in px
g.drawPolygon(head[0], head[1], headSize, headSize);
Hope it helped.
Regards -Max

How to implement an actionListener for space bar as action event

I have this set up to update pretty constantly on the timer, but I want to be able to pause the timer with the spacebar. I have attempted to implement an actionListener, but I am not sure what to apply it to. Most of the examples I can find relate to buttons or text boxes, not keyboard presses inside a jpanel. I have printed src to the console and it doesn't appear to be registering my spacebar as an event... I have tried adding the actionListener, but I am not getting something about the syntax. Any help would be appreciated.
public class Arena extends JFrame {
private PaintPanel paintPanel;
public Arena() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setMinimumSize(new Dimension(1000, 720));
paintPanel = new PaintPanel();
getContentPane().add(paintPanel, BorderLayout.CENTER);
paintPanel.setBackground(Color.black);
paintPanel.setFocusable(true);
//paintPanel.addActionListener(this);
pack();
paintPanel.initGame();
}
class PaintPanel extends JPanel implements ActionListener {
private List<Gladiator> gladiators;
private Timer timer;
private Ai AI;
private Load loadObject;
public void initGame() {
timer = new Timer(500, this);
timer.start();
AI = new Ai(gladiators);
loadObject = new Load();
}
#Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
System.out.println("************* "+src);
// if (src == spacebar) {
// } else if (src = timer) {
AI.runAI();
try {
Thread.sleep(100);
System.out.println("sleeping");
} catch (InterruptedException d) {
System.err.println("Caught : InterruptedException" + d.getMessage());
}
repaint();
// }
}
public PaintPanel(){
super();
gladiators = new ArrayList<Gladiator>();
String[][] gladiatorInfo = new String[100][25];
String[] gladiatorRaw = new String[100];
String[][] parsedInfo = new String[250][100];
Gladiator[] gladiator = new Gladiator[20];
int[] matchInfo = new int[3];
int numberofcontestants = 0;
gladiatorRaw = loadObject.getGladiators(gladiatorRaw);
parsedInfo = loadObject.parseStats(gladiatorRaw);
Venue venue = new Venue();
matchInfo = loadObject.getMatchSettings(matchInfo);
venue.populateVenue(matchInfo);
gladiator = createGladiators(venue);
for (int a = 0; a < venue.contestants; a++) {
System.out.println("Populating Gladiator "+a);
gladiator[a].populategladiators(parsedInfo,a);
gladiator[a].getEquipment();
gladiator[a].contestantNumber = a;
gladiators.add(gladiator[a]);
}
}
public Gladiator[] createGladiators(Venue venue) {
int[][] initialPlacement = new int[20][2];
Gladiator[] gladiator = new Gladiator[(venue.contestants)];
initialPlacement = loadObject.loadInitialPlacement(venue.contestants);
for (int a = 0; a < venue.contestants; a++) {
System.out.println("Add gladiator "+a);
gladiator[a] = new Gladiator(initialPlacement[a][0],initialPlacement[a][1]);
System.out.println(initialPlacement[a][0]+","+initialPlacement[a][1]);
}
return gladiator;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
try {
BufferedImage background = ImageIO.read(new File("background.png"));
g.drawImage(background,0,0,this);
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
for (Gladiator s : gladiators){
s.draw(g2);
}
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Arena gamePanel = new Arena();
gamePanel.setVisible(true);
}
});
}
}
Also, is there a getEvent() key code for the spacebar? Can't seem to find one. Thanks
You should use the key bindings API
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "space");
am.put("space", new AbstractAction() {
public void actionPerformed(ActionEvent evt) {
if (timer.isRunning()) {
timer.stop();
} else {
timer.start();
}
}
});
The InputMap/ActionMap can be applied to any component that extends from JComponent, but in your case, I'd suggest attaching it to your PaintPane

Categories