How to refactor a repetitive line of code java - 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);

Related

Determining the sequence of two clicks a user makes

public class GlassActionListener{
JButton first;
JButton second;
#Override
public void actionPerformed(ActionEvent e) {
if(first == null)
{
first = (JButton) e.getSource();
}
else
{
second = (JButton) e.getSource();
// do something
// clean up
first = null;
second = null;
}
}
}
public class GUIControl {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
showGUI();
}
});
}
public static void showGUI() {
JFrame frame = new JFrame("MyFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JButton glass1 = new JButton("glass1");
JButton glass2 = new JButton("glass2");
JButton glass3 = new JButton("glass3");
frame.getContentPane().add(glass1);
frame.getContentPane().add(glass2);
frame.getContentPane().add(glass3);
frame.pack();
frame.setVisible(true);
glass1.addActionListener(??);
glass2.addActionListener(??);
glass3.addActionListener(??);
// I want to store the first two clicks in these variables
from = "glassX";
to = "glassY";
puzzle.move(from, to);
}
The user will spill soda between the glasses. The first JButton the user clicks out of the three available determines the "from" initial glass and the second JButton the user clicks out of the three available determines the "to" destination glass.
How can I determine the specific two JButtons that the user clicked?
Everytime the user clicks two out of the three JButtons I want to store the string associated with those two JButtons in a "from" and "to" variable.
Is there any way to do this?
make an ActionListener and use JButton#addActionListener to add it to all three buttons. The event has a source field you can use.
ActionListener listener = new ActionListener() {
JButton first;
JButton second;
#Override
public void actionPerformed(ActionEvent e) {
if(first == null)
{
first = (JButton) e.getSource();
}
else
{
second = (JButton) e.getSource();
// do something
// clean up
first = null;
second = null;
}
}
};
glass1.addActionListener(listener);
glass2.addActionListener(listener);
glass3.addActionListener(listener);
Handling the logic inside the listener is a little dirty, but that's the idea.
firstbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//do something here first button is clicked
}
} );
you can add listeners to buttons like this.and use a class variable to track how many times the buttons are clicked.
eg:
public class GUIControl {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
showGUI();
}
});
}
public static void showGUI() {
JFrame frame = new JFrame("MyFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JButton glass1 = new JButton("glass1");
JButton glass2 = new JButton("glass2");
JButton glass3 = new JButton("glass3");
String from = "";
String to = "";
int click_count = 0;
glass1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(click_count ==0)
{
from = "glassX";
click_count = 1;
}else if(click_count ==1)
{
from = "glassY";
click_count = 0;
}
}
} );
glass2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(click_count ==0)
{
from = "glassX";
click_count = 1;
}else if(click_count ==1)
{
from = "glassY";
click_count = 0;
}
}
} );
glass3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(click_count ==0)
{
from = "glassX";
click_count = 1;
}else if(click_count ==1)
{
from = "glassY";
click_count = 0;
}
}
} );
frame.getContentPane().add(glass1);
frame.getContentPane().add(glass2);
frame.getContentPane().add(glass3);
frame.pack();
frame.setVisible(true);
// I want to store the first two clicks in these variables
}

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.

Need help printing text to a TextArea from another class in Java

Just need some help printing text to a TextArea for a class project. I have a method that generates 5 random numbers between 0-100 and want it to print to a TextArea but I am unsure on how to do that. (Right now I just have Syste.out.println as a placeholder but I would like to remove that)
public class Interface
{
public Interface()
{
}
public static void randomNumber()
{
Random randomNumber = new Random();
System.out.println("Generating 5 Random Numbers.");
for (int randomNum = 1; randomNum <= 5; ++randomNum)
{
int randomInt = randomNumber.nextInt(5);
System.out.println("Random Number: " + randomInt);
}
System.out.println("Done.");
}
}
public class InterfacePanel extends JPanel
{
private InterfaceController baseController;
private SpringLayout baseLayout;
private JButton buttonOne;
private JButton buttonTwo;
private JButton buttonThree;
private JButton buttonFour;
private JLabel lableOne;
private JLabel lableTwo;
private JLabel lableThree;
private JLabel lableFour;
private TextArea textField;
public InterfacePanel(InterfaceController baseController)
{
setBackground(Color.DARK_GRAY);
this.baseController = baseController;
buttonOne = new JButton("Random Numbers");
buttonTwo = new JButton("Two");
buttonThree = new JButton("Three");
buttonFour = new JButton("Four");
lableOne = new JLabel("5 Random Numbers");
lableTwo = new JLabel("Two");
lableThree = new JLabel("Three");
lableFour = new JLabel("Four");
baseLayout = new SpringLayout();
textField = new TextArea();
setupPanel();
setupLayout();
setupListeners();
}
private void setupPanel()
{
this.setLayout(baseLayout);
this.add(lableOne);
this.add(buttonOne);
this.add(buttonTwo);
this.add(buttonThree);
this.add(buttonFour);
this.add(lableTwo);
this.add(lableThree);
this.add(lableFour);
this.add(textField);
}
private void setupLayout()
private void setupListeners()
{
buttonOne.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent click)
{
Interface.randomNumber();
}
});
buttonTwo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent click)
{
}
});
buttonThree.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent click)
{
}
});
buttonFour.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent click)
{
}
});
}
}
Add a parameter of JTextArea in randomNumber() method.
public static void randomNumber(JTextArea myText){
Random randomNumber = new Random();
System.out.println("Generating 5 Random Numbers.");
for (int randomNum = 1; randomNum <= 5; ++randomNum)
{
int randomInt = randomNumber.nextInt(5);
myText.setText(myText.getText() + randomInt + "\n");
}
System.out.println("Done.");
}
And call randomNumber() method in InterfacePanel class this way
Interface.randomNumber(textField);

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

Can not fill an array in thread

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.

Categories