Java lottery game efficiency, swing [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I believe this is not the kind of question I should be asking here so I apologize in advance. I have an exam in 2 days and the teacher that was supposed to give me a lesson clearing out all of my questions had to cancel, so now I have no one to ask. I am resolving an exam from last year, and one of the questions is to make a little java program where we pretty much simulate a lottery game of 6 numbers. My question is about efficiency, the exam is written on paper and I feel like if I was to write everything I typed on the computer I would not have enough time, we have 90 minutes and this is only one of the problems, swing is not my strong point so that leads me to think that I could write this in much fewer lines. The public instance variable 'key' is there to simulate a method from another class that generates a random key that we do not need to implement. We are only allowed to use FlowLayout, BorderLayout, CardLayout and GridLayout.
public class Grupo2A extends JFrame {
private JPanel panelCont = new JPanel();
private JPanel panelUser = new JPanel();
private JPanel panelResult = new JPanel();
private JPanel p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11;
private JLabel l1, l2, l3, l4, l5, l6, l7, l8, l9;
private JTextField t1, t2, t3, t4, t5, t6;
private JButton b1, b2, b3;
private int[] userKey = new int[6];
private CardLayout cl = new CardLayout();
private GridLayout gl1 = new GridLayout(8, 1);
private GridLayout gl2 = new GridLayout(3, 1);
public int[] key = {12, 13, 16, 22, 33, 40};
private static final int WINDOW_HEIGHT1 = 600;
private static final int WINDOW_HEIGHT2 = 150;
private static final int WINDOW_WIDTH1 = 300;
public Grupo2A() {
panelCont.setLayout(cl);
panelCont.add(panelUser, "panelUser");
panelCont.add(panelResult, "panelResult");
panelUser.setLayout(gl1);
panelResult.setLayout(gl2);
setSize(WINDOW_WIDTH1, WINDOW_HEIGHT1);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
add(panelCont);
createComponents();
createPanelUser();
createPanelResult();
cl.show(panelCont, "panelUser");
setVisible(true);
}
private void createComponents() {
l1 = new JLabel("Lottery");
l2 = new JLabel("1");
l3 = new JLabel("2");
l4 = new JLabel("3");
l5 = new JLabel("4");
l6 = new JLabel("5");
l7 = new JLabel("6");
t1 = new JTextField(10);
t2 = new JTextField(10);
t3 = new JTextField(10);
t4 = new JTextField(10);
t5 = new JTextField(10);
t6 = new JTextField(10);
b1 = new JButton("Play");
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
int[] userKey = new int[6];
userKey[0] = Integer.parseInt(t1.getText());
userKey[1] = Integer.parseInt(t2.getText());
userKey[2] = Integer.parseInt(t3.getText());
userKey[3] = Integer.parseInt(t4.getText());
userKey[4] = Integer.parseInt(t5.getText());
userKey[5] = Integer.parseInt(t6.getText());
setUserKey(userKey);
l8.setText("You got " + correctNumbers() + " numbers");
l9.setText("The key was: " + Arrays.toString(key));
cl.show(panelCont, "panelResult");
setSize(WINDOW_WIDTH1, WINDOW_HEIGHT2);
}
});
b2 = new JButton("Clear");
b2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
t1.setText("");
t2.setText("");
t3.setText("");
t4.setText("");
t5.setText("");
t6.setText("");
}
});
p1 = new JPanel();
p2 = new JPanel();
p3 = new JPanel();
p4 = new JPanel();
p5 = new JPanel();
p6 = new JPanel();
p7 = new JPanel();
p8 = new JPanel();
p9 = new JPanel();
p10 = new JPanel();
p11 = new JPanel();
}
private void createPanelUser() {
p1.add(l1);
panelUser.add(p1);
p2.add(l2);
p2.add(t1);
panelUser.add(p2);
p3.add(l3);
p3.add(t2);
panelUser.add(p3);
p4.add(l4);
p4.add(t3);
panelUser.add(p4);
p5.add(l5);
p5.add(t4);
panelUser.add(p5);
p6.add(l6);
p6.add(t5);
panelUser.add(p6);
p7.add(l7);
p7.add(t6);
panelUser.add(p7);
p8.add(b1);
p8.add(b2);
panelUser.add(p8);
}
private void createPanelResult() {
l8 = new JLabel("You got " + correctNumbers() + " numbers");
l9 = new JLabel("The key was: " + Arrays.toString(key));
b3 = new JButton("Ok");
b3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
cl.show(panelCont, "panelUser");
setSize(WINDOW_WIDTH1, WINDOW_HEIGHT1);
}
});
p9.add(l8);
p10.add(l9);
p11.add(b3);
panelResult.add(p9);
panelResult.add(p10);
panelResult.add(p11);
}
private int correctNumbers() {
int cont = 0;
for (int i = 0; i < userKey.length; i++) {
for (int j = 0; j < key.length; j++) {
if (userKey[i] == key[j]) {
cont++;
break;
}
}
}
System.out.println(cont);
return cont;
}
private void setUserKey(int[] userKey) {
this.userKey = userKey;
}
}

I really hope you aren't asked to write a UI on paper in an exam. That would be a very silly way to test your knowledge given it doesn't resemble anything you'd ever need to do in practice.
There are a lot of ways your code could be improved in readability. But with respect to being clear and succinct, a key principle is DRY: don't repeat yourself.
For example, you have declared and initialised 6 panels, labels and fields with almost identical code. That's nearly always a sign you should be encapsulating your code in a separate class. Something like:
private class NumberPanel extends JPanel {
private final JLabel label;
private final JTextField field;
public NumberPanel(int place) {
super(new BorderLayout());
this.label = new JLabel(Integer.toString(place));
this.field = new JTextField(10);
add(label, BorderLayout.WEST);
add(field, BorderLayout.EAST);
}
public int getValue() {
return Integer.valueOf(field.getText());
}
}
private final List<NumberPanel> numberPanels =
IntStream.rangeClosed(1, 6)
.mapToObj(NumberPanel::new).collect(toList());

Related

I'm using JTabbedPane for my quiz program, not sure how to get my buttons to display the answers

