Java JTextfield focus - java

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

Related

Java : How to Save a File and overwrite it and display combobox strings?

I am working on a school project using BlueJay and I have created two classes in package Logic which are the Game class, and the VectorGames class.
In my package GUI, I created a class called AddGame and ViewGame class.
The issue that I have encountered is that, when I click the Save Button on Addgame, it saves the file only once. When I try to save it doesn't do or say anything it just stays there returning nothing. Another issue encountered is that on ViewGame, the gameType column is remaining empty ( this is from combo type box )
AddGame code :
package GUI;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import Logic.*;
public class AddGame extends JFrame implements ActionListener{
private JPanel north, south, east, west, center;
private JLabel titleLabel, westLabel, eastLabel;
private JTextField gameNameFld, gameKeyFld;
private JComboBox gameTypeCombo;
private JButton saveButton, clearButton;
private VectorGames vg;
public AddGame(){
super("Adding a Game");
this.setLayout(new BorderLayout());
vg = new VectorGames();
vg.readFromFile();
//north panel
north = new JPanel();
this.add(north,BorderLayout.NORTH);
titleLabel = new JLabel("Add a game below");
titleLabel.setFont(new Font("Verdana",Font.BOLD,20));
titleLabel.setForeground(Color.black);
north.add(titleLabel);
//west and east panels
west = new JPanel();
east = new JPanel();
this.add(west, BorderLayout.WEST);
this.add(east, BorderLayout.EAST);
westLabel = new JLabel(" ");
eastLabel = new JLabel(" ");
west.add(westLabel);
east.add(eastLabel);
//center panel
center = new JPanel();
this.add(center, BorderLayout.CENTER);
center.setLayout(new GridLayout(4,2,0,20));
gameNameFld = new JTextField();
gameKeyFld = new JTextField();
gameTypeCombo = new JComboBox();
gameTypeCombo.setModel(new DefaultComboBoxModel(new String[]
{"<--Select-->", "Arcade", "Puzzle", "Adventure", "Shooter", "Roleplay"}));
center.add(createLabel("Game Name"));
center.add(gameNameFld);
center.add(createLabel("Game Key"));
center.add(gameKeyFld);
center.add(createLabel("Game Type"));
center.add(gameTypeCombo);
//south panel
south = new JPanel();
south.setLayout(new FlowLayout());
this.add(south, BorderLayout.SOUTH);
clearButton = new JButton("Clear");
south.add(clearButton);
clearButton.addActionListener(this);
saveButton = new JButton("Save");
south.add(saveButton);
saveButton.addActionListener(this);
this.setSize(300,400);
this.setLocation(50,50);
this.setVisible(true);
}
private JLabel createLabel(String title){
return new JLabel(title);
}
private void clearFields(){
gameNameFld.setText("");
gameKeyFld.setText("");
gameTypeCombo.setSelectedIndex(0);
}
private boolean validateForm(){
boolean flag = false;
if(gameNameFld.getText().equals("")||gameKeyFld.getText().equals("")||
gameTypeCombo.getSelectedIndex()==0){
flag = true;
}
return flag;
}
public void actionPerformed(ActionEvent event){
if (event.getSource() == clearButton){
clearFields();
}
if(event.getSource() == saveButton){
if(validateForm() == true){
JOptionPane.showMessageDialog(null,"You have empty fields",
"Empty Fields", JOptionPane.ERROR_MESSAGE);
} else if(vg.checkGamebyGameKey(gameKeyFld.getText()) == true){
JOptionPane.showMessageDialog(null,"Game Key already exists!",
"Game Key Check", JOptionPane.ERROR_MESSAGE);
} else {
Game tempGame = new Game(gameNameFld.getText(),gameKeyFld.getText(),
(String)gameTypeCombo.getSelectedItem());
vg.addGame(tempGame);
vg.saveToFile();
JOptionPane.showMessageDialog(null, "Game added successfully!", "Adding a Game",
JOptionPane.INFORMATION_MESSAGE);
clearFields();
}
}
}
}
ViewGame code:
package GUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import Logic.*;
public class ViewGame extends JFrame {
private JTable table;
private VectorGames vg;
public ViewGame(){
super("Viewing Games by Name");
this.setLayout(new BorderLayout());
vg = new VectorGames();
vg.readFromFile();
vg.sortGamesByName();
int numOfGames = vg.getVectorSize();
int count = 0;
Game tempGame = new Game();
String[] tableHeader = {"Game Name", "Game Type", "Game Key"};
Object [][] tableContent = new Object[numOfGames][3];
for(int i = 0; i < numOfGames; i++){
tempGame = vg.getGamesByIndex(count);
tableContent[i][0] = tempGame.getGameName();
tableContent[i][2] = tempGame.getGameType();
tableContent[i][1] = tempGame.getGameKey();
}
table = new JTable (tableContent, tableHeader);
JScrollPane scrollPane = new JScrollPane(table);
table.setPreferredScrollableViewportSize(new Dimension(500, 400));
this.add(table.getTableHeader(), BorderLayout.NORTH);
this.add(table, BorderLayout.CENTER);
this.setSize(500,600);
this.setLocation(100,50);
this.setVisible(true);
}
}
Game code:
package Logic;
import java.io.*;
public class Game implements Serializable{ // Using serializable to allow easy save and read access
//Initializing variables related to Game
private String gameName, gameKey, gameType;
//Creating a constructor with the parameters for class Games
public Game(String gameName, String gamekey, String gameType){
setGameName(gameName);
setGameKey(gameKey);
setGameType(gameType);
}
//Setting up a parameterless constructor for class Games
public Game(){
}
public String getGameName(){//Get Method for gameName
return gameName;
}
public String getGameKey(){//Get Method for gameKey
return gameKey;
}
public String getGameType(){//Get Method for gameType
return gameType;
}
public void setGameName(String gameName){//Set Method for gameName
this.gameName = gameName;
}
public void setGameKey(String gameKey){//Set Method for gameKey
this.gameKey = gameKey;
}
public void setGameType(String gameType){//Set Method for gameType
this.gameType = gameType;
}
public String toString(){
return "Game Name : " + gameName + "\nGame Key : "
+ gameKey + "\nGame Type ; " + gameType;
}
}
VectorGames code:
package Logic;
import java.util.*;
import java.io.*;
import java.lang.*;
public class VectorGames extends IOException{
/* Add a Game, Remove a Game, getVectorGame Size, print allGamesAvailable,
* saveToFile , searchGame and return boolean literal, searchGame and return
* client object, sort games, readFromFile.
*
*/
private Vector<Game> games;
public VectorGames(){
games = new Vector<Game>();
}
//Adding a Game
public void addGame(Game game){
games.add(game);
}
public void deleteGame(Game game){
games.remove(game);
}
public int getVectorSize(){
return games.size();
}
public void clearVector(){
games.clear();
}
public void printGames(){
for(Game tempGame : games){
System.out.println(tempGame.toString());
System.out.println("");
}
}
public Game getGamesByIndex(int i){
Game tempGame = new Game();
if (i < getVectorSize()){
tempGame = games.get(i);
}
return tempGame;
}
public void sortGamesByName(){
Game currentGame = new Game();
Game nextGame = new Game();
Game tempGame = new Game();
for(int i = 0; i < getVectorSize(); i++){
for(int j = 0; j < getVectorSize()-i-1; j++){
currentGame = games.elementAt(j);
nextGame = games.elementAt(j+1);
if(currentGame.getGameName().compareTo(nextGame.getGameName())>0){
tempGame = currentGame;
games.setElementAt(nextGame, j);
games.setElementAt(tempGame, j+1);
}
}
}
}
public boolean checkGamebyGameKey(String gameKey){
boolean flag = false;
for(Game tempGames : games){
if(tempGames .getGameKey().equals(gameKey)){
flag = true;
}
}
return flag;
}
public Game accessGameByGameName(String gameName){
Game foundGameName = new Game();
for(Game tempGames: games){
if(tempGames.getGameName().equals(gameName)){
foundGameName = tempGames;
}
}
return foundGameName;
}
public void saveToFile(){
try{
File f = new File("C:/Users/Denis/Desktop/GameStore/Databases","gameList.obj");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(games);
oos.flush();
oos.close();
}catch (IOException ioe){
System.err.println("Cannot write to file!");
}
}
public void readFromFile(){
try{
File f = new File("C:/Users/Denis/Desktop/GameStore/Databases","gameList.obj");
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
games = (Vector<Game>) ois.readObject();
ois.close();
} catch (FileNotFoundException fnfe){
System.err.println("Cannot find file!");
}catch (IOException ioe){
System.err.println("Cannot read from file!");
}catch(ClassNotFoundException cnfe){
System.err.println("Client class cannot be found!");
}
}
}
Main class: GameCenter
public class GameCenter extends JFrame {
public static void main(String... args) {
SwingUtilities.invokeLater(() -> new GameCenter().setVisible(true));
}
public GameCenter() {
super("Game Center");
init();
}
private void init() {
setLayout(new BorderLayout(5, 5));
Model model = new Model();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("Add", new AddTabPanel(model));
tabbedPane.add("View", new ViewTabPanel(model));
add(tabbedPane, BorderLayout.CENTER);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400, 500);
setMinimumSize(new Dimension(400, 500));
setResizable(false);
}
}
Game entity:
final class Game {
private static final Pattern RECORD = Pattern.compile("(?<key>.+)\\|(?<name>.+)\\|(?<type>.+)");
private final String name;
private final String key;
private final String type;
public static Game createFromRecord(String str) {
Matcher matcher = RECORD.matcher(str);
return matcher.matches() ? new Game(matcher.group("name"), matcher.group("key"), matcher.group("type")) : null;
}
public Game(String name, String key, String type) {
this.name = name;
this.key = key;
this.type = type;
}
public String getName() {
return name;
}
public String getKey() {
return key;
}
public String getType() {
return type;
}
public String serialize() {
return String.format("%s|%s|%s", key, name, type);
}
}
Table model:
final class Model extends AbstractTableModel {
private static final long serialVersionUID = 1858846855164475327L;
private final Map<String, Game> keyGame = new TreeMap<>();
private final List<Game> data = new ArrayList<>();
private File file;
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public void add(String name, String key, String type) {
keyGame.put(key, new Game(name, key, type));
fireTableDataChanged();
}
public void remove(int rowIndex) {
keyGame.remove(data.get(rowIndex).getKey());
fireTableDataChanged();
}
public void save() throws IOException {
if (file == null)
return;
try (FileWriter out = new FileWriter(file, false)) {
for (Game game : keyGame.values())
out.write(game.serialize() + '\n');
}
}
public void read() throws IOException {
if (file == null)
return;
keyGame.clear();
for (String record : Files.readAllLines(file.toPath())) {
Game game = Game.createFromRecord(record);
if (game != null)
keyGame.put(game.getKey(), game);
}
fireTableDataChanged();
}
private enum Column {
NAME("Game Name", Game::getName),
KEY("Game Key", Game::getKey),
TYPE("Game Type", Game::getType);
private final String title;
private final Function<Game, Object> get;
Column(String title, Function<Game, Object> get) {
this.title = title;
this.get = get;
}
public Object getValue(Game game) {
return get.apply(game);
}
}
// ========== AbstractTableModel ==========
#Override
public void fireTableDataChanged() {
data.clear();
data.addAll(keyGame.values());
super.fireTableDataChanged();
}
// ========== TableModel ==========
#Override
public int getRowCount() {
return data.size();
}
#Override
public int getColumnCount() {
return Column.values().length;
}
#Override
public String getColumnName(int columnIndex) {
return Column.values()[columnIndex].title;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return Column.values()[columnIndex].getValue(data.get(rowIndex));
}
}
AddGame tab panel:
final class AddTabPanel extends JPanel implements ActionListener, DocumentListener {
private final Model model;
private final JTextField nameField = new JTextField();
private final JTextField keyField = new JTextField();
private final JLabel nameLabel = new JLabel("Game Name");
private final JLabel keyLabel = new JLabel("Game Key");
private final JLabel typeLabel = new JLabel("Game Type");
private final JComboBox<String> typeCombo = createGameTypeCombo();
private final JButton openButton = new JButton("Open");
private final JButton saveButton = new JButton("Save");
private final JButton clearButton = new JButton("Clear");
public AddTabPanel(Model model) {
this.model = model;
init();
addListeners();
}
private void init() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = createConstraints();
add(createTitlePanel(), gbc);
add(createMainPanel(), gbc);
add(createButtonPanel(), gbc);
gbc.weighty = 1;
add(Box.createVerticalGlue(), gbc);
onNameFieldChanged();
onKeyFieldChanged();
onTypeComboChanged();
}
private static JPanel createTitlePanel() {
JLabel label = new JLabel("Add a game below");
label.setFont(new Font("Verdana", Font.BOLD, 20));
JPanel panel = new JPanel();
panel.add(label);
return panel;
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new GridLayout(3, 2, 5, 5));
panel.add(nameLabel);
panel.add(nameField);
panel.add(keyLabel);
panel.add(keyField);
panel.add(typeLabel);
panel.add(typeCombo);
return panel;
}
private static GridBagConstraints createConstraints() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
return gbc;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel();
panel.add(clearButton);
panel.add(saveButton);
panel.add(openButton);
return panel;
}
private static JComboBox<String> createGameTypeCombo() {
JComboBox<String> combo = new JComboBox<>();
combo.setModel(new DefaultComboBoxModel<>(new String[] { "<--Select-->", "Arcade", "Puzzle", "Adventure", "Shooter", "Roleplay" }));
return combo;
}
private void addListeners() {
clearButton.addActionListener(this);
saveButton.addActionListener(this);
openButton.addActionListener(this);
nameField.getDocument().addDocumentListener(this);
keyField.getDocument().addDocumentListener(this);
typeCombo.addActionListener(this);
}
private void validateFields() {
String name = nameField.getText().trim();
String key = keyField.getText().trim();
int type = typeCombo.getSelectedIndex();
saveButton.setEnabled(!name.isEmpty() && !key.isEmpty() && type != 0);
}
private void onNameFieldChanged() {
nameLabel.setForeground(nameField.getText().trim().isEmpty() ? Color.RED : Color.BLACK);
validateFields();
}
private void onKeyFieldChanged() {
keyLabel.setForeground(keyField.getText().trim().isEmpty() ? Color.RED : Color.BLACK);
validateFields();
}
private void onTypeComboChanged() {
typeLabel.setForeground(typeCombo.getSelectedIndex() == 0 ? Color.RED : Color.BLACK);
validateFields();
}
private void onCleanButton() {
nameField.setText(null);
keyField.setText(null);
typeCombo.setSelectedIndex(0);
validateFields();
}
private void onSaveButton() {
String name = nameField.getText().trim();
String key = keyField.getText().trim();
String type = (String)typeCombo.getSelectedItem();
model.add(name, key, type);
if (model.getFile() == null) {
JFileChooser fileChooser = new JFileChooser();
int res = fileChooser.showSaveDialog(this);
model.setFile(res == JFileChooser.APPROVE_OPTION ? fileChooser.getSelectedFile() : null);
}
try {
model.save();
} catch(Exception e) {
JOptionPane.showMessageDialog(this, "Cannot save file", e.getMessage(), JOptionPane.ERROR_MESSAGE);
}
}
private void onOpenButton() {
JFileChooser fileChooser = new JFileChooser();
int res = fileChooser.showOpenDialog(null);
model.setFile(res == JFileChooser.APPROVE_OPTION ? fileChooser.getSelectedFile() : null);
try {
model.read();
} catch(Exception e) {
JOptionPane.showMessageDialog(this, "Cannot read file", e.getMessage(), JOptionPane.ERROR_MESSAGE);
}
}
// ========== ActionListener ==========
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == typeCombo)
onTypeComboChanged();
else if (e.getSource() == clearButton)
onCleanButton();
else if (e.getSource() == saveButton)
onSaveButton();
else if (e.getSource() == openButton)
onOpenButton();
}
// ========== DocumentListener ==========
#Override
public void insertUpdate(DocumentEvent e) {
if (e.getDocument() == nameField.getDocument())
onNameFieldChanged();
else if (e.getDocument() == keyField.getDocument())
onKeyFieldChanged();
}
#Override
public void removeUpdate(DocumentEvent e) {
if (e.getDocument() == nameField.getDocument())
onNameFieldChanged();
else if (e.getDocument() == keyField.getDocument())
onKeyFieldChanged();
}
#Override
public void changedUpdate(DocumentEvent e) {
}
}
ViewGame tab panel:
final class ViewTabPanel extends JPanel implements ActionListener, PopupMenuListener {
private final Model model;
private final JTable table = new JTable();
private final JPopupMenu popupMenu = new JPopupMenu();
private final JMenuItem deleteItem = new JMenuItem("Delete");
public ViewTabPanel(Model model) {
this.model = model;
init();
addListeners();
}
private void init() {
setLayout(new GridLayout(1, 1));
add(new JScrollPane(table));
popupMenu.add(deleteItem);
table.setComponentPopupMenu(popupMenu);
table.setAutoCreateRowSorter(true);
table.setModel(model);
table.updateUI();
}
private void addListeners() {
popupMenu.addPopupMenuListener(this);
deleteItem.addActionListener(this);
}
// ========== ActionListener ==========
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == deleteItem) {
model.remove(table.getSelectedRow());
try {
model.save();
} catch(Exception e) {
JOptionPane.showMessageDialog(this, "Cannot save file", e.getMessage(), JOptionPane.ERROR_MESSAGE);
}
}
}
// ========== PopupMenuListener ==========
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent event) {
if (event.getSource() == popupMenu) {
SwingUtilities.invokeLater(() -> {
int rowAtPoint = table.rowAtPoint(SwingUtilities.convertPoint(popupMenu, new Point(0, 0), table));
if (rowAtPoint > -1)
table.setRowSelectionInterval(rowAtPoint, rowAtPoint);
});
}
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent event) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent event) {
}
}

