Overwriting pre-defined array - java

I have an array named columnsArray[] it is pre-defined to contain 6 Strings. When i run my method columns() it should overwrite the columnsArray[] with a new array of Strings that the user selects by checking boxes.
The way i have tried to implement this adds each box checked to an arrayList and then convert the arrayList to array[]. However when the code is run, columnsArray is not overwritten.
Here is my code so far:
public class EditView {
private JFrame frame;
JCheckBox appNo, name, program, date, pName, country, fileLoc, email, uni,
countryUni, degree, classification, funding, supervisor,
rejectedBy, misc;
public ArrayList<String> columnArrLst;
public String[] columnsArray = { "Application Number", "Name", "Program",
"Date", "Project Name", "Country of Uni" };
public EditView() {
}
public void makeFrame() {
frame = new JFrame("Edit View");
frame.setPreferredSize(new Dimension(300, 350));
Container contentPane = frame.getContentPane();
contentPane.setLayout(new GridLayout(0, 2, 20, 20));
appNo = new JCheckBox("appNo");
name = new JCheckBox("Name");
program = new JCheckBox("Program");
date = new JCheckBox("Date");
pName = new JCheckBox("Project Title");
country = new JCheckBox("Country of Origin");
fileLoc = new JCheckBox("Current File Location");
// countryRef = new JCheckBox("");
email = new JCheckBox("Email address");
uni = new JCheckBox("Last University");
countryUni = new JCheckBox("Country of last Uni");
degree = new JCheckBox("Degree");
classification = new JCheckBox("Degree Classification");
funding = new JCheckBox("funding");
supervisor = new JCheckBox("Supervisor");
rejectedBy = new JCheckBox("Rejected By");
misc = new JCheckBox("Miscelaneous");
contentPane.add(appNo);
contentPane.add(name);
contentPane.add(program);
contentPane.add(date);
contentPane.add(pName);
contentPane.add(country);
contentPane.add(fileLoc);
contentPane.add(email);
contentPane.add(uni);
contentPane.add(countryUni);
contentPane.add(degree);
contentPane.add(classification);
contentPane.add(supervisor);
contentPane.add(rejectedBy);
contentPane.add(misc);
JButton changeView = new JButton("Change View");
changeView.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
columns();
frame.dispose();
}
});
contentPane.add(changeView);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public String[] columns() {
columnArrLst = new ArrayList<String>();
if (appNo.isSelected()) {
columnArrLst.add("AppNo");
}
if (name.isSelected()) {
columnArrLst.add("Name");
}
if (date.isSelected()) {
columnArrLst.add("Date");
}
if (fileLoc.isSelected()) {
columnArrLst.add("file Location");
}
if (country.isSelected()) {
columnArrLst.add("Country");
}
if (email.isSelected()) {
columnArrLst.add("Email");
}
if (uni.isSelected()) {
columnArrLst.add("University");
}
if (countryUni.isSelected()) {
columnArrLst.add("Country of Uni");
}
if (degree.isSelected()) {
columnArrLst.add("Degree");
}
if (classification.isSelected()) {
columnArrLst.add("Degree Classification");
}
if (pName.isSelected()) {
columnArrLst.add("ProjectName");
}
if (funding.isSelected()) {
columnArrLst.add("Funding");
}
if (supervisor.isSelected()) {
columnArrLst.add("Supervisor");
}
if (rejectedBy.isSelected()) {
columnArrLst.add("rejected By");
}
if (misc.isSelected()) {
columnArrLst.add("Miscelaneous");
}
columnsArray = new String[columnArrLst.size()];
columnArrLst.toArray(columnsArray);
return columnsArray;
}
}
Any ideas why it isn't overwriting? Thanks for any help.

Try this one
columnsArray = columnArrLst.toArray(new String[columnArrLst.size()]);
Hope it helps.

replace 2nd last line [columnArrLst.toArray(columnsArray);] with following.
columnsArray = columnArrLst.toArray(columnsArray);

There is nothing wrong with your code, array contents are actually changing when you use it as
EditView e = new EditView();
e.makeFrame();
and insert a print loop after
columnArrLst.toArray(columnsArray);
Note that your JFrame is displayed in a different Thread. If you want to check the values, you need to explicitly wait until the button is pressed to see them changed. If you are doing something like:
EditView e = new EditView();
e.makeFrame();
for (String s : e.columnsArray) { System.out.println(s);}
This will print the old values, since the printing thread is actually a different one and prints the values immediately.

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

Determining the right answer in my quiz

