ListSelectionListener and CardLayout - java

I'm creating a program that reads data from a file, displays it on a GUI that has a JList and JButtons. I am trying to write it with CardLayout so the appropriate JPanel can be displayed when an item is selected from the JList or a JButton is clicked (i.e. next, previous, first and last). I am able to successfully read from the file and display data to the GUI. I've run into 2 problems and I've tried searching online for answers but cant seem to figure it out:
1) How do I get the JPanels to switch using CardLayout?
2) How do I get the data to be displayed in the GUI in text fields when a user clicks an item from the JList? The JList does appear and my ListSelectionListener is working because when I click on a particular item, it will print to the console (as a test).
If I comment out all of the JPanels except for 1, then it is correctly displayed but when I place all of them, then it does not switch.
So far, I have this for my ListSelectionListener (as an inner class):
public class CancerSelectionListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent e) {
Integer selection = (Integer)(((JList) e.getSource()).getSelectedIndex());
if(selection == 0) {
System.out.println("blah"); // works
// switch to the corresponding JPanel in CardLayout
}
}
}
String[] tester;
String teste;
listModel = new DefaultListModel();
for(int i = 0; i < 36; i++) {
tester = _controller.readCancer(i); // reads from the file, this part works!
teste = tester[0];
listModel.addElement(teste);
}
cancerList = new JList(listModel);
cancerList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cancerList.setSelectedIndex(-1);
cancerList.setVisibleRowCount(5);
cancerListScroller = new JScrollPane(cancerList);
CardLayout myCardLayout;
myCardLayout = new CardLayout();
mainPanel2.setLayout(myCardLayout);
myCardLayout.show(mainPanel2, "test");
CancerPanels.aplPanel apl = new CancerPanels.aplPanel();
CancerPanels.fcPanels fc = new CancerPanels.fcPanels();
CancerPanels.vhlsPanels vhls = new CancerPanels.vhlsPanels();
CancerPanels.pdgPanels pdg = new CancerPanels.pdgPanels();
CancerPanels.cebpaPanels cebpa = new CancerPanels.cebpaPanels();
mainPanel2.add(apl.aplReturn(), "test");
mainPanel2.add(fc.fcReturn());
mainPanel2.add(vhls.vhlsReturn());
mainPanel2.add(pdg.pdgReturn());
mainPanel2.add(cebpa.cebpaReturn());
// I have 37 JPanels that are placed in the JPanel that uses CardLayout but I didn't post all of them as it would take up lots of space
The data for each JPanel is populated from static inner classes in the CancerPanels class (only showing 1 as each is very long!)
public class CancerPanels extends CancerGUI {
static JPanel cards;
static CancerController _cons = new CancerController();
static String[] cancerData;
static JScrollPane treatmentsScroller = new JScrollPane(txtTreatments, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
static JScrollPane causesScroller = new JScrollPane(txtCauses, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
static JScrollPane symptomsScroller = new JScrollPane(txtSymptoms, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
public static class aplPanel extends JPanel {
public JPanel aplReturn() {
treatmentsScroller.setViewportView(txtTreatments);
txtTreatments.setEditable(false);
causesScroller.setViewportView(txtCauses);
txtCauses.setEditable(false);
symptomsScroller.setViewportView(txtSymptoms);
txtSymptoms.setEditable(false);
cards = new JPanel(new GridLayout(6,1));
cancerData = _cons.readCancer(0);
resultName.setText(cancerData[0]);
txtSymptoms.setText(cancerData[1]);
txtCauses.setText(cancerData[2]);
txtTreatments.setText(cancerData[3]);
resultRate.setText(cancerData[4]);
resultPrognosis.setText(cancerData[5]);
cards.add(resultName);
cards.add(symptomsScroller);
cards.add(causesScroller);
cards.add(treatmentsScroller);
cards.add(resultRate);
cards.add(resultPrognosis);
return cards;
}
}
Edit:
Here is my most recent attempt. I can scroll through the JList but it doesn't properly display the correct corresponding JPanel (in fact it doesn't display anything, except whenever I click the last button, I don't know why that button works). I successfully managed to place an ItemListener on a JComboBox but ultimately, I want the CardLayout to work. Our instructor provided us with sample code to use but when I try it, the JPanels do not switch (or if they do they're hidden, not sure why).
Each of my listeners are public inner classes in the overall CancerGUI class.
public CancerGUI() {
CancerPanels.aplPanel apl = new CancerPanels.aplPanel();
CancerPanels.fcPanels fc = new CancerPanels.fcPanels();
CancerPanels.vhlsPanels vhls = new CancerPanels.vhlsPanels();
// more than 30 JPanels that I add to the JPanel that uses CardLayout, so I only posted 3
// each of them uses the GridLayout
mainPanel2 = new JPanel(new CardLayout());
mainPanel2.add(apl.aplReturn(), "1");
mainPanel2.add(fc.fcReturn(), "2");
mainPanel2.add(vhls.vhlsReturn(), "3");
CancerActionButtons _cab = new CancerActionButtons();
btnNext = new JButton("Next");
btnPrevious = new JButton("Previous");
btnFirst = new JButton("First");
btnLast = new JButton("Last");
btnClear = new JButton("Clear");
btnNext.addActionListener(_cab);
btnPrevious.addActionListener(_cab);
btnFirst.addActionListener(_cab);
btnLast.addActionListener(_cab);
CancerItemListener _item = new CancerItemListener(); // this listener works!
renalC.addItemListener(_item);
skinC.addItemListener(_item);
brainC.addItemListener(_item);
bladderC.addItemListener(_item);
ovarianC.addItemListener(_item);
pancC.addItemListener(_item);
breastC.addItemListener(_item);
String[] tester;
String teste;
listModel = new DefaultListModel();
for(int i = 0; i < 36; i++) {
tester = _controller.readCancer(i);
teste = tester[0];
listModel.addElement(teste);
}
cancerList = new JList(listModel);
cancerList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cancerList.setSelectedIndex(-1);
cancerList.setVisibleRowCount(5);
cancerListScroller = new JScrollPane(cancerList);
ListSelection _list = new ListSelection();
cancerList.addListSelectionListener(_list);
JScrollPane treatmentsScroller = new JScrollPane(txtTreatments, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
treatmentsScroller.setViewportView(txtTreatments);
JScrollPane causesScroller = new JScrollPane(txtCauses, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
causesScroller.setViewportView(txtCauses);
JScrollPane symptomsScroller = new JScrollPane(txtSymptoms, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
symptomsScroller.setViewportView(txtSymptoms);
public class ListSelection implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent e) {
String selection = (String)(((JList)e.getSource()).getSelectedValue());
((CardLayout) mainPanel2.getLayout()).show(mainPanel2, selection);
((CardLayout) mainPanel2.getLayout()).show(mainPanel2, selection);
}
}
public class CancerActionButtons implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
switch(e.getActionCommand()) {
case "First":
((CardLayout) mainPanel2.getLayout()).first(mainPanel2);
cancerCount = 1;
break;
case "Last":
((CardLayout) mainPanel2.getLayout()).last(mainPanel2);
cancerCount = 11;
break;
case "Previous":
((CardLayout) mainPanel2.getLayout()).previous(mainPanel2);
cancerCount--;
cancerCount = cancerCount < 1 ? 11 : cancerCount;
break;
case "Next":
((CardLayout) mainPanel2.getLayout()).next(mainPanel2);
cancerCount++;
cancerCount = cancerCount > 11 ? 1 : cancerCount; //
break;
}
cancerList.setSelectedIndex(cancerCount-1);
}
}
/**
* Inner class that responds to any user interaction with a JComboBox for
* general types of cancers.
*/
public class CancerItemListener implements ItemListener {
#Override
public void itemStateChanged(ItemEvent e) {
JPanel showPanel = new JPanel();
if(e.getStateChange() == ItemEvent.SELECTED) {
String selection = (String) e.getItem();
if(selection.equalsIgnoreCase("skin cancer")) {
CancerPanels.skin skin = new CancerPanels.skin();
showPanel = skin.skinReturn();
} else if (selection.equalsIgnoreCase("bladder cancer")) {
CancerPanels.bladder bladder = new CancerPanels.bladder();
showPanel = bladder.bladderReturn();
} else if (selection.equalsIgnoreCase("pancreatic cancer")) {
CancerPanels.pancreatic pancreatic = new CancerPanels.pancreatic();
showPanel = pancreatic.returnPancreatic();
} else if (selection.equalsIgnoreCase("renal cancer")) {
CancerPanels.renal renal = new CancerPanels.renal();
showPanel = renal.returnRenal();
} else if (selection.equalsIgnoreCase("ovarian cancer")) {
CancerPanels.ovarian ovarian = new CancerPanels.ovarian();
showPanel = ovarian.ovarianReturn();
} else if (selection.equalsIgnoreCase("breast cancer")) {
CancerPanels.breast breast = new CancerPanels.breast();
showPanel = breast.returnBreast();
} else if (selection.equalsIgnoreCase("brain cancer")) {
CancerPanels.brain brain = new CancerPanels.brain();
showPanel = brain.returnBrain();
} else if (selection.equalsIgnoreCase("von hippel-lindau syndrome")) {
CancerPanels.vhlsPanels vhls = new CancerPanels.vhlsPanels();
showPanel = vhls.vhlsReturn();
}
JOptionPane.showMessageDialog(null, showPanel);
}
}
}
Seperate class where the JPanels are made before being added to CardLayout:
public class CancerPanels extends CancerGUI {
static String name;
static JPanel cards;
static CancerController _cons = new CancerController();
static String[] cancerData;
static JScrollPane treatmentsScroller = new JScrollPane(txtTreatments, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
static JScrollPane causesScroller = new JScrollPane(txtCauses, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
static JScrollPane symptomsScroller = new JScrollPane(txtSymptoms, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
public static class aplPanel extends JPanel {
public JPanel aplReturn() {
treatmentsScroller.setViewportView(txtTreatments);
txtTreatments.setEditable(false);
causesScroller.setViewportView(txtCauses);
txtCauses.setEditable(false);
symptomsScroller.setViewportView(txtSymptoms);
txtSymptoms.setEditable(false);
cards = new JPanel(new GridLayout(6,1));
cancerData = _cons.readCancer(0);
resultName.setText(cancerData[0]);
txtSymptoms.setText(cancerData[1]);
txtCauses.setText(cancerData[2]);
txtTreatments.setText(cancerData[3]);
resultRate.setText(cancerData[4]);
resultPrognosis.setText(cancerData[5]);
cards.add(resultName);
cards.add(symptomsScroller);
cards.add(causesScroller);
cards.add(treatmentsScroller);
cards.add(resultRate);
cards.add(resultPrognosis);
return cards;
}

In essence what you are trying to do is to change the state of one class from another.
How this is done with Swing GUI's is no different for how it is done for non-GUI programs: one class calls the public methods of another class.
One key is to have wiring to allow this to occur which means references for one class needs to be available to the other class so that appropriate methods can be called on appropriate references. The devil as they say is in the details.
"1) How do I get the JPanels to switch using CardLayout?" -- So the class that holds the CardLayout could for instance have the public methods, next(), previous(), and perhaps show(SOME_STRING_CONSTANT) or some other swapView(...) method.
"2) How do I get the data to be displayed in the GUI in text fields when a user clicks an item from the JList?" -- This will involve the use of listeners -- the class holding the JTextFields will listen for notification from the class that holds the JList, and when notified gets the necessary information from the list-displaying class. A PropertyChangeListener could work well here.
e.g.,
public class CancerSelectionListener implements ListSelectionListener {
private CardDisplayingView cardDisplayingView = null;
public CancerSelectionListener(CardDisplayingView cardDisplayingView) {
this.cardDisplayingView = cardDisplayingView;
}
#Override
public void valueChanged(ListSelectionEvent e) {
int selection = ((JList) e.getSource()).getSelectedIndex();
if(selection == 0) {
if (cardDisplayingView != null) {
cardDisplayingView.swapView(...);
}
}
}
}

Related

How can i access a linked list that is implement by me form outside of class

I have a linked list that store bunch of instrument as an object. And i want to access and display it on a GUI. What are some good ways to access it instead of just create a method and return the list to the GUI.
Pls gives some advice.
I will be appreciated.
It depends if you mean the class or an instance of your class. If you mean a class its just an import. If you need an instance of a class there are other ways like making it static (quick and dirty) or using a singleton if just one copy is allowed.
class InstrumentDisplayPanel extends JPanel implements ActionListener {
JPanel status = new JPanel();
JPanel action = new JPanel();
JLabel name = new JLabel();
JLabel number = new JLabel();
JButton next = new JButton("next");
JButton previous = new JButton("previous");
InstrumentDisplayPanel() {
this.setPreferredSize(new Dimension(200,200));
DoublyLinkedList<Instrument> instrumentList = FileRead.loadInstrument();
Node tempNode = instrumentList.getFirstItem();
Item tempItem = (Item)tempNode.getItem();
name.setText(tempItem.getName());
number.setText(tempItem.getNumber());
status.add(name);
status.add(number);
action.add(next);
action.add(previous);
add(status);
add(action);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == next) {
}
}
}
public static DoublyLinkedList<MusicSheet> loadMusicSheet(){
System.out.println("I am loading");
Scanner musicSheetInput = null;
try
{
musicSheetInput = new Scanner(new File("musicSheet.txt"));
}
catch(FileNotFoundException instrument)
{
System.out.println("File does Not Exist Please Try Again: ");
}
DoublyLinkedList<MusicSheet> musicSheetList = new DoublyLinkedList<MusicSheet>();
while (musicSheetInput.hasNextLine()){
String name = musicSheetInput.next();
String number = musicSheetInput.next();
String description = musicSheetInput.nextLine();
if(name.equals("GuitarSheet")){
musicSheetList.add(new GuitarSheet(name,number,description));
}
else if(name.equals("ViolinSheet")){
musicSheetList.add(new ViolinSheet(name,number,description));
}
else if(name.equals("CelloSheet")){
musicSheetList.add(new CelloSheet(name,number, description));
}
}
musicSheetList.display();
return musicSheetList;
}

Information from first form to second form swing java

I have 2 forms. In the first form, I create an object suggestion. Then I have to do something with it and submit it to the second form. How can I open a second window after filling out the first form?
This is my first form:
public class FormNum1 extends JFrame {
JButton clearConfermation, conferm;
JLabel dateofDeparture, dateofArrival, cityFrom, cityTo;
JTextField dateofDepartureTextField, dateofArrivalTextField, cityFromTextField, cityToTextField;
static Suggestion suggestion;
Boolean n = false;
JFrame form1 = new JFrame("form1");
ActionListener actionPerformed;
public FormNum1(){
form1.setVisible(true);
form1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
form1.setSize(1200,250);
//setResizable(false);
form1.setLocationRelativeTo(null);
form1.setLayout(new FlowLayout());
clearConfermation = new JButton("Make clear");
conferm = new JButton("Confirm information ");
dateofDeparture = new JLabel("Date of Departure");
dateofArrival = new JLabel("Date of Arrival");
cityFrom = new JLabel("City From");
cityTo = new JLabel("City to");
dateofDepartureTextField = new JTextField(10);
dateofArrivalTextField = new JTextField(10);
cityFromTextField = new JTextField(10);
cityToTextField = new JTextField(10);
form1.add(clearConfermation);
form1.add(conferm);
form1.add(dateofDeparture);
form1. add(dateofDepartureTextField);
form1.add(dateofArrival);
form1.add(dateofArrivalTextField);
form1.add(cityFrom);
form1.add(cityFromTextField);
form1.add(cityTo);
form1.add(cityToTextField);
actionPerformed = new InformationFromFormOne();
conferm.addActionListener(actionPerformed);
clearConfermation.addActionListener(actionPerformed);
}
class InformationFromFormOne implements ActionListener{
public void actionPerformed(ActionEvent e) {
if (e.getSource() == conferm){
String dateOfDeparture = (dateofDepartureTextField.getText());
String dateOfArrival = (dateofArrivalTextField.getText());
String cityFrom = (cityFromTextField.getText());
String cityTo = (cityToTextField.getText());
suggestion = new Suggestion(dateOfDeparture, dateOfArrival, true, cityFrom, cityTo);
setVisible(false);
form1.dispose();
}
if (e.getSource() == clearConfermation){
dateofArrivalTextField.setText(null);
dateofDepartureTextField.setText(null);
cityFromTextField.setText(null);
cityToTextField.setText(null);
}
}
}
}
My second form is
public class FormNum2 extends JFrame{
static JFrame form2 = new JFrame("form2");
public FormNum2() {
form2.setSize(1200,600);
//frame.setResizable(false);
form2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
form2.setLocationRelativeTo(null);
form2.setVisible(true);
}
}
Main class
public class Main extends Thread{
public static void main(String[] args) {
FormNum1 form1 = new FormNum1();
FormNum2 form2 = new FormNum2();
}
}
After the first frame processing set the second frame to visible, put FormNum2 .setVisible(true); to show the second form.
If you want to open the second window after the filling of the object in the first then you should call FormNum2 form2 = new FormNum2() after the object is filled. It seems like you would want to add this line after form1.dispose().

How to add listener event to JList elements which are added by DefaultListModel object?

I have created 2 JLists 'addGroupList' and 'addApkList'. I am adding elements to addGroupList using model.addElement(arrayList1.get(arrayList1.size()-1)); the thing is, I want to update addApkList based on selected value of addGroupList. For this, I'm trying to add event listener so that I can act upon something when list item is selected but the event is not trigerring.
What do I do to accomplish this?
following is the code I'm using.
model1 = new DefaultListModel();
model2 = new DefaultListModel();
addApkList = new JList(model1);
addGroupList = new JList(model2);
scrollPane1 = new JScrollPane();
scrollPane1.setViewportView(addApkList);
scrollPane2 = new JScrollPane();
scrollPane2.setViewportView(addGroupList);
this way i've defined JList.
in following way i've added elements to addGroupList
model1.addElement(arrayList1.get(arrayList1.size()-1));
and in following way I've added listener to it.
addGroupList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent lse) {
if (!lse.getValueIsAdjusting()) {
System.out.println("Selection trigerred");
}
}
});
There doesnt seem to happen any change with this code. what m i doing wrong?
I've also tried following
model1.addListDataListener(new ListDataListener() {
#Override
public void intervalAdded(ListDataEvent lde) {
System.out.println("ddddddddddd");
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void intervalRemoved(ListDataEvent lde) {
System.out.println("ddddddddddd");
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void contentsChanged(ListDataEvent lde) {
System.out.println("ddddddddddd");
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
In following way i've added elements to addGroupList
model1.addElement(arrayList1.get(arrayList1.size()-1));
No you haven't. model1 is the list model for addApkList not addGroupList:
addApkList = new JList(model1);
It should be model2.addElement(arrayList1.get(arrayList1.size()-1)).
In any case I suspect you're expecting for a ListSelectionEvent being fired when you just simply add an item to list model. That won't happen. You need to set the added item as the selected one:
Object item = arrayList1.get(arrayList1.size()-1);
model2.addElement(item);
addGroupList.setSelectedValue(item, true);
Take a look to JList.setSelectedValue(Object anObject, boolean shouldScroll) for further details.
I have created 2 JLists 'addGroupList' and 'addApkList'. I am adding
elements to addGroupList using
model.addElement(arrayList1.get(arrayList1.size()-1)); the thing is, I
want to update addApkList based on selected value of addGroupList. For
this, I'm trying to add event listener so that I can act upon
something when list item is selected but the event is not trigerring.
What do I do to accomplish this? following is the code I'm using.
for example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Testing extends JFrame {
private static final long serialVersionUID = 1L;
private DefaultListModel listModel = new DefaultListModel();
private DefaultListModel listModelEmpty = new DefaultListModel();
private JList list = new JList(listModel);
private JList listEmpty = new JList(listModelEmpty);
private JPanel panel = new JPanel(new GridLayout(1, 1));
private int currentSelectedRow = 0;
private int xX = 0;
public Testing() {
setLocation(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
for (int x = 0; x < 9; x++) {
listModel.addElement("" + x);
xX++;
}
JScrollPane sp = new JScrollPane(list);
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent lse) {
if (!lse.getValueIsAdjusting()) {
System.out.println("Selection trigerred");
}
}
});
JScrollPane spEmpty = new JScrollPane(listEmpty);
panel.add(spEmpty);
panel.add(sp);
add(panel, BorderLayout.CENTER);
JButton btn1 = new JButton("Reset Model CastingModel");
add(btn1, BorderLayout.NORTH);
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//list.clearSelection();
DefaultListModel model = (DefaultListModel) list.getModel();
model.removeAllElements();
for (int x = 0; x < 9; x++) {
model.addElement("" + (x + xX));
xX++;
}
list.setModel(model);
}
});
JButton btn2 = new JButton("Reset Model directly from Model");
add(btn2, BorderLayout.SOUTH);
btn2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//list.clearSelection();
listModel.removeAllElements();
for (int x = 0; x < 9; x++) {
listModel.addElement("" + (x + xX));
xX++;
}
}
});
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Testing().setVisible(true);
}
});
}
}