Get text of each JTextArea

I've code like this:
public main() {
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(700, 500);
//tabbed pane
add(tb);
}
public JTextArea txtArea() {
JTextArea area = new JTextArea();
String st = String.valueOf(tab);
area.setName(st);
return area;
}
public static void main (String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new main();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source==mnew) {
tab++;
tb.add("Untitled-"+tab,new JPanel().add(txtArea()));
int s = tb.getSelectedIndex();
s = tb.getTabCount()-1;
tb.setSelectedIndex(s);
}
if(source==save) {
int s = tb.getSelectedIndex()+1;
}
Every click on the "New" menu item, code creates new tab with new panel and textarea (it's similar to a lot of text editors like notepad++).
After clicked "Save" in menu bar I want to get text from focused jtextarea.
Please help.
Add a document listener to the text area.
public JTextArea txtArea() {
JTextArea area = new JTextArea();
tstDocumentListener dcL = new tstDocumentListener();
area.getDocument().addDocumentListener(dcL);
String st = String.valueOf(tab);
area.setName(st);
return area;
}
tstDocumentListener
public class tstDocumentListener implements DocumentListener
{
public void changedUpdate(DocumentEvent e) {}
public void removeUpdate(DocumentEvent e)
{
String newString = "";
int lengthMe = e.getDocument().getLength();
try
{
newString = e.getDocument().getText(0,lengthMe);
System.out.println(newString);
}
catch(Exception exp)
{
System.out.println("Error");
}
}
public void insertUpdate(DocumentEvent e)
{
String newString = "";
int lengthMe = e.getDocument().getLength();
try
{
newString = e.getDocument().getText(0,lengthMe);
System.out.println(newString);
}
catch(Exception exp)
{
System.out.println("Error");
}
}
}
Edit
As for getting the text when you gain or lose focus on the text area
public JTextArea txtArea() {
JTextArea area = new JTextArea();
CustomFocusListener cFL = new CustomFocusListener();
area.addFocusListener(cFL);
String st = String.valueOf(tab);
area.setName(st);
return area;
}
CustomFocusListener
public class CustomFocusListener implements FocusListener
{
#Override
public void focusGained(FocusEvent e)
{
String parseMe = "";
JTextArea src;
try
{
src = (JTextArea)e.getSource();
parseMe = src.getText();
System.out.println(parseMe);
}
catch (ClassCastException ignored)
{
}
}
#Override
public void focusLost(FocusEvent e)
{
String parseMe = "";
JTextArea src;
try
{
src = (JTextArea)e.getSource();
parseMe = src.getText();
System.out.println(parseMe);
}
catch (ClassCastException ignored)
{
}
}
}

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);

how to detect what user my program is in in java

I am working on a word processor and i need to know what user my program is in so that my program can auto detect it on start and save the files in their my Documents. Im using java. and i have no precode for the directory detect. but in case this helps here is my code:
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import java.util.*;
#SuppressWarnings("serial")
class Word1 extends JFrame implements ActionListener, KeyListener{
ClassLoader Idr = this.getClass().getClassLoader();
static JPanel pnl = new JPanel();
public static JTextField Title = new JTextField("Document",25);
static JTextArea Body = new JTextArea("Body", 48, 68);
public static JScrollPane pane = new JScrollPane(Body);
JTextField textField = new JTextField();
JButton saveButton = new JButton("Save File");
JButton editButton = new JButton("Edit File");
JButton deleteButton = new JButton("Delete");
public static String Input = "";
public static String Input2 = "";
public static String Text = "";
public static void main(String[] args){
#SuppressWarnings("unused")
Word1 gui = new Word1();
}
public void ListB(){
// Directory path here
String username = JOptionPane.showInputDialog(getContentPane(), "File to Delete", "New ", JOptionPane.PLAIN_MESSAGE);
String path = "C:\\Users\\"+username+"\\Documents\\";
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
String files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT")){
ArrayList<String> doclist = new ArrayList<String>();
doclist.add(files);
System.out.print(doclist);
String l = doclist.get(i);
}
}
}
}
public Word1()
{
ListB();
setTitle("Ledbetter Word");
setSize(800, 850);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
add(pnl);
Body.setLineWrap(true);
Body.setWrapStyleWord(true);
Body.setEditable(true);
Title.setEditable(true);
Title.addKeyListener(keyListen2);
saveButton.addActionListener(this);
editButton.addActionListener(len);
deleteButton.addActionListener(len2);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
Body.addKeyListener(keyListen);
pnl.add(saveButton);
pnl.add(editButton);
pnl.add(deleteButton);
pnl.add(Title);
pnl.add(pane);
setVisible(true);
}
KeyListener keyListen = new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
#SuppressWarnings("unused")
char keyText = e.getKeyChar();
}
#Override
public void keyPressed(KeyEvent e) {
}//ignore
#Override
public void keyReleased(KeyEvent e) {
Word1.Input = Body.getText();
}//ignore
};
KeyListener keyListen2 = new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
#SuppressWarnings("unused")
char keyText = e.getKeyChar();
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
Word1.Input2 = Title.getText();
}
};
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
#Override
public void actionPerformed(ActionEvent e) {
if( e.getSource() == saveButton ){
try {
BufferedWriter fileOut = new BufferedWriter(new FileWriter("C:\\Users\\David\\Documents\\"+Title.getText()+".txt"));
fileOut.write(Word1.Input);
fileOut.close();
JOptionPane.showMessageDialog(getParent(), "Successfully saved to your documents", "Save", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ECX) {
JOptionPane.showMessageDialog(getParent(), "There was an error saving your file", "Save-Error", JOptionPane.ERROR_MESSAGE);
}
}
}
ActionListener len = new ActionListener(){
#SuppressWarnings({ "resource" })
public void actionPerformed(ActionEvent e){
if(e.getSource() == editButton);{
String filename = JOptionPane.showInputDialog(getParent(), "File to Delete", "Deletion", JOptionPane.PLAIN_MESSAGE);
Word1.Body.setText("");
try{
FileReader file = new FileReader(filename+".txt");
BufferedReader reader = new BufferedReader(file);
String Text = "";
while ((Text = reader.readLine())!= null )
{
Word1.Body.append(Text+"\n");
}
Word1.Title.setText(filename);
} catch (IOException e2) {
JOptionPane.showMessageDialog(getParent(), "Open File Error\nFile may not exist", "Error!", JOptionPane.ERROR_MESSAGE);
}
}
}
};
ActionListener len2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == deleteButton);{
String n = JOptionPane.showInputDialog(getParent(), "File to Delete", "Deletion", JOptionPane.PLAIN_MESSAGE);
Delete(new File(n+".txt"));
}
}
};
public void Delete(File Files){
Files.delete();
}
}
Assuming you are targeting windows (My Documents hint) you can try this.
String myDocumentsPath = System.getProperty("user.home") + "/Documents";

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