sorry for the simple question, but I'm really new to this and can't really find an answer. I'm confused on how to add two (or more) JButtons. I can't seem to get both to show, only one ever shows, which is the "Division" one.
My most recent attempt is below. How can I get both buttons to show at the button of the window?
public class Calculator implements ActionListener {
private JFrame frame;
private JTextField xfield, yfield;
private JLabel result;
private JButton subtractButton;
private JButton divideButton;
private JPanel xpanel;
public Calculator() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
xpanel = new JPanel();
xpanel.setLayout(new GridLayout(3,2));
xpanel.add(new JLabel("x:"));
xfield = new JTextField("0", 5);
xpanel.add(xfield);
xpanel.add(new JLabel("y:"));
yfield = new JTextField("0", 5);
xpanel.add(yfield);
xpanel.add(new JLabel("x*y="));
result = new JLabel("0");
xpanel.add(result);
frame.add(xpanel, BorderLayout.NORTH);
subtractButton = new JButton("Subtract");
frame.add(subtractButton, BorderLayout.SOUTH);
subtractButton.addActionListener(this);
divideButton = new JButton("Division");
frame.add(divideButton, BorderLayout.SOUTH);
divideButton.addActionListener(this);
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent event) {
int x = 0;
int y = 0;
String xText = xfield.getText();
String yText = yfield.getText();
try {
x = Integer.parseInt(xText);
}
catch (NumberFormatException e) {
x = 0;
}
try {
y = Integer.parseInt(yText);
}
catch (NumberFormatException e) {
y = 0;
}
result.setText(Integer.toString(x-y));
}
}
You need to add both buttons in a JPanel before adding that JPanel in the SOUTH of your frame.
So instead of
subtractButton = new JButton("Subtract");
frame.add(subtractButton, BorderLayout.SOUTH);
subtractButton.addActionListener(this);
divideButton = new JButton("Division");
frame.add(divideButton, BorderLayout.SOUTH);
divideButton.addActionListener(this);
You can do this
JPanel southPanel = new JPanel();
subtractButton = new JButton("Subtract");
southPanel.add(subtractButton);
subtractButton.addActionListener(this);
divideButton = new JButton("Division");
southPanel.add(divideButton);
divideButton.addActionListener(this);
frame.add(southPanel , BorderLayout.SOUTH);
Use Eclipse and WindowBuilder for your Swing interfaces and add as many buttons as you like or move them around with your mouse. Its much easier especially if you are new to this and you'll learn a lot from the generated code.
Related
I am trying to add a JScrollPane (createTeamScrollPane) to a JPanel (createTeamPanel) that I have. I have a frame, with a BorderLayout with the NORTH portion being used by a JPanel called tabMenu, and then the CENTER portion I would like my 'createTeamPanel' to have this scrolling ability as it will have more content than what I can fit on the screen at once. I am then adding both panels to the frame. Currently the code as is runs but the window appears blank. Once resizing the window, I then see the 3 buttons in the NORTH portion of my frame (why is this happening?) and when I click on 'Create Team' it brings up the list of JLabels and JButtons I expect but I don't see any scrolling bars?
public static void main (String args[]) {
JFrame frame = new JFrame();
frame.setTitle("v0.01");
frame.setSize(800, 800);
//frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel tabMenu = new JPanel();
JPanel createTeamPanel = new JPanel();
createTeamPanel.setLayout(new BoxLayout(createTeamPanel, BoxLayout.Y_AXIS));
createTeamPanel.setSize(800, 700);
createTeamPanel.setVisible(showCreateTeamPanel);
createTeamPanel.setBackground(Color.gray);
JScrollPane createTeamScrollPane = new JScrollPane(createTeamPanel);
createTeamScrollPane.setBounds(50, 50, 200, 500);
createTeamScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
createTeamScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
createTeamScrollPane.setPreferredSize(new Dimension(500,500));
//createTeamPanel.add(createTeamScrollPane);
List<Player> teamList = MockTeams.initTeam();
int xcoord = 100;
int ycoord = 50;
for(Player player : teamList) {
JLabel label = new JLabel(player.getName());
label.setBounds(xcoord, ycoord, Constants.buttonWidth, Constants.buttonHeight);
JButton addToTeamBtn = new JButton("Add to team");
addToTeamBtn.setBounds(xcoord + 100, ycoord, Constants.buttonWidth, Constants.buttonHeight);
addToTeamBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myTeam.add(player);
addToTeamBtn.setEnabled(false);
}
});
createTeamPanel.add(label);
//createTeamFrame.add(label);
createTeamPanel.add(addToTeamBtn);
//createTeamFrame.add(addToTeamBtn);
ycoord += 50;
}
JButton createTeamBtn = new JButton("Create Team");
createTeamBtn.setBounds(0,0,150,20);
createTeamBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Hide/Show Create team panel
if (!showCreateTeamPanel) {
showCreateTeamPanel = true;
createTeamPanel.setVisible(showCreateTeamPanel);
} else {
showCreateTeamPanel = false;
createTeamPanel.setVisible(showCreateTeamPanel);
}
}
});
JButton manageTeamBtn = new JButton("Team Statistics");
manageTeamBtn.setBounds(100,150,150,40);
JButton resetBtn = new JButton("Reset Season");
resetBtn.setBounds(100,200,150,40);
tabMenu.add(createTeamBtn);
tabMenu.add(manageTeamBtn);
tabMenu.add(resetBtn);
mainPanel.add(tabMenu, BorderLayout.NORTH);
mainPanel.add(createTeamPanel, BorderLayout.CENTER);
frame.add(mainPanel);
}
Expected result is to see a scrolling ability on the createTeamPanel but it is not there.
Fixed: I was able to add the JScrollPane to the mainPanel with:
mainPanel.add(createTeamScrollPane, BorderLayout.CENTER);
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.
It was working before I added the 3D array of textfields, then nothing showed from all I have created. After removing them, still nothing shows up. How do I add a 3D array of JTextFields without ruining the whole layout?
I initialized them first:
int numOfPuzzles;
int puzzleSize;
JTabbedPane tabbedPane;
JPanel[] southPanel;
JPanel[] centerPanel;
JPanel[] sudokuPanel;
JPanel[] buttonsPanel;
JButton[] nextButton;
JButton[] prevButton;
ArrayList<int[][]> sudoku;
JTextField[][][] textFields;
public SudokuSolverUI(ArrayList<int[][]> sudoku){
this.sudoku = sudoku;
this.numOfPuzzles = numOfPuzzles;
this.puzzleSize = puzzleSize;
this.setTitle("Sudoku XY");
this.setVisible(true);
this.setSize(900, 700);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setComponents();
}
then at public void setComponents I instantiated the necessary components, added them to the panel, then:
public void setComponents(){
this.tabbedPane = new JTabbedPane();
centerPanel = new JPanel[this.numOfPuzzles];
sudokuPanel = new JPanel[this.numOfPuzzles];
buttonsPanel = new JPanel[this.numOfPuzzles];
southPanel = new JPanel[this.numOfPuzzles];
nextButton = new JButton[this.numOfPuzzles];
prevButton = new JButton[this.numOfPuzzles];
for(int i=0;i<this.numOfPuzzles;i++){
nextButton[i] = new JButton("Next");
nextButton[i].addActionListener(this);
prevButton[i] = new JButton("Prev");
prevButton[i].addActionListener(this);
centerPanel[i] = new JPanel();
sudokuPanel[i] = new JPanel();
buttonsPanel[i] = new JPanel();
southPanel[i] = new JPanel();
for(int j=0;j<this.sudoku.get(i).length;j++){
for(int k=0;k<this.sudoku.get(i).length;k++){
textFields[i][j][k] tf = new JTextField();
sudokuPanel[i].add(tf);
}
}
southPanel[i].setLayout(new FlowLayout());
southPanel[i].add(prevButton[i]);
southPanel[i].add(nextButton[i]);
centerPanel[i].setLayout(new BorderLayout());
centerPanel[i].add(southPanel[i], BorderLayout.SOUTH);
centerPanel[i].add(sudokuPanel[i], BorderLayout.CENTER);
centerPanel[i].add(buttonsPanel[i], BorderLayout.EAST);
centerPanel[i].setVisible(true);
centerPanel[i].validate();
tabbedPane.addTab("Puzzle #"+(i+1), centerPanel[i]);
this.getContentPane().add(tabbedPane);
}
}
nothing shows up. Please help.
If this is all you'll get a NullPointerException which you should be able to see at the console. You did not initialize numOfPuzzle but you use it as index in setComponents.
the mission here is to create JButtons from a String in ActionListener, but we need a way to refresh the GUI panel so it know that there is now variable for the button creater in the GUI. i have a feeling that the button creater must be in ActionListener and there is a command like repaint() or removeAll that is missing inside the ActionListener.
public JButton[] turneringer = null;
JButton AntallTurneringer = new JButton("number of buttons");
JMenuBar meny = new JMenuBar();
JMenu fil = new JMenu("somthing");
JMenuItem angre = new JMenuItem("deleate on button");
JMenuItem angre2 = new JMenuItem("deleate all buttons");
int d;
int i;
public GUI(){
this.setTitle("somthing");
this.setSize(500,500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
this.setJMenuBar(meny);
meny.add(fil);
fil.add(angre2);
fil.add(angre);
angre2.addActionListener(this);
angre.addActionListener(this);
AntallTurneringer.addActionListener(this);
this.add(AntallTurneringer);
AntallTurneringer.setVisible(true);
if(d > 0){
turneringer = new JButton[d];
for(i = 0; i < d; i++){
turneringer[d] = new JButton();
turneringer[d].addActionListener(this);
turneringer[d].setText("Turnering "+(i+1));
turneringer[d].setVisible(true);
this.add(turneringer[d]);
}}
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource().equals(AntallTurneringer)){
String tu = JOptionPane.showInputDialog(null, "number of buttons");
d = Integer.parseInt(tu);
}
}
You could use a separate panel for the buttons. would simplify the whole thing.
private JPanel buttonPnl;
public void actionPerformed(ActionEvent e){
buttonPnl.invalidate();
buttonPnl.clear();
//create the new buttons
buttonPnl.validate();
buttonPnl.repaint();
}
I have solved it, it were no need for repainting or clearing anything. the first problem in the code were that i had used [d] inside the array, and not[i]. the second problem were the placement of the for loop. this is the working code under.
public JButton[] turneringer = null;
JButton AntallTurneringer = new JButton("Velg antall turneringer");
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
int d;
public GUI(){
this.setTitle("Squash Turnering");
this.setLayout(new GridLayout());
this.setSize(500,500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
panel1.setBackground(Color.BLACK);
panel2.setBackground(Color.RED);
AntallTurneringer.addActionListener(this);
AntallTurneringer.setVisible(true);
panel1.add(AntallTurneringer);
add(panel1);
add(panel2);
panel2.setVisible(false);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource().equals(AntallTurneringer)){
String tu = JOptionPane.showInputDialog(null, "number of buttons you want to add");
d = Integer.parseInt(tu);
turneringer = new JButton[d];
for(int i = 0; i < d; i++){
turneringer[i] = new JButton();
turneringer[i].addActionListener(this);
turneringer[i].setText("Turnering "+(i+1));
turneringer[i].setVisible(true);
turneringer[i].setSize(100, 100);
panel2.add(turneringer[i]);
}
panel1.setVisible(false);
panel2.setVisible(true);
}
}}
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.