Printing String of JList Selections with ListSelectionListener in Java

fairly new to java here. I'm writing a GUI program of which I want to be able to append the strings (rather than the index number) of selected list items to a text area using a JButton. I am unaware of which java method would allow me to do this. When I use the getSelectedIndex method, it only allows me to append the index number, rather than the string value of the list item to my text area. If it is still unclear what I am asking, here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class FantasyInterface extends JFrame implements ActionListener{
private JList list1;
private JList list2;
private JLabel runningbacks;
private JButton addPlayer1;
private JButton addPlayer2;
private JTextArea text;
String lineSeparator = System.getProperty("line.separator");
private String[] rbs = {"Matt Forte", "Arian Foster", "Maurice Jones-Drew", "Adrian Peterson", "Ray Rice"};
FantasyTeam team1 = new FantasyTeam(5);
FantasyTeam team2 = new FantasyTeam(5);
public FantasyInterface(){
super("Fantasy Football Simulator");
// Set up listsPanel
JPanel listsPanel = new JPanel();
runningbacks = new JLabel("Running Backs:");
listsPanel.add(runningbacks);
list1 = new JList(rbs);
list1.setVisibleRowCount(5);
list1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
listsPanel.add(list1);
addPlayer1 = new JButton("Add To Team 1");
listsPanel.add(addPlayer1);
list2 = new JList(rbs);
list2.setVisibleRowCount(5);
list2.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
listsPanel.add(list2);
addPlayer2 = new JButton("Add To Team 2");
listsPanel.add(addPlayer2);
// Add formatted JPanels to Content Pane
getContentPane().add(listsPanel, BorderLayout.NORTH);
// Set up textPanel, where info will appear
JPanel textPanel = new JPanel();
text = new JTextArea(20, 20);
textPanel.add(text);
// Add formatted JPanels to Content Pane
getContentPane().add(text, BorderLayout.SOUTH);
ListSelectionListener listSelectionListener = new ListSelectionListener() {
public void valueChanged(ListSelectionEvent listSelectionEvent) {
//System.out.println("First index: " + listSelectionEvent.getFirstIndex());
//System.out.println(", Last index: " + listSelectionEvent.getLastIndex());
boolean adjust = listSelectionEvent.getValueIsAdjusting();
//System.out.println(", Adjusting? " + adjust);
if (!adjust) {
JList list = (JList) listSelectionEvent.getSource();
int selections[] = list.getSelectedIndices();
Object selectionValues[] = list.getSelectedValues();
for (int i = 0, n = selections.length; i < n; i++) {
if (i == 0) {
System.out.println(" Selections: ");
}
System.out.println(selections[i] + "/" + selectionValues[i] + " ");
}
}
}
};
list1.addListSelectionListener(listSelectionListener);
addPlayer1.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
Object srcObj = event.getSource();
if (srcObj == addPlayer1){
text.append(lineSeparator + list1.getSelectedIndex());
}
}
}
The last part,
if (srcObj == addPlayer1){
text.append(lineSeparator + list1.getSelectedIndex());
}
is where I am wondering if there is a method to get the selected index in string form. Thanks to anyone who helps!
Use:
if (!list1.isSelectionEmpty()) {
text.append(lineSeparator + list1.getModel().getElementAt(list1.getSelectedIndex()));
}