As it says, I'm not sure how to loop through the array so it would display the question in each pane, I got 8 panes and each of them should contain a question, I've managed to get it working for one (question 1 displays first entry in the array) but not the others.
Any suggestions?
int total = 0;
int counter = 0;
JPanel question1 = new JPanel();
JPanel question2 = new JPanel();
JPanel question3 = new JPanel();
JPanel question4 = new JPanel();
JPanel question5 = new JPanel();
JPanel question6 = new JPanel();
JPanel question7 = new JPanel();
JPanel question8 = new JPanel();
JTabbedPane quiz = new JTabbedPane();
JLabel lblQuestion1 = new JLabel();
JLabel lblQuestion2 = new JLabel();
JLabel lblQuestion3 = new JLabel();
JLabel lblQuestion4 = new JLabel();
JLabel lblQuestion5 = new JLabel();
JLabel lblQuestion6 = new JLabel();
JLabel lblQuestion7 = new JLabel();
JLabel lblQuestion8 = new JLabel();
JButton question1A = new JButton("Answer A");
JButton question1B = new JButton("Answer B");
JButton question1C = new JButton("Answer C");
JButton question2A = new JButton("Answer A");
JButton question2B = new JButton("Answer B");
JButton question2C = new JButton("Answer C");
JButton question3A = new JButton("Answer A");
JButton question3B = new JButton("Answer B");
JButton question3C = new JButton("Answer C");
Problem[] probList = new Problem[5];
public QuizEasy(){
createLabel();
createTabs();
questionsEasy();
problems();
nextQuestion();
updateScreen();
setTitle("Easy Questions");
setSize(680,300);
getContentPane().add(quiz);
JButton finish = new JButton("Finish Quiz");
question8.add(finish);
ButtonHandler phandler = new ButtonHandler();
finish.addActionListener(phandler);
setVisible(true);
}
public void nextQuestion(){
//go forward one question if possible
counter++;
if (counter >= probList.length){
counter = probList.length - 1;
} // end if
updateScreen();
}
public void updateScreen(){
Problem p = probList[counter];
lblQuestion1.setText(p.getQuestion());
question1A.setText(p.getAnsA());
question1B.setText(p.getAnsB());
question1C.setText(p.getAnsC());
lblQuestion2.setText(p.getQuestion());
question2A.setText(p.getAnsA());
question2B.setText(p.getAnsB());
question2C.setText(p.getAnsC());
}
public void questionsEasy(){
question1.add(question1A);
question1.add(question1B);
question1.add(question1C);
question2.add(question2A);
question2.add(question2B);
question2.add(question2C);
question3.add(question3A);
question3.add(question3B);
question3.add(question3C);
}
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",
"Ailien",
"Mandarin",
"C"
);
probList[4] = new Problem(
"What is the airspeed velocity of an unladen swallow?",
"42 beats per second",
"10 miles per hour",
"African or European?",
"C"
);
}
public void createLabel(){
/*JLabel easyQuestion1 = new JLabel();
easyQuestion1.setText("What level do you need in the game Runescape to cut oak?");
question1.add(easyQuestion1);*/
lblQuestion1 = new JLabel("Question");
lblQuestion2 = new JLabel("Question");
lblQuestion3 = new JLabel("Question");
lblQuestion4 = new JLabel("Question");
lblQuestion5 = new JLabel("Question");
lblQuestion6 = new JLabel("Question");
lblQuestion7 = new JLabel("Question");
lblQuestion8 = new JLabel("Question");
question1.add(lblQuestion1);
question2.add(lblQuestion2);
question3.add(lblQuestion3);
question4.add(lblQuestion4);
question5.add(lblQuestion5);
question6.add(lblQuestion6);
question7.add(lblQuestion7);
question8.add(lblQuestion8);
}
public void createTabs(){
quiz.addTab("Question 1", question1);
quiz.addTab("Question 2", question2);
quiz.addTab("Question 3", question3);
quiz.addTab("Question 4", question4);
quiz.addTab("Question 5", question5);
quiz.addTab("Question 6", question6);
quiz.addTab("Question 7", question7);
quiz.addTab("Question 8", question8);
}
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"
);
System.exit(0);
}
public static void main(String[] args) {
QuizEasy tab = new QuizEasy();
}
}
To make things easier you could create a method called CreateTabs which would build every tab based on your list of problems(probList). See code below:
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());
question.add(ansA);
question.add(ansB);
question.add(ansC);
quiz.addTab("Question " + (i+1), question);
}
}
In the QuizEasy constructor you would have something like:
public QuizEasy() {
problems();
CreateTabs();
...
}

Best way to pass values from JTextField into a method?