So my current quiz generates panes and buttons which go in the panes, there is a array which holds all the answers and questions as you can see below
int total = 0;
int counter = 0;
JTabbedPane quiz = new JTabbedPane();
Problem[] probList = new Problem[6];
JLabel lblOutput;
JPanel finishQuiz = new JPanel();
JButton finish = new JButton("Finish Quiz");
public QuizEasy(){
problems();
CreateTabs();
setTitle("Easy Questions");
setSize(680,300);
getContentPane().add(quiz);
ButtonHandler phandler = new ButtonHandler();
finish.addActionListener(phandler);
setVisible(true);
}
public void CreateTabs() {
JPanel question = null;
JLabel lbQuestion = null;
JButton ansA = null;
JButton ansB = null;
JButton ansC = null;
for (int i=0;i<probList.length;i++) {
question = new JPanel();
lbQuestion = new JLabel(probList[i].getQuestion());
question.add(lbQuestion);
ansA = new JButton(probList[i].getAnsA());
ansB = new JButton(probList[i].getAnsB());
ansC = new JButton(probList[i].getAnsC());
lblOutput = new JLabel("Please click on your answer");
question.add(ansA);
question.add(ansB);
question.add(ansC);
question.add(lblOutput);
quiz.addTab("Question " + (i+1), question);
}
quiz.addTab("Finish Quiz", finishQuiz);
finishQuiz.add(finish);
}
public void problems(){
probList[0] = new Problem(
"What is the meaning of life?",
"Only god knows",
"42",
"huh?",
"B"
);
probList[1] = new Problem(
"What level woodcutting do you need to cut oaks in runescape",
"15",
"20",
"99",
"C"
);
probList[2] = new Problem(
"Who has recieved the highest amount of oscars?",
"Walt Disney",
"You",
"Leonardo Di Caprio",
"A"
);
probList[3] = new Problem(
"What is the most spoken native tounge in the world?",
"English",
"Kek",
"Mandarin",
"C"
);
probList[4] = new Problem(
"Deva was the Roman name for which British city?",
"Bristol",
"Chester",
"London",
"B"
);
probList[5] = new Problem(
"Which herb is one of the main ingredients of Pesto Sauce?",
"Basil",
"Chester",
"London",
"A"
);
}
class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
showSummary();
}
}
public void showSummary(){
JOptionPane.showMessageDialog(null,"You have completed the quiz, here are your results" + counter
);
System.exit(0);
}
public static void main(String[] args) {
QuizEasy tab = new QuizEasy();
}
}
I'm not quite sure how to make the buttons correspond to the right answer, any advice? I've tried to mess around with counters and such but I didn't manage to get it working in the end. any help is appreciated!
You can assign a JButton to each position in the array.
JButton button1 = new JButton("Button 1");
Then you need an action listener which goes like this
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source instanceof JButton) {
JButton btn = (JButton)source;
// Go ahead and do what you like
}
}
});

ArrayList , JFrame, JLabel

I am trying to create and simple program that has the user input 4 fields using the JFrame and textfields. Save those into a class. Put that class into an ArrayList (So they have the option to delete / or add more "classes" to it later). Then display all the contents of the ArrayList on one Frame.
I got the four fields to work I believe , but the part where the ArrayList contents are supposed to be displayed is not working ( I get a blank frame ).
this is my add into the arrayList ..
public void newEntryFrame()
{
JFrame entryFrame = new JFrame("Passafe");
entryFrame.setVisible(true);
entryFrame.setSize(500, 500);
entryFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
entryFrame.setLocationRelativeTo(null);
entryFrame.setLayout(new FlowLayout());
header.setFont(new Font("Serif", Font.BOLD, 16));
entryFrame.add(header);
entryFrame.add(nameLabel);
entryFrame.add(nametf);
entryFrame.add(usernameLabel);
entryFrame.add(usernametf);
entryFrame.add(passwordLabel);
entryFrame.add(passwordtf);
entryFrame.add(descriptionLabel);
entryFrame.add(descriptiontf);
entryFrame.add(enterButton);
enterButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if(source == enterButton)
{
name = nametf.getText();
description = descriptiontf.getText();
username = usernametf.getText();
password = passwordtf.getText();
totalEntries++;
JOptionPane.showMessageDialog(null, "SAVED");
}
else if(source == okButton)
{
JOptionPane.showMessageDialog(null, "Ok Button Works");
}
}
this is what I have to display the arrayList.
public void viewEntryFrame()
{
JFrame viewFrame = new JFrame("Passafe");
viewFrame.setSize(500, 500);
viewFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
viewFrame.setLocationRelativeTo(null);
viewFrame.setLayout(new FlowLayout());
viewFrame.add(listHeader);
newEntry tempView = new newEntry();
for(int i = 0; i < totalEntries; ++i)
{
tempView = entries.get(i);
viewFrame.add(tempView.display);
}
viewFrame.add(okButton);
okButton.addActionListener(this);
viewFrame.setVisible(true);
}
I might be doing this completely wrong if so could you point me in the right direction.
I don't think you ever called setContentPane() A JFrame has only one component in the main part of it. You have to create a JPanel to which you can add all of the components you want, then add that to your JFrame.
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add(/**whatever you want in your JFrame**/);
//...
panel.add(/**whatever you want in your JFrame**/);
frame.setContentPane(panel);
You never seem to be adding anything to your entries list...
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if(source == enterButton)
{
name = nametf.getText();
description = descriptiontf.getText();
username = usernametf.getText();
password = passwordtf.getText();
totalEntries++;
// Nope, nothing here...
JOptionPane.showMessageDialog(null, "SAVED");
}
//...
}
Also, this is very dangrouos...
newEntry tempView = new newEntry();
for(int i = 0; i < totalEntries; ++i)
{
tempView = entries.get(i);
viewFrame.add(tempView.display);
}
Rather the relying on the actual side of the ArrayList, you relying on some other variable, which may or may not equal the actual size, instead you should be using ArrayList#size, for example
for(int i = 0; i < entries.size(); ++i)
{
newEntry tempView = entries.get(i);
viewFrame.add(tempView.display);
}
Or if you're using Java 5+...
for(newEntry tempView : enties)
{
viewFrame.add(tempView.display);
}

