Best way to pass values from JTextField into a method? - java

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.

Related

Place label for text box above the box and not to the side

As stated in the title i need to move the label for the text box to be above the box and not to the side. attached i have a picutres of what i mean. what i have vs what i want i have tried searching for it but i cannot seem to find the answer im looking for/not exactly sure what to look up. I have tried using JFrame but it made a separate window unless i need to make the entire GUI a JFrame for me to get the result i want?
Also the actionPerformed method has things but it is irrelevant to the question but displays correctly still.
import java.awt.event.\*;
import javax.swing.\*;
import java.text.DecimalFormat;
public class Project4 extends JFrame implements ActionListener {
private JTextArea taArea = new JTextArea("", 30, 20);
ButtonGroup group = new ButtonGroup();
JTextField name = new JTextField(20);
boolean ch = false;
boolean pep = false;
boolean sup = false;
boolean veg = false;
DecimalFormat df = new DecimalFormat("##.00");
double cost = 0.0;
public Project4() {
initUI();
}
public final void initUI() {
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
getContentPane().add(panel1, "North");
getContentPane().add(panel2, "West");
getContentPane().add(panel3, "Center");
getContentPane().add(panel4, "East");
panel4.setLayout(new BoxLayout(panel4, BoxLayout.Y_AXIS));
getContentPane().add(panel5, "South");
JButton button = new JButton("Place Order");
button.addActionListener(this);
panel5.add(button);
JButton button2 = new JButton("Clear");
button2.addActionListener(this);
panel5.add(button2);
panel3.add(taArea);
JCheckBox checkBox1 = new JCheckBox("Cheese Pizza") ;
checkBox1.addActionListener(this);
panel4.add(checkBox1);
JCheckBox checkBox2 = new JCheckBox("Pepperoni Pizza");
checkBox2.addActionListener(this);
panel4.add(checkBox2);
JCheckBox checkBox3 = new JCheckBox("Supreme Pizza");
checkBox3.addActionListener(this);
panel4.add(checkBox3);
JCheckBox checkBox4 = new JCheckBox("Vegetarian Pizza");
checkBox4.addActionListener(this);
panel4.add(checkBox4);
JRadioButton radioButton1 = new JRadioButton("Pick Up");
group.add(radioButton1);
radioButton1.addActionListener(this);
panel1.add(radioButton1);
JRadioButton radioButton2 = new JRadioButton("Delivery");
group.add(radioButton2);
radioButton2.addActionListener(this);
panel1.add(radioButton2);
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
panel5.add(name_label);
panel5.add(name);
setSize(600, 300);
setTitle("Pizza to Order");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent action) {
}
public static void main(String[] args) {
Project4 ex = new Project4();
ex.setVisible(true);
}
}
You can use a nested JPanel with another layout in order to achieve that. I would go with BorderLayout here. You can also other layouts that allow vertical orientation. Visiting the visual guide to Layout Managers will help you spot them.
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
JPanel verticalNestedPanel = new JPanel(new BorderLayout());
verticalNestedPanel.add(name_label, BorderLayout.PAGE_START);
verticalNestedPanel.add(name, BorderLayout.PAGE_END);
panel5.add(verticalNestedPanel);

Having Multiple JButtons

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.

Effect on JTextfield due to JComboBox

I am using JCombobox and just below that there is a panel which contains JTextFields. Whenever i click on the dropdown (JCombobox) some portion of JTextField disappears itself. I don't know what to do. I am unable to post a pic of the problem here because i am a new user and my reputation is below 10.
public class MainClass {
public static void main(String args[]){
Form form = new Form();
int width = 400;
int height = 400;
form.setSize(width, height);
form.setVisible(true);
form.setTitle("Create Network");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
form.setLocation((screenSize.width-width)/2, (screenSize.height-height)/2);
}
}
This is the form class
public class Form extends JFrame {
private JLabel ipAddress, networkTopo, numNodes;
private JTextField nodes;
private JButton addIp;
private JButton removeIp;
private JButton next, back;
private JPanel jPanel, jPanel1, jPanel2, commonPanel;
private JComboBox<String> dropDown;
private String[] topologies = { "Grid", "Diagnol Grid", "Bus", "Ring",
"Star" };
public Form() {
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
setResizable(false);
this.getContentPane().setBackground(Color.WHITE);
// add(Box.createRigidArea(new Dimension(0,10)));
GridLayout commonPanelLayout = new GridLayout(0, 2);
commonPanelLayout.setVgap(10);
commonPanel = new JPanel(commonPanelLayout);
commonPanel.setVisible(true);
commonPanel.setAlignmentX(commonPanel.LEFT_ALIGNMENT);
commonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
commonPanel.setBackground(Color.white);
numNodes = new JLabel("Number of Nodes");
commonPanel.add(numNodes);
nodes = new JTextField(20);
commonPanel.add(nodes);
networkTopo = new JLabel("Network Topology");
commonPanel.add(networkTopo);
dropDown = new JComboBox<String>(topologies);
dropDown.setBackground(Color.WHITE);
commonPanel.add(dropDown);
add(commonPanel);
add(Box.createRigidArea(new Dimension(0, 10)));
ipAddress = new JLabel("IP Addresses");
ipAddress.setAlignmentX(ipAddress.LEFT_ALIGNMENT);
ipAddress.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
add(ipAddress);
add(Box.createRigidArea(new Dimension(0, 10)));
jPanel = new JPanel(new FlowLayout());
jPanel.setVisible(true);
jPanel.setAlignmentX(jPanel.LEFT_ALIGNMENT);
jPanel.setBackground(Color.WHITE);
// jPanel1.setAutoscrolls(true);
add(jPanel);
GridLayout layout = new GridLayout(0, 1);
jPanel1 = new JPanel();
layout.setVgap(10);
// jPanel1.setBackground(Color.WHITE);
jPanel1.setVisible(true);
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(jPanel1);
scroll.setAutoscrolls(true);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setPreferredSize(new Dimension(300, 150));
jPanel1.setPreferredSize(new Dimension(scroll.getPreferredSize().width,
Integer.MAX_VALUE));
jPanel.add(scroll);
jPanel2 = new JPanel(new GridLayout(0, 1, 10, 10));
jPanel2.setBackground(Color.WHITE);
jPanel2.setVisible(true);
jPanel.add(jPanel2);
addIp = new JButton("Add");
jPanel2.add(addIp);
removeIp = new JButton("Remove");
jPanel2.add(removeIp);
JPanel savePanel = new JPanel(new FlowLayout());
savePanel.setVisible(true);
savePanel.setAlignmentX(savePanel.LEFT_ALIGNMENT);
savePanel.setBackground(Color.white);
back = new JButton("Back");
back.setAlignmentX(next.LEFT_ALIGNMENT);
back.setEnabled(false);
savePanel.add(back);
next = new JButton("Next");
next.setAlignmentX(next.LEFT_ALIGNMENT);
savePanel.add(next);
add(savePanel);
AddIPEvent addIPEvent = new AddIPEvent();
addIp.addActionListener(addIPEvent);
RemoveIPEvent removeIPEvent = new RemoveIPEvent();
removeIp.addActionListener(removeIPEvent);
}
public class AddIPEvent implements ActionListener {
public void actionPerformed(ActionEvent e) {
JPanel subPanel = new JPanel(new FlowLayout());
// subPanel.setBackground(Color.WHITE);
subPanel.setVisible(true);
JCheckBox jCheckBox = new JCheckBox();
// jCheckBox.setBackground(Color.WHITE);
subPanel.add(jCheckBox);
JTextField ip = new JTextField(12);
subPanel.add(ip);
JTextField nodesInIp = new JTextField(6);
nodesInIp.setVisible(false);
subPanel.add(nodesInIp);
jPanel1.add(subPanel);
jPanel1.repaint();
jPanel1.revalidate();
}
}
public class RemoveIPEvent implements ActionListener {
public void removeIP(Container container) {
for (Component c : container.getComponents()) {
if (c instanceof JCheckBox) {
if (((JCheckBox) c).isSelected()) {
jPanel1.remove(container);
jPanel.revalidate();
jPanel1.repaint();
}
} else if (c instanceof Container) {
removeIP((Container) c);
}
}
}
public void actionPerformed(ActionEvent e) {
removeIP(jPanel1);
}
}
}
After Clicking on the Add button and then clicking on the JComboBox will make portion of JTextField dissapear. Could someone pls point out the mistake?
Whenever i click on the dropdown (JCombobox) some portion of JTextField disappears itself.
//jPanel1.setPreferredSize(new Dimension(scroll.getPreferredSize().width, Integer.MAX_VALUE));
Don't set the preferred size of components. The layout manager will determine the preferred size as components are added/removed. Then scrollbars will appear as required.
jPanel1.repaint();
jPanel1.revalidate();
The order should be:
jPanel1.revalidate();
jPanel1.repaint();
The revalidate() first invokes the layout manager before it is repainted.
//form.setSize(width, height);
form.pack();
Again, don't try to set the size. Let the layout managers do their jobs. The pack() will size the frame based on the sizes of the components added to the frame.

Java Nesting Panels Transparency issue with alpha value

I'm a third grade computer engineer student and I'm trying to do a game project. I added a background image to my JFrame. And I tried to make the other panels transparent which I added to frame. I use alpha value for this, Ex: new Color(0,0,0,125). I olso use cardLayout in my program and for every calling a new segment or new page at the center panel; alphavalue takes the whole panels transparency and implement it to the selected panel and it creates a problem. Example : I have 7 buttons at left panel and when I click crimes button, crime panel comes to the center panel and left panel comes inside of center panel with buttons again(transparently).
I have 16 classes, so I only added main class.
Sorry for bad grammar. I hope you can understand me and help me.
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
public class TheMafia {
public static ImageIcon scale(ImageIcon i,int x,int y) {
Image img = i.getImage();
Image newimg = img.getScaledInstance(x,y,Image.SCALE_SMOOTH);
i = new ImageIcon(newimg);
return i;
}
public static void setButton (JButton b,int x,int y) {
b.setPreferredSize(new Dimension(x,y));
b.setBackground(Color.gray);
b.setForeground(Color.white);
b.setBorder(new LineBorder(Color.black,1));
b.setFont(new Font("Serif",Font.BOLD,18));
}
public static void main(String[] args) {
ImageIcon home2 = new ImageIcon("home.jpg");
home2 = scale(home2,1366,768);
JFrame theMafia = new JFrame();
theMafia.setTitle("The Mafia Game - Best game in the world!");
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
theMafia.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theMafia.setContentPane(new JLabel(home2));
theMafia.setLayout(new BorderLayout());
//theMafia.setLayout(new FlowLayout());
//theMafia.setExtendedState(JFrame.MAXIMIZED_BOTH);
theMafia.setSize(800,700);
theMafia.setLocationRelativeTo(null);
theMafia.setVisible(true);
p1.setBackground(new Color(0,0,0,35));
p2.setBackground(new Color(0,0,0,65));
p1.setPreferredSize(new Dimension(250,150));
p2.setPreferredSize(new Dimension(250,150));
//theMafia.add(p1);
//theMafia.add(p2);
// kullanıcı oluşturuldu
User u1 = new User();
// suçlar oluşturuldu
Crime c1 = new Crime();
c1.setName("Yaşlı Kadın");
c1.setDifficulty(5);
c1.setStrength(1);
c1.setMoney(11);
Crime c2 = new Crime();
c2.setName("Dükkan Hırsızlığı");
c2.setDifficulty(10);
c2.setStrength(3);
c2.setMoney(67);
Crime c3 = new Crime();
c3.setName("Araba Hırsızlığı");
c3.setDifficulty(20);
c3.setStrength(6);
c3.setMoney(133);
// suçun seçilmesi
final JPanel crimes = new JPanel(new CardLayout());
//crimes.setBackground(new Color(0,0,0,65));
ImageIcon suçişle = new ImageIcon("suçişle.jpg");
suçişle = scale(suçişle,50,50);
JButton yap = new JButton("Suçu işle!",suçişle);
setButton(yap,100,65);
JPanel crime1 = new JPanel(new GridLayout(2,1));
crime1.setBackground(new Color(0,0,0,35));
crime1.setForeground(Color.white);
JLabel crime1Info = new JLabel("Suç : "+c1.getName()+"\n Para : "+c1.getMoney()+"\n Yapabilme ihtimali : "+c1.getCapable()+"\n Güç : "+c1.getStrength());
crime1Info.setFont(new Font("Serif",Font.BOLD,15));
crime1.add(crime1Info);
crime1.add(yap);
JPanel crime2 = new JPanel(new GridLayout(2,1));
crime2.setBackground(new Color(0,0,0,35));
crime2.setForeground(Color.white);
JLabel crime2Info = new JLabel("Suç : "+c2.getName()+"\n Para : "+c2.getMoney()+"\n Yapabilme ihtimali : "+c2.getCapable()+"\n Güç : "+c2.getStrength());
crime2Info.setFont(new Font("Serif",Font.BOLD,15));
crime2.add(crime2Info);
crime2.add(yap);
JPanel crime3 = new JPanel();
crime3.setBackground(new Color(0,0,0,35));
crime3.setForeground(Color.white);
JLabel crime3Info = new JLabel("Suç : "+c3.getName()+"\n Para : "+c3.getMoney()+"\n Yapabilme ihtimali : "+c3.getCapable()+"\n Güç : "+c3.getStrength());
crime2Info.setFont(new Font("Serif",Font.BOLD,15));
crime3.add(crime3Info);
crime3.add(yap);
crimes.add(crime1,c1.getName());
crimes.add(crime2,c2.getName());
crimes.add(crime3,c3.getName());
String crimesNames [] = {c1.getName(),c2.getName(),c3.getName()};
JComboBox crimesbox = new JComboBox(crimesNames);
crimesbox.setEditable(false);
crimesbox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout) (crimes.getLayout());
cl.show(crimes,(String)evt.getItem());
}
});
// menu
final JPanel menus = new JPanel(new CardLayout());
//menus.setBackground(new Color(0,0,0,35));
// crime
JPanel crime = new JPanel(new BorderLayout());
crime.setBackground(new Color(0,0,0,35));
crime.add(crimesbox,BorderLayout.PAGE_START);
crime.add(crimes,BorderLayout.SOUTH);
ImageIcon crimeimage = new ImageIcon("thief.png");
crimeimage = scale(crimeimage,50,50);
final JButton crimeButton = new JButton("Suçlar",crimeimage);
setButton(crimeButton,178,76);
crimeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) (menus.getLayout());
if (e.getSource() == crimeButton) {
cl.show(menus,"suç");
}
}
});
// weapon shop
JPanel weaponShop = new JPanel();
//weaponShop.setBackground(new Color(0,0,0,125));
final JButton weaponShopButton = new JButton("Silah Dükkanı");
setButton(weaponShopButton,178,76);
// building
JPanel buildingPanel = new JPanel();
//buildingPanel.setBackground(new Color(0,0,0,125));
final JButton buildingButton = new JButton("Binalar");
setButton(buildingButton,178,76);
// nightlife
JPanel nightLife = new JPanel();
//nightLife.setBackground(new Color(0,0,0,35));
final JButton nightLifeButton = new JButton("Gece Hayatı");
setButton(nightLifeButton,178,76);
// treatment center
JPanel treatmentCenter = new JPanel();
//treatmentCenter.setBackground(new Color(0,0,0,35));
final JButton treatmentCenterButton = new JButton("Tedavi Merkezi");
setButton(treatmentCenterButton,178,76);
// casino
JPanel casinoPanel = new JPanel();
//casinoPanel.setBackground(new Color(0,0,0,35));
final JButton casinoButton = new JButton("Gazino");
setButton(casinoButton,178,76);
// home page
JPanel home = new JPanel();
home.setBackground(new Color(0,0,0,35));
ImageIcon homeimage = new ImageIcon("home.jpg");
homeimage = scale(homeimage,1200,800);
JLabel homelabel= new JLabel();
home.add(homelabel);
ImageIcon homeicon = new ImageIcon("home_icon.png");
homeicon = scale(homeicon,50,50);
final JButton homeButton = new JButton("Home",homeicon);
setButton(homeButton,178,76);
homeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) (menus.getLayout());
if (e.getSource() == homeButton) {
cl.show(menus,"home");
}
}
});
menus.add(home,"home");
menus.add(crime,"suç");
menus.add(weaponShop,"silahDükkanı");
menus.add(buildingPanel,"bina");
menus.add(nightLife,"geceHayatı");
menus.add(treatmentCenter,"TedaviMerkezi");
menus.add(casinoPanel,"gazino");
Color grisi=new Color(13,13,13);
JPanel menusButton = new JPanel(new GridLayout(10,1));
//menusButton.setBackground(grisi);
menusButton.add(homeButton);
menusButton.add(crimeButton);
menusButton.add(weaponShopButton);
menusButton.add(buildingButton);
menusButton.add(nightLifeButton);
menusButton.add(treatmentCenterButton);
menusButton.add(casinoButton);
menusButton.setOpaque(false);
theMafia.add(menusButton,BorderLayout.WEST);
theMafia.add(menus,BorderLayout.CENTER);
}
}
Swing does not handle transparent background properly. Swing expects components to be either opaque or non-opaque and the transparency causes a problem because the component is neither.
Check out Background With Transparency for more information and a couple of solutions to solve the problem.

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.

Categories