Currently working on a BMR/TDEE calculator. This calculator consists of taking the users age, gender, weight and height, and uses this information to calculate a BMR and TDEE value. I've created a GUI for this, and my final step is to do the actual calculations. (Some minor changes left to do i.e. changing the height panel but thats irrelevant to this question).
What is the best way to pass instance variables into static methods? My JTextField's are instance variables within my class, and I have two methods to calculate BMR and TDEE respectively (static methods).
Code is posted below.
The variables I need to use are pretty much all the textField ones, and these need to be passed into calcBMR() and calcTDEE(). My initial idea was to make all of these variables static and just use getText() and plug these values into the formula I'm using, which goes something along the lines of:
10 x weight (kg) + 6.25 x height (cm) - 5 x age (y) + 5.
Does this way sound feasible or is there a better way given my code? Any advice on how to do this efficiently is appreciated.
public class BmrCalcv2 extends JFrame {
// Frames and main panels
static JFrame mainFrame;
static JPanel mainPanel;
static JPanel combinedGAHWpanel; // combines genderPanel, agePanel, heightPanel, weightPanel - this
// is a BorderLayout, whereas
// gender/agePanel are FlowLayouts.
static JPanel weightHeightPanel; // Combines weight and height panel into out flowlayout panel, which is then combined into the above borderlayout panel
// Image components
static JPanel imgPanel;
private JLabel imgLabel;
private JLabel activityLevelHelp;
// Menu-bar components
static JMenuBar menuBar;
static JMenu saveMenu, optionMenu, helpMenu;
// Age components
static JPanel agePanel;
private JLabel ageLabel;
private JLabel yearsLabel;
private JTextField ageTextField;
// Gender components
static JPanel genderPanel;
private JLabel genderLabel;
private JRadioButton genderMale;
private JRadioButton genderFemale;
// Height components
static JPanel heightPanel;
private JLabel heightLabel;
private JTextField heightCMField;
private JLabel heightFTLabel;
private JLabel heightINCHLabel;
private JTextField heightFTField;
private JTextField heightINCHField;
private JToggleButton cmButton;
private JToggleButton feetButton;
// Weight components
static JPanel weightPanel;
private JLabel weightLabel;
private JTextField weightField;
private JToggleButton kgButton;
private JToggleButton lbButton;
// TDEE and BMR Components
static JPanel tdeePanel;
static JPanel tdeeBMRPanel;
static JPanel activityLevelPanel;
static JPanel bmrTDEEValuesPanel;
static JPanel bmrValuePanel;
static JPanel tdeeValuePanel;
private JLabel tdeeQuestionLabel;
private JLabel activityLevelLabel;
private JComboBox activityLevelBox;
private JRadioButton tdeeYes;
private JRadioButton tdeeNo;
private JLabel bmrLabel;
private JLabel tdeeLabel;
private JButton calculate;
// Default values for gender/weight/height and other variables
String[] activityLevels = {"Sedentary", "Lightly Active", "Moderately Active", "Very Active", "Extra Active"};
String genderSelection = "M";
String weightSelection = "kg";
String heightSelection = "cm";
String tdeeSelection = "no";
String ageValue;
String weightValue;
String heightValue;
static String bmrValue = "N/A";
static String tdeeValue = "N/A";
public BmrCalcv2(String title) {
// Main JFrame
setTitle("BMR/TDEE Calculator");
mainPanel = new JPanel();
// All JPanel declarations
menuBar = new JMenuBar();
imgPanel = new JPanel();
agePanel = new JPanel();
genderPanel = new JPanel();
heightPanel = new JPanel();
weightPanel = new JPanel();
weightHeightPanel = new JPanel(new BorderLayout());
combinedGAHWpanel = new JPanel(new BorderLayout()); // Create a new panel used to combine
// genderPanel, agePanel, weightPanel, heightPanel below
tdeeBMRPanel = new JPanel(new BorderLayout());
tdeePanel = new JPanel();
activityLevelPanel = new JPanel();
bmrTDEEValuesPanel = new JPanel(new BorderLayout());
bmrValuePanel = new JPanel();
tdeeValuePanel = new JPanel();
// Image panel declaration
imgLabel = new JLabel(new ImageIcon("filesrc//mainlogo.png"));
activityLevelHelp = new JLabel(new ImageIcon("filesrc//question-mark.png"));
imgPanel.add(imgLabel);
// JPanel layout managers
agePanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
genderPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
// Menu JComponents
saveMenu = new JMenu("Save");
optionMenu = new JMenu("Options");
helpMenu = new JMenu("Help");
menuBar.add(saveMenu);
menuBar.add(optionMenu);
menuBar.add(helpMenu);
// Age JComponents
ageLabel = new JLabel("Age:");
yearsLabel = new JLabel("<html><i>years</i><html>");
ageTextField = new JTextField(5);
agePanel.add(ageLabel);
agePanel.add(ageTextField);
agePanel.add(yearsLabel);
// Gender JComponents
genderLabel = new JLabel("Gender:");
genderMale = new JRadioButton("Male", true);
genderFemale = new JRadioButton("Female");
genderPanel.add(genderLabel);
genderPanel.add(genderMale);
genderPanel.add(genderFemale);
ButtonGroup genderGroup = new ButtonGroup(); // groups male and female radio buttons together so that only one can be selected
genderGroup.add(genderMale);
genderGroup.add(genderFemale);
genderMale.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String genderSelection = "M";
}
});
genderFemale.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String genderSelection = "F";
}
});
// Height JComponents
heightLabel = new JLabel("Height:");
heightCMField = new JTextField(4);
heightFTField = new JTextField(3);
heightFTLabel = new JLabel("ft");
heightINCHLabel = new JLabel("inch");
heightINCHField = new JTextField(3);
cmButton = new JToggleButton("cm", true);
feetButton = new JToggleButton("feet");
heightPanel.add(heightLabel);
ButtonGroup heightGroup = new ButtonGroup();
heightGroup.add(cmButton);
heightGroup.add(feetButton);
heightPanel.add(heightCMField);
heightPanel.add(heightFTField);
heightPanel.add(heightFTLabel);
heightPanel.add(heightINCHField);
heightPanel.add(heightINCHLabel);
heightPanel.add(cmButton);
heightPanel.add(feetButton);
heightFTField.setVisible(false);
heightFTLabel.setVisible(false);
heightINCHField.setVisible(false);
heightINCHLabel.setVisible(false);
cmButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
heightSelection = "cm";
heightINCHField.setVisible(false);
heightFTField.setVisible(false);
heightFTLabel.setVisible(false);
heightINCHLabel.setVisible(false);
heightCMField.setVisible(true);
weightPanel.revalidate();
weightPanel.repaint();
}
});
feetButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
heightSelection = "feet";
heightINCHField.setVisible(true);
heightFTField.setVisible(true);
heightFTLabel.setVisible(true);
heightINCHLabel.setVisible(true);
heightCMField.setVisible(false);
weightPanel.revalidate();
weightPanel.repaint();
}
});
// Weight JComponents
weightLabel = new JLabel("Weight:");
weightField = new JTextField(4);
kgButton = new JToggleButton("kg", true);
lbButton = new JToggleButton("lbs");
weightPanel.add(weightLabel);
weightPanel.add(weightField);
weightPanel.add(kgButton);
weightPanel.add(lbButton);
ButtonGroup weightGroup = new ButtonGroup();
weightGroup.add(kgButton);
weightGroup.add(lbButton);
kgButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
weightSelection = "kg";
}
});
lbButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
weightSelection = "lb";
}
});
// tdee JComponents
tdeeQuestionLabel = new JLabel("Calculate TDEE Also?");
tdeeYes = new JRadioButton("Yes");
tdeeNo = new JRadioButton("No", true);
ButtonGroup tdeeButton = new ButtonGroup();
tdeeButton.add(tdeeYes);
tdeeButton.add(tdeeNo);
tdeePanel.add(tdeeQuestionLabel);
tdeePanel.add(tdeeYes);
tdeePanel.add(tdeeNo);
// activitylevel JComponents
activityLevelLabel = new JLabel("Activity Level: ");
activityLevelBox = new JComboBox(activityLevels);
activityLevelBox.setSelectedIndex(0);
activityLevelPanel.add(activityLevelLabel);
activityLevelPanel.add(activityLevelBox);
activityLevelPanel.add(activityLevelHelp);
activityLevelBox.setEnabled(false);
activityLevelHelp
.setToolTipText("<html><b>Sedentary:</b> little or no exercise, deskjob<<br /><b>Lightly Active:</b> little exercise/sports 1-3 days/week<br /><b>Moderately active:</b> moderate exercise/sports 3-5 days/week<br /><b>Very active:</b> hard exercise or sports 6-7 days/week<br /><b>Extra active:</b> hard daily exercise or sports & physical labor job </html>");
tdeeYes.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
tdeeSelection = "yes";
activityLevelBox.setEnabled(true);
}
});
tdeeNo.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
tdeeSelection = "no";
activityLevelBox.setEnabled(false);
}
});
// tdee and BMR value components
bmrValue = calcBmr();
bmrLabel = new JLabel("<html><br /><br /><font size=4>You have a <i><font color=red>BMR</font></i> of: " + bmrValue + "<font></html>");
tdeeLabel = new JLabel("<html><br /><font size=4>You have a <i><font color=red>TDEE</font></i> of: " + tdeeValue + "<font></html>");
calculate = new JButton("Calculate");
bmrTDEEValuesPanel.add(calculate, BorderLayout.NORTH);
bmrTDEEValuesPanel.add(bmrLabel, BorderLayout.CENTER);
bmrTDEEValuesPanel.add(tdeeLabel, BorderLayout.SOUTH);
// Debugging panels for buttons (remove when complete)
calculate.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println("Male:" + genderMale.isSelected());
System.out.println("Female:" + genderFemale.isSelected() + "\n");
System.out.println("Kg:" + kgButton.isSelected());
System.out.println("LB:" + lbButton.isSelected() + "\n");
System.out.println("CM:" + cmButton.isSelected());
System.out.println("Feet:" + feetButton.isSelected() + "\n");
System.out.println("TDEE Yes:" + tdeeYes.isSelected());
System.out.println("TDEE No:" + tdeeNo.isSelected());
System.out.println("-------------------------------------");
}
});
// Adding sub JPanels to main JPanel
mainPanel.add(imgPanel);
combinedGAHWpanel.add(agePanel, BorderLayout.NORTH); // Combine genderPanel and agePanel (which are both flowLayouts) into a
// single BorderLayout panel where agePanel is given the Northern spot and
// genderPanel is given the center spot in the panel
weightHeightPanel.add(weightPanel, BorderLayout.NORTH); // Nested borderlayouts, the weightHeightPanel is another borderLayout which is nested
// into the southern position of the combinedGAHW border layout.
weightHeightPanel.add(heightPanel, BorderLayout.CENTER);
weightHeightPanel.add(tdeeBMRPanel, BorderLayout.SOUTH);
combinedGAHWpanel.add(genderPanel, BorderLayout.CENTER);
combinedGAHWpanel.add(weightHeightPanel, BorderLayout.SOUTH);
mainPanel.add(combinedGAHWpanel);
// adding to tdeeBMRPanel
tdeeBMRPanel.add(tdeePanel, BorderLayout.NORTH);
tdeeBMRPanel.add(activityLevelPanel, BorderLayout.CENTER);
tdeeBMRPanel.add(bmrTDEEValuesPanel, BorderLayout.SOUTH);
// Adding main JPanel and menubar to JFrame
setJMenuBar(menuBar);
add(mainPanel);
}
public static String calcBmr() {
return bmrValue;
}
public static String calcTDEE() {
return tdeeValue;
}
public static void main(String[] args) {
BmrCalcv2 gui = new BmrCalcv2("BMR/TDEE Calculator");
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setSize(330, 500);
gui.setResizable(false);
}
}
Thanks.