Change background of JLabel in runtime using reflection

I need to change background of JLabels dynamically.
I've 70 JLabels in a class. All JLabels represent some specific items. The items names are same as the variable of JLabel. The Sold Items names are saved in database. If I run a query that will return an array of the sold items. The sold items that are same as the JLabel should change the background. Rest will not change.
I've got the variables of all fields like this:
Field fld[] = BlueLine.class.getDeclaredFields();
for (int i = 0; i < fld.length; i++)
{
System.out.println("Variable Name is : " + fld[i].getName());
}
How can I cast my fld to a JLabel and change background of the JLabel when certain condition meets ? for example:
if(fld[i] == label5){
label5.setBackground.(Color.red);
} // or something like this. ?
Any outline will help.
Currently you're just looking at the fields themselves - you're interested in the values of those fields. For example:
Object value = fld[i].get(target); // Or null for static fields
if (value == label5) {
...
}
Here target is a reference to the object whose fields you want to get the values from. For static fields, just use null, as per the comment.
It's not at all clear that all of this is a good idea, however - problems which can be solved with reflection are often better solved in a different way. We don't really have enough context to advise you of specifics at the moment, but I would recommend that you at least try to think of cleaner designs.
Try it using Jcomponent.putClientProperty() and Jcomponent.getClientProperty().
Steps to follow:
First set the name of the JLabel same as its variable name
Put it as client property of JPanel where JLabel is added
Get it back using client property from JPanel using name of JLabel
Note: you can access it by using Field.getName() as defined in your question.
Sample code :
final JFrame frame = new JFrame();
final JPanel panel = new JPanel();
panel.addContainerListener(new ContainerListener() {
#Override
public void componentRemoved(ContainerEvent e) {
String name = e.getChild().getName();
if (name != null) {
System.out.println(name + " removed");
panel.putClientProperty(name, null);
}
}
#Override
public void componentAdded(ContainerEvent e) {
String name = e.getChild().getName();
if (name != null) {
System.out.println(name + " added");
panel.putClientProperty(name, e.getChild());
}
}
});
MyLabels myLabels = new MyLabels();
panel.add(myLabels.getProduct1());
panel.add(myLabels.getProduct2());
panel.add(myLabels.getProduct3());
JButton btn = new JButton("Product1 and Product3 are sold");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String[] soldItems = new String[] { "Product1", "Product3" };
for (String soldItem : soldItems) {
Object obj = panel.getClientProperty(soldItem);
if (obj instanceof JLabel) {
((JLabel) obj).setForeground(Color.RED);
}
}
}
});
panel.add(btn);
frame.add(panel);
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
MyLabels.java:
class MyLabels {
private JLabel Product1;
private JLabel Product2;
private JLabel Product3;
public MyLabels() {
Product1 = new JLabel("Product1");
Product1.setName(Product1.getText());
Product2 = new JLabel("Product2");
Product2.setName(Product2.getText());
Product3 = new JLabel("Product3");
Product3.setName(Product3.getText());
}
public JLabel getProduct1() {
return Product1;
}
public void setProduct1(JLabel product1) {
Product1 = product1;
}
public JLabel getProduct2() {
return Product2;
}
public void setProduct2(JLabel product2) {
Product2 = product2;
}
public JLabel getProduct3() {
return Product3;
}
public void setProduct3(JLabel product3) {
Product3 = product3;
}
}

ListSelectionListener and CardLayout

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(...);
}
}
}
}

Categories