Array in Gui to Increment - java
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);
...
Related
Trying to create a calculator with Java. Button inputs won't print in the textfield
I'm trying to create a scientific calculator for class. I'm not sure where I'm going wrong, but it will not print any button inputs into the textfield. Does anybody know where I'm going wrong? Problems come from the 'calc' class at the bottom of the code. I've only coded the calculator to respond to number inputs, so no other buttons will work, but the number buttons should work and I don't know how to fix it. I'm still very new to programming package scientificcalc; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ScientificCalc extends JFrame { JFrame Frame; JPanel Panel; JTextField Text; JButton Button[]= new JButton[25]; // Array holds all calculator buttons String val0, val1, val2; // Each val records a button pressed public ScientificCalc() { val0 = val1 = val2 = ""; Frame = new JFrame("Scientific Calculator"); Panel = new JPanel(); Panel.setBackground(Color.RED); Text = new JTextField(20); Text.setEditable(false); Frame.setVisible(true); Frame.setSize(400,400); Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ActionListener a = null; // Following Lines create each button Button[0] = new JButton("0"); Button[0].addActionListener(a); Button[1] = new JButton("1"); Button[1].addActionListener(a); Button[2] = new JButton("2"); Button[2].addActionListener(a); Button[3] = new JButton("3"); Button[3].addActionListener(a); Button[4] = new JButton("4"); Button[4].addActionListener(a); Button[5] = new JButton("5"); Button[5].addActionListener(a); Button[6] = new JButton("6"); Button[6].addActionListener(a); Button[7] = new JButton("7"); Button[7].addActionListener(a); Button[8] = new JButton("8"); Button[8].addActionListener(a); Button[9] = new JButton("9"); Button[9].addActionListener(a); Button[10] = new JButton("+"); Button[10].addActionListener(a); Button[11] = new JButton("-"); Button[11].addActionListener(a); Button[12] = new JButton("*"); Button[12].addActionListener(a); Button[13] = new JButton("/"); Button[13].addActionListener(a); Button[14] = new JButton("SQRT"); Button[14].addActionListener(a); Button[15] = new JButton("Sin"); Button[15].addActionListener(a); Button[16] = new JButton("Cos"); Button[16].addActionListener(a); Button[17] = new JButton("Tan"); Button[17].addActionListener(a); Button[18] = new JButton("1/x"); Button[18].addActionListener(a); Button[19] = new JButton("x^2"); Button[19].addActionListener(a); Button[20] = new JButton("log"); Button[20].addActionListener(a); Button[21] = new JButton("!"); Button[21].addActionListener(a); Button[22] = new JButton("."); Button[22].addActionListener(a); Button[23] = new JButton("="); Button[23].addActionListener(a); Button[24] = new JButton("Clear"); Button[24].addActionListener(a); // Following Lines add everything to Panel and Frame Panel.add(Text); Panel.add(Button[0]); Panel.add(Button[1]); Panel.add(Button[2]); Panel.add(Button[3]); Panel.add(Button[4]); Panel.add(Button[5]); Panel.add(Button[6]); Panel.add(Button[7]); Panel.add(Button[8]); Panel.add(Button[9]); Panel.add(Button[10]); Panel.add(Button[11]); Panel.add(Button[12]); Panel.add(Button[13]); Panel.add(Button[14]); Panel.add(Button[15]); Panel.add(Button[16]); Panel.add(Button[17]); Panel.add(Button[18]); Panel.add(Button[19]); Panel.add(Button[20]); Panel.add(Button[21]); Panel.add(Button[22]); Panel.add(Button[23]); Panel.add(Button[24]); Frame.add(Panel); } public class calc implements ActionListener { public void actionPerformed(ActionEvent e) { String i = e.getActionCommand(); if ((i.charAt(0) >= '0' && i.charAt(0) <= '9') || i.charAt(0) == '.') { if (!val1.equals("")) { val2 = val2 + i; } else { val0 = val0 + i; // Sets location of each digit when button is pressed } Text.setText(val0+val1+val2); } } } public static void main(String[] args) { new ScientificCalc(); } }
You're currently adding your ActionListener a which you set to null to all of your buttons. Change ActionListener a = null to ActionListener a = new calc();
You forgot to initialize calc object by ActionListener a = new calc(); Use field names starting with small letters! Use loops instead of repetitive code! Start class names with capital letters! Name calc class by CustomActionListener Below there is pretty code! Question: why do you check it if it's always false? if (!val1.equals("")) package scientificcalc; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ScientificCalc extends JFrame { JFrame frame; JPanel panel; JTextField textField; JButton[] buttonArray = new JButton[25]; // Array holds all calculator buttons String val0, val1, val2; // Each val records a button pressed public ScientificCalc() { val0 = val1 = val2 = ""; frame = new JFrame("Scientific Calculator"); panel = new JPanel(); panel.setBackground(Color.RED); textField = new JTextField(20); textField.setEditable(false); frame.setVisible(true); frame.setSize(400, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); CustomActionListener actionListener = new CustomActionListener(); // Following Lines create each button buttonArray[0] = new JButton("0"); buttonArray[1] = new JButton("1"); buttonArray[2] = new JButton("2"); buttonArray[3] = new JButton("3"); buttonArray[4] = new JButton("4"); buttonArray[5] = new JButton("5"); buttonArray[6] = new JButton("6"); buttonArray[7] = new JButton("7"); buttonArray[8] = new JButton("8"); buttonArray[9] = new JButton("9"); buttonArray[10] = new JButton("+"); buttonArray[11] = new JButton("-"); buttonArray[12] = new JButton("*"); buttonArray[13] = new JButton("/"); buttonArray[14] = new JButton("SQRT"); buttonArray[15] = new JButton("Sin"); buttonArray[16] = new JButton("Cos"); buttonArray[17] = new JButton("Tan"); buttonArray[18] = new JButton("1/x"); buttonArray[19] = new JButton("x^2"); buttonArray[20] = new JButton("log"); buttonArray[21] = new JButton("!"); buttonArray[22] = new JButton("."); buttonArray[23] = new JButton("="); buttonArray[24] = new JButton("Clear"); for (int i = 0; i < buttonArray.length; i++) { buttonArray[i].addActionListener(actionListener); } // Following Lines add everything to Panel and Frame panel.add(textField); for (JButton jButton : buttonArray) { panel.add(jButton); } frame.add(panel); } class CustomActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { String i = e.getActionCommand(); if ((i.charAt(0) >= '0' && i.charAt(0) <= '9') || i.charAt(0) == '.') { if (!val1.equals("")) { val2 = val2 + i; } else { val0 = val0 + i; // Sets location of each digit when button is pressed } textField.setText(val0 + val1 + val2); } } } public static void main(String[] args) { new ScientificCalc(); } }
Java lottery game efficiency, swing [closed]
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());
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.
BoxLayout can't be shared. Trying to add multiple labels from an array into a BoxLayout Panel
I know there are plenty of BoxLayout questions on here, however I can't find one that fixes my problem. I need my scoreDescPanel to show each label directly below each other (like a list) however I'm having problems with BoxLayout. The priblem occurs on the line scoreDescPanel.add(lblScoreDesc[i]); at the bottom. private JFrame frame; private JPanel panel; private JPanel dicePanel; private JButton btnRoll; private JButton[] btnDice = new JButton[5]; private JPanel mainPanel; private JPanel scoreDescPanel; private JPanel scoreBtnPanel; private JLabel[] lblScoreDesc = new JLabel[20]; private JButton[] btnScore = new JButton[20]; private Yahtzee y = new Yahtzee(); public YahtzeeGUI(){ createWindow(); addButtonRoll(); addButtonDice(); addMainPanel(); addScoreDesc(); //addScoreCardUpper(); //addScoreCardLower(); frame.add(panel); frame.setVisible(true); } public void createWindow(){ frame = new JFrame(); frame.setTitle("Yahtzee"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(1000,700); panel = new JPanel(new BorderLayout()); dicePanel = new JPanel(); mainPanel = new JPanel(); scoreDescPanel = new JPanel(); } public void addButtonRoll(){ btnRoll = new JButton ("Roll the Dice"); btnRoll.addActionListener(new RollHandler()); dicePanel.add (btnRoll); panel.add(dicePanel, BorderLayout.SOUTH); } public void addButtonDice(){ for (int i = 0; i < btnDice.length; i++){ btnDice[i] = new JButton(String.valueOf(y.dice[i].getFaceValue())); btnDice[i].addActionListener(new HoldHandler()); dicePanel.add (btnDice[i]); } panel.add(dicePanel, BorderLayout.SOUTH); } public void addMainPanel(){ mainPanel.setLayout(new BorderLayout()); mainPanel.setBackground(Color.red); panel.add(mainPanel, BorderLayout.CENTER); } public void addScoreDesc(){ lblScoreDesc[0] = new JLabel("UPPER SECTION"); lblScoreDesc[1] = new JLabel("Aces"); lblScoreDesc[2] = new JLabel("Twos"); lblScoreDesc[3] = new JLabel("Threes"); lblScoreDesc[4] = new JLabel("Fours"); lblScoreDesc[5] = new JLabel("Fives"); lblScoreDesc[6] = new JLabel("Sixes"); lblScoreDesc[7] = new JLabel("TOTAL SCORE"); lblScoreDesc[8] = new JLabel("BONUS"); lblScoreDesc[9] = new JLabel("TOTAL UPPER"); lblScoreDesc[10] = new JLabel("LOWER SECTION"); lblScoreDesc[11] = new JLabel("3 of a Kind"); lblScoreDesc[12] = new JLabel("4 of a Kind"); lblScoreDesc[13] = new JLabel("Full House"); lblScoreDesc[14] = new JLabel("Small Straight"); lblScoreDesc[15] = new JLabel("Large Straight"); lblScoreDesc[16] = new JLabel("Yahtzee!"); lblScoreDesc[17] = new JLabel("Chance"); lblScoreDesc[18] = new JLabel("TOTAL LOWER"); lblScoreDesc[19] = new JLabel("GRAND TOTAL"); mainPanel.add(scoreDescPanel, BorderLayout.WEST); scoreDescPanel.setLayout(new BoxLayout(mainPanel,BoxLayout.Y_AXIS)); for(int i = 0; i < lblScoreDesc.length; i++){ scoreDescPanel.add(lblScoreDesc[i]); } }
BoxLayout doesn't allow a different target container from that on which the layout is being set, i.e. scoreDescPanel.setLayout(new BoxLayout(mainPanel,BoxLayout.Y_AXIS)); should be scoreDescPanel.setLayout(new BoxLayout(scoreDescPanel, BoxLayout.Y_AXIS)); Read: How to Use BoxLayout
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(); } }