So I do know what an StackOverflowError is, the problem however is I can't find it here. I am supposed to make a simple GUI with labels, text fields and buttons. One of these buttons is supposed to "clear" the text fields, so I add that by putting text field as an argument in the constructor, but when I actually add the text fields i just get an stack overflow error. Here is the code:
Orders class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Orders extends JFrame {
public Orders() {
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(4, 2, 2, 2));
JLabel name = new JLabel("Item name:");
JLabel number = new JLabel("Number of:");
JLabel cost = new JLabel("Cost:");
JLabel amount = new JLabel("Amount owed:");
JTextField nameJtf = new JTextField(10);
JTextField numberJtf = new JTextField(10);
JTextField costJtf = new JTextField(10);
JTextField amountJtf = new JTextField(10);
panel1.add(name);
panel1.add(nameJtf);
panel1.add(number);
panel1.add(numberJtf);
panel1.add(cost);
panel1.add(costJtf);
panel1.add(amount);
panel1.add(amountJtf);
JPanel panel2 = new JPanel();
JButton calculate = new JButton("Calculate");
JButton save = new JButton("Save");
JButton clear = new JButton("Clear");
JButton exit = new JButton("Exit");
panel2.add(calculate);
panel2.add(save);
panel2.add(clear);
panel2.add(exit);
OnClick action = new OnClick(exit, clear, save, calculate, nameJtf, numberJtf, costJtf, amountJtf);
exit.addActionListener(action);
this.setTitle("Otto's Items Orders Calculator");
this.add(panel1, BorderLayout.NORTH);
this.add(panel2, BorderLayout.SOUTH);
this.setSize(400, 200);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
new Orders();
}
}
OnClick class :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class OnClick extends Orders implements ActionListener {
private JButton exitModify = null;
private JButton clearModify = null;
private JButton saveModify = null;
private JButton calculateModify = null;
private JTextField nameModify = null;
private JTextField numberModify = null;
private JTextField costModify = null;
private JTextField amountModify = null;
public OnClick (JButton _exitModify, JButton _clearModify, JButton _saveModify, JButton _calculateModify, JTextField _nameModify, JTextField _numberModify, JTextField _costModify, JTextField _amountModify) {
exitModify = _exitModify;
clearModify = _clearModify;
saveModify = _saveModify;
calculateModify = _calculateModify;
nameModify = _nameModify;
numberModify = _numberModify;
costModify = _numberModify;
amountModify = _amountModify;
}
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o == this.exitModify) {
System.exit(0);
} else if (o == this.clearModify) {
amountModify = null;
nameModify = null;
costModify = null;
numberModify = null;
}
}
}
As soon as I add nameJtf I get this error.
Related
I am not sure what I am doing wrong. I am trying to create 4 buttons using the arrays and passing the method to the Set Panel class. When I run it I only get one button. Any help would be great. Essentially what I want is a Panel with four buttons, through the use of Methods.
public class SetButtons extends JButton implements ActionListener {
JButton [] buttonArray = new JButton[4];
JButton exitBtn, newGameBtn, checkBtn, clearBtn;
Font myFont = new Font("ink free", Font.BOLD,22);
public SetButtons(){
this.exitBtn = new JButton("Exit");
this.newGameBtn = new JButton("New Game");
this.checkBtn = new JButton("Check Answer");
this.clearBtn = new JButton("Clear");
this.buttonArray[0] = exitBtn;
this.buttonArray[1] = newGameBtn;
this.buttonArray[2] = checkBtn;
this.buttonArray[3] = clearBtn;
for (int i = 0; i < 4; i++){
this.buttonArray[i].addActionListener(this);
this.buttonArray[i].setFont(myFont);
this.buttonArray[i].setFocusable(false);
this.buttonArray[i].setLayout(new FlowLayout());
}
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == this){
System.exit(0);
}
}
}
import javax.swing.*;
import java.awt.*;
public class SetPanel extends JPanel {
Font myFont = new Font("ink free", Font.BOLD,22);
SetLabels labels;
SetButtons exitButton;
SetPanel(){
SetButtons btn = new SetButtons();
this.add(btn);
this.setBackground(Color.darkGray);
this.setLayout(new FlowLayout());
}
}
I am trying to make a calculator program where click a button and then it would add to the Java Text Field(Not the Java Text Area), and I use the ActionEvent e to figure out the action. Then using the actionCommand where I get the actionListener I try to add the text to the java text field. And somehow it is not updating into the java text field. Is this a problem with repaint or something.
Here's my code
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.io.Writer;
import java.util.ArrayList;
public class Calculator extends JFrame implements ActionListener {
String actionCommand = "";
ArrayList<Integer> numberSet1 = new ArrayList<Integer>();
ArrayList<Integer> numberSet2 = new ArrayList<Integer>();
JLabel jl = new JLabel();
JPanel jp = new JPanel();
int number1 = 0;
int number2 = 0;
JTextField jtf = new JTextField();
JButton btn1;
JTextArea jta = new JTextArea();
public Calculator() {
super("Calculator");
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600,600);
jp.setLayout(new BorderLayout());
JTextField jtf = new JTextField("This is the text field");
jtf.setSize(getWidth(),50);
add(jtf, BorderLayout.NORTH);
jtf.setBackground(Color.YELLOW);
jtf.setEditable(false);
JPanel jp = new JPanel();
Font myFont = new Font("Serif", Font.BOLD, 32);
jp.setLayout(new GridLayout(4,4));
JButton butt0 = new JButton("0");
butt0.setFont(myFont);
JButton butt1 = new JButton("1");
butt1.setFont(myFont);
JButton butt2 = new JButton("2");
butt2.setFont(myFont);
JButton butt3 = new JButton("3");
butt3.setFont(myFont);
JButton butt4 = new JButton("4");
butt4.setFont(myFont);
JButton butt5 = new JButton("5");
butt5.setFont(myFont);
JButton butt6 = new JButton("6");
butt6.setFont(myFont);
JButton butt7 = new JButton("7");
butt7.setFont(myFont);
JButton butt8 = new JButton("8");
butt8.setFont(myFont);
JButton butt9 = new JButton("9");
butt9.setFont(myFont);
JButton butt10 = new JButton("+");
butt10.setFont(myFont);
JButton butt11 = new JButton("-");
butt11.setFont(myFont);
JButton butt12 = new JButton("*");
butt12.setFont(myFont);
JButton butt13 = new JButton("/");
butt13.setFont(myFont);
JButton butt14 = new JButton("=");
butt14.setFont(myFont);
JButton butt15 = new JButton("clear");
butt15.setFont(myFont);
butt1.setBackground(Color.cyan);
butt2.setBackground(Color.cyan);
butt3.setBackground(Color.cyan);
butt4.setBackground(Color.cyan);
butt5.setBackground(Color.cyan);
butt6.setBackground(Color.cyan);
butt7.setBackground(Color.cyan);
butt8.setBackground(Color.cyan);
butt9.setBackground(Color.cyan);
butt10.setBackground(Color.red);
butt11.setBackground(Color.red);
butt12.setBackground(Color.red);
butt13.setBackground(Color.red);
butt14.setBackground(Color.red);
butt15.setBackground(Color.red);
butt0.setBackground(Color.cyan);
butt10.setForeground(Color.lightGray);
butt11.setForeground(Color.lightGray);
butt12.setForeground(Color.lightGray);
butt13.setForeground(Color.lightGray);
butt14.setForeground(Color.lightGray);
butt15.setForeground(Color.lightGray);
jp.add(butt0);
jp.add(butt1);
jp.add(butt2);
jp.add(butt3);
jp.add(butt4);
jp.add(butt5);
jp.add(butt6);
jp.add(butt7);
jp.add(butt8);
jp.add(butt9);
jp.add(butt10);
jp.add(butt11);
jp.add(butt12);
jp.add(butt13);
jp.add(butt14);
jp.add(butt15);
butt0.addActionListener(this);
butt0.setActionCommand("0");
butt1.addActionListener(this);
butt1.setActionCommand("1");
butt2.addActionListener(this);
butt2.setActionCommand("2");
butt3.addActionListener(this);
butt3.setActionCommand("3");
butt4.addActionListener(this);
butt4.setActionCommand("4");
butt5.addActionListener(this);
butt5.setActionCommand("5");
butt6.addActionListener(this);
butt6.setActionCommand("6");
butt7.addActionListener(this);
butt7.setActionCommand("7");
butt8.addActionListener(this);
butt8.setActionCommand("8");
butt9.addActionListener(this);
butt9.setActionCommand("9");
butt10.addActionListener(this);
butt10.setActionCommand("+");
butt11.addActionListener(this);
butt11.setActionCommand("-");
butt12.addActionListener(this);
butt12.setActionCommand("*");
butt13.addActionListener(this);
butt13.setActionCommand("/");
butt14.addActionListener(this);
butt14.setActionCommand("=");
butt15.addActionListener(this);
butt15.setActionCommand("clear");
add(jp, BorderLayout.CENTER);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
actionCommand = e.getActionCommand();
System.out.println("Clicked" + actionCommand);
jtf.setText(actionCommand);
}
public void phase1() {
while (!(actionCommand.equals("+")) || !(actionCommand.equals("-")) || !(actionCommand.equals("*")) || !(actionCommand.equals("/")) || !(actionCommand.equals("clear")) || !(actionCommand.equals("="))) {
numberSet1.add(Integer.parseInt(actionCommand));
}
for(int i = 0; i < numberSet1.size(); i++) {
}
}
public void phase2() {
}
public int calculations() {
return 0;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
}
}
You have two different JTextField variables that are both named jtf.
The first is an instance variable, which you have declared with JTextField jtf = new JTextField();, and is accessible from anywhere in the class.
The second is a local variable, which you have declared with JTextField jtf = new JTextField("This is the text field");, and is only accessible in the constructor of Calculator.
The problem is that the second jtf (the local variable) is being added to the UI, while the first jtf (the instance variable) is what's being updated by the action event.
To fix this, change this (near the top of the class): JTextField jtf = new JTextField();
to this: JTextField jtf;
And then change this (in the constructor):
JTextField jtf = new JTextField("This is the text field");
to this: jtf = new JTextField("This is the text field");
Then, you'll only have one jtf variable (which will be an instance variable), and your action event should work.
Just remove this line:
JTextField jtf = new JTextField("This is the text field");
from constructor.
The first is an instance variable, JTextField e.g. jtf is accessible from anywhere in the class.
I am writing an eJuice Calculator. Its nowhere near finished as you will see below. My question is: I have 4 JCheckBoxes, and 5 editable JTextFields; can I use one ActionListener to do have the program execute stuff. Or do I need one listener for the CheckBoxes and one for the TextField?
This is a rough draft of code.
package ejuicecalculatorv2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EJuiceCalculatorV2 extends JFrame {
//Form Controls
private JCheckBox isPGbasedNic_CB = new JCheckBox("PG Based NIC");
private JCheckBox isPGbasedFlavor_CB = new JCheckBox("PG Based Flavor");
private JCheckBox isVGbasedNic_CB = new JCheckBox("VG Based NIC");
private JCheckBox isVGbasedFlavor_CB = new JCheckBox("VG Based Flavor");
private JTextField batchSize_TF = new JTextField(5);
private JLabel batchSize_LB = new JLabel("Batch Size:");
private JTextField baseNicStrength_TF = new JTextField(5);
private JLabel baseNicStrength_LB = new JLabel("Base NIC Strength:");
private JTextField targetNicStrength_TF = new JTextField(5);
private JLabel targetNicStrength_LB = new JLabel("Target NIC Strength:");
private JTextField totalNic_TF = new JTextField(5);
private JLabel totalNic_LB = new JLabel("Total NIC:");
private JTextField flavorStrength_TF = new JTextField(5);
private JLabel flavorStrength_LB = new JLabel("Flavoring Strength:");
private JTextField totalFlavor_TF = new JTextField(5);
private JLabel totalFlavor_LB = new JLabel("Total Flavoring:");
private JTextField vgRatio_TF = new JTextField(5);
private JLabel vgRatio_LB = new JLabel("VG Ratio:");
private JTextField pgRatio_TF = new JTextField(5);
private JLabel pgRatio_LB = new JLabel("PG Ratio:");
private JTextField additionalVG_TF = new JTextField(5);
private JLabel additionalVG_LB = new JLabel("Additional VG:");
private JTextField additionalPG_TF = new JTextField(5);
private JLabel additionalPG_LB = new JLabel("Additional PG:");
private JTextField totalVG_TF = new JTextField(5);
private JLabel totalVG_LB = new JLabel("Total VG:");
private JTextField totalPG_TF = new JTextField(5);
private JLabel totalPG_LB = new JLabel("Total PG:");
private JTextField vgBasedIng_TF = new JTextField(5);
private JLabel vgBasedIng_LB = new JLabel("Total VG Ingredients:");
private JTextField pgBasedIng_TF = new JTextField(5);
private JLabel pgBasedIng_LB = new JLabel("Total PG Ingredients:");
//Variables
private boolean _PGnicFlag;
private boolean _VGnicFlag;
private boolean _PGflavorFlag;
private boolean _VGflavorFlag;
private double baseNic;
private double targetNic;
private double totalNic;
private double flavorStrength;
private double totalFlavor;
private double batchSize;
private double totalPG;
private double totalVG;
private double additionalVG;
private double additionalPG;
private double pgBasedIng;
private double vgBasedIng;
private double pgRatio;
private double vgRatio;
public EJuiceCalculatorV2() {
super("EJuice Calculator V2");
setLayout(new FlowLayout());
//Add CheckBoxes
add(isPGbasedNic_CB);
add(isPGbasedFlavor_CB);
add(isVGbasedNic_CB);
add(isVGbasedFlavor_CB);
//Add TextFields and Labels
add(batchSize_LB);
add(batchSize_TF);
add(vgRatio_LB);
add(vgRatio_TF);
add(pgRatio_LB);
add(pgRatio_TF);
add(baseNicStrength_LB);
add(baseNicStrength_TF);
add(targetNicStrength_LB);
add(targetNicStrength_TF);
add(flavorStrength_LB);
add(flavorStrength_TF);
//Add ActionListeners
ActionListener actionListener = new ActionHandler();
isPGbasedNic_CB.addActionListener(actionListener);
isPGbasedFlavor_CB.addActionListener(actionListener);
isVGbasedNic_CB.addActionListener(actionListener);
isVGbasedFlavor_CB.addActionListener(actionListener);
batchSize_TF.addActionListener(actionListener);
vgRatio_TF.addActionListener(actionListener);
pgRatio_TF.addActionListener(actionListener);
baseNicStrength_TF.addActionListener(actionListener);
targetNicStrength_TF.addActionListener(actionListener);
flavorStrength_TF.addActionListener(actionListener);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class ActionHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent event){
//if event.getSource() == JCheckBox then execute the following code.
if(checkBox.isSelected()){
if(checkBox == isPGbasedNic_CB){
_PGnicFlag = true;
_VGnicFlag = false;
checkBox = isVGbasedNic_CB;
checkBox.setSelected(false);
}
else if(checkBox == isVGbasedNic_CB){
_VGnicFlag = true;
_PGnicFlag = false;
checkBox = isPGbasedNic_CB;
checkBox.setSelected(false);
}
else if(checkBox == isVGbasedFlavor_CB){
_VGflavorFlag = true;
_PGflavorFlag = false;
checkBox = isPGbasedFlavor_CB;
checkBox.setSelected(false);
}
else if(checkBox == isPGbasedFlavor_CB){
_PGflavorFlag = true;
_VGflavorFlag = false;
checkBox = isVGbasedFlavor_CB;
checkBox.setSelected(false);
}
}
else{
if(checkBox == isPGbasedNic_CB){
_PGnicFlag = false;
_VGnicFlag = true;
}
else if(checkBox == isVGbasedNic_CB){
_VGnicFlag = false;
_PGnicFlag = true;
}
else if(checkBox == isVGbasedFlavor_CB){
_VGflavorFlag = false;
_PGflavorFlag = true;
}
else if(checkBox == isPGbasedFlavor_CB){
_PGflavorFlag = false;
_VGflavorFlag = true;
}
}
}
}
public static void main(String[] args) {
// TODO code application logic here
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run (){
new EJuiceCalculatorV2().setVisible(true);
}
});
}
}
My question is: I have 4 JCheckBoxes, and 5 editable JTextFields; can I use one ActionListener to do have the program execute stuff. Or do I need one listener for the CheckBoxes and one for the TextField?
You have a bunch of control components, but none appear ones that would initiate an action from the GUI. Rather all of them, the JCheckBoxes and the JTextFields are there to get input, and you appear to be missing one final component, such as a JButton. I would add this component to your GUi, and I would add a single ActionListener to it and it alone. And then when pressed, it would check the state of the check boxes and the text components and then based on their state, give the user the appropriate response.
Also some, if not most or all of the JTextFields, I'd change to either JComboBoxes or JSpinners, to limit the input that the user can enter to something that is allowable since you don't want the user entering "yes" into the "Batch Size" JTextField.
For example:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.JSpinner.DefaultEditor;
#SuppressWarnings("serial")
public class JuiceTwo extends JPanel {
private static final String[] FLAVORS = {"Flavor 1", "Flavor 2", "Flavor 3", "Flavor 4"};
private static final Integer[] ALLOWABLE_BATCH_SIZES = {1, 2, 5, 10, 15, 20};
private static final String[] ALLOWABLE_VG_RATIOS = {"1/4", "1/3", "1/2", "1/1", "2/1", "3/1", "4/1", "8/1", "16/1"};
private List<JCheckBox> flavorBoxes = new ArrayList<>();
private JComboBox<Integer> batchSizeCombo;
private JSpinner vgRatioSpinner;
public JuiceTwo() {
// JPanel to hold the flavor JCheckBoxes
JPanel flavorPanel = new JPanel(new GridLayout(0, 1)); // hold them in vertical grid
flavorPanel.setBorder(BorderFactory.createTitledBorder("Flavors"));
for (String flavor : FLAVORS) {
JCheckBox flavorBox = new JCheckBox(flavor);
flavorBox.setActionCommand(flavor);
flavorPanel.add(flavorBox);
flavorBoxes.add(flavorBox);
}
batchSizeCombo = new JComboBox<>(ALLOWABLE_BATCH_SIZES);
SpinnerListModel vgRatioModel = new SpinnerListModel(ALLOWABLE_VG_RATIOS);
vgRatioSpinner = new JSpinner(vgRatioModel);
JComponent editor = vgRatioSpinner.getEditor();
if (editor instanceof DefaultEditor) {
((DefaultEditor)editor).getTextField().setColumns(4);
}
JButton getSelectionButton = new JButton("Get Selection");
getSelectionButton.setMnemonic(KeyEvent.VK_S);
getSelectionButton.addActionListener(new SelectionActionListener());
add(flavorPanel);
add(Box.createHorizontalStrut(20));
add(new JLabel("Batch Size:"));
add(batchSizeCombo);
add(Box.createHorizontalStrut(20));
add(new JLabel("VG Ratio:"));
add(vgRatioSpinner);
add(Box.createHorizontalStrut(20));
add(getSelectionButton);
}
private class SelectionActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
for (JCheckBox flavorBox : flavorBoxes) {
System.out.printf("%s selected: %b%n", flavorBox.getActionCommand(), flavorBox.isSelected());
}
System.out.println("Batch Size: " + batchSizeCombo.getSelectedItem());
System.out.println("VG Ration: " + vgRatioSpinner.getValue());
System.out.println();
}
}
private static void createAndShowGui() {
JuiceTwo mainPanel = new JuiceTwo();
JFrame frame = new JFrame("JuiceTwo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class filecabinet extends JFrame implements ActionListener {
private String folder = "";
//create buttons
private JButton a = new JButton("A");
private JButton b = new JButton("B");
private JButton c = new JButton("C");
private JButton d = new JButton("D");
private JButton e = new JButton("E");
private JButton f = new JButton("F");
private JButton g = new JButton("G");
private JButton h = new JButton("H");
private JButton i = new JButton("I");
private JButton j = new JButton("J");
private JButton k = new JButton("K");
private JButton l = new JButton("L");
private JButton m = new JButton("M");
private JButton n = new JButton("N");
private JButton o = new JButton("O");
private JButton p = new JButton("P");
private JButton q = new JButton("Q");
private JButton r = new JButton("R");
private JButton s = new JButton("S");
private JButton t = new JButton("T");
private JButton u = new JButton("U");
private JButton v = new JButton("V");
private JButton w = new JButton("W");
private JButton x = new JButton("X");
private JButton y = new JButton("Y");
private JButton z = new JButton("Z");
//create panels
private JPanel aF = new JPanel();
private JPanel gL = new JPanel();
private JPanel mR = new JPanel();
private JPanel sX = new JPanel();
private JPanel yZ = new JPanel();
private JPanel readout = new JPanel();
private JLabel notify = new JLabel("You have selected folder " + folder);
public void ComposePane(){
//set buttons to panels
aF.add(a);
aF.add(b);
aF.add(c);
aF.add(d);
aF.add(e);
aF.add(f);
//set layout of panels
aF.setLayout(new GridLayout(2,3));
gL.add(g);
gL.add(h);
gL.add(i);
gL.add(j);
gL.add(k);
gL.add(l);
gL.setLayout(new GridLayout(2,3));
mR.add(m);
mR.add(n);
mR.add(o);
mR.add(p);
mR.add(q);
mR.add(r);
mR.setLayout(new GridLayout(2,3));
sX.add(s);
sX.add(t);
sX.add(u);
sX.add(v);
sX.add(w);
sX.add(x);
sX.setLayout(new GridLayout(2,3));
yZ.add(y);
yZ.add(z);
yZ.add(readout);
readout.add(notify);
yZ.setLayout(new GridLayout(2,3));
}
public filecabinet(){
setTitle("File Cabinet");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5,1));
ComposePane();
add(aF);
add(gL);
add(mR);
add(sX);
add(yZ);
addActionListener();
}
public void actionPerformed(ActionEvent e) {
folder = ((JButton) e.getSource()).getText();
}
public void addActionListener(){
a.addActionListener(this);
b.addActionListener(this);
c.addActionListener(this);
d.addActionListener(this);
e.addActionListener(this);
f.addActionListener(this);
g.addActionListener(this);
h.addActionListener(this);
i.addActionListener(this);
j.addActionListener(this);
k.addActionListener(this);
l.addActionListener(this);
m.addActionListener(this);
n.addActionListener(this);
o.addActionListener(this);
p.addActionListener(this);
q.addActionListener(this);
r.addActionListener(this);
s.addActionListener(this);
t.addActionListener(this);
u.addActionListener(this);
v.addActionListener(this);
w.addActionListener(this);
x.addActionListener(this);
y.addActionListener(this);
z.addActionListener(this);
}
public static void main(String[]args){
filecabinet frame = new filecabinet();
final int WIDTH = 600;
final int HEIGHT = 600;
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
}
}
I would prefer not to have to write out a listener for every button
and I was wandering if I could just get the text contained in the button.
such as "You have selected foler X", X is the button chosen.
Again, either use arrays and/or a for loop to consolidate your code getting rid of code redundancy. For example:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class FileCabinet2 extends JPanel {
public static final char FIRST_LETTER = 'A';
public static final char LAST_LETTER = 'Z';
private static final float lARGE_FONT_POINTS = 32f;
private static final int GRID_COLS = 3;
private JLabel chosenLabel = new JLabel();
public FileCabinet2() {
JPanel letterPanel = new JPanel(new GridLayout(0, GRID_COLS));
ActionListener btnListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
chosenLabel.setText(evt.getActionCommand());
}
};
for (char c = FIRST_LETTER; c <= LAST_LETTER; c++) {
String buttonTitle = String.valueOf(c);
JButton button = new JButton(buttonTitle);
setFontPoints(button, lARGE_FONT_POINTS);
letterPanel.add(button);
button.addActionListener(btnListener);
}
JLabel selectionLabel = new JLabel("Selection: ", SwingConstants.RIGHT);
setFontPoints(selectionLabel, lARGE_FONT_POINTS);
setFontPoints(chosenLabel, lARGE_FONT_POINTS);
JPanel bottomPanel = new JPanel(new GridLayout(1, 0));
bottomPanel.add(selectionLabel);
bottomPanel.add(chosenLabel);
bottomPanel.setBorder(BorderFactory.createEtchedBorder());
setLayout(new BorderLayout());
add(letterPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private void setFontPoints(JComponent jComp, float points) {
jComp.setFont(jComp.getFont().deriveFont(points));
}
private static void createAndShowGui() {
FileCabinet2 mainPanel = new FileCabinet2();
JFrame frame = new JFrame("File Cabinet");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Now if you want to change how many button columns there are, all you need to do is change one constant, GRID_COLS, and the same for the size of the font, just change LARGE_FONT_POINTS.
For this:
would prefer not to have to write out a listener for every button
Create a method that accept the JPanel as the parameter and then iterate to each component in JPanel, add the action listener if the component is JButton
This one:
I was wandering if I could just get the text contained in the button.
Just set the value in the JLabel. You already get the button content right?
So, the full code is:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class filecabinet extends JFrame implements ActionListener {
private String folder = "";
// create buttons
private JButton a = new JButton("A");
private JButton b = new JButton("B");
private JButton c = new JButton("C");
private JButton d = new JButton("D");
private JButton e = new JButton("E");
private JButton f = new JButton("F");
private JButton g = new JButton("G");
private JButton h = new JButton("H");
private JButton i = new JButton("I");
private JButton j = new JButton("J");
private JButton k = new JButton("K");
private JButton l = new JButton("L");
private JButton m = new JButton("M");
private JButton n = new JButton("N");
private JButton o = new JButton("O");
private JButton p = new JButton("P");
private JButton q = new JButton("Q");
private JButton r = new JButton("R");
private JButton s = new JButton("S");
private JButton t = new JButton("T");
private JButton u = new JButton("U");
private JButton v = new JButton("V");
private JButton w = new JButton("W");
private JButton x = new JButton("X");
private JButton y = new JButton("Y");
private JButton z = new JButton("Z");
// create panels
private JPanel aF = new JPanel();
private JPanel gL = new JPanel();
private JPanel mR = new JPanel();
private JPanel sX = new JPanel();
private JPanel yZ = new JPanel();
private JPanel readout = new JPanel();
private JLabel notify = new JLabel("You have selected folder " + folder);
public void ComposePane() {
// set buttons to panels
aF.add(a);
aF.add(b);
aF.add(c);
aF.add(d);
aF.add(e);
aF.add(f);
// set layout of panels
aF.setLayout(new GridLayout(2, 3));
gL.add(g);
gL.add(h);
gL.add(i);
gL.add(j);
gL.add(k);
gL.add(l);
gL.setLayout(new GridLayout(2, 3));
mR.add(m);
mR.add(n);
mR.add(o);
mR.add(p);
mR.add(q);
mR.add(r);
mR.setLayout(new GridLayout(2, 3));
sX.add(s);
sX.add(t);
sX.add(u);
sX.add(v);
sX.add(w);
sX.add(x);
sX.setLayout(new GridLayout(2, 3));
yZ.add(y);
yZ.add(z);
yZ.add(readout);
readout.add(notify);
yZ.setLayout(new GridLayout(2, 3));
}
public filecabinet() {
setTitle("File Cabinet");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 1));
ComposePane();
add(aF);
add(gL);
add(mR);
add(sX);
add(yZ);
addActionListener(aF);
addActionListener(gL);
addActionListener(mR);
addActionListener(sX);
addActionListener(yZ);
}
public void actionPerformed(ActionEvent e) {
folder = ((JButton) e.getSource()).getText();
// set the label with folder value
notify.setText("You have selected folder " + folder);
}
// Attach event handler to each JButton in JPanel
public void addActionListener(JPanel panel) {
Component[] components = panel.getComponents();
for (Component component : components) {
if (component instanceof JButton) {
((JButton) component).addActionListener(this);
}
}
}
public static void main(String[] args) {
filecabinet frame = new filecabinet();
final int WIDTH = 600;
final int HEIGHT = 600;
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
}
}
A quick review of your code, brought your code down to this length.
Imagine, what you can achieve if you give it a bit more insight.
Furthermore, when you see that in your code, you are repeating some
lines again and again for the same thingy, you can indeed think of a
pattern that can accomplish that for you in a rightful manner, with
fewer keystrokes.
Try this modified code of yours :-)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class Filecabinet extends JFrame implements ActionListener {
private String folder = "";
//create buttons
private JButton[] button = new JButton[26];
//create panels
private JPanel aF = new JPanel();
private JPanel gL = new JPanel();
private JPanel mR = new JPanel();
private JPanel sX = new JPanel();
private JPanel yZ = new JPanel();
private JPanel readout = new JPanel();
private JLabel notify = new JLabel("You have selected folder " + folder);
public void ComposePane(){
init_Buttons(button);
//set buttons to panels
for (int i = 0; i < 6; i++)
aF.add(button[i]);
//set layout of panels
aF.setLayout(new GridLayout(2,3));
for (int i = 6; i < 12; i++)
gL.add(button[i]);
gL.setLayout(new GridLayout(2,3));
for (int i = 12; i < 18; i++)
mR.add(button[i]);
mR.setLayout(new GridLayout(2,3));
for (int i = 18; i < 24; i++)
sX.add(button[i]);
sX.setLayout(new GridLayout(2,3));
for (int i = 24; i < 26; i++)
yZ.add(button[i]);
yZ.add(readout);
readout.add(notify);
yZ.setLayout(new GridLayout(2,3));
}
private void init_Buttons(JButton[] button)
{
int value = 65;
for (int i = 0; i < button.length; i++)
{
button[i] = new JButton(Character.toString((char) value++));
button[i].addActionListener(this);
}
}
public Filecabinet(){
setTitle("File Cabinet");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5,1));
ComposePane();
add(aF);
add(gL);
add(mR);
add(sX);
add(yZ);
}
public void actionPerformed(ActionEvent e) {
folder = ((JButton) e.getSource()).getText();
notify.setText(folder);
}
public static void main(String[]args){
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
Filecabinet frame = new Filecabinet();
final int WIDTH = 600;
final int HEIGHT = 600;
//frame.setSize(WIDTH, HEIGHT);
frame.pack();
frame.setVisible(true);
}
});
}
}
You can subclass JButton and write a constructor for the subclass that takes in as a parameter a reference to the action listener, your JFrame.
For instance, your subclass could simply be:
public class YourButton extends JButton {
public YourButton(String title, ActionListener listener) {
super(title);
this.addActionListener(listener);
}
}
So instead of:
private JButton a = new JButton("A");
You would call:
private YourButton a = new YourButton("A", this);
Additionally, as others have suggested, your actionPerformed(ActionEvent e) method requires you to update your notify JLabel instance to reflect the selected button's title.
Hope that helps!
Here is my 1st frame - I want went I input text in textfield example name then click button report will display output to 2nd frame using textArea... please help me
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class Order extends JFrame implements ActionListener
{
private JPanel pInfo,pN, pIC, pDate,Blank,pBlank, button, pTotal;
private JLabel nameL,icL,DateL;
private JTextField nameTF, icTF;
private JFormattedTextField DateTF;
private JButton calB,clearB,exitB,reportB;
public Order()
{
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.setBackground(Color.gray);
pInfo = new JPanel();
pN = new JPanel();
pIC = new JPanel();
pDate = new JPanel();
nameTF = new JTextField(30);
icTF = new JTextField(30);
DateTF = new JFormattedTextField(
java.util.Calendar.getInstance().getTime());
DateTF.setEditable (false);
DateTF.addActionListener(this);
nameL = new JLabel(" NAME : ",SwingConstants.RIGHT);
icL = new JLabel(" IC : ",SwingConstants.RIGHT);
DateL = new JLabel(" DATE :",SwingConstants.RIGHT);
pInfo.setLayout(new GridLayout(10,2,5,5));
pInfo.setBorder(BorderFactory.createTitledBorder
(BorderFactory.createEtchedBorder(),"ORDER"));
pN.add(nameL);
pN.add(nameTF);
pIC.add(icL);
pIC.add(icTF);
pDate.add(DateL);
pDate.add(DateTF);
pInfo.add(pN);
pInfo.add(pIC);
pInfo.add(pDate);
pInfo.setBackground(Color.GRAY);
pN.setBackground(Color.gray);
pIC.setBackground(Color.gray);
pDate.setBackground(Color.gray);
nameL.setForeground(Color.black);
icL.setForeground(Color.black);
DateL.setForeground(Color.black);
nameTF.setBackground(Color.pink);
icTF.setBackground(Color.pink);
DateTF.setBackground(Color.pink);
contentPane.add(pInfo,BorderLayout.CENTER);
Blank = new JPanel();
pBlank = new JPanel();
button = new JPanel();
calB = new JButton("CALCULATE");
calB.setToolTipText("Click to calculate");
clearB = new JButton("RESET");
clearB.setToolTipText("Click to clear");
reportB = new JButton ("REPORT");
reportB.setToolTipText ("Click to print");
exitB = new JButton("EXIT");
exitB.setToolTipText("Click to exit");
Blank.setLayout(new GridLayout(2,2));
Blank.setBorder(BorderFactory.createTitledBorder
(BorderFactory.createEtchedBorder(),""));
button.setLayout(new GridLayout(1,4));
button.add(calB,BorderLayout.WEST);
button.add(clearB,BorderLayout.CENTER);
button.add(reportB,BorderLayout.CENTER);
button.add(exitB,BorderLayout.EAST);
Blank.add(pBlank);
Blank.add(button);
contentPane.add(Blank,BorderLayout.SOUTH);
Blank.setBackground(Color.gray);
pBlank.setBackground(Color.gray);
calB.setForeground(Color.black);
clearB.setForeground(Color.black);
reportB.setForeground(Color.black);
exitB.setForeground(Color.black);
calB.setBackground(Color.pink);
clearB.setBackground(Color.pink);
reportB.setBackground(Color.pink);
exitB.setBackground(Color.pink);
calB.addActionListener(this);
clearB.addActionListener(this);
reportB.addActionListener(this);
exitB.addActionListener(this);
}
public void actionPerformed(ActionEvent p)
{
if (p.getSource() == calB)
{
}
else if (p.getSource() == clearB)
{
}
else if (p.getSource () == reportB)
{
}
else if (p.getSource() == exitB)
{
}
}
public static void main (String [] args)
{
Order frame = new Order();
frame.setTitle("Order");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);//center the frame
}
}
If you only have one String to pass, add it to the constructor of your second JFrame:
public class SecondFrame extends JFrame {
public SecondFrame(String someValueFromFirstFrame) {
someTextField.setText(someValueFromFirstFrame);
}
}
and pass it when creating the second JFrame:
SecondFrame secondFrame = new SecondFrame(firstTextField.getText());
If there is more than one attribute to pass, consider putting them together in another class and pass the instance of this class. This saves you from changing the constructor every time you need to pass an additional variable.
Simply add some reference to the first frame in the second or pass the value you're interested in to the second frame before you display it.
As for the code example you requested:
public class SecondFrame extends JFrame {
private JFrame firstFrame;
public SecondFrame(JFrame firstFrame) {
this.firstFrame = firstFrame;
}
}
Now you can obtain everything there is to obtained from the firstFrame through the internal reference to it.