Array of ImageIcons, change contents of array on drag and drop

I have an array of ImageIcons, and I can drag and drop other Icons onto them to replace them. When I hit a button a new JFrame is created from the array of ImageIcons.
If I do this without dragging any other Icons on to the original array, it works. However once I drop a different imageicon into the array, I get an error when I hit the button.
I'm just wondering if this is even possible at all?
I've considered other approaches of using a JTable for the top panel, or trying to use an ArrayList, but I'm not too comfortable using them. If anyone has any opinion on how this should be done, please let me know!
I shortened this example as much as possible(at 200 lines it's not exactly short). But this is exactly what my problem is...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Properties;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;
import java.lang.String.*;
public class test extends JFrame {
JPanel storyPanel, rightStoryPanel, leftStoryPanel,centerStoryPanel, imageSelectPanel, CreatePanel, storyFramePanel, storycard;
TransferHandler handler;
MouseListener listener;
CardLayout cl3;
JLabel[] storyLabel = new JLabel[20];
JButton playStory, nextStory,addtargetbutton;
int count, start, i, j,stop, start1;
public test(){
CreatePanel = new JPanel(new BorderLayout());
storyPanel = new JPanel(new BorderLayout());
rightStoryPanel = new JPanel(new GridLayout(6,1));
leftStoryPanel = new JPanel(new GridLayout(6,1));
centerStoryPanel = new JPanel();
JScrollPane centerscroll = new JScrollPane(centerStoryPanel);
addtargetbutton = new JButton("Add Another Image Slot");
addtargetbutton.addActionListener(new createbuttons());
playStory = new JButton("Play your story!");
leftStoryPanel.add(playStory);
playStory.addActionListener(new createbuttons());
leftStoryPanel.add(addtargetbutton);
imageSelectPanel = new JPanel(new FlowLayout());
storyPanel.add(rightStoryPanel,BorderLayout.EAST);
storyPanel.add(leftStoryPanel, BorderLayout.WEST);
storyPanel.add(centerscroll, BorderLayout.CENTER);
CreatePanel.add(storyPanel, BorderLayout.NORTH);
CreatePanel.add(imageSelectPanel, BorderLayout.CENTER);
count= 3;
start= 0;
stop = 0;
start1= 0;
ImageSelection();
targetpanel();
getContentPane().add(CreatePanel);
}//End Create}
public void ImageSelection(){
int i = 0;
int j = 0;
TransferHandler handler = new TransferHandler("icon") {
#Override
public boolean canImport(TransferSupport support) {
return super.canImport(support)
&& support.getComponent().getParent() != imageSelectPanel;}
};
MouseListener listener = new MouseAdapter(){
public void mousePressed(MouseEvent e){
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
System.out.println(e);}
}; // Drag & Drop mouse
try{
String imagePath = "";
BufferedImage[] CreateImagesFromDB = new BufferedImage[40];
JLabel[] ImageLabel = new JLabel[40];
while (count > start1) {
i = 1;
CreateImagesFromDB[i] = ImageIO.read(new File("one.jpg"));
ImageLabel[i] = new JLabel(new ImageIcon(CreateImagesFromDB[i]));
imageSelectPanel.add(ImageLabel[i]);
ImageLabel[i].addMouseListener(listener);
ImageLabel[i].setTransferHandler(handler);
i++;
start1++;
}
}//EndTRY
catch(Exception e){
System.out.println("CATCH"+ e);
}//end catch
}
public void targetpanel(){
TransferHandler handler = new TransferHandler("icon") {
#Override
public boolean canImport(TransferSupport support) {
return super.canImport(support)
&& support.getComponent().getParent() != imageSelectPanel;
}
};
MouseListener listener = new MouseAdapter(){
public void mousePressed(MouseEvent e){
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
};
BufferedImage[] storyImages = new BufferedImage[20];
try{
while(count > start){
storyImages[j] = ImageIO.read(new File("TargetImg.jpg"));
storyLabel[j] = new JLabel(new ImageIcon(storyImages[j]));
centerStoryPanel.add(storyLabel[j]);
storyLabel[j].addMouseListener(listener);
storyLabel[j].setTransferHandler(handler);
j++;
start++;
centerStoryPanel.revalidate();
//validate();
System.out.println("J in Loop is: "+j );
}//end while Loop
//System.out.println("J is equalto: "+j);
} catch(Exception e) {};
}// End TargetPanel
public void storyFrame (JLabel[] storyArray){
int i = 0;
storyFramePanel = new JPanel(new BorderLayout());
nextStory = new JButton("Next Image");
nextStory.addActionListener(new createbuttons());
storycard = new JPanel();
cl3 = new CardLayout();
storycard.setLayout(cl3);
JPanel[] storyImgPanel = new JPanel[20];
JLabel[] imglab = new JLabel[20];
storyImgPanel[i]= new JPanel();
while( i < j){
storyImgPanel[i].add(new JLabel(storyArray[i].getIcon()));
storycard.add(storyImgPanel[i], ""+i);
i++;
}
JFrame story = new JFrame("Story");
story.setSize(500,500);
storyFramePanel.add(storycard, BorderLayout.CENTER);
storyFramePanel.add(nextStory, BorderLayout.EAST);
story.add(storyFramePanel);
cl3.show(storycard, "1");
story.setVisible(true);
}
public static void main(String[] args){
System.out.println("Application Running");
JFrame mainframe = new test();
mainframe.setTitle("Let Me Know!");
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.setSize(1000,1000);
mainframe.setVisible(true);
}
class createbuttons implements ActionListener{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == addtargetbutton){
count++;
targetpanel();
System.out.println("Trying to add another TargetImg, count = "+count);
}
if(e.getSource() == playStory){
storyFrame(storyLabel);
}
if(e.getSource() == nextStory){
cl3.next(storycard);
System.out.println("button pressed");
}
}
}
}
I figured it out:
Firstly, each time you call targetpanel(), you create a new instance of storyLabel, but then you are behaving like you have it already populated from the previous calls. So the result is:
first call:
storyLabel[0] = something;
storyLabel[1] = something;
storyLabel[2] = something;
storyLabel[3] = null;
storyLabel[4] = null.... etc
second call (you added another image slot):
storyLabel[0] = null;
storyLabel[1] = null;
storyLabel[2] = null;
storyLabel[3] = something;
storyLabel[4] = null.... etc
So when you use this array in the storyboard, you get NullPointerException.
You need to create the array only once. So remove storyLabel = new JLabel[20] from targetpanel() and initialize the array in the constructor, or even better in the declaration:
...
CardLayout cl3;
JLabel[] storyLabel = new JLabel[20];
JButton playStory, nextStory, addtargetbutton;
...
Secondly, when displaying the images using the storyFrame(), you change the parent of the supplied JLabels and they subsequently disappear from the storyPanel. You must create new instances of JLabel for the storyboard.
In storyFrame(), instead of
storyImgPanel[i].add(storyArray[i]);
write
storyImgPanel[i].add(new JLabel(storyArray[i].getIcon()));
If I do all this the program is working.
There's not enough in your code to really give you a good answer. One of these two lines:
storyImgPanel[i].add(storyArray[i]);
storycard.add(storyImgPanel[i], ""+i);
would be my guess. The component you're adding in is null (either storyArray[i] or storyImgPanel[i]. Probably the first, since you're creating the second in the loop.
If you could post all your code, it would be easier. Or, (preferably) post a self-contained small example.

Categories