Information from first form to second form swing java - 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().

Related

How can I set up a JFrame button to open another JFrame, and then receive information once the second jframe is closed?

This is part of a project for school, and I'm stuck and need someone to bounce ideas off of. I have a game where there is an option to sign up or sign in for a machine-local game so a record can be kept of the person's scores. The game is run from a base GUI JFrame, and I want to make buttons to bring up secondary windows for the person to sign in or sign up, before closing out of them. I need to pass the validated username back to the initial GUI/game class so I can store it for the following game so the game score can be added under that user. I just need to pass the username back and I'm not sure how to go about it. This is the main GUI code up to where I'm having my issue:
public class MathFactsGUI extends JFrame
{
// instance variables
private JTextField problemJTextField, answerJTextField;
private JLabel equalJLabel;
private JButton additionJButton, multiplicationJButton;
private JButton signupJButton, signinJButton;
private JButton submitJButton;
private JLabel scoreJLabel,resultJLabel;
//private JButton reviewButton;
private String username;
private Userbase userbase;
private JLabel introJLabel;
Quiz quiz;
/**
* Constructor for objects of class MathFactsGUI
*/
public MathFactsGUI()
{
super("Math Facts Quiz");
userbase = Userbase.getUserbase();
username = "guest";
/* code here has been removed to be abbreviated */
// Action listener for buttons
additionJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
quiz = new Quiz('+');
problemJTextField.setText(quiz.getCurrentProblem());
additionJButton.setEnabled(false);
multiplicationJButton.setEnabled(false);
signupJButton.setEnabled(false);
signinJButton.setEnabled(false);
}
});
multiplicationJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
quiz = new Quiz('x');
problemJTextField.setText(quiz.getCurrentProblem());
additionJButton.setEnabled(false);
multiplicationJButton.setEnabled(false);
signupJButton.setEnabled(false);
signinJButton.setEnabled(false);
}
});
signinJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JDialo
}
});
signupJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
MathFactsSignUpGUI signUpGUI = new MathFactsSignUpGUI();
gui.setVisible(true);
}
});
}
This is the JFrame I wrote for the sign-up button:
public class MathFactsSignUpGUI extends JDialog {
private JTextField usernameJTextField, userPassJTextField, userFirstNameJTextField;
private JLabel usernameJLabel, userPassJLabel, userFirstNameJLabel;
private JButton submitJButton;
private String username;
private String userPass;
private String userFirstName;
public MathFactsSignUpGUI(){
usernameJLabel = new JLabel("Username:");
usernameJTextField = new JTextField();
userPassJLabel = new JLabel("Password:");
userPassJTextField = new JTextField();
userFirstNameJLabel = new JLabel("Player First Name:");
userFirstNameJTextField = new JTextField();
Box usernameBox = Box.createHorizontalBox();
usernameBox.add(usernameJLabel);
usernameBox.add(usernameJTextField);
Box userPassBox = Box.createHorizontalBox();
userPassBox.add(userPassJLabel);
userPassBox.add(userPassJTextField);
Box userFirstBox = Box.createHorizontalBox();
userFirstBox.add(userFirstNameJLabel);
userFirstBox.add(userFirstNameJTextField);
submitJButton = new JButton("Submit");
submitJButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
username = usernameJTextField.getText();
userPass = userPassJTextField.getText();
userFirstName = userFirstNameJTextField.getText();
if (!checkValid(username) || !checkValid(userPass) || !checkValid(userFirstName)){
JOptionPane.showMessageDialog(null, "All fields must have values.");
} else if (Userbase.getUserbase().userExist(username)==true){
JOptionPane.showMessageDialog(null, "Username is taken, please choose another.");
} else {
Userbase.getUserbase().addUser(username, new User(username, userPass, userFirstName));
MathFactsGUI.setUsername(username);
}
}
});
JPanel mfSignUp = new JPanel()
mfSignUp.setLayout(new GridLayout(0,1));
mfSignUp.add(usernameBox);
mfSignUp.add(userPassBox);
mfSignUp.add(userFirstBox);
mfSignUp.add(submitJButton);
}
public String signIn(){
return username;
}
public boolean checkValid(String a){
if (a == null || a.length() == 0){
return false;
} else {
return true;
}
}
}```
I was thinking of implementing a WindowListener action for when the sign-up/sign-in frames close, but I'm not sure that will work. I was also looking into JDialog, but I'm not sure if it has the layout/text verification properties I need.
Use a JOptionPane. It will simplify your layout without the need for creating a separate JFrame and easily pass values back to wherever it was called from. You can then make it check for valid username when you click OK.
Try this site. It gives a good rundown with example images
First you need to understand that this is an object, so you can create some global variables which will contains this information(username,password,Nickname), i recommend to pull info from MathFactsSignUpGUI by using ScheduledExecutorService. It will pull info from this sign up gui in every 100ms, than it will destroy itself, here is an example:
MathFactsSignUpGUI su = new MathFactsSignUpGUI ();
su.setVisible(true);
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(new Runnable(){
public void run(){
if(!su.username.isEmpty() && !su.userPass.isEmpty() && !su.userFirstName.isEmpty() ){
if(su.isLogin){ //if player is loggining
//do something here
}else{//if user is registered
//do something here
}
System.out.println("Check complete");
service.shutdown();//to destroy this service after recieving the data
}
}
}, 100, TimeUnit.MICROSECONDS);

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

How do I update a JLabel in a JPanel?

I am having trouble getting the image on my JLabel to update in the JPanel. I do not see what the problem is. I have tried removing the existing JLabel and adding a new one to the JPanel but that doesn't work. Here is the code I am trying to get the animaiton to work on. My key listener works fine so I am sure there is some problem in this class:
import javax.swing.*;
import java.awt.event.*;
public class Character extends JPanel{
//Constructs array that holds running frames
static ImageIcon running[] = new ImageIcon[19];
static int i = 0;
//Contstructs label that holds the current image frame
static JLabel characterLabel = new JLabel();
//Creates imageicon to be returned to the character and stored in characterLabel
static ImageIcon character = new ImageIcon();
Timer runningTimer = new Timer(300, new RunningListener());
public Character() {
running[0] = new ImageIcon("running 1.png");
running[1] = new ImageIcon("running 2.png");
running[2] = new ImageIcon("running 3.png");
running[3] = new ImageIcon("running 4.png");
running[4] = new ImageIcon("running 5.png");
running[5] = new ImageIcon("running 6.png");
running[6] = new ImageIcon("running 7.png");
running[7] = new ImageIcon("running 8.png");
running[8] = new ImageIcon("running 9.png");
running[9] = new ImageIcon("running 10.png");
running[10] = new ImageIcon("running 11.png");
running[11] = new ImageIcon("running 12.png");
running[12] = new ImageIcon("running 13.png");
running[13] = new ImageIcon("running 14.png");
running[14] = new ImageIcon("running 15.png");
running[15] = new ImageIcon("running 16.png");
running[16] = new ImageIcon("running 17.png");
running[17] = new ImageIcon("running 18.png");
running[18] = new ImageIcon("running 19.png");
characterLabel.setIcon(running[0]);
this.add(characterLabel);
}
private void refreshCharacter(){
this.remove(characterLabel);
characterLabel.setIcon(running[i]);
this.add(characterLabel);
i++;
if (i > 18){
i = 0;
}
}
private class RunningListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
refreshCharacter();
}
}
}
I suppose that this JPanel may be the problem aswell but I doubt it:
import javax.swing.*;
//Panel that manages the game
public class GamePanel extends JPanel{
//Adds stuff to GamePanel to send to Frame
public GamePanel(){
this.addKeyListener(new KeyInput());
this.add(new Character());
}
}
Here is the key listener:
import java.awt.event.*;
//Listens for key actions
public class KeyInput implements KeyListener{
//Constructs character
Character c = new Character();
public void keyPressed(KeyEvent evt) {
int key = evt.getKeyCode();
//When the right key is pressed, start the timer that starts the running animation
if(key == KeyEvent.VK_RIGHT){
c.runningTimer.start();
}
}
public void keyReleased(KeyEvent evt){
int key = evt.getKeyCode();
//When the right key is released, the timer that starts the running animation is stopped
if(key == KeyEvent.VK_RIGHT){
c.runningTimer.stop();
}
}
//There is no use for this... it just has to be there
public void keyTyped(KeyEvent evt){
}
}
and here is the frame:
import javax.swing.*;
public class Frame{
//Creates window and calls to GamePanel
public static void main (String[]args){
GamePanel gamePanel = new GamePanel();
JFrame window = new JFrame("Game");
window.add(gamePanel);
window.setLocation(50,50);
window.setSize(1000,650);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
gamePanel.requestFocus();
}
}
If you're trying to change a displayed image, if you can avoid it, don't remove JLabels or components, but rather swap a JLabel's Icon. If you're not trying to change an image, but do something different, then please give us more detail on your desired behavior, since all you tell us is that you're trying "animation", and that's somewhat broad.
e.g.,
private void refreshCharacter() {
i++;
i %= running.length;
characterLabel.setIcon(running[i]);
}

error: method addActionListener in class AbstractButton cannot be applied to given types

I'm trying to add music to my program as to make it sound like a commercial so to say, lol it's in regards to a Pizza company called PizzaPalooza but I am getting a few errors such as
error: method addActionListener in class AbstractButton cannot be applied to given types
JPizza.java:77: error: incompatible types
if(source = playButton)
^
required: boolean
found: Object
JPizza.java:69: error: method addActionListener in class AbstractButton cannot be applied to given types;
playButton.addActionListener(this);
^
required: ActionListener
found: JPizza
just a few examples, for these I have tried to create a new object of source
But I do not understand what it means by method addActionListener in class AbstractButton cannot be applied to given types
For these would I have to redo the entire thing and extend the ActionListener? or can I do it another way? I'm having a difficult time understanding the JApplets.
Thanks in Advance!
this is the part of the code that is throwing the problems:
public void init()
{
Container Con = getContentPane();
con.setLayout (new FlowLayout());
con.add(listenLabel);
con.add(playButton);
con.add(stopButton);
playButton.addActionListener(this);
stopButton.addActionListener(this);
music = getAudioClip(getCodeBase(),"business.mid");
}
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if(source = playButton)
music.loop();
else
music.stop();
}
and this is the rest of my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class JPizza extends JFrame implements ItemListener
{
FlowLayout flow = new FlowLayout();
JLabel companyName = new JLabel("PizzaPalooza");
JComboBox<String> sizeBox = new JComboBox<String>();
JLabel sizeList = new JLabel("Size List");
JComboBox<String> toppingBox = new JComboBox<String>();
JLabel toppingList = new JLabel("Topping List");
JTextField totPrice = new JTextField(10);
JLabel orderName = new JLabel("Name of Order");
JTextField oName = new JTextField(15);
JLabel listenLabel = new JLabel("Listen to our theme!");
JButton playButton = new JButton("Play");
JButton stopButton = new JButton("Stop");
AudioClip music;
int totalPrice = 0;
int sizeNum, toppingNum;
int sPrice, tPrice, sumPrice;
int[] sizePrice = {0,7,9,11,14};
int[] toppingPrice = {0,0,1,1,1,1};
String output;
public JPizza()
{
super("PizzaPalooza");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(flow);
add(companyName);
companyName.setFont(new Font("Ariel", Font.BOLD, 20));
sizeBox.addItem("None");
sizeBox.addItem("Small");
sizeBox.addItem("Medium");
sizeBox.addItem("Large");
sizeBox.addItem("Extra large");
toppingBox.addItem("None");
toppingBox.addItem("Cheese");
toppingBox.addItem("Sausage");
toppingBox.addItem("Pepperoni");
toppingBox.addItem("Green pepper");
toppingBox.addItem("Onion");
add(sizeList);
add(sizeBox);
sizeBox.addItemListener(this);
add(toppingList);
add(toppingBox);
toppingBox.addItemListener(this);
add(totPrice);
add(oName);
add(orderName);
}
public static void main(String[] arguments)
{
JPizza pframe = new JPizza();
pframe.setSize(380,200);
pframe.setVisible(true);
}
public void init()
{
Container Con = getContentPane();
con.setLayout (new FlowLayout());
con.add(listenLabel);
con.add(playButton);
con.add(stopButton);
playButton.addActionListener(this);
stopButton.addActionListener(this);
music = getAudioClip(getCodeBase(),"business.mid");
}
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if(source = playButton)
music.loop();
else
music.stop();
}
public void itemStateChanged(ItemEvent list)
{
Object source = list.getSource();
if (source == sizeBox)
{
sizeNum = sizeBox.getSelectedIndex();
sPrice = sizePrice[sizeNum];
sumPrice = sPrice + tPrice;
output = "Total Price $" + sumPrice;
totPrice.setText(output);
}
else if (source == toppingBox)
{
toppingNum = toppingBox.getSelectedIndex();
tPrice = toppingPrice[toppingNum];
sumPrice = sPrice + tPrice;
output = "Total Price $" + sumPrice;
totPrice.setText(output);
}
}
}
First error
if(source = playButton)
is an assignment, not a boolean comparator. It yields the outcome of the assignment, which in this case is a Button object. Instead, you need to write:
if(source == playButton)
Notice the double-equals.
Second error
JPizza is not an ActionListener - you need to let it extend this interface if you want to use it as one:
public class JPizza extends JFrame implements ActionListener

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