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
}
}
});
Related
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().
I'm doing a programming exercise.
Miles and kilometer converter.(both case)
However, If I input number and press "Enter", nothing happened.
I don't know what part I need to modify... :(
Help me please..
public class Grid1 extends JFrame{
private JLabel label1,label2;
private JTextField textField1,textField2;
private Container container;
private GridLayout grid1;
// set up GUI
public Grid1(){
super( "Miles to Km / Km to Mile" );
grid1 = new GridLayout( 2, 2 );
container = getContentPane();
container.setLayout( grid1 );
label1 = new JLabel("Mile");
container.add(label1);
textField1 = new JTextField("");
container.add( textField1 );
label2 = new JLabel("Kilometer");
container.add(label2);
textField2 = new JTextField( "" );
container.add( textField2 );
TextFieldHandler handler = new TextFieldHandler();
textField1.addActionListener(handler);
JButton submit = new JButton("Submit");
submit.addActionListener(handler);
setSize(300, 100);
setVisible(true);
}
private class TextFieldHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
float miles = 0, km = 0;
String string = "";
if(event.getSource() == textField1){
string = "textField1: " + event.getActionCommand();
km = miles * 1.609344f;
}else if(event.getSource() == textField2){
string = "textField2: " + event.getActionCommand();
miles = km / 1.609344f;
}
}
}
public static void main( String args[]){
Grid1 application = new Grid1();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
} // end class GridLayoutDemo
You should remove handler from variable textField1 if you need to update data from button click. And in handler class you shold store data into result field/label.
In your case it looks like:
private class TextFieldHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
// In both cases you should get value from textField,
// parse it and store computed values in another field
float miles = 0, km = 0;
try {
if(event.getSource() == textField1){
// Value form field stored in String, you should parse Integer from it
miles = Integer.parseInt(textField1.getText());
km = miles * 1.609344f;
textField2.setText(String.format("%f", km));
}else if(event.getSource() == textField2){
// Value form field stored in String, you should parse Integer from it
km = Integer.parseInt(textField2.getText());
miles = km / 1.609344f;
textField1.setText(String.format("%f", km));
}
} catch(NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Wrong value", "Input error");
}
}
}
Since you are working with a single frame and a single button, I would suggest to set the following line:
frame.getRootPane().setDefaultButton(submitButton);
You can set a default button on each frame you control, the button you set in this method, will automatically listen to enter and invoke your actionPerformed.
You can also use a KeyListener and extend the functionality for your button in this case or in future exercises or projects.
Hope it helps.
All the best... and happy coding :)
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(...);
}
}
}
}
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.
I have an array of ImageIcons, and I can drag and drop other Icons onto them to replace them. When I hit a button a new JFrame is created from the array of ImageIcons.
If I do this without dragging any other Icons on to the original array, it works. However once I drop a different imageicon into the array, I get an error when I hit the button.
I'm just wondering if this is even possible at all?
I've considered other approaches of using a JTable for the top panel, or trying to use an ArrayList, but I'm not too comfortable using them. If anyone has any opinion on how this should be done, please let me know!
I shortened this example as much as possible(at 200 lines it's not exactly short). But this is exactly what my problem is...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Properties;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;
import java.lang.String.*;
public class test extends JFrame {
JPanel storyPanel, rightStoryPanel, leftStoryPanel,centerStoryPanel, imageSelectPanel, CreatePanel, storyFramePanel, storycard;
TransferHandler handler;
MouseListener listener;
CardLayout cl3;
JLabel[] storyLabel = new JLabel[20];
JButton playStory, nextStory,addtargetbutton;
int count, start, i, j,stop, start1;
public test(){
CreatePanel = new JPanel(new BorderLayout());
storyPanel = new JPanel(new BorderLayout());
rightStoryPanel = new JPanel(new GridLayout(6,1));
leftStoryPanel = new JPanel(new GridLayout(6,1));
centerStoryPanel = new JPanel();
JScrollPane centerscroll = new JScrollPane(centerStoryPanel);
addtargetbutton = new JButton("Add Another Image Slot");
addtargetbutton.addActionListener(new createbuttons());
playStory = new JButton("Play your story!");
leftStoryPanel.add(playStory);
playStory.addActionListener(new createbuttons());
leftStoryPanel.add(addtargetbutton);
imageSelectPanel = new JPanel(new FlowLayout());
storyPanel.add(rightStoryPanel,BorderLayout.EAST);
storyPanel.add(leftStoryPanel, BorderLayout.WEST);
storyPanel.add(centerscroll, BorderLayout.CENTER);
CreatePanel.add(storyPanel, BorderLayout.NORTH);
CreatePanel.add(imageSelectPanel, BorderLayout.CENTER);
count= 3;
start= 0;
stop = 0;
start1= 0;
ImageSelection();
targetpanel();
getContentPane().add(CreatePanel);
}//End Create}
public void ImageSelection(){
int i = 0;
int j = 0;
TransferHandler handler = new TransferHandler("icon") {
#Override
public boolean canImport(TransferSupport support) {
return super.canImport(support)
&& support.getComponent().getParent() != imageSelectPanel;}
};
MouseListener listener = new MouseAdapter(){
public void mousePressed(MouseEvent e){
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
System.out.println(e);}
}; // Drag & Drop mouse
try{
String imagePath = "";
BufferedImage[] CreateImagesFromDB = new BufferedImage[40];
JLabel[] ImageLabel = new JLabel[40];
while (count > start1) {
i = 1;
CreateImagesFromDB[i] = ImageIO.read(new File("one.jpg"));
ImageLabel[i] = new JLabel(new ImageIcon(CreateImagesFromDB[i]));
imageSelectPanel.add(ImageLabel[i]);
ImageLabel[i].addMouseListener(listener);
ImageLabel[i].setTransferHandler(handler);
i++;
start1++;
}
}//EndTRY
catch(Exception e){
System.out.println("CATCH"+ e);
}//end catch
}
public void targetpanel(){
TransferHandler handler = new TransferHandler("icon") {
#Override
public boolean canImport(TransferSupport support) {
return super.canImport(support)
&& support.getComponent().getParent() != imageSelectPanel;
}
};
MouseListener listener = new MouseAdapter(){
public void mousePressed(MouseEvent e){
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
};
BufferedImage[] storyImages = new BufferedImage[20];
try{
while(count > start){
storyImages[j] = ImageIO.read(new File("TargetImg.jpg"));
storyLabel[j] = new JLabel(new ImageIcon(storyImages[j]));
centerStoryPanel.add(storyLabel[j]);
storyLabel[j].addMouseListener(listener);
storyLabel[j].setTransferHandler(handler);
j++;
start++;
centerStoryPanel.revalidate();
//validate();
System.out.println("J in Loop is: "+j );
}//end while Loop
//System.out.println("J is equalto: "+j);
} catch(Exception e) {};
}// End TargetPanel
public void storyFrame (JLabel[] storyArray){
int i = 0;
storyFramePanel = new JPanel(new BorderLayout());
nextStory = new JButton("Next Image");
nextStory.addActionListener(new createbuttons());
storycard = new JPanel();
cl3 = new CardLayout();
storycard.setLayout(cl3);
JPanel[] storyImgPanel = new JPanel[20];
JLabel[] imglab = new JLabel[20];
storyImgPanel[i]= new JPanel();
while( i < j){
storyImgPanel[i].add(new JLabel(storyArray[i].getIcon()));
storycard.add(storyImgPanel[i], ""+i);
i++;
}
JFrame story = new JFrame("Story");
story.setSize(500,500);
storyFramePanel.add(storycard, BorderLayout.CENTER);
storyFramePanel.add(nextStory, BorderLayout.EAST);
story.add(storyFramePanel);
cl3.show(storycard, "1");
story.setVisible(true);
}
public static void main(String[] args){
System.out.println("Application Running");
JFrame mainframe = new test();
mainframe.setTitle("Let Me Know!");
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.setSize(1000,1000);
mainframe.setVisible(true);
}
class createbuttons implements ActionListener{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == addtargetbutton){
count++;
targetpanel();
System.out.println("Trying to add another TargetImg, count = "+count);
}
if(e.getSource() == playStory){
storyFrame(storyLabel);
}
if(e.getSource() == nextStory){
cl3.next(storycard);
System.out.println("button pressed");
}
}
}
}
I figured it out:
Firstly, each time you call targetpanel(), you create a new instance of storyLabel, but then you are behaving like you have it already populated from the previous calls. So the result is:
first call:
storyLabel[0] = something;
storyLabel[1] = something;
storyLabel[2] = something;
storyLabel[3] = null;
storyLabel[4] = null.... etc
second call (you added another image slot):
storyLabel[0] = null;
storyLabel[1] = null;
storyLabel[2] = null;
storyLabel[3] = something;
storyLabel[4] = null.... etc
So when you use this array in the storyboard, you get NullPointerException.
You need to create the array only once. So remove storyLabel = new JLabel[20] from targetpanel() and initialize the array in the constructor, or even better in the declaration:
...
CardLayout cl3;
JLabel[] storyLabel = new JLabel[20];
JButton playStory, nextStory, addtargetbutton;
...
Secondly, when displaying the images using the storyFrame(), you change the parent of the supplied JLabels and they subsequently disappear from the storyPanel. You must create new instances of JLabel for the storyboard.
In storyFrame(), instead of
storyImgPanel[i].add(storyArray[i]);
write
storyImgPanel[i].add(new JLabel(storyArray[i].getIcon()));
If I do all this the program is working.
There's not enough in your code to really give you a good answer. One of these two lines:
storyImgPanel[i].add(storyArray[i]);
storycard.add(storyImgPanel[i], ""+i);
would be my guess. The component you're adding in is null (either storyArray[i] or storyImgPanel[i]. Probably the first, since you're creating the second in the loop.
If you could post all your code, it would be easier. Or, (preferably) post a self-contained small example.