Hey so I have a problem with my JTable where it is not updating the table when I set its model to a new one with data within it. I have checked and all the arrays have data values within them, coming from another class. The cData array has all the right strings and values. But it doesnt seem to update. Here is the code, I commented where I think it is going wrong:
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class DetentionStats extends JPanel
{
private JLabel title, houseTitle;
private JPanel leftPanel, rightPanel, dormPanel, housePanel, dormButtonPanel, dormStatsPanel, ADormPanel, BDormPanel, CDormPanel, DDormPanel;
private JButton ADorm, BDorm, CDorm, DDorm, Update;
private JTable statsList, houseList;
private JScrollPane statsListScroll, houseListScroll;
private final int numberOfColumns = 4;
private String[] statsColumnNames = {"Name", "Reason"};
private String[] houseColumnNames = {"Name","Reason","Dorm","Completed"};
private ArrayList<Detention> completedDetentions;
private DefaultTableModel statsTable, updateCompleted, houseTable, aDormModel, bDormModel, cDormModel, dDormModel;
public DetentionStats()
{
completedDetentions = new ArrayList<Detention>();
title = new JLabel("Statistics");
title.setFont(new Font("Arial", Font.BOLD, 24));
title.setHorizontalAlignment(JLabel.CENTER);
title.setVerticalAlignment(JLabel.CENTER);
setLayout(new BorderLayout());
ADorm = new JButton("A Dorm");
DormListener aDormListener = new DormListener();
ADorm.addActionListener(aDormListener);
aDormModel = new DefaultTableModel(statsColumnNames, 0);
ADormPanel = new JPanel();
ADormPanel.add(ADorm);
ADormPanel.setPreferredSize(new Dimension(100, 50));
ADormPanel.setBackground(Color.lightGray);
BDorm = new JButton("B Dorm");
DormListener bDormListener = new DormListener();
BDorm.addActionListener(bDormListener);
bDormModel = new DefaultTableModel(statsColumnNames, 0);
BDormPanel = new JPanel();
BDormPanel.add(BDorm);
BDormPanel.setPreferredSize(new Dimension(100, 50));
BDormPanel.setBackground(Color.lightGray);
CDorm = new JButton("C Dorm");
DormListener cDormListener = new DormListener();
CDorm.addActionListener(cDormListener);
cDormModel = new DefaultTableModel(statsColumnNames, 0);
CDormPanel = new JPanel();
CDormPanel.add(CDorm);
CDormPanel.setPreferredSize(new Dimension(100, 50));
CDormPanel.setBackground(Color.lightGray);
DDorm = new JButton("D Dorm");
DormListener dDormListener = new DormListener();
DDorm.addActionListener(dDormListener);
dDormModel = new DefaultTableModel(statsColumnNames, 0);
DDormPanel = new JPanel();
DDormPanel.add(DDorm);
DDormPanel.setPreferredSize(new Dimension(100, 50));
DDormPanel.setBackground(Color.lightGray);
dormButtonPanel = new JPanel();
dormButtonPanel.setLayout(new GridLayout(2,2));
dormButtonPanel.add(ADormPanel);
dormButtonPanel.add(BDormPanel);
dormButtonPanel.add(CDormPanel);
dormButtonPanel.add(DDormPanel);
dormButtonPanel.setBackground(Color.lightGray);
//--------------------------------------------------------------------------------------------------------------------------
statsTable = new DefaultTableModel(statsColumnNames, 0);
statsList = new JTable(statsTable);
statsListScroll = new JScrollPane(statsList);
statsList.setPreferredScrollableViewportSize(new Dimension(470,260));
dormStatsPanel = new JPanel();
dormStatsPanel.add(statsListScroll);
dormStatsPanel.setBackground(Color.lightGray);
dormPanel = new JPanel();
dormPanel.setLayout(new GridLayout(2,1));
dormPanel.add(dormButtonPanel);
dormPanel.add(dormStatsPanel);
//---------------------------------------------------------------------------------------------------------------------------
houseTitle = new JLabel("Completed Detentions");
houseTitle.setFont(new Font("Arial", Font.BOLD, 14));
houseTitle.setHorizontalAlignment(JLabel.CENTER);
houseTitle.setVerticalAlignment(JLabel.CENTER);
Update = new JButton("Update");
UpdateListener uListener = new UpdateListener();
Update.addActionListener(uListener);
houseTable = new DefaultTableModel(houseColumnNames, 0);
houseList = new JTable(houseTable);
houseListScroll = new JScrollPane(houseList);
houseList.setPreferredScrollableViewportSize(new Dimension(470,540));
housePanel = new JPanel();
housePanel.setLayout(new BorderLayout());
housePanel.setBackground(Color.lightGray);
housePanel.add(Update, BorderLayout.EAST);
housePanel.add(houseTitle, BorderLayout.CENTER);
housePanel.add(houseListScroll, BorderLayout.SOUTH);
leftPanel = new JPanel();
leftPanel.add(dormPanel);
leftPanel.setBackground(Color.lightGray);
rightPanel = new JPanel();
rightPanel.add(housePanel);
rightPanel.setBackground(Color.lightGray);
add(title, BorderLayout.NORTH);
add(leftPanel, BorderLayout.WEST);
add(rightPanel, BorderLayout.EAST);
setPreferredSize(new Dimension(1050,670));
setBackground(Color.lightGray);
setVisible(true);
}
public void completeDetention(Detention d)
{
completedDetentions.add(d);
updateCompletedDetentions();
dormSort();
}
private void dormSort()
{
Object[][] dData = new Object[completedDetentions.size()][numberOfColumns];
for(int i = 0; i < completedDetentions.size(); i++)
{
Detention d = completedDetentions.get(i);
if(d.getDorm() == Detention.Dorm.aDorm)
{
dData[i][0] = d.getName();
dData[i][0] = d.getReason();
aDormModel = new DefaultTableModel(dData, statsColumnNames);
}
else if(d.getDorm() == Detention.Dorm.bDorm)
{
dData[i][0] = d.getName();
dData[i][0] = d.getReason();
bDormModel = new DefaultTableModel(dData, statsColumnNames);
}
else if(d.getDorm() == Detention.Dorm.cDorm)
{
dData[i][0] = d.getName();
dData[i][0] = d.getReason();
cDormModel = new DefaultTableModel(dData, statsColumnNames);
}
else if(d.getDorm() == Detention.Dorm.dDorm)
{
dData[i][0] = d.getName();
dData[i][0] = d.getReason();
dDormModel = new DefaultTableModel(dData, statsColumnNames);
}
}
}
private void updateCompletedDetentions()
{
Object[][] cData = new Object[completedDetentions.size()][numberOfColumns];
for(int i = 0; i < completedDetentions.size(); i++)
{
Detention d = completedDetentions.get(i);
//-------------------------------------------
cData[i][0] = d.getName();
//-------------------------------------------
cData[i][1] = d.getReason();
//-------------------------------------------
if(d.getDorm() == Detention.Dorm.aDorm)
{
cData[i][2] = "A Dorm";
}
else if(d.getDorm() == Detention.Dorm.bDorm)
{
cData[i][2] = "B Dorm";
}
else if(d.getDorm() == Detention.Dorm.cDorm)
{
cData[i][2] = "C Dorm";
}
else if(d.getDorm() == Detention.Dorm.dDorm)
{
cData[i][2] = "D Dorm";
}
else
{
cData[i][2] = "No Dorm Selected";
}
//-------------------------------------------
cData[i][3] = new Boolean(true);
}
//this is where it is going wrong (i think)
updateCompleted = new DefaultTableModel(cData, houseColumnNames);
houseList.setModel(updateCompleted);
}
private class UpdateListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
updateCompletedDetentions();
dormSort();
}
}
private class DormListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if(source == ADorm)
{
statsList.setModel(aDormModel);
}
else if(source == BDorm)
{
statsList.setModel(bDormModel);
}
else if(source == CDorm)
{
statsList.setModel(cDormModel);
}
else if(source == DDorm)
{
statsList.setModel(dDormModel);
}
}
}
}
Runnable example:
public class Table extends JPanel
{
private DefaultTableModel updateTable;
private String[] columnNames = {"Name","Last Name","Location"};
private JTable table;
public Table()
{
defaultTable = new JTable(columnNames, 0);
table = new JTable(defaultTable);
}
public void update()
{
Object[][] data = new Object[array.size()][numberOfColumns];
for(int i = 0; i < array.size(); i++)
{
Detention c = detentionArray.get(i)
data[i][0] = c.getFirstName();
data[i][1] = c.getLastName();
data[i][2] = c.getLocation();
}
updateTable = new DefaultTableModel(data, columnNames);
table.setModel(updateTable);
}
}
You might need to use this as last line in updateCompletedDetentions() method.
fireTableDataChanged();
Related
I'm trying to save data from a GUI I made, to a text document. In the GUI I have a menubar with a menu for opening and saving. they both work just fine. the problem is with the finish button. The finish button has to save to a text document without that popup box showing (without this
https://gyazo.com/41fd2370025c7c49cb375c0f64936597).
It has to save in the background without the user having to click "ok" or "save" in my case. It has to save automatically basically. Here is my code:
public class Survey extends JFrame {
public JLabel label;
public JLabel age;
JPanel panel = new JPanel();
JComboBox<String> majorsList;
JTextField textField;
JRadioButton Male;
JRadioButton Female;
JCheckBox workButton;
JCheckBox homeButton;
JCheckBox pcButton;
Integer ageInfo;
int hasJob;
int isHome;
int hasPC;
int age1;
int workAns;
int homeAns;
int PCAns;
String majorsInfo;
String rbinfoMale;
String rbinfoFemale;
String sex;
File fileToSave;
String file_name;
String My_File;
JPanel rButton;
ButtonGroup bg1;
JFileChooser fileChooser;
File fileToOpen;
StringBuilder sb;
String fullcombo;
JFrame parentFrame;
JMenuItem openItem;
JMenuItem saveItem;
File file;
ArrayList<String> allInputs = new ArrayList<String>();
public Survey() {
fileChooser = new JFileChooser();
//JTextField textfield = new JTextField();
//textfield.add(textfield(), BorderLayout.NORTH);
JPanel finishButton = new JPanel();
finishButton.add(finish());
JPanel northPanel = new JPanel();
northPanel.add(age());
JPanel centerPanel = new JPanel();
centerPanel.add(Majors());
centerPanel.add(RadioButtons());
centerPanel.add(locationWork());
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
menuBar.add(createFileMenu());
menuBar.add(createDrawMenu());
//ageInput.add(createTextField());
//createTextField();
//textField = new JTextField(10);
//textField.setBounds(5, 5, 280, 50);
//panel.add(textField, BorderLayout.NORTH);
add(northPanel, BorderLayout.NORTH);
add(centerPanel, BorderLayout.CENTER);
add(finishButton, BorderLayout.SOUTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(800, 600);
}
public static void main(String args[]) {
Survey c = new Survey();
c.setTitle("Survey");
c.setVisible(true);
}
public JMenu createFileMenu() {
JMenu menu = new JMenu("File");
saveItem = new JMenuItem("Save");
openItem = new JMenuItem("Open");
JMenuItem quitItem = new JMenuItem("Quit");
ActionListener listener = new ExitItemListener();
quitItem.addActionListener(listener);
ActionListener listener2 = new SaveItemListener();
saveItem.addActionListener(listener2);
ActionListener listener3 = new OpenItemListener();
openItem.addActionListener(listener3);
menu.add(saveItem);
menu.add(openItem);
menu.add(quitItem);
return menu;
}
public JMenu createDrawMenu() {
JMenu menu = new JMenu("Draw");
saveItem = new JMenuItem("Save");
openItem = new JMenuItem("Open");
JMenuItem quitItem = new JMenuItem("Quit");
ActionListener listener = new ExitItemListener();
quitItem.addActionListener(listener);
ActionListener listener2 = new SaveItemListener();
saveItem.addActionListener(listener2);
menu.add(saveItem);
menu.add(openItem);
menu.add(quitItem);
return menu;
}
public JPanel finish() {
JButton finish = new JButton("Finish");
panel.add(finish);
ActionListener listener = new ExitItemListener();
finish.addActionListener(listener);
ActionListener listener2 = new SaveItemListener();
finish.addActionListener(listener2);
return panel;
}
public JPanel age() {
JPanel textf = new JPanel();
textf.add(age = new JLabel("Age: "));
textField = new JTextField(10);
textField.setBounds(5, 5, 280, 50);
textField.setFont(textField.getFont().deriveFont(20f));
textf.setBorder(new BevelBorder(0));
textf.add(textField);
return textf;
}
public JPanel Majors() {
JPanel majorPanel = new JPanel();
String[] majorsStrings = {"Biology", "Chemistry", "Computer Science", "Engineering"};
majorsList = new JComboBox<String>(majorsStrings);
majorsList.setBorder(new TitledBorder(new EtchedBorder(), "College"));
majorsList.setSelectedIndex(3);
majorsList.addActionListener(majorsList);
majorPanel.add(majorsList);
return majorPanel;
}
public JPanel RadioButtons() {
bg1 = new ButtonGroup();
rButton = new JPanel();
Male = new JRadioButton("Male");
Female = new JRadioButton("Female");
rButton.setLayout(new GridLayout(2, 1));
bg1.add(Male);
bg1.add(Female);
rButton.add(Male);
rButton.add(Female);
return rButton;
}
public JPanel locationWork() {
workButton = new JCheckBox("Work");
homeButton = new JCheckBox("Have Children");
pcButton = new JCheckBox("Own PC");
JPanel cButton = new JPanel();
workButton.setMnemonic(KeyEvent.VK_C);
homeButton.setMnemonic(KeyEvent.VK_G);
pcButton.setMnemonic(KeyEvent.VK_H);
cButton.setLayout(new GridLayout(3, 1));
cButton.add(workButton);
cButton.add(homeButton);
cButton.add(pcButton);
return cButton;
}
private String inputCombo(int age1, String major, String sex, int work, int kids, int comp) {
String newAge = Integer.toString(age1);
String hasWork = Integer.toString(work);
String hasKids = Integer.toString(kids);
String hasComp = Integer.toString(comp);
String combo = major + ", " + newAge + ", " + sex + ", " + hasWork + ", " + hasKids + ", " + hasComp;
return combo;
}
private ArrayList<String> inputData() {
boolean catcher = true;
try {
age1 = Integer.parseInt(textField.getText());
} catch (IllegalFormatException ex) {
catcher = false;
System.out.println("Not an integer");
}
majorsInfo = majorsList.getSelectedItem().toString();
if (Male.isSelected()) {
sex = "Male";
} else if (Female.isSelected()) {
sex = "Female";
} else {
sex = "";
catcher = false;
}
if (workButton.isSelected()) {
workAns = 1;
} else {
workAns = 0;
}
if (homeButton.isSelected()) {
homeAns = 1;
} else {
homeAns = 0;
}
if (pcButton.isSelected()) {
PCAns = 1;
} else {
PCAns = 0;
}
if (catcher) {
fullcombo = inputCombo(age1, majorsInfo, sex, workAns, homeAns, PCAns);
allInputs.add(fullcombo);
} else {
System.out.println("Fill out all fields please");
}
return allInputs;
}
class ExitItemListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
}
class SaveItemListener implements ActionListener {
public void actionPerformed(ActionEvent event1) {
try {
fileChooser.showSaveDialog(Survey.this);
if (fileChooser.showSaveDialog(Survey.this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
StringBuilder sb = new StringBuilder();
FileWriter fw = new FileWriter(file, true);
for (String a : inputData()) {
sb.append(a);
sb.append("\r\n");
}
fw.write(sb.toString());
fw.flush();
fw.close();
}
} catch (IOException ex) {
}
}
}
class OpenItemListener implements ActionListener {
public void actionPerformed(ActionEvent event2) {
File file = fileChooser.getSelectedFile();
fileChooser.showOpenDialog(Survey.this);
}
}
}
ive searched online for the answer for a few hours now, so far i havent found anything helpful, i have a JDialog that is supposed to send an object back to the JPanel that called it, after running the code several times i noticed that the JPanel Constructor Finishes before i can press the Save button inside the JDialog,
my problem is this,
how do i pass the object from the JDialog to the JPanel and in which part of the Jpanel Code do i write it?
Here is the JPanel Code:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class AquaPanel extends JPanel implements ActionListener
{
private JFrame AQF;
private BufferedImage img;
private HashSet<Swimmable> FishSet;
private int FishCount;
private AddAnimalDialog JDA;
public AquaPanel(AquaFrame AQ)
{
super();
FishCount=0;
this.setSize(800, 600);
this.AQF = AQ;
gui();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
// if(!FishSet.isEmpty())
// {
// Iterator ITR = FishSet.iterator();
//
// while(ITR.hasNext())
// {
// ((Swimmable) ITR.next()).drawAnimal(g);
// }
// }
}
private void AddAnim()
{
Swimmable test = null;
JDA = new AddAnimalDialog(test);
JDA.setVisible(true);//shows jdialog box needs to set to false on new animal
}
private void Sleep()
{
}
private void Wake()
{
}
private void Res()
{
}
private void Food()
{
}
private void Info()
{
}
private void gui()
{
JPanel ButtonPanel = new JPanel();
Makebuttons(ButtonPanel);
this.setLayout(new BorderLayout());
this.setBackground(Color.WHITE);
ButtonPanel.setLayout(new GridLayout(1,0));
this.add(ButtonPanel,BorderLayout.SOUTH);
}
private void Makebuttons(JPanel ButtonPanel)
{
JButton Addanim = new JButton("Add Animal");
Addanim.setBackground(Color.LIGHT_GRAY);
Addanim.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
AddAnim();
}
});
JButton Sleep = new JButton("Sleep");
Sleep.setBackground(Color.LIGHT_GRAY);
Sleep.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Sleep();
}
});
JButton Wake = new JButton("Wake Up");
Wake.setBackground(Color.LIGHT_GRAY);
Wake.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Wake();
}
});
JButton Res = new JButton("Reset");
Res.setBackground(Color.LIGHT_GRAY);
Res.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Res();
}
});
JButton Food = new JButton("Food");
Food.setBackground(Color.LIGHT_GRAY);
Food.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Food();
}
});
JButton Info = new JButton("Info");
Info.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Info();
}
});
Info.setBackground(Color.LIGHT_GRAY);
JButton ExitAQP = new JButton("Exit");
ExitAQP.setBackground(Color.LIGHT_GRAY);
ExitAQP.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
ButtonPanel.add(Addanim);
ButtonPanel.add(Sleep);
ButtonPanel.add(Wake);
ButtonPanel.add(Res);
ButtonPanel.add(Food);
ButtonPanel.add(Info);
ButtonPanel.add(ExitAQP);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()=="Confirm Add")
{
if(JDA.GetDone())
{
FishSet.add(JDA.GetAnim()) ;
JOptionPane.showMessageDialog(this, JDA.GetAnim().getAnimalName());
}
}
}
public void setBackgr(int sel)
{
switch (sel)
{
case 0:
img=null;
this.setBackground(Color.WHITE);
break;
case 1:
img=null;
this.setBackground(Color.BLUE);
break;
case 2:
try {
img = ImageIO.read(new File("src/aquarium_background.jpg"));
} catch (IOException e) {
System.out.println("incorrect input image file path!!!!");
e.printStackTrace();
}
}
}
private void ConfirmAnimal()
{
if(JDA.GetAnim()!=null)
{
JOptionPane.showMessageDialog(this, "fish exists");
}
else
{
JOptionPane.showMessageDialog(this, "fish doesn't exists");
}
}
}
and the JDialog Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AddAnimalDialog extends JDialog
{
private JTextField SizeField;
private JTextField HSpeedField;
private JTextField VSpeedField;
private int SelectedAnimal;
private int SelectedColor;
private Boolean IsDone;
private JButton SaveBTN;
Swimmable Animal;
public AddAnimalDialog(Swimmable Anim)
{
super();
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
IsDone = false;
gui();
Anim = Animal;
}
private void gui()
{
this.setSize(new Dimension(400, 300));
JPanel panel = new JPanel();
this.getContentPane().add(panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{151, 62, 63, 0};
gbl_panel.rowHeights = new int[]{20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0, 1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel AnimName = new JLabel("Animal Type:");
GridBagConstraints gbc_AnimName = new GridBagConstraints();
gbc_AnimName.insets = new Insets(0, 0, 5, 5);
gbc_AnimName.gridx = 0;
gbc_AnimName.gridy = 1;
panel.add(AnimName, gbc_AnimName);
JComboBox AnimTypecomboBox = new JComboBox();
AnimTypecomboBox.addItem("Fish");
AnimTypecomboBox.addItem("Jellyfish");
GridBagConstraints gbc_AnimTypecomboBox = new GridBagConstraints();
gbc_AnimTypecomboBox.insets = new Insets(0, 0, 5, 5);
gbc_AnimTypecomboBox.anchor = GridBagConstraints.NORTH;
gbc_AnimTypecomboBox.gridx = 1;
gbc_AnimTypecomboBox.gridy = 1;
panel.add(AnimTypecomboBox, gbc_AnimTypecomboBox);
JLabel AnimSize = new JLabel("Size(between 20 to 320):");
GridBagConstraints gbc_AnimSize = new GridBagConstraints();
gbc_AnimSize.insets = new Insets(0, 0, 5, 5);
gbc_AnimSize.gridx = 0;
gbc_AnimSize.gridy = 2;
panel.add(AnimSize, gbc_AnimSize);
SizeField = new JTextField();
GridBagConstraints gbc_SizeField = new GridBagConstraints();
gbc_SizeField.insets = new Insets(0, 0, 5, 5);
gbc_SizeField.fill = GridBagConstraints.HORIZONTAL;
gbc_SizeField.gridx = 1;
gbc_SizeField.gridy = 2;
panel.add(SizeField, gbc_SizeField);
SizeField.setColumns(10);
JLabel HSpeed = new JLabel("Horizontal Speed(between 1 to 10):");
GridBagConstraints gbc_HSpeed = new GridBagConstraints();
gbc_HSpeed.insets = new Insets(0, 0, 5, 5);
gbc_HSpeed.gridx = 0;
gbc_HSpeed.gridy = 3;
panel.add(HSpeed, gbc_HSpeed);
HSpeedField = new JTextField();
GridBagConstraints gbc_HSpeedField = new GridBagConstraints();
gbc_HSpeedField.insets = new Insets(0, 0, 5, 5);
gbc_HSpeedField.fill = GridBagConstraints.HORIZONTAL;
gbc_HSpeedField.gridx = 1;
gbc_HSpeedField.gridy = 3;
panel.add(HSpeedField, gbc_HSpeedField);
HSpeedField.setColumns(10);
JLabel VSpeed = new JLabel("Vertical Speed(between 1 to 10):");
GridBagConstraints gbc_VSpeed = new GridBagConstraints();
gbc_VSpeed.insets = new Insets(0, 0, 5, 5);
gbc_VSpeed.gridx = 0;
gbc_VSpeed.gridy = 4;
panel.add(VSpeed, gbc_VSpeed);
VSpeedField = new JTextField();
GridBagConstraints gbc_VSpeedField = new GridBagConstraints();
gbc_VSpeedField.insets = new Insets(0, 0, 5, 5);
gbc_VSpeedField.fill = GridBagConstraints.HORIZONTAL;
gbc_VSpeedField.gridx = 1;
gbc_VSpeedField.gridy = 4;
panel.add(VSpeedField, gbc_VSpeedField);
VSpeedField.setColumns(10);
JLabel lblAnimalColor = new JLabel("Animal Color:");
GridBagConstraints gbc_lblAnimalColor = new GridBagConstraints();
gbc_lblAnimalColor.insets = new Insets(0, 0, 5, 5);
gbc_lblAnimalColor.gridx = 0;
gbc_lblAnimalColor.gridy = 5;
panel.add(lblAnimalColor, gbc_lblAnimalColor);
JComboBox ColorComboBox = new JComboBox();
ColorComboBox.setModel(new DefaultComboBoxModel(new String[] {"Red", "Magenta", "Cyan", "Blue", "Green"}));
GridBagConstraints gbc_ColorComboBox = new GridBagConstraints();
gbc_ColorComboBox.insets = new Insets(0, 0, 5, 5);
gbc_ColorComboBox.fill = GridBagConstraints.HORIZONTAL;
gbc_ColorComboBox.gridx = 1;
gbc_ColorComboBox.gridy = 5;
panel.add(ColorComboBox, gbc_ColorComboBox);
JButton btnAddAnimal = new JButton("Confirm Add");
GetInput(btnAddAnimal,AnimTypecomboBox,ColorComboBox);
GridBagConstraints gbc_btnAddAnimal = new GridBagConstraints();
gbc_btnAddAnimal.insets = new Insets(0, 0, 0, 5);
gbc_btnAddAnimal.gridx = 0;
gbc_btnAddAnimal.gridy = 9;
panel.add(btnAddAnimal, gbc_btnAddAnimal);
JButton btnClear = new JButton("Clear");
GridBagConstraints gbc_btnClear = new GridBagConstraints();
gbc_btnClear.gridx = 2;
gbc_btnClear.gridy = 9;
panel.add(btnClear, gbc_btnClear);
}
private Color Getcolor(Object obj)
{
Color clr=Color.RED;
if(obj instanceof String)
{
switch((String)obj)
{
case "Red":
clr = Color.RED;
break;
case "Magenta":
clr = Color.MAGENTA;
break;
case "Cyan":
clr = Color.CYAN;
break;
case "Blue":
clr = Color.BLUE;
break;
case "Green":
clr = Color.GREEN;
break;
}
}
return clr;
}
private Fish MakeFish(int size,Color col,int horSpeed,int verSpeed)
{
return new Fish(size,col,horSpeed,verSpeed);
}
private Jellyfish MakeJellyfish(int size,Color col,int horSpeed,int verSpeed)
{
return new Jellyfish(size,col,horSpeed,verSpeed);
}
public Swimmable GetAnim()
{
return Animal;
}
public Boolean GetDone()
{
return IsDone;
}
private void GetInput(JButton Jbtn,JComboBox type,JComboBox col)
{
Jbtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
if((type.getSelectedItem() instanceof String)&&
((String)type.getSelectedItem()=="Fish"))
{
Color clr=Color.RED;
Object tmp = col.getSelectedItem();
if(col.getSelectedItem() instanceof String)
{
clr = Getcolor(tmp);
}
int size = Integer.parseInt(SizeField.getText());
int Hspeed = Integer.parseInt(HSpeedField.getText());
int VSpeed = Integer.parseInt(VSpeedField.getText());
Animal = MakeFish(size,clr,Hspeed,VSpeed);
}
else if((type.getSelectedItem() instanceof String)&&
((String)type.getSelectedItem()=="Jellyfish"))
{
Color clr=Color.RED;
Object tmp = type.getSelectedItem();
if(col.getSelectedItem() instanceof String)
{
clr = Getcolor(tmp);
}
int size = Integer.parseInt(SizeField.getText());
int Hspeed = Integer.parseInt(HSpeedField.getText());
int VSpeed = Integer.parseInt(VSpeedField.getText());
Animal = MakeJellyfish(size,clr,Hspeed,VSpeed);
}
IsDone=true;
Hide();
SaveBTN = Jbtn;
}
});
}
private void Hide()
{
this.setVisible(false);
}
public JButton GetBTN()
{
return SaveBTN;
}
}
So in short in the JDialog i need to get information from comboboxes and texfields and send that data to an object constructor, and on the "Save" button click i need to transfer the Object from the JDialog that i created with the constructor to the JPanel, how do i do it?
i realized i can send the JPanel to the JDialog and in the JDialog's code where i create the object, i modify the Jpanel's Hashset accordingly
basically i am working on a tetris game and i want to implement a 2 player versus mode.
for now i have a working single player and now i want to make a gui for a 2 player multiplayer. (i will make a second keylistener and a endGame condition later)
however, when i add both gamepanels (what displays the state of the game after retreiving the state of the game from the boardhandler (1 or 2 depending on which player)) i dont get a correct display/gui.
this is what it looks like:
https://gyazo.com/58f37beab249c975cd4acdb8ae0e0154
this is what it should look like (but i want 2 boards displayed since this screenshot is from singleplayerwindow):
https://gyazo.com/4aecf061109844504a05387fb3d39e8f
anyone know what i am doing wrong and/or how i could fix it ?
thank you <3
package gui;
import tetris.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
public class MultiPlayerWindow extends JPanel
{
private GameLoop gameLoop1 ;
private GameLoop gameLoop2 ;
private boolean gameLoopHasStarted1 ;
private boolean gameLoopHasStarted2 ;
private BoardHandler bh1 ;
private BoardHandler bh2 ;
private HighScoreList highScoreList;
private HumanInput inputController ;
private HumanInput inputController2 ;
private JPanel scorePanel;
private JPanel rightPanel;
public MultiPlayerWindow( MainMenu mainMenu ){
//create the variables
Board board1 = new Board(10 , 20 ) ;
Board board2 = new Board(10 , 20 ) ;
final HumanInput inputController1 = new HumanInput() ;
final HumanInput inputController2 = new HumanInput() ;
this.bh1 = new BoardHandler(board1 , true) ;
this.bh2 = new BoardHandler(board2 , true) ;
this.highScoreList = new HighScoreList() ;
//behaviour
this.addKeyListener(inputController1);
this.addKeyListener(inputController2);
this.setFocusable(true);
this.requestFocusInWindow() ;
this.setLayout(new GridBagLayout());
//create panels
scorePanel = new JPanel() ;
scorePanel.setLayout(new GridBagLayout());
scorePanel.setSize(Config.LEFTPANEL_SIZE);
rightPanel = new JPanel() ;
rightPanel.setLayout(new GridBagLayout());
rightPanel.setSize(Config.RIGHTPANEL_SIZE);
//create the ScoreBoard
final ScoreBoard scoreBoard = new ScoreBoard() ;
GridBagConstraints d = new GridBagConstraints() ;
d.gridx = 0 ;
d.gridy = 0 ;
scorePanel.add(scoreBoard , d) ;
d.insets = new Insets(30,10,10,0);
//add a timer to update ScoreBoard
new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//System.out.println("Trying to update score");
scoreBoard.setScore(gameLoop1.getScore());
scoreBoard.setScore(gameLoop2.getScore());
}
}).start();
//create the Highscore Board
HighScoreBoard highScoreBoard = new HighScoreBoard(highScoreList);
d = new GridBagConstraints();
d.gridx = 0;
d.gridy = 1;
d.insets = new Insets(30,10,10,0);
scorePanel.add(highScoreBoard, d);
//create the combobox to choose between tetris and pentris
String[] optionStrings = {"Tetris", "Pentris"};
final JComboBox optionList = new JComboBox(optionStrings);
optionList.setSelectedIndex(0);
optionList.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(optionList.getSelectedIndex() == 0)
{
bh1.switchToTetris();
bh2.switchToTetris();
}
else if(optionList.getSelectedIndex() == 1)
{
bh1.switchToPentris();
bh2.switchToPentris();
}
}
});
optionList.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
optionList.requestFocus();
}
#Override
public void focusLost(FocusEvent e) {
}
});
d = new GridBagConstraints();
d.gridx = 0;
d.gridy = 2;
d.weightx = 0.5;
d.insets = new Insets(30,10,10,0);
scorePanel.add(optionList, d);
//add the scorePanel
d = new GridBagConstraints();
d.gridx = 1;
d.gridy = 0;
this.add(scorePanel, d);
final GamePanel gamePanel1 = new GamePanel(board1);
final GamePanel gamePanel2 = new GamePanel(board2);
gamePanel1.setSize(Config.GAMEPANEL_SIZE);
gamePanel2.setSize(Config.GAMEPANEL_SIZE);
d = new GridBagConstraints();
d.gridx = 0;
d.gridy = 0;
this.add(gamePanel1, d);
d = new GridBagConstraints();
d.gridx = 2;
d.gridy = 0;
this.add(gamePanel2, d);
//set the Thread
gameLoop1 = new GameLoop(bh1, inputController1, gamePanel1, highScoreList);
gameLoop2 = new GameLoop(bh2, inputController2, gamePanel2, highScoreList);
gameLoop1.start();
gameLoop2.start();
gameLoopHasStarted1 = false;
gameLoopHasStarted2 = false;
//add the buttons
JPanel buttonPanel = new JPanel();
buttonPanel.setAlignmentX(30);
buttonPanel.setLayout(new GridLayout(3,1,10,10));
d = new GridBagConstraints();
d.gridx = 0;
d.weightx = 0.2;
d.gridy = 0;
d.insets = new Insets(200,20,0,20);
rightPanel.add(buttonPanel, d);
//backbutton
d = new GridBagConstraints();
d.gridx = 0;
d.gridy = 1;
d.anchor = GridBagConstraints.SOUTH;
d.insets = new Insets(20, 20, 0, 20);
rightPanel.add(new BackButton(mainMenu), d);
//add the right panel
d = new GridBagConstraints();
d.gridx = 3;
d.gridy = 0;
this.add(rightPanel, d);
final JButton startButton = new JButton("Start");
startButton.requestFocus(false);
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(!gameLoopHasStarted1 && !gameLoopHasStarted2)
{
try{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run(){
gameLoopHasStarted1 = true;
gameLoopHasStarted2 = true;
gameLoop1.startNewGame();
gameLoop2.startNewGame();
optionList.setEnabled(false);
requestFocusInWindow();
startButton.setEnabled(false);
}
});
}
catch(Exception expenction)
{
expenction.printStackTrace();
}
}
}
});
buttonPanel.add(startButton);
//pause button
final JButton pauseButton = new JButton("Pause ");
buttonPanel.add(pauseButton);
pauseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(!gameLoop1.isPaused() && !gameLoop2.isPaused()) {
gameLoop1.setPaused(true);
gameLoop2.setPaused(true);
pauseButton.setText("Unpause");
}
else if(gameLoop1.isPaused()&& gameLoop2.isPaused())
{
gameLoop1.setPaused(false);
gameLoop2.setPaused(false);
pauseButton.setText("Pause ");
}
}
});
//reset button
JButton resetButton = new JButton("Reset");
buttonPanel.add(resetButton);
resetButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
bh1.resetBoard();
bh2.resetBoard();
optionList.setEnabled(true);
if(gameLoop1.isRunning() && gameLoop2.isRunning())
{
gameLoop1.apruptGameEnd();
gameLoop2.apruptGameEnd();
}
gameLoopHasStarted1 = false;
gameLoopHasStarted2 = false;
gamePanel1.repaint();
gamePanel2.repaint();
startButton.setEnabled(true);
gameLoop1.setPaused(false);
gameLoop2.setPaused(false);
pauseButton.setText("Pause");
scoreBoard.setScore(0);
}
});
//focuslistener for inputController
this.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
}
#Override
public void focusLost(FocusEvent e) {
requestFocusInWindow();
}
});
}
public Dimension getPreferredSize()
{
return Config.SINGLE_PLAYER_SIZE;
}
}
fixed it.
public Dimension getPreferredSize()
{
return Config.SINGLE_PLAYER_SIZE;
}
this last part was what was messing it up, the rest of the code works fine but was previously then (for some tbh unknown reason) messed up by this. not 100% sure why...
Here's the initialization of the controls.
public void init(){
...
c = new JComboBox();
....
c.addActionListener(this);
p2 = new JPanel();
vt = new Vector();
ChannelList cl = new ChannelList();
lchannels = new JList(vt);
lchannels.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jp = new JScrollPane(lchannels);
cl.createList();
p2.add(jp);
p2.setBorder(new TitledBorder("Channel Titles Available"));
p2.setLayout(new GridLayout(1,1,10,10));
}
The part of actionPerformed() method is supposed to determine the selection from JCombobox, and put the correct objects to JList.
#Override
public void actionPerformed(ActionEvent e) {
JComboBox c = (JComboBox)e.getSource();
String genre = (String)c.getSelectedItem();
System.out.println(genre);
vt = new Vector();
ChannelList cl = new ChannelList();
lchannels = new JList(vt);
lchannels.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jp = new JScrollPane(lchannels);
cl.createList();
for(int i =0; i < cl.chList.length; i++){
char chGenre = cl.chList[i].getChGenre();
switch(genre){
case "All Genres":
vt.add(cl.chList[i].getChTitle());
break;
case "Entertainment":
if(chGenre == 'e')
vt.add(cl.chList[i].getChTitle());
break;
}
}
}
Here's a part of ChannelList:
public void createList()
{
chList = new ChannelInfo[19];
chList[0] = new ChannelInfo("BBC Canada",3.99, 5.99,'e',"bbccan.jpg");
chList[1] = new ChannelInfo("Bloomberg TV",3.99, 5.99,'n',"bloom.jpg");
...
}
There is no error message while running the program. The first part of actionPerformed which prints the String is working properly (which is useless).
However, there's no result showing in JList.
In order to make it more clear, here's the whole file:
import javax.swing.*;
import java.awt.*;
import java.text.*;
import java.util.Vector;
import java.util.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.util.*;
public class AS4Temp extends JApplet implements ItemListener, ActionListener{
JPanel p,p1,p2;
JComboBox c;
JList lchannels;
JScrollPane jp;
Vector vt;
Container con;
public void init(){
p = new JPanel();
p.setLayout(new GridLayout(3,3,10,10));
//Genre
p1 = new JPanel();
c = new JComboBox();
c.addItem("Please Select Genre of Channel");
c.addItem("All Genres");
c.addItem("Entertainment");
c.addItem("Movie");
c.addItem("News/Business");
c.addItem("Sci-Fi");
c.addItem("Sports");
c.addActionListener(this);
p1.add(c);
p1.setLayout(new FlowLayout());
p1.setBorder(new TitledBorder("Channel Genre"));
//Channels
p2 = new JPanel();
vt = new Vector();
ChannelList cl = new ChannelList();
lchannels = new JList(vt);
lchannels.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jp = new JScrollPane(lchannels);
cl.createList();
/*
for(int i =0; i < cl.chList.length; i++){
char chGenre = cl.chList[i].getChGenre();
if(chGenre == 'e')
vt.add(cl.chList[i].getChTitle());
}*/
p2.add(jp);
p2.setBorder(new TitledBorder("Channel Titles Available"));
p2.setLayout(new GridLayout(1,1,10,10));
//all panels
p.add(p1);
p.add(p2);
con = getContentPane();
con.add(p);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JComboBox c = (JComboBox)e.getSource();
String genre = (String)c.getSelectedItem();
System.out.println(genre);
ChannelList cl = new ChannelList();
cl.createList();
switch(genre){
case "All Genres":
for(int i =0; i < cl.chList.length; i++){
char chGenre = cl.chList[i].getChGenre();
vt.add(cl.chList[i].getChTitle());
}
break;
case "Entertainment":
for(int i =0; i < cl.chList.length; i++){
char chGenre = cl.chList[i].getChGenre();
if(chGenre == 'e')
vt.add(cl.chList[i].getChTitle());
}
break;
}
/*
for(int i =0; i < cl.chList.length; i++){
char chGenre = cl.chList[i].getChGenre();
switch(genre){
case "All Genres":
vt.add(cl.chList[i].getChTitle());
break;
case "Entertainment":
if(chGenre == 'e')
vt.add(cl.chList[i].getChTitle());
break;
}
}*/
}
}
I'm guessing here based on partial information, but I see you creating new components including a new JList and a new JScrollPane:
lchannels = new JList(vt);
lchannels.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jp = new JScrollPane(lchannels);
But I don't see that JScrollPane being added to anything, and so it would make sense that none of that would display.
It seems that you may want to go about this very differently, that rather than creating a new JList() and new JScrollPane(...) you probably want to create a new JList model and set the existing JList with this new model, either that or simply change the data held by the existing JList model.
Consider creating a DefaultListModelField object inside of your actionPerformed method, say called listModel, callingaddElement(...)` on it to fill it with data, and then call
myList.setModel(listModel);
on your existing and displayed JList.
For example, here is my minimal example program, or MCVE:
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Mcve extends JPanel {
private static final String[] DATA = {"One", "Two", "Three", "Four", "Five"};
private DefaultComboBoxModel<String> comboModel = new DefaultComboBoxModel<>();
private JComboBox<String> comboBox = new JComboBox<>(comboModel);
private DefaultListModel<String> listModel = new DefaultListModel<>();
private JList<String> list = new JList<>(listModel);
public Mcve() {
list.setPrototypeCellValue(String.format("%30s", " "));
list.setVisibleRowCount(10);;
// fill combo box's model with a bunch of junk
for (int i = 0; i < 10; i++) {
for (int j = 0; j < DATA.length; j++) {
String text = DATA[j] + " " + i;
comboModel.addElement(text);
}
}
Action buttonAction = new ButtonAction("Transfer Data");
comboBox.addActionListener(buttonAction);
add(comboBox);
add(new JScrollPane(list, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
add(new JButton(buttonAction));
}
private class ButtonAction extends AbstractAction {
public ButtonAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Object selection = comboBox.getSelectedItem();
if (selection != null) {
listModel.addElement(selection.toString());
}
}
}
private static void createAndShowGui() {
Mcve mainPanel = new Mcve();
JFrame frame = new JFrame("Mcve");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
You're using a Vector in place of list model, and you seem to be assuming that changing the Vector later on in your program will change the JList -- but it won't. Instead get rid of that Vector, vt, and again please do what I recommend -- use a DefaultListModel in its place. For example, please see changes to code below. Changes are marked with // !! comments:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
public class AS4Temp extends JApplet implements ActionListener {
JPanel p, p1, p2;
JComboBox c;
JList lchannels;
JScrollPane jp;
// !! Vector vt;
private DefaultListModel<String> listModel = new DefaultListModel<>(); // !!
Container con;
public void init() {
p = new JPanel();
p.setLayout(new GridLayout(3, 3, 10, 10));
// Genre
p1 = new JPanel();
c = new JComboBox();
c.addItem("Please Select Genre of Channel");
c.addItem("All Genres");
c.addItem("Entertainment");
c.addItem("Movie");
c.addItem("News/Business");
c.addItem("Sci-Fi");
c.addItem("Sports");
c.addActionListener(this);
p1.add(c);
p1.setLayout(new FlowLayout());
p1.setBorder(new TitledBorder("Channel Genre"));
// Channels
p2 = new JPanel();
// !! vt = new Vector();
ChannelList cl = new ChannelList();
// !! lchannels = new JList(vt);
lchannels = new JList<>(listModel); // !!
lchannels.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jp = new JScrollPane(lchannels);
cl.createList();
/*
* for(int i =0; i < cl.chList.length; i++){ char chGenre =
* cl.chList[i].getChGenre(); if(chGenre == 'e')
* vt.add(cl.chList[i].getChTitle()); }
*/
p2.add(jp);
p2.setBorder(new TitledBorder("Channel Titles Available"));
p2.setLayout(new GridLayout(1, 1, 10, 10));
// price
// all panels
p.add(p1);
p.add(p2);
con = getContentPane();
con.add(p);
}
#Override
public void actionPerformed(ActionEvent e) {
JComboBox c = (JComboBox) e.getSource();
String genre = (String) c.getSelectedItem();
System.out.println(genre);
ChannelList cl = new ChannelList();
cl.createList();
switch (genre) {
case "All Genres":
for (int i = 0; i < cl.chList.length; i++) {
char chGenre = cl.chList[i].getChGenre();
// !! vt.add(cl.chList[i].getChTitle());
listModel.addElement(cl.chList[i].getChTitle()); // !!
}
break;
case "Entertainment":
for (int i = 0; i < cl.chList.length; i++) {
char chGenre = cl.chList[i].getChGenre();
if (chGenre == 'e')
// !! vt.add(cl.chList[i].getChTitle());
listModel.addElement(cl.chList[i].getChTitle()); // !!
}
break;
}
}
}
// !! added to make your code compilable
// !! in the future, please don't force us to do this kludge
class ChannelList {
public Channel[] chList;
public ChannelList() {
createList();
}
public void createList() {
chList = new Channel[5];
chList[0] = new Channel("Foobar1", 'e');
chList[1] = new Channel("Foobar2", 'e');
chList[2] = new Channel("Foobar3", 'e');
chList[3] = new Channel("Foobar4", 'e');
chList[4] = new Channel("Foobar5", 'e');
}
}
// !! added to make your code compilable
// !! in the future, please don't force us to do this kludge
class Channel {
private String title;
private char genre;
public Channel(String title, char genre) {
this.title = title;
this.genre = genre;
}
public char getChGenre() {
return genre;
}
public String getChTitle() {
return title;
}
#Override
public String toString() {
return "Channel [title=" + title + ", genre=" + genre + "]";
}
}
Problem is you are adding a new JList on actionPerformed() and you have not added the list to the container.
lchannels = new JList(vt);
Well you don't need to add a new list on selection, all you need is to update the list model itself on selection.
I am getting a NullPointerException on line 27 (listOfWindTurbines.addItemListener(new dropDownListener());) when I try to run my program. Please Help!
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class PlannerMain {
JFrame frame;
JButton makeMap;
JPanel panel;
JLabel outcome;
JComboBox listOfWindTurbines;
String[] windTurbineSpace = new String[10];
Integer[] windTurbineLengths = new Integer[10];
Integer[] windTurbineWidths = new Integer[10];
JTextField lengthOfRoom, widthOfRoom, widthObjectNeeds, lengthObjectNeeds;
int lengthOfRoomInt, widthOfRoomInt, widthObjectNeedsInt, lengthObjectNeedsInt, largerObjectMeasurement, numberOfItems, numberOfItemsShort;
public static void main(String[] args){
PlannerMain p = new PlannerMain();
}
public PlannerMain(){
windTurbineLengths[0] = 1;
windTurbineWidths[0] = 1;
for(int i = 0;i<=9;i++){
int wNum = i + 1;
windTurbineSpace[i] = "Windturbine "+ wNum;
}
listOfWindTurbines.addItemListener(new dropDownListener());
frame = new JFrame("Minecraft Land Planner");
outcome = new JLabel();
panel = new JPanel();
makeMap = new JButton("Make Map");
lengthOfRoom = new JTextField("Length of Room");
widthOfRoom = new JTextField("Width of Room");
widthObjectNeeds = new JTextField("Width Object Needs");
lengthObjectNeeds = new JTextField("Length Object Needs");
listOfWindTurbines = new JComboBox(windTurbineSpace);
makeMap.addActionListener(new makeMapListener());
frame.setSize(580,550);
frame.add(panel);
panel.add(makeMap);
panel.add(lengthOfRoom);
panel.add(widthOfRoom);
panel.add(lengthObjectNeeds);
panel.add(widthObjectNeeds);
panel.add(listOfWindTurbines);
panel.add(outcome);
frame.setVisible(true);
}
class makeMapListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
lengthOfRoomInt = Integer.parseInt(lengthOfRoom.getText());
widthOfRoomInt = Integer.parseInt(widthOfRoom.getText());
lengthObjectNeedsInt = Integer.parseInt(lengthObjectNeeds.getText());
widthObjectNeedsInt = Integer.parseInt(widthObjectNeeds.getText());
if(lengthObjectNeedsInt<=widthObjectNeedsInt){
largerObjectMeasurement = widthObjectNeedsInt;
}
if(widthObjectNeedsInt<=lengthObjectNeedsInt){
largerObjectMeasurement = lengthObjectNeedsInt;
}
numberOfItems = (lengthOfRoomInt/lengthObjectNeedsInt)*(widthOfRoomInt/widthObjectNeedsInt);
outcome.setText(String.valueOf(numberOfItems));
lengthOfRoom.setSize(30, 20);
widthOfRoom.setSize(30, 20);
widthObjectNeeds.setSize(30, 10);
lengthObjectNeeds.setSize(100, 20);
}
}
class dropDownListener implements ItemListener{
public void itemStateChanged(ItemEvent event) {
if(event.getStateChange() == ItemEvent.SELECTED){
lengthObjectNeeds.setText(Integer.toString(windTurbineLengths[listOfWindTurbines.getSelectedIndex()]));
widthObjectNeeds.setText(Integer.toString(windTurbineLengths[listOfWindTurbines.getSelectedIndex()]));
}
}
}
}
You need to initialize the listOfWindTurbines variable, for example:
JComboBox listOfWindTurbines = new JComboBox();