How to add a focus traversal with a different hotkey?

I am having a problem implementing the last part of this program, which is to make it where pressing the Enter key moves the active field from one text field to the next one in order (1,2,3,4).
This needs to be done without removing the focus cycling that is used by the tab key.
I have no idea how to even begin doing that, the only thing I've found in the API is replacing the traversal policy with your own, but I don't want to replace it I want to create a new one that runs in parallel with the default one.
public class unit27 {
JButton button1 = new JButton("add to next cup");
JButton button2 = new JButton("add to next cup");
JButton button3 = new JButton("add to next cup");
JButton button4 = new JButton("add to next cup");
JTextField text1 = new JTextField("4");
JTextField text2 = new JTextField("4");
JTextField text3 = new JTextField("4");
JTextField text4 = new JTextField("4");
JLabel label1 = new JLabel("Cup 1");
JLabel label2 = new JLabel("Cup 2");
JLabel label3 = new JLabel("Cup 3");
JLabel label4 = new JLabel("Cup 4");
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
public unit27() {
mainPanel.setLayout(new GridLayout(2, 4));
panel1.setLayout(new GridLayout(1, 3));
panel2.setLayout(new GridLayout(1, 3));
panel3.setLayout(new GridLayout(1, 3));
panel4.setLayout(new GridLayout(1, 3));
frame.add(mainPanel);
frame.setSize(800, 800);
frame.setVisible(true);
mainPanel.add(panel1);
mainPanel.add(panel2);
mainPanel.add(panel3);
mainPanel.add(panel4);
panel1.add(label1);
panel1.add(button1);
panel1.add(text1);
panel2.add(label2);
panel2.add(button2);
panel2.add(text2);
panel3.add(label3);
panel3.add(button3);
panel3.add(text3);
panel4.add(label4);
panel4.add(button4);
panel4.add(text4);
button1.add(text1);
button1.addActionListener(new MyListener1());
button2.addActionListener(new MyListener2());
button3.addActionListener(new MyListener3());
button4.addActionListener(new MyListener4());
// end class
}
class MyListener1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(text1.getText());
int b = Integer.parseInt(text2.getText());
int c = a + b;
text2.setText(Integer.toString(c));
}
}
class MyListener2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(text2.getText());
int b = Integer.parseInt(text3.getText());
int c = a + b;
text3.setText(Integer.toString(c));
}
}
class MyListener3 implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(text3.getText());
int b = Integer.parseInt(text4.getText());
int c = a + b;
text4.setText(Integer.toString(c));
}
}
class MyListener4 implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(text4.getText());
int b = Integer.parseInt(text1.getText());
int c = a + b;
text1.setText(Integer.toString(c));
}
}
public static void main(String[] args) {
new unit27();
}
}
Swing does not allow 2 focus cycles to be run at the same time. If you really need to have a second focus cycle (and not just add enter to the focus traversal keys), then what you could do is:
Create a Map which determines your cycle.
On each component with the extra cycle add a key binding for Enter that gets the next visible field in your cycle and calls requestFocus on it.
You would have to maintain the map and create custom checks to see if the next component is visible or should be skipped.

Debugging code I have with 2 classes and a JFrame that holds 4 JPanels

I am looking for help to debug this program that I have written there are, no errors but the goal is to create a frame with three panels inside of it each of which has a titled border. I am having difficulty because my prompt requires of me to make 2 constructors and 2 classes so when I call the DailySales class in main I feel it doesn't include the other class.
So basically how can I make the panels show up while still keeping two classes and two constructors and how would I add titled borders to each of the JPanels, sorry but I'm having difficulty with the Oracle tutorial.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class DailySales extends JPanel {
final int lPizzaPrice = 12;
final int mPizzaPrice = 9;
final int sPizzaPrice = 6;
final int bSticksPrice = 3;
final double tax = .06;
final int dailyOper = 1000;
String lPizza;
String mPizza;
String sPizza;
String bSticks;
int largePizza;
int mediumPizza;
int smallPizza;
int breadSticks;
int totalLargePizza;
int totalMediumPizza;
int totalSmallPizza;
int totalBreadSticks;
int totalSales;
double totalTax;
double netSales;
int operCost;
double profit;
private FlowLayout dailyFlow;
private Container container;
JLabel lPizzaLabel = new JLabel("Large Pizza");//creating labels
JLabel mPizzaLabel = new JLabel("Medium Pizza");
JLabel sPizzaLabel = new JLabel("Small Pizza");
JLabel bSticksLabel = new JLabel("Bread Sticks");
JLabel totalSalesLabel = new JLabel("Total Sales");
JLabel totalTaxLabel = new JLabel("Total Tax");
JLabel netSalesLabel = new JLabel("Net Sales");
JLabel dailyCostLabel = new JLabel("Daily Oper Cost");
JLabel profitLabel = new JLabel("Profit or Loss");
JTextField largeField = new JTextField(10);
JTextField mediumField = new JTextField(10);
JTextField smallField = new JTextField(10);
JTextField breadField = new JTextField(10);
JTextField totalLargeField = new JTextField(10);
JTextField totalMediumField = new JTextField(10);
JTextField totalSmallField = new JTextField(10);
JTextField totalBreadField = new JTextField(10);
JTextField totalSalesField = new JTextField(10);
JTextField totalTaxField = new JTextField(10);
JTextField netSalesField = new JTextField(10);
JTextField dailyCostField = new JTextField(10);
JTextField profitField = new JTextField(10);
JButton clearButton = new JButton("Clear Fields");//Creating buttons
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
JPanel subPanel1 = new JPanel();
JPanel subPanel2 = new JPanel();
JPanel subPanel3 = new JPanel();
JPanel top = new JPanel();
public class GUI extends JPanel {
public GUI() {
subPanel1.setLayout(dailyFlow);
subPanel1.add(lPizzaLabel, largeField);
subPanel1.add(mPizzaLabel, mediumField);
subPanel1.add(sPizzaLabel, smallField);
subPanel1.add(bSticksLabel, breadField);
subPanel1.setSize(100, 100);
subPanel2.setLayout(dailyFlow);
subPanel2.add(totalLargeField);
subPanel2.add(totalMediumField);
subPanel2.add(totalSmallField);
subPanel2.add(totalBreadField);
subPanel3.setLayout(dailyFlow);
subPanel3.add(totalSalesLabel, totalSalesField);
subPanel3.add(totalTaxLabel, totalTaxField);
subPanel3.add(netSalesLabel, netSalesField);
subPanel3.add(dailyCostLabel, dailyCostField);
subPanel3.add(profitLabel, profitField);
top.setBackground(Color.red);
JLabel title = new JLabel("Eve's Pizza Daily Sales");
title.setFont(new Font("Helvetica", 1, 14));
top.add(title);
totalSalesField.setEditable(false);//making total field uneditable
totalTaxField.setEditable(false);
netSalesField.setEditable(false);
dailyCostField.setEditable(false);
profitField.setEditable(false);
}
}
public DailySales() //creating a constructor
{
/**
* The constructor with all the layout informations and operators
*
*
* Also adding all labels, textfields, and buttons to frame. making the
* total field uneditable
*/
JFrame frame = new JFrame();
frame.add(subPanel1);
frame.add(subPanel2);
frame.add(subPanel3);
frame.add(top);
frame.setSize(600, 450);
frame.setVisible(true);
clearButton.addActionListener(new ActionListener() {//initial button removes all entered text
public void actionPerformed(ActionEvent e) {
largeField.setText("");
mediumField.setText("");
smallField.setText("");
breadField.setText("");
totalLargeField.setText("");
totalMediumField.setText("");
totalSmallField.setText("");
totalBreadField.setText("");
totalSalesField.setText("");
totalTaxField.setText("");
netSalesField.setText("");
dailyCostField.setText("");
profitField.setText("");
}
});
calculateButton.addActionListener(new ActionListener() {//update button calculates all the inputs and displays everything
public void actionPerformed(ActionEvent e) {
lPizza = largeField.getText();
mPizza = mediumField.getText();
sPizza = smallField.getText();
bSticks = breadField.getText();
largePizza = Integer.parseInt(lPizza);
mediumPizza = Integer.parseInt(mPizza);
smallPizza = Integer.parseInt(sPizza);
breadSticks = Integer.parseInt(bSticks);
totalLargePizza = (lPizzaPrice * largePizza);
totalMediumPizza = (mPizzaPrice * mediumPizza);
totalSmallPizza = (sPizzaPrice * smallPizza);
totalBreadSticks = (bSticksPrice * breadSticks);
totalLargeField.setText("" + totalLargePizza);
totalMediumField.setText("" + totalMediumPizza);
totalSmallField.setText("" + totalSmallPizza);
totalBreadField.setText("" + totalBreadSticks);
totalSales = (totalLargePizza + totalMediumPizza + totalSmallPizza + totalBreadSticks);
totalTax = (totalSales * tax);
netSales = (totalSales - totalTax);
profit = (netSales - dailyOper);
/**
* calculates total by adding all entered values if else
* statements for different situations that calculate the
* different between total and diet
*/
if (profit > 0) {
profitLabel.setText("Profit of ");
} else if (profit < 0) {
profitLabel.setText("Loss of ");
} else if (profit == 0) {
profitLabel.setText("No profit or loss ");
}
if (largePizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (mediumPizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (smallPizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (breadSticks < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
}
}
});
exitButton.addActionListener(new ActionListener() {//close button closes the program when clicked on
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new DailySales();
}
}
There's still a lot you can do to make this better, but this works.
public class DailySales extends JPanel {
final int lPizzaPrice = 12, mPizzaPrice = 9, sPizzaPrice = 6, bSticksPrice = 3;
final double tax = .06;
final int dailyOper = 1000;
String lPizza, mPizza, sPizza, bSticks;
int largePizza, mediumPizza, smallPizza, breadSticks, totalLargePizza,
totalMediumPizza, totalSmallPizza, totalBreadSticks;
int totalSales;
double totalTax;
double netSales;
int operCost;
double profit;
JLabel lPizzaLabel = new JLabel("Large Pizza");
JLabel mPizzaLabel = new JLabel("Medium Pizza");
JLabel sPizzaLabel = new JLabel("Small Pizza");
JLabel bSticksLabel = new JLabel("Bread Sticks");
JLabel totalSalesLabel = new JLabel("Total Sales");
JLabel totalTaxLabel = new JLabel("Total Tax");
JLabel netSalesLabel = new JLabel("Net Sales");
JLabel dailyCostLabel = new JLabel("Daily Oper Cost");
JLabel profitLabel = new JLabel("Profit or Loss");
JTextField largeField = new JTextField(10);
JTextField mediumField = new JTextField(10);
JTextField smallField = new JTextField(10);
JTextField breadField = new JTextField(10);
JTextField totalLargeField = new JTextField(10);
JTextField totalMediumField = new JTextField(10);
JTextField totalSmallField = new JTextField(10);
JTextField totalBreadField = new JTextField(10);
JTextField totalSalesField = new JTextField(10);
JTextField totalTaxField = new JTextField(10);
JTextField netSalesField = new JTextField(10);
JTextField dailyCostField = new JTextField(10);
JTextField profitField = new JTextField(10);
JButton clearButton = new JButton("Clear Fields");// Creating buttons
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
JPanel subPanel1 = new JPanel();
JPanel subPanel2 = new JPanel();
JPanel subPanel3 = new JPanel();
JPanel top = new JPanel();
public class GUI extends JPanel {
public GUI() {
subPanel1.setLayout(new GridLayout(4, 2));
subPanel1.add(lPizzaLabel);
subPanel1.add(largeField);
subPanel1.add(mPizzaLabel);
subPanel1.add(mediumField);
subPanel1.add(sPizzaLabel);
subPanel1.add(smallField);
subPanel1.add(bSticksLabel);
subPanel1.add(breadField);
subPanel1.setBorder(BorderFactory.createTitledBorder("Panel 1"));
// subPanel2.setLayout(new BoxLayout(subPanel2, BoxLayout.Y_AXIS)); // Same as next line
subPanel2.setLayout(new GridLayout(4, 1));
subPanel2.add(totalLargeField);
subPanel2.add(totalMediumField);
subPanel2.add(totalSmallField);
subPanel2.add(totalBreadField);
subPanel2.setBorder(BorderFactory.createTitledBorder("Panel 2"));
subPanel3.setLayout(new GridLayout(5, 2));
subPanel3.add(totalSalesLabel);
subPanel3.add(totalSalesField);
subPanel3.add(totalTaxLabel);
subPanel3.add(totalTaxField);
subPanel3.add(netSalesLabel);
subPanel3.add(netSalesField);
subPanel3.add(dailyCostLabel);
subPanel3.add(dailyCostField);
subPanel3.add(profitLabel);
subPanel3.add(profitField);
JLabel title = new JLabel("Eve's Pizza Daily Sales");
title.setFont(new Font("Helvetica", 1, 14));
top.add(title);
top.setBackground(Color.YELLOW);
totalSalesField.setEditable(false);// making total field uneditable
totalTaxField.setEditable(false);
netSalesField.setEditable(false);
dailyCostField.setEditable(false);
profitField.setEditable(false);
}
}
public DailySales() // creating a constructor
{
/**
* The constructor with all the layout informations and operators Also
* adding all labels, textfields, and buttons to frame. making the total
* field uneditable
*/
new GUI();
JPanel mainPanel = new JPanel(new GridLayout(2, 2));
mainPanel.add(subPanel1);
mainPanel.add(subPanel2);
mainPanel.add(subPanel3);
JPanel buttonPanel = new JPanel();
buttonPanel.add(clearButton);
buttonPanel.add(calculateButton);
buttonPanel.add(exitButton);
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(top, BorderLayout.PAGE_START);
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.getContentPane().add(buttonPanel, BorderLayout.PAGE_END);
frame.setSize(600, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
clearButton.addActionListener(new ActionListener() {// initial button
// removes all
// entered text
public void actionPerformed(ActionEvent e) {
largeField.setText("");
mediumField.setText("");
smallField.setText("");
breadField.setText("");
totalLargeField.setText("");
totalMediumField.setText("");
totalSmallField.setText("");
totalBreadField.setText("");
totalSalesField.setText("");
totalTaxField.setText("");
netSalesField.setText("");
dailyCostField.setText("");
profitField.setText("");
}
});
calculateButton.addActionListener(new ActionListener() {// update button
// calculates
// all the
// inputs and
// displays
// everything
public void actionPerformed(ActionEvent e) {
lPizza = largeField.getText();
mPizza = mediumField.getText();
sPizza = smallField.getText();
bSticks = breadField.getText();
largePizza = Integer.parseInt(lPizza);
mediumPizza = Integer.parseInt(mPizza);
smallPizza = Integer.parseInt(sPizza);
breadSticks = Integer.parseInt(bSticks);
totalLargePizza = (lPizzaPrice*largePizza);
totalMediumPizza = (mPizzaPrice*mediumPizza);
totalSmallPizza = (sPizzaPrice*smallPizza);
totalBreadSticks = (bSticksPrice*breadSticks);
totalLargeField.setText(""+totalLargePizza);
totalMediumField.setText(""+totalMediumPizza);
totalSmallField.setText(""+totalSmallPizza);
totalBreadField.setText(""+totalBreadSticks);
totalSales = (totalLargePizza+totalMediumPizza+totalSmallPizza+totalBreadSticks);
totalTax = (totalSales*tax);
netSales = (totalSales-totalTax);
profit = (netSales-dailyOper);
/**
* calculates total by adding all entered values if else
* statements for different situations that calculate the
* different between total and diet
*/
if (profit>0) {
profitLabel.setText("Profit of ");
} else if (profit<0) {
profitLabel.setText("Loss of ");
} else if (profit==0) {
profitLabel.setText("No profit or loss ");
}
if (largePizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (mediumPizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (smallPizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (breadSticks<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
}
}
});
exitButton.addActionListener(new ActionListener() {// close button
// closes the
// program when
// clicked on
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new DailySales();
}
}

Array in Gui to Increment

Hi i have a trouble in my program because i need to set an array for easy way of incrementing it because it is sales so i declare of my array like this iam not yet done of my program this is my program so far .
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class We extends JFrame
{
public static JPanel panel2 = new JPanel();
public static String totallist,addprod;
public static int grandtotal,ve,xxx,z,x,adding,pay,totalp,totalc,payment;
public static JTextField in = new JTextField(z);
public static JTextField ki = new JTextField(15);
public static double disc,totalbayad,sukli;
public static int benta[] = new int [11];
public static String prod[] = new String[11];
public static void main(String[] args)
{
We frameTabel = new We();
prod[1] = "Palmolive";
prod[2] = "Egg";
prod[3] = "Milo";
prod[4] = "Noodles";
prod[5] = "PancitCanton";
prod[6] = "CornBeef";
prod[7] = "LigoSardines";
prod[8] = "CokeSakto";
prod[9] = "RcBig";
prod[10] = "GibsonLespaulGuitar";
benta[1] = 6;
benta[2] = 5;
benta[3] = 6;
benta[4] = 9;
benta[5] = 10;
benta[6] = 25;
benta[7] = 16;
benta[8] = 6;
benta[9] = 16;
benta[10] = 14000;
}
JFrame frame = new JFrame("Customer");
JFrame prodcho = new JFrame("Unofficial receipt");
JFrame want = new JFrame("Buy AGain");
JFrame ftinda = new JFrame("Item && Prices");
JButton blogin = new JButton("Login");
JPanel panel = new JPanel();
JTextField txuser = new JTextField(15);
JPasswordField pass = new JPasswordField(15);
JLabel lab = new JLabel("Username :");
JLabel pas = new JLabel("Password :");
JLabel cos;
//JPanel panel = new JPanel();
JButton y1;
JButton y2;
We()
{
super("Enter Your Account !");
setSize(300,200);
setLocation(500,280);
panel.setLayout (null);
txuser.setBounds(90,30,150,20);
pass.setBounds(90,65,150,20);
blogin.setBounds(110,100,80,20);
lab.setBounds(15,28,150,20);
pas.setBounds(15,63,150,20);
panel.add(lab);
panel.add(pas);
panel.add(blogin);
panel.add(txuser);
panel.add(pass);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
actionlogin();
}
public void actionlogin()
{
blogin.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String puname = txuser.getText();
String ppaswd = pass.getText();
if(puname.equals("vincent") && ppaswd.equals("puge"))
{
setVisible(false);
JPanel panel1 = new JPanel();
frame.setVisible(true);
frame.setSize(300,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout());
cos = new JLabel("Do you have a Customer ?");
y1 = new JButton("Yes");
y2 = new JButton("No");
panel1.setLayout(null);
cos.setBounds(70,30,150,20);
y1.setBounds(80,65,150,20);
y2.setBounds(140,65,150,20);
y1.setSize(55,30);
y2.setSize(55,30);
panel1.add(y1);
panel1.add(y2);
panel1.add(cos);
frame.add(panel1);
y1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
Object source = ae.getSource();
if(source == y1)
{
frame.setVisible(false);
//--------------------------------------
int boundsStart=10;
panel.l2.add(new JLabel("-Product-").setBounds(20,boundsStart,150,20));
boundsStart+=20;
for (int i=1; i<11; i++)
{
panel2.add(new JLabel(i+"."+prod[i]).setBounds(20,boundsStart,150,20));
boundsStart+=20;
}
boundsStart = 30; //reset bounds counter
for (int i=1; i<11; i++)
{
panel2.add(new JLabel(""+benta[i]).setBounds(20,boundsStart,150,20));
boundsStart+=20;
}
//You could then change the other JLabels that came after this point in the same way I just did
//price,ent,law, and qx
//--------------------------------------
JLabel vince = new JLabel("-Product-");
JLabel l1 = new JLabel("1."+prod[1]);
JLabel l2 = new JLabel("2."+prod[2]);
JLabel l3 = new JLabel("3."+prod[3]);
JLabel l4 = new JLabel("4."+prod[4]);
JLabel l5 = new JLabel("5."+prod[5]);
JLabel l6 = new JLabel("6."+prod[6]);
JLabel l7 = new JLabel("7."+prod[7]);
JLabel l8 = new JLabel("8."+prod[8]);
JLabel l9 = new JLabel("9."+prod[9]);
JLabel l10 = new JLabel("10."+prod[10]);
JLabel p1 = new JLabel(""+benta[1]);
JLabel p2 = new JLabel(""+benta[2]);
JLabel p3 = new JLabel(""+benta[3]);
JLabel p4 = new JLabel(""+benta[4]);
JLabel p5 = new JLabel(""+benta[5]);
JLabel p6 = new JLabel(""+benta[6]);
JLabel p7 = new JLabel(""+benta[7]);
JLabel p8 = new JLabel(""+benta[8]);
JLabel p9 = new JLabel(""+benta[9]);
JLabel p10 = new JLabel(""+benta[10]);
JLabel price = new JLabel("-Price-");
JButton ent = new JButton("Enter");
JLabel law = new JLabel("Enter No. of Product");
JLabel qx = new JLabel("Enter Quantity");
ftinda.setVisible(true);
ftinda.setSize(350,350);
ftinda.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ftinda.setLayout(new GridLayout());
panel2.setLayout(null);
vince.setBounds(20,10,150,20);
l1.setBounds(20,30,150,20);
l2.setBounds(20,50,150,20);
l3.setBounds(20,70,150,20);
l4.setBounds(20,90,150,20);
l5.setBounds(20,110,150,20);
l6.setBounds(20,130,150,20);
l7.setBounds(20,150,150,20);
l8.setBounds(20,170,150,20);
l9.setBounds(20,190,150,20);
l10.setBounds(20,210,150,20);
p1.setBounds(230,30,150,20);
p2.setBounds(230,50,150,20);
p3.setBounds(230,70,150,20);
p4.setBounds(230,90,150,20);
p5.setBounds(230,110,150,20);
p6.setBounds(230,130,150,20);
p7.setBounds(230,150,150,20);
p8.setBounds(230,170,150,20);
p9.setBounds(230,190,150,20);
p10.setBounds(230,210,150,20);
price.setBounds(225,10,150,20);
in.setBounds(150,250,150,20);
law.setBounds(20,253,150,20);
qx.setBounds(20,280,150,20);
ki.setBounds(150,280,150,20);
ent.setBounds(220,250,150,20);
in.setSize(42,20);
ki.setSize(42,20);
ent.setSize(65,50);
panel2.add(vince);
panel2.add(l1);
panel2.add(l2);
panel2.add(l3);
panel2.add(l4);
panel2.add(l5);
panel2.add(l6);
panel2.add(l7);
panel2.add(l8);
panel2.add(l9);
panel2.add(l10);
panel2.add(p1);
panel2.add(p2);
panel2.add(p3);
panel2.add(p4);
panel2.add(p5);
panel2.add(p6);
panel2.add(p7);
panel2.add(p8);
panel2.add(p9);
panel2.add(p10);
panel2.add(price);
panel2.add(in);
panel2.add(law);
panel2.add(ent);
panel2.add(qx);
panel2.add(ki);
ftinda.add(panel2);
ent.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
ftinda.setVisible(false);
JPanel panel3 = new JPanel();
JLabel cos1 = new JLabel("Do you want to buy more ?");
JButton yy = new JButton("Yes");
JButton nn = new JButton("No");
panel3.setLayout(null);
cos1.setBounds(70,30,150,20);
yy.setBounds(80,65,150,20);
nn.setBounds(140,65,150,20);
yy.setSize(55,30);
nn.setSize(55,30);
panel3.add(cos1);
panel3.add(yy);
panel3.add(nn);
want.add(panel3);
want.setVisible(true);
want.setSize(300,200);
want.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
want.setLayout(new GridLayout());
addprod = prod[];
adding = benta[];
totalp =
totalc = totalp;
totallist = totallist + addprod +"" +x+ "pcs = "+totalc+"pesos";
nn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ea)
{
Object source1 = ea.getSource();
{
if(source1 == nn)
{
JPanel panel4 = new JPanel();
panel4.setLayout(null);
prodcho.setVisible(true);
prodcho.setSize(300,200);
prodcho.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
prodcho.setLayout(new GridLayout());
prodcho.add(panel4);
}
}
}
});
}
});
}
}
});
}
else
{
JOptionPane.showMessageDialog(null,"Wrong Password / Username");
txuser.setText("");
pass.setText("");
txuser.requestFocus();
}
}
});
}
}
As PeterMmm stated arrayLists should be able to solve your predicament. ArrayLists allow you to make an array of any type very easily and has a very nice interface such as
mylist.add(element)
Maroun Maroun also made a valid point that you can approach this much more nicely using a loop so that you can avoid the large amount of repitition in your code, but its not necessary to do so if you are happy with it.
Hopefully the following sample of using ArrayList can help you:
http://javarevisited.blogspot.de/2011/05/example-of-arraylist-in-java-tutorial.html
And if you want more information about arraylist here is the docs:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
My last tip, while looking at your code is to add an actionListener to your button, as currently it does nothing ;)
ent.addActionListener(new ActionListener()
{
#Override
public void actionPerformed( ActionEvent e )
{
//..do stuff here or call a function to do stuff :)
}
});
You might want to check out putting this into a bigger loop. You could set up a loop and then use generic statements to add Labels and size them instead of adding a different Label object for each one. It would cut about 20 lines of code.
EDIT: By loops I was talking about how to deal with setting bounds and adding to the panel. An example would be something like
while(condition)
{
panel.add(new JLabel(information).setBounds(bounds));
}
This gets rid of the repetition of having code like:
JLabel p1 = new JLabel(info);
JLabel p2 = new JLabel(info2);
...
panel1.add(p1);
panel1.add(p2);
...
p1.setBounds(bounds1);
p2.setBounds(bounds2);
...

Categories