ArrayList , JFrame, JLabel - java

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

Related

How to add text and delete text using GUI in Java

I am creating a dumb phone (like old traditional phone) and I'm using GUI programming. I need help with dialing the numbers. I don't know how to get the numbers to pop up on the display and stay there, and also use the delete button to delete the numbers that is up on the display too. I will post a youtube link so you can see a sample run.
I am currently stuck on passing the text from the button of each number that should display the number, however it's displaying the text of the button. I also, don't know how to keep the number there when other buttons are pressed without it being reset.
Here is my code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.*;
public class DumbPhone extends JFrame
{
private static final long serialVersionUID = 1L;
private static final int WIDTH = 300;
private static final int HEIGHT = 500;
private static final String CALL_BUTTON_TEXT = "Call";
private static final String TEXT_BUTTON_TEXT = "Text";
private static final String DELETE_BUTTON_TEXT = "Delete";
private static final String CANCEL_BUTTON_TEXT = "Cancel";
private static final String SEND_BUTTON_TEXT = "Send";
private static final String END_BUTTON_TEXT = "End";
private static final String CALLING_DISPLAY_TEXT = "Calling...";
private static final String TEXT_DISPLAY_TEXT = "Enter text...";
private static final String ENTER_NUMBER_TEXT = "Enter a number...";
private JTextArea display;
private JButton topMiddleButton;
private JButton topLeftButton;
private JButton topRightButton;
private JButton[] numberButtons;
private JButton starButton;
private JButton poundButton;
private boolean isNumberMode = true;
private String lastPressed = "";
private int lastCharacterIndex = 0;
private Date lastPressTime;
public DumbPhone()
{
setTitle("Dumb Phone");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createContents();
setVisible(true);
topLeftButton.setEnabled(false);
}
private void createContents()
{
//create JPanel, and JTextArea display
JPanel panel = new JPanel(new GridLayout(5,3));
display = new JTextArea();
display.setPreferredSize(new Dimension(280, 80));
display.setFont(new Font("Helvetica", Font.PLAIN, 32));
display.setLineWrap(true);
display.setEnabled(false);
panel.add(display);
//create JButtons
topLeftButton = new JButton(DELETE_BUTTON_TEXT);
topMiddleButton = new JButton((CALL_BUTTON_TEXT));
topRightButton = new JButton((TEXT_BUTTON_TEXT));
numberButtons = new JButton[10];
numberButtons[1] = new JButton("<html><center>1<br></center></html>");
numberButtons[2] = new JButton("<html><center>2<br>ABC</center></html>");
numberButtons[3] = new JButton("<html><right>3<br>DEF</right></html>");
numberButtons[4] = new JButton("<html><center>4<br>GHI</center></html>");
numberButtons[5] = new JButton("<html><center>5<br>JKL</center></html>");
numberButtons[6] = new JButton("<html><center>6<br>MNO</center></html>");
numberButtons[7] = new JButton("<html><center>7<br>PQRS</center></html>");
numberButtons[8] = new JButton("<html><center>8<br>TUV</center></html>");
numberButtons[9] = new JButton("<html><center>9<br>WXYZ</center></html>");
numberButtons[0] = new JButton("<html><center>0<br>space</center></html>");
poundButton = new JButton("#");
starButton = new JButton("*");
//add JButtons to buttons JPanel
panel.add(topLeftButton);
panel.add(topMiddleButton);
panel.add(topRightButton);
panel.add(numberButtons[1]);
panel.add(numberButtons[2]);
panel.add(numberButtons[3]);
panel.add(numberButtons[4]);
panel.add(numberButtons[5]);
panel.add(numberButtons[6]);
panel.add(numberButtons[7]);
panel.add(numberButtons[8]);
panel.add(numberButtons[9]);
panel.add(starButton);
panel.add(numberButtons[0]);
panel.add(poundButton);
//add Listener instance (inner class) to buttons
topLeftButton.addActionListener(new Listener());
topMiddleButton.addActionListener(new Listener());
topRightButton.addActionListener(new Listener());
//JButton[] array = new JButton[10];
for (int i = 0; i < numberButtons.length; i++)
{
numberButtons[i].addActionListener(new Listener());
numberButtons[i] = new JButton(String.valueOf(i));
}
starButton.addActionListener(new Listener());
poundButton.addActionListener(new Listener());
//add display and buttons to JFrame
setLayout(new BorderLayout());
add(display, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
}
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == topLeftButton)
{
if(lastPressTime == null)
{
display.setText(ENTER_NUMBER_TEXT);
}
else
{
topLeftButton.setEnabled(true);
lastCharacterIndex--;
lastPressed = lastPressTime.toString();
}
}
else if(e.getSource() == topMiddleButton)
{
if(lastPressTime == null || lastCharacterIndex == 0)
{
display.setText(ENTER_NUMBER_TEXT);
}
else
{
display.setText(CALLING_DISPLAY_TEXT);
}
}
else if(e.getSource() == topRightButton)
{
if(lastPressTime == null || lastCharacterIndex == 0)
{
display.setText(TEXT_DISPLAY_TEXT);
}
else
{
display.setText(CALLING_DISPLAY_TEXT);
}
}
else
{
topLeftButton.setEnabled(true);
if (e.getSource() instanceof JButton)
{
//String text = ((JButton) e.getSource()).getText();
display.setText(lastPressed + " f" + numberButtons[lastCharacterIndex].getText());
}
}
Date currentPress = new Date();
long currentTime = currentPress.getTime();
if(lastPressTime != null)
{
//long lastPressTime = lastPressTime.getTime();
//subtract lastPressTime from currentPress time to find amount of time elapsed since last button pressed.
}
lastPressTime = currentPress;
String buttonLetters = ""; // Parse Letter from button (e.g "abc").
//update lastCharacterIndex.
lastCharacterIndex++;
lastCharacterIndex = lastCharacterIndex % buttonLetters.length();
}
}
for example, if I push the button 2, instead of giving me "2", it will give me < html>< center>2ABC < / center >< / html >
Therefore, I need help with
Having the numberButtons, when pushed to show the numbers that were pushed.
Be able to delete those numbers.
Here is the link to the sample run: https://www.youtube.com/watch?v=evmGWlMSqqg&feature=youtu.be
Try starting the video 20 seconds in.
to delete the number, you can use the labelname.setText("")
At a basic level, you simply want to maintain the "numbers" separately from the UI. This commonly known as a "model". The model lives independently of the UI and allows the model to be represented in any number of possible ways based on the needs of the application.
In your case, you could use a linked list, array or some other simple sequential based list, but the easiest is probably to use a StringBuilder, as it provides the functionality you require (append and remove) and can make a String very simply.
So, the first thing you need to do is create an instance of model as an instance level field;
private StringBuilder numbers = new StringBuilder(10);
this will allow the buffer to be accessed any where within the instance of the class.
Then you need to update the model...
else
{
topLeftButton.setEnabled(true);
if (e.getSource() instanceof JButton)
{
String text = numberButtons[lastCharacterIndex].getText();
numbers.append(text);
}
}
To remove the last character you can simply use something like...
if (numbers.length() > 0) {
numbers.deleteCharAt(numbers.length() - 1);
}
Then, when you need to, you update the UI using something like...
display.setText(numbers.toString());
Now, this is just basic concepts, you will need to take the ideas and apply it to your code base

Get the number of checkboxes in Swing

I've a swing with some 50 check boxes, and a sample code for 3 is below.
JCheckBox checkboxOne = new JCheckBox("One");
JCheckBox checkboxTwo = new JCheckBox("Two");
JCheckBox checkboxThree = new JCheckBox("Three");
// add these check boxes to the container...
// add an action listener
ActionListener actionListener = new ActionHandler();
checkboxOne.addActionListener(actionListener);
checkboxTwo.addActionListener(actionListener);
checkboxThree.addActionListener(actionListener);
 
// code of the action listener class
 
class ActionHandler implements ActionListener {
    #Override
    public void actionPerformed(ActionEvent event) {
        JCheckBox checkbox = (JCheckBox) event.getSource();
        if (checkbox == checkboxOne) {
            System.out.println("Checkbox #1 is clicked");
        } else if (checkbox == checkboxTwo) {
            System.out.println("Checkbox #2 is clicked");
        } else if (checkbox == checkboxThree) {
            System.out.println("Checkbox #3 is clicked");
        }
    }
}
Here i want to loop through the 50 checkboxes like creating an ArrayList of the available checkboxes and loop them to check which is checked. I'm unable to understand on how to create a ArrayList of checkboxes.
I referred to Array of checkboxes in java, but i'm unable to understand how do i use it?
Please let me know how can do this.
Create an ArrayList of JCheckBox and add them in order.
Then, you can use the indexOf() function to retrieve the number, like so:
public class TestFrame extends JFrame {
public TestFrame() {
setLayout(new GridLayout());
setSize(500, 500);
JCheckBox checkboxOne = new JCheckBox("One");
JCheckBox checkboxTwo = new JCheckBox("Two");
JCheckBox checkboxThree = new JCheckBox("Three");
final ArrayList<JCheckBox> checkBoxes = new ArrayList<>();
add(checkboxOne);
add(checkboxTwo);
add(checkboxThree);
checkBoxes.add(checkboxOne);
checkBoxes.add(checkboxTwo);
checkBoxes.add(checkboxThree);
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
JCheckBox checkbox = (JCheckBox) event.getSource();
int index = checkBoxes.indexOf(checkbox) + 1;
System.out.println("Checkbox #" + index + " is clicked");
}
};
checkboxOne.addActionListener(actionListener);
checkboxTwo.addActionListener(actionListener);
checkboxThree.addActionListener(actionListener);
}
public static void main(String[] args) {
TestFrame frame = new TestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Please note that this is adaptation of your code. This example was made as close as possible to your code so that the only modifications present are supposed to reflect the point I'm trying to get across.
Edit
Since you modified your question and a new one was made, here goes the second part of the answer:
and in my action listener, I was trying to get the checked boxes values, but it is throwing null as name and though I've checked, the output shows as not selected.
Modify your code to use getText() instead of getName(), such as:
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println(checkBoxes.size());
for (int i = 0; i < checkBoxes.size(); i++) {
if (checkBoxes.get(i).isSelected()) {
System.out.println(" Checkbox " + i + " and " + checkBoxes.get(i).getText() + " is selected");
} else {
System.out.println(
" Checkbox " + i + " and " + checkBoxes.get(i).getText() + " is noooooot selected");
}
}
}
});
In order to define an ArrayList with CheckBoxes please refer to following example:
List<JCheckBox> chkBoxes = new ArrayList<JCheckBox>();
Add your JCheckBox elements to the ArrayList using standard approach, for example:
JCheckBox chkBox1 = new JCheckBox();
chkBoxes.add(chkBox1);
Interatve over the list and carry out check if selected using JCheckBox method #.isSelected() as follows:
for(JCheckBox chkBox : chkBoxes){
chkBox.isSelected(); // do something with this!
}
If you need to get all checkboxes from actual existing Frame / Panel, you can use getComponents() method and one by one deside if it's checkbox (not sure if getComponents is supported by all containers)
eg.:
Component[] comps = jScrollPane.getComponents();
ArrayList<JCheckBox> chckBoxes= new ArrayList<JCheckBox>();
for(Component comp : comps) {
if(comp instanceof JCheckBox) {
chckBoxes.add((JCheckBox) comp);
}
}
(Founded # Get all swing components in a container )

Making a button write to one JTextField in an Array

I'm working on a TextTwist java implementation and I'm currently working on the GUI. I was wondering if some of you Swing geniuses could help me out. I'm trying to do a GUI where whenever a button is clicked, the text of that button is written into the first empty textField below it. I'm having trouble thinking through how to do it. What I've tried so far makes the first button click fill all the TextFields.
Any help or pointers in the right direction would be great.
private void makeButtonLayout() {
this.charArray = new char[6];
ArrayList<Character> charArrayList = new ArrayList<Character>();
this.charArray = this.randomString.toCharArray();
for(char tempCharacter : this.charArray){
charArrayList.add(tempCharacter);
}
for (int i = 0; i< 6; i++){
JButton letterButton = new JButton();
Character buttonCharacter = charArrayList.get(i);
charArrayList.remove(i);
String letterString = buttonCharacter.toString();
letterButton.setText(letterString);
this.letterButtonsArray.add(letterButton);
}
for (final JButton currentButton : this.letterButtonsArray){
this.buttonPanel.add(currentButton);
currentButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
int i = 0;
currentButton.setVisible(false);
JTextField temporaryTextField = new JTextField();
String temporaryString = currentButton.getText();
temporaryTextField.setText(temporaryString);
if(textFieldArray.get(i).getText().isEmpty()){
textFieldArray.get(i).setText(temporaryString);
return;
}else{
i++;
return;
}
}
});
}
}
I think you method is really strange. You mixed initialization code and execution code. Do it like this:
for (final JButton currentButton : this.letterButtonsArray){
this.buttonPanel.add(currentButton);
currentButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
currentButton.setVisible(false);
String temporaryString = currentButton.getText();
for(int i = 0; i < textFieldArray.size(); i++)
JTextField elem = textFieldArray.get(i);
if(elem.getText().equals("")){ // or if you don't want spaces do: elem.getText().trim().equals("");
elem.setText(temporaryString);
break;
}
}
}
});
}

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