This is as the title says, I need your help to refresh the contents of a JLabel.
I explain my worries.
I have a first JFarm or I have a calendar (a DatePicker) which allows me to select a date and a button.
When I click on the button it opens a new window and in this famous window I have my JLabel or I would like to see my date.
In this last window I wrote:
System.out.println(datePicker.getDate());
labelDate.setText(datePicker.getDate());
When I first open my window everything works fine, but if I close it, I change the date in my DatePicker and reopen the window by clicking on my button the date does not change !!!
It always remains on the first date sent.
Yet my:
System.out.println(datePicker.getDate());
Returns the correct date correctly each time.
Do you have an idea ?
Thank you all.
I post my full code but it's very long and not very clean... sorry.
the main window :
public class App extends JFrame{
private JPanel contentPane;
static final int rowMultiplier = 4;
private DatePicker datePicker;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
App frame = new App();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public App() throws SQLException{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
this.setTitle("Absences Management");
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
// =================== PanelTitle ===================================
JPanel panelTitle = new JPanel();
contentPane.add(panelTitle, BorderLayout.NORTH);
JLabel labelTitle = new JLabel("Absence Management");
panelTitle.add(labelTitle);
// ================== PanelMenu =====================================
JPanel panelMenu = new JPanel();
contentPane.add(panelMenu, BorderLayout.WEST);
panelMenu.setLayout(new BoxLayout(panelMenu, BoxLayout.Y_AXIS));
// Border and name for the panel
panelMenu.setBorder(BorderFactory.createTitledBorder(" Menu "));
// create buttons and set the actions for the menu
JButton buttonAddClass = new JButton(new ActionButtonClassManagement(this,"Class management"));
JButton buttonQuit = new JButton(new ActionButtonQuit(this," Quit "));
// add different components in the Panel Menu
panelMenu.add(buttonAddClass);
panelMenu.add(buttonQuit);
// ================= PanelCalendar ==================================
JPanel panelCalendar = new JPanel();
contentPane.add(panelCalendar, BorderLayout.CENTER);
panelCalendar.setAlignmentX(CENTER_ALIGNMENT);
// black border for the panel
panelCalendar.setBorder(BorderFactory.createTitledBorder(" Calendar "));
JLabel labelCalendar = new JLabel("CALENDAR :");
panelCalendar.add(labelCalendar);
// ===== create the calendar
// settings
DatePickerSettings dateSettings = new DatePickerSettings();
dateSettings.setVisibleClearButton(false);
// set the current date by default
dateSettings.setAllowEmptyDates(false);
datePicker = new DatePicker(dateSettings);
// create a icon
URL dateImageURL = FullDemo.class.getResource("/img/calendar20x20.png");
Image calendarImage = Toolkit.getDefaultToolkit().getImage(dateImageURL);
ImageIcon calendarIcon = new ImageIcon(calendarImage);
// create button and set the icon
JButton datePickerButton = datePicker.getComponentToggleCalendarButton();
datePickerButton.setText("");
datePickerButton.setIcon(calendarIcon);
// add the calendar to the PanelCalendar
panelCalendar.add(datePicker);
// create a button Show absences
JButton buttonAbsence = new JButton(new ActionButtonAbsences(this,"Absences", datePicker));
//add the button to the panelCalendar
panelCalendar.add(buttonAbsence);
}
}
The class for my button Absence :
public class ActionButtonAbsences extends AbstractAction{
private App windowAbsence;
private DatePicker datePicker = new DatePicker();
private String dateString = new String();
public ActionButtonAbsences(App app, String textButton, DatePicker datePicker) {
// TODO Auto-generated constructor stub
super(textButton);
this.datePicker = datePicker;
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
dateString = datePicker.getText();
WindowAbsence fen = new WindowAbsence(windowAbsence, datePicker, dateString);
}
}
And the window that opens when I press the button Absence :
public class WindowAbsence extends JDialog implements ActionListener{
private static JPanel panelWindow = new JPanel(new BorderLayout());
private JPanel panelTitle = new JPanel();
private JPanel panelWindowLeft = new JPanel();
private JPanel panelWindowRight = new JPanel();
private JComboBox comboBoxClass;
private JComboBox comboBoxStudent;
private DatePicker datePicker;
private JLabel labelDate = new JLabel();
private String dateString = new String();
private ModelTable modelTableAbsence = new ModelTable();
private JTable tableAbsence = new JTable(modelTableAbsence);
public WindowAbsence(Frame frame, DatePicker datePicker, String date){
//super call the constructor of the main window
// the first argument is the mother window
// the second argument disable this window
super(frame,true);
labelDate.setText(datePicker.getText());
this.dateString = date;
// add BorderLayout in this Window
this.setLayout(new BorderLayout());
// name of the window
this.setTitle("Absences");
// size of the window
this.setSize(700, 600);
// effect for the red cross
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setLocationRelativeTo(null);
this.datePicker = datePicker;
// =================== Data bases connection ============================
/**
* download mysql-connector-java-5.1.40.tar.gz
* https://dev.mysql.com/downloads/file/?id=470332
* Clic droit sur le dossier du projet
* Clic right on the folder of the project
* Build Path
* Add external Archive
*/
DataBase database = new DataBase();
String url = "jdbc:mysql://localhost:3306/AbsenceManagement";
String user = "root";
String pass = "";
String driver = "com.mysql.jdbc.Driver";
try {
database.connectionDataBase(url, user, pass, driver);
// ================== PANEL TITLE ==================================
//JLabel labelDate = new JLabel();
panelTitle.add(labelDate);
//labelDate.setText(datePicker.getText());
date = datePicker.getText();
System.out.println("date: "+date);
labelDate.setText(date);
panelWindow.add(panelTitle, BorderLayout.NORTH);
// ================ PANEL LEFT =====================================
panelWindowLeft.setBorder(BorderFactory.createTitledBorder(" Absences "));
// =========== panelComboBoxLabelClass ======================
JPanel panelLabelComboBoxClass = new JPanel();
panelLabelComboBoxClass.setLayout(new BoxLayout(panelLabelComboBoxClass, BoxLayout.LINE_AXIS));
JLabel labelComboBoxClass = new JLabel("Class :");
comboBoxClass = new JComboBox();
comboBoxClass.addItem("");
panelLabelComboBoxClass.add(labelComboBoxClass);
panelLabelComboBoxClass.add(comboBoxClass);
Statement statementClass = DataBase.connection.createStatement();
ResultSet resultClass = statementClass.executeQuery("SELECT class FROM Class");
//receive the MetaData
ResultSetMetaData resultMetaClass = (ResultSetMetaData) resultClass.getMetaData();
// add the data in the row
while(resultClass.next()){
comboBoxClass.addItem(resultClass.getObject(1));
}
comboBoxClass.addActionListener(this);
resultClass.close();
statementClass.close();
// =========== panelComboBoxLabelStudent ======================
JPanel panelLabelComboBoxStudent = new JPanel();
panelLabelComboBoxStudent.setLayout(new BoxLayout(panelLabelComboBoxStudent, BoxLayout.LINE_AXIS));
JLabel labelComboBoxStudent = new JLabel("Student :");
comboBoxStudent = new JComboBox();
panelLabelComboBoxStudent.add(labelComboBoxStudent);
panelLabelComboBoxStudent.add(comboBoxStudent);
// ========== panelComboBoxHour ===============================
int rowMultiplier = 4;
int row = rowMultiplier;
TimePickerSettings timeSettings = new TimePickerSettings();
timeSettings.setDisplayToggleTimeMenuButton(true);
timeSettings.setDisplaySpinnerButtons(false);
JPanel panelComboBoxHour = new JPanel();
panelComboBoxHour.setLayout(new BoxLayout(panelComboBoxHour, BoxLayout.LINE_AXIS));
JLabel labelComboBoxFrom = new JLabel("From :");
panelComboBoxHour.add(labelComboBoxFrom);
TimePicker timePickerFrom = new TimePicker(timeSettings);
timePickerFrom = new TimePicker();
panelComboBoxHour.add(timePickerFrom, getConstraints(1, (row * rowMultiplier), 1));
//panelComboBoxHour.addLabel(panelComboBoxHour, 1, (row++ * rowMultiplier), "Time 1, Default Settings:");
JLabel labelComboBoxTo = new JLabel("To :");
panelComboBoxHour.add(labelComboBoxTo);
TimePicker timePickerTo = new TimePicker();
timePickerTo = new TimePicker();
panelComboBoxHour.add(timePickerTo, getConstraints(1, (row * rowMultiplier), 1));
// ========== panel button add absence ==============
JPanel panelButtonAddAbsence = new JPanel();
panelButtonAddAbsence.setLayout(new BoxLayout(panelButtonAddAbsence, BoxLayout.LINE_AXIS));
JButton buttonAddAbsence = new JButton("Add Absence");
panelButtonAddAbsence.add(buttonAddAbsence);
// ========================================
panelWindowLeft.setLayout(new BoxLayout(panelWindowLeft, BoxLayout.PAGE_AXIS));
panelWindowLeft.add(panelLabelComboBoxClass);
panelWindowLeft.add(panelLabelComboBoxStudent);
panelWindowLeft.add(panelComboBoxHour);
panelWindowLeft.add(panelButtonAddAbsence);
panelWindow.add(panelWindowLeft, BorderLayout.WEST);
// ====================== PANEL RIGHT ================================
panelWindowRight.setBorder(BorderFactory.createTitledBorder(" Absences "));
//=================== TABLE =======================================
Statement statementAbsence = DataBase.connection.createStatement();
// requet SQL
ResultSet resultAbsence;
ResultSetMetaData resultMetaAbsence;
modelTableAbsence.addColumn("Student");
modelTableAbsence.addColumn("Date");
modelTableAbsence.addColumn("To");
modelTableAbsence.addColumn("From");
// requete SQL
resultAbsence = statementAbsence.executeQuery("SELECT * FROM Absence WHERE `dateAbsence`='"+datePicker.getDate().toString()+"'");
//receive the MetaData
resultMetaAbsence = (ResultSetMetaData) resultAbsence.getMetaData();
modelTableAbsence.fireTableDataChanged();
if(!resultAbsence.next()){
System.out.println("null");
}else{
// add the data in the row
do{
modelTableAbsence.addRow(new Object[]{
resultAbsence.getObject(2).toString(),
resultAbsence.getObject(3).toString(),
resultAbsence.getObject(4).toString(),
resultAbsence.getObject(5).toString()
});
}while(resultAbsence.next());
// close the statementClass
statementAbsence.close();
resultAbsence.close();
// ========= replace id student by firstName and lastName
Statement statementNameStudent = DataBase.connection.createStatement();
ResultSet resultNameStudent = null;
int nbRow = modelTableAbsence.getRowCount();
for(int i = 0; i < nbRow; i++){
resultNameStudent = statementNameStudent.executeQuery("SELECT firstName, lastName FROM Student WHERE `id`='"+modelTableAbsence.getValueAt((i), 0)+"'");
// add the data in the row
while(resultNameStudent.next()){
modelTableAbsence.setValueAt(
(resultNameStudent.getObject(1)+" "+resultNameStudent.getObject(2)),i,0);
}
}
statementNameStudent.close();
resultNameStudent.close();
}
// =================================================================
JScrollPane scrollPane = new JScrollPane(tableAbsence);
panelWindowRight.add(scrollPane);
panelWindow.add(panelWindowRight, BorderLayout.CENTER);
this.setContentPane(panelWindow);
this.setVisible(true);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static GridBagConstraints getConstraints(int gridx, int gridy, int gridwidth) {
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.WEST;
gc.gridx = gridx;
gc.gridy = gridy;
gc.gridwidth = gridwidth;
return gc;
}
// model table for table schedule
public class ModelTableSchedule extends DefaultTableModel {
ModelTableSchedule(Object[][] dataStudent, String[] columnNamesStudent) {
super(dataStudent, columnNamesStudent);
}
// the function return always false, the table is never editable
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
public void actionPerformed(ActionEvent arg0) {
modelTableAbsence.fireTableDataChanged();
// =================== Data bases connection ============================
/**
* download mysql-connector-java-5.1.40.tar.gz
* https://dev.mysql.com/downloads/file/?id=470332
* Clic droit sur le dossier du projet
* Clic right on the folder of the project
* Build Path
* Add external Archive
*/
DataBase database = new DataBase();
String url = "jdbc:mysql://localhost:3306/AbsenceManagement";
String user = "root";
String pass = "";
String driver = "com.mysql.jdbc.Driver";
try {
database.connectionDataBase(url, user, pass, driver);
// add value in ComboBox
Statement statementStudent;
comboBoxStudent.removeAllItems();
statementStudent = DataBase.connection.createStatement();
ResultSet resultStudent = statementStudent.executeQuery("SELECT * FROM `Student` WHERE `class` LIKE '"+comboBoxClass.getSelectedItem().toString()+"'");
//receive the MetaData
ResultSetMetaData resultMetaStudent = (ResultSetMetaData) resultStudent.getMetaData();
// add the data in the row
while(resultStudent.next()){
comboBoxStudent.addItem((resultStudent.getObject(2)+" "+resultStudent.getObject(3)));
}
comboBoxStudent.revalidate();
resultStudent.close();
statementStudent.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thank you for your help.
Again me,
I found my error !
In my WindowAbsence :
private static JPanel panelWindow = new JPanel(new BorderLayout());
The panel it was in static...
i hope will serve for someone !
Related
I'm very new at using JPanels/Tabs and so have run into a bunch of issues with my code.
I've created a table from SQL that I want to be able to be viewed inside of a tab.
So I have a class first of all that includes a login and then takes you to a window with three tabs:
public class UserInterface
{
UserInterface() {
JFrame frame = new JFrame(); //create a frame
frame.setTitle("Bet Worthiness"); //sets title of frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //system exit when user closes window
frame.setResizable(false); //prevents user from resizing frame
JTextField text = new JTextField(10); //creates a text box
frame.getContentPane().setBackground(new Color(255, 243, 181)); //background colour
//Create panels
JPanel accountTab = new JPanel();
JPanel bettingTab = new JPanel();
JPanel leaderboardTab = new JPanel();
JTabbedPane tabs = new JTabbedPane(); //Create the tab container
tabs.setBounds(40, 20, 1400, 700); //Set tab container position
//Account Details label
JLabel accountLabel = new JLabel();
accountLabel.setText("Account Details");
accountLabel.setFont(new Font("Helvetica", Font.BOLD, 20));
accountTab.add(accountLabel);
//Betting label
JLabel bettingLabel = new JLabel();
bettingLabel.setText("Place Bets");
bettingLabel.setFont(new Font("Helvetica", Font.BOLD, 20));
bettingTab.add(bettingLabel);
//Leaderboard label
JLabel leaderboardLabel = new JLabel();
leaderboardLabel.setText("Leaderboard");
leaderboardLabel.setFont(new Font("Helvetica", Font.BOLD, 20));
leaderboardTab.add(leaderboardLabel);
//Associate each panel with the corresponding tab
tabs.add("Account", accountTab);
tabs.add("Betting", bettingTab);
tabs.add("Leaderboard", leaderboardTab);
frame.add(tabs); //Add tabs to the frame
frame.setSize(1500, 800);
frame.setLayout(null);
frame.setVisible(true);
}
}
I have then created a table on SQL in a separate class that I want to be embedded in the 'leaderboard' tab:
public class Leaderboard extends JFrame {
public void displayLeaderboard() {
try
{
String url = "jdbc:mysql://localhost:3306/bettingappdb";
String user = "root";
String password = "lucyb";
Connection con = DriverManager.getConnection(url, user, password);
String query = "SELECT * FROM users";
Statement stm = con.createStatement();
ResultSet res = stm.executeQuery(query);
String columns[] = { "Username", "Success Rate" };
String data[][] = new String[20][3];
int i = 0;
while (res.next()) {
String nom = res.getString("Username");
int successRate = res.getInt("SuccessRate");
data[i][0] = nom;
data[i][1] = successRate + "";
i++;
}
DefaultTableModel model = new DefaultTableModel(data, columns);
JTable table = new JTable(model);
table.setShowGrid(true);
table.setShowVerticalLines(true);
JScrollPane pane = new JScrollPane(table);
JFrame f = new JFrame("Leaderboard");
JPanel panel = new JPanel();
panel.add(pane);
f.add(panel);
f.setSize(500, 500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
} catch(SQLException e) {
e.printStackTrace();
}
}
}
Is there any way to put this table within the tab? Thank you :)
You could add the following to your Code.
JPanel lbTab = new JPanel();
Leaderboard leaderboard = new Leaderboard();
lbTab.add(leaderboard);
the Leaderboard is now in your JTabbedPane. If you want to add the Leaderboard as well as the leaderboardLabel in one Tab i suggest something like https://docs.oracle.com/javase/tutorial/uiswing/components/panel.html or How to layout? (JFrame, JPanel, etc.) for your first steps :) .
What I am after is I would like for whenever someone checks a checkbox, the text for which the box they selected is output to the right panel(I have a split pane). Right now it is not responding so I don't think my BoxHandler is working properly(implements ItemListener). My function addBoxListeners is supposed to add item listeners for each checkbox that I have and the function I overrode in BoxHandler, function itemStateChanged should add text to the right panel, and I know that addText is working because I tested it outside of the itemListener stuff.
void addText(String s) { // adds text to the right panel, adds string s
JLabel temp = new JLabel();
temp.setText(s);
temp.setBorder(border1);
rightPanel.add(temp);
}
void addBoxes() {
int i = 0;
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
for (i = 0; i < 10; i++) {
JCheckBox tempBox = new JCheckBox("word " + i);
boxes.add(tempBox);
leftPanel.add(tempBox, gbc);
//leftPanel.add(new JCheckBox("word" + i), gbc);
}
}
private class BoxHandler implements ItemListener{
public void itemStateChanged(ItemEvent event) {
for (JCheckBox checkBox : boxes) {
if (checkBox.isSelected() ) {
addText(checkBox.getText());
}
}
}
}
void addBoxListeners() { // add listeners to all the boxes in the arraylist
BoxHandler handler = new BoxHandler();
int i = 0;
for ( i = 0; i < boxes.size(); i++) {
boxes.get(i).addItemListener(handler);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CheckBox2 cb = new CheckBox2();
cb.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
cb.pack();
cb.setLocationRelativeTo(null);
cb.addBoxListeners();
cb.setVisible(true);
}
Below is part of my class declaration:
public class CheckBox2 extends JFrame {
private ArrayList<JCheckBox> boxes = new ArrayList<JCheckBox>();
JSplitPane splitPane;
EmptyBorder border1 = new EmptyBorder(5, 5, 5, 5);
private JPanel leftPanel = new JPanel();
private JPanel rightPanel = new JPanel();
JLabel labelOne = new JLabel();
JLabel labelTwo = new JLabel();
...
I've been trying to get te grips of Java (just because:)). At the moment I'm stuck on a 'calculator'. My intention is to select a overall subject through a ComboBox after which a second ComboBox shows which units can be calculated for said subject.
My problem is that the second ComboBox does not update and I'm having a hard time finding my oversight. Is anyone able to show my where I'm going wrong?
note: The terms for unitstring are placeholders for the time being:).
public class UserInterface implements Runnable{
String unitstring = "Select a subject";
#Override
public void run() {
JFrame frame = new JFrame("Radiation Calculator 2.0");
frame.setPreferredSize(new Dimension(350, 250));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
createComponents(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public void createComponents(Container container) {
GridLayout layout = new GridLayout(4, 2);
container.setLayout(layout);
JLabel subject = new JLabel("Select a subject");
String[] subjectStrings = {"Wavelenght", "Radioactive Decay", "Radiation Dose"};
JComboBox subjectsel = new JComboBox(subjectStrings);
subjectsel.addActionListener(this::actionPerformed);
JLabel unit = new JLabel("Select a unit");
String[] unitStrings = {unitstring};
JComboBox unitsel = new JComboBox(unitStrings);
JLabel input = new JLabel("Select a input");
JTextField userinput = new JTextField("");
JButton calculate = new JButton("Calculate");
JTextArea result = new JTextArea("");
container.add(subject);
container.add(subjectsel);
container.add(unit);
container.add(unitsel);
container.add(input);
container.add(userinput);
container.add(calculate);
container.add(result);
}
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
int print = cb.getSelectedIndex();
System.out.println(print);
unitArray(print);
}
public void unitArray(int x) {
if (x == 0) {
unitstring = "Lambda";
}
if (x == 1) {
unitstring = "Bequerel";
}
if (x == 2) {
unitstring = "Gray";
}
System.out.println(unitstring);
}
}
i wrote a code using GridLayou, however i cant manage to delete the grey background and use the img i plugged as a background, and the picture demonstrate the problem:
Can someone please help?
this is the code
public class mainClass {
private static JButton start;
static BackgroundPanel bp = null;
static JFrame mainf = null;
static int R;
final static boolean shouldFill = true;
// group turns boolean
boolean redTurn = false;
boolean blueTurn = false;
boolean greenTurn = false;
boolean yellowTurn = false;
// boards
static ImageIcon gameBoard;
static ImageIcon blueBoard;
static ImageIcon qBoard;
// dice
static JButton dice_1 = null;
public static void main(String[] args) throws IOException {
mainf = new JFrame ("سين جيم");
// background
BufferedImage mFrame = ImageIO.read(new File("B1.png"));
bp = new BackgroundPanel(mFrame);
mainf.add(bp);
bp.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// c.fill = GridBagConstraints.HORIZONTAL;
// Hi string
JLabel hi = new JLabel ("أهلا وسهلا بكم في لعبة الليدو");
Font fs = hi.getFont();
hi.setFont(fs.deriveFont(50f));
bp.add(hi);
// empty
// button
start = new JButton ( "لنبدأاللعب");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20; //make this component tall
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(10,0,0,0); //top padding
bp.add(start, c);
// Action Listener
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// starting the game area
// emptying all
bp.removeAll();
bp.revalidate();
bp.repaint();
BufferedImage mFrame2= null;
try {
// changing background
mFrame2 = ImageIO.read(new File("B2.png"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// setting new background
bp = new BackgroundPanel(mFrame2);
bp.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// adding gameBoard
gameBoard = new ImageIcon("gameBoard.png");
JLabel gameBoard_1 = new JLabel(gameBoard);
bp.add(gameBoard_1);
// adding blueBoard
blueBoard = new ImageIcon("blueBoard.png");
JLabel blueBoard_1 = new JLabel(blueBoard);
bp.add(blueBoard_1);
GridLayout experimentLayout = new GridLayout(4,4); // rows | , cols-
blueBoard_1.setLayout(experimentLayout);
// gameName panel
JPanel gameName = new JPanel();
gameName.setLayout(new GridLayout(1,0));
JLabel Ledu= new JLabel ("لعبة اللدو");
Font font3 = new Font("Verdana", Font.BOLD, 30);
Ledu.setFont(font3);
Ledu.setForeground(Color.WHITE);
gameName.add(Ledu);
// teamPanel
JPanel teamName = new JPanel();
teamName.setLayout(new GridLayout(2,0));
JLabel blue= new JLabel ("الفريق الأرزق");
Font font2 = new Font("Verdana", Font.BOLD, 20);
blue.setFont(font2);
blue.setForeground(Color.BLUE);
JLabel red= new JLabel ("الفريق الأحمر");
red.setFont(font2);
red.setForeground(Color.RED);
JLabel yellow= new JLabel ("الفريق الأصفر");
yellow.setFont(font2);
yellow.setForeground(Color.YELLOW);
JLabel green= new JLabel ("الفريق الأخضر");
green.setFont(font2);
green.setForeground(Color.GREEN);
// team panel
teamName.add(blue);
teamName.add(red);
teamName.add(yellow);
teamName.add(green);
// adding question
JPanel question = new JPanel();
question.setLayout(new GridLayout(3,2));
ImageIcon q = new ImageIcon("Q.png");
JLabel q_1 = new JLabel(q);
// adding Question panel
question.add(q_1);
// dicePanel
final JPanel dicePanel = new JPanel();
dicePanel.setLayout(new GridLayout(4,0));
ImageIcon dice = new ImageIcon("dice.png");
dice_1 = new JButton(dice);
// adding dice panel
dicePanel.add(dice_1);
dice_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dicePanel.remove(dice_1);
dicePanel.revalidate();
dicePanel.repaint();
ImageIcon dice = new ImageIcon("dice.gif");
dice_1 = new JButton(dice);
dicePanel.add(dice_1);
// random number
Random r = new Random();
R = r.nextInt(10) + 2;
System.out.println(R);
}
});
// Centeralizing Ledu
Ledu.setHorizontalAlignment(SwingConstants.CENTER);
gameName.setAlignmentX(Component.CENTER_ALIGNMENT);
blue.setHorizontalAlignment(SwingConstants.CENTER);
red.setHorizontalAlignment(SwingConstants.CENTER);
yellow.setHorizontalAlignment(SwingConstants.CENTER);
green.setHorizontalAlignment(SwingConstants.CENTER);
teamName.setAlignmentX(Component.CENTER_ALIGNMENT);
// no backgrounf color
Ledu.setOpaque( false );
gameName.setOpaque( false );
blue.setOpaque( false );
red.setOpaque( false );
yellow.setOpaque( false );
green.setOpaque( false );
teamName.setOpaque( false );
question.setOpaque( false );
dicePanel.setOpaque( false );
// final add
blueBoard_1.add(gameName, BorderLayout.PAGE_START);
blueBoard_1.add(teamName, BorderLayout.CENTER);
blueBoard_1.add(question, BorderLayout.LINE_END);
blueBoard_1.add(dicePanel, BorderLayout.PAGE_END);
/*
// add dice
ImageIcon dice = new ImageIcon("dice.png");
dice_1 = new JButton(dice);
dice_1.setSize(100, 70);
bp.add(dice_1);
// changin to moving dice
dice_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bp.remove(dice_1);
bp.revalidate();
bp.repaint();
ImageIcon dice = new ImageIcon("dice.gif");
dice_1 = new JButton(dice);
dice_1.setSize(100, 70);
bp.add(dice_1);
// random number
Random r = new Random();
int R = r.nextInt(10) + 2;
System.out.println(R);
}
});
*/
mainf.setContentPane(bp);
};}); // end of start actionListener
mainf.pack();
mainf.setVisible(true);
};
// dice class
}
A JPanel is opaque by default so you see a grey background.
You need to use:
panel.setOpaque( false );
if you add a panel to your component containing the background image.
By the way you should NOT be using static variables. Look at the examples from the Swing tutorial for a better way to create your frames. That is create a class to represent your game. This would be a JPanel. Then you define all the variables you need for you game in this class. Then you simple add the panel to the frame. You should NOT be createing components in the main() method.
Currently working on a BMR/TDEE calculator. This calculator consists of taking the users age, gender, weight and height, and uses this information to calculate a BMR and TDEE value. I've created a GUI for this, and my final step is to do the actual calculations. (Some minor changes left to do i.e. changing the height panel but thats irrelevant to this question).
What is the best way to pass instance variables into static methods? My JTextField's are instance variables within my class, and I have two methods to calculate BMR and TDEE respectively (static methods).
Code is posted below.
The variables I need to use are pretty much all the textField ones, and these need to be passed into calcBMR() and calcTDEE(). My initial idea was to make all of these variables static and just use getText() and plug these values into the formula I'm using, which goes something along the lines of:
10 x weight (kg) + 6.25 x height (cm) - 5 x age (y) + 5.
Does this way sound feasible or is there a better way given my code? Any advice on how to do this efficiently is appreciated.
public class BmrCalcv2 extends JFrame {
// Frames and main panels
static JFrame mainFrame;
static JPanel mainPanel;
static JPanel combinedGAHWpanel; // combines genderPanel, agePanel, heightPanel, weightPanel - this
// is a BorderLayout, whereas
// gender/agePanel are FlowLayouts.
static JPanel weightHeightPanel; // Combines weight and height panel into out flowlayout panel, which is then combined into the above borderlayout panel
// Image components
static JPanel imgPanel;
private JLabel imgLabel;
private JLabel activityLevelHelp;
// Menu-bar components
static JMenuBar menuBar;
static JMenu saveMenu, optionMenu, helpMenu;
// Age components
static JPanel agePanel;
private JLabel ageLabel;
private JLabel yearsLabel;
private JTextField ageTextField;
// Gender components
static JPanel genderPanel;
private JLabel genderLabel;
private JRadioButton genderMale;
private JRadioButton genderFemale;
// Height components
static JPanel heightPanel;
private JLabel heightLabel;
private JTextField heightCMField;
private JLabel heightFTLabel;
private JLabel heightINCHLabel;
private JTextField heightFTField;
private JTextField heightINCHField;
private JToggleButton cmButton;
private JToggleButton feetButton;
// Weight components
static JPanel weightPanel;
private JLabel weightLabel;
private JTextField weightField;
private JToggleButton kgButton;
private JToggleButton lbButton;
// TDEE and BMR Components
static JPanel tdeePanel;
static JPanel tdeeBMRPanel;
static JPanel activityLevelPanel;
static JPanel bmrTDEEValuesPanel;
static JPanel bmrValuePanel;
static JPanel tdeeValuePanel;
private JLabel tdeeQuestionLabel;
private JLabel activityLevelLabel;
private JComboBox activityLevelBox;
private JRadioButton tdeeYes;
private JRadioButton tdeeNo;
private JLabel bmrLabel;
private JLabel tdeeLabel;
private JButton calculate;
// Default values for gender/weight/height and other variables
String[] activityLevels = {"Sedentary", "Lightly Active", "Moderately Active", "Very Active", "Extra Active"};
String genderSelection = "M";
String weightSelection = "kg";
String heightSelection = "cm";
String tdeeSelection = "no";
String ageValue;
String weightValue;
String heightValue;
static String bmrValue = "N/A";
static String tdeeValue = "N/A";
public BmrCalcv2(String title) {
// Main JFrame
setTitle("BMR/TDEE Calculator");
mainPanel = new JPanel();
// All JPanel declarations
menuBar = new JMenuBar();
imgPanel = new JPanel();
agePanel = new JPanel();
genderPanel = new JPanel();
heightPanel = new JPanel();
weightPanel = new JPanel();
weightHeightPanel = new JPanel(new BorderLayout());
combinedGAHWpanel = new JPanel(new BorderLayout()); // Create a new panel used to combine
// genderPanel, agePanel, weightPanel, heightPanel below
tdeeBMRPanel = new JPanel(new BorderLayout());
tdeePanel = new JPanel();
activityLevelPanel = new JPanel();
bmrTDEEValuesPanel = new JPanel(new BorderLayout());
bmrValuePanel = new JPanel();
tdeeValuePanel = new JPanel();
// Image panel declaration
imgLabel = new JLabel(new ImageIcon("filesrc//mainlogo.png"));
activityLevelHelp = new JLabel(new ImageIcon("filesrc//question-mark.png"));
imgPanel.add(imgLabel);
// JPanel layout managers
agePanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
genderPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
// Menu JComponents
saveMenu = new JMenu("Save");
optionMenu = new JMenu("Options");
helpMenu = new JMenu("Help");
menuBar.add(saveMenu);
menuBar.add(optionMenu);
menuBar.add(helpMenu);
// Age JComponents
ageLabel = new JLabel("Age:");
yearsLabel = new JLabel("<html><i>years</i><html>");
ageTextField = new JTextField(5);
agePanel.add(ageLabel);
agePanel.add(ageTextField);
agePanel.add(yearsLabel);
// Gender JComponents
genderLabel = new JLabel("Gender:");
genderMale = new JRadioButton("Male", true);
genderFemale = new JRadioButton("Female");
genderPanel.add(genderLabel);
genderPanel.add(genderMale);
genderPanel.add(genderFemale);
ButtonGroup genderGroup = new ButtonGroup(); // groups male and female radio buttons together so that only one can be selected
genderGroup.add(genderMale);
genderGroup.add(genderFemale);
genderMale.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String genderSelection = "M";
}
});
genderFemale.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String genderSelection = "F";
}
});
// Height JComponents
heightLabel = new JLabel("Height:");
heightCMField = new JTextField(4);
heightFTField = new JTextField(3);
heightFTLabel = new JLabel("ft");
heightINCHLabel = new JLabel("inch");
heightINCHField = new JTextField(3);
cmButton = new JToggleButton("cm", true);
feetButton = new JToggleButton("feet");
heightPanel.add(heightLabel);
ButtonGroup heightGroup = new ButtonGroup();
heightGroup.add(cmButton);
heightGroup.add(feetButton);
heightPanel.add(heightCMField);
heightPanel.add(heightFTField);
heightPanel.add(heightFTLabel);
heightPanel.add(heightINCHField);
heightPanel.add(heightINCHLabel);
heightPanel.add(cmButton);
heightPanel.add(feetButton);
heightFTField.setVisible(false);
heightFTLabel.setVisible(false);
heightINCHField.setVisible(false);
heightINCHLabel.setVisible(false);
cmButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
heightSelection = "cm";
heightINCHField.setVisible(false);
heightFTField.setVisible(false);
heightFTLabel.setVisible(false);
heightINCHLabel.setVisible(false);
heightCMField.setVisible(true);
weightPanel.revalidate();
weightPanel.repaint();
}
});
feetButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
heightSelection = "feet";
heightINCHField.setVisible(true);
heightFTField.setVisible(true);
heightFTLabel.setVisible(true);
heightINCHLabel.setVisible(true);
heightCMField.setVisible(false);
weightPanel.revalidate();
weightPanel.repaint();
}
});
// Weight JComponents
weightLabel = new JLabel("Weight:");
weightField = new JTextField(4);
kgButton = new JToggleButton("kg", true);
lbButton = new JToggleButton("lbs");
weightPanel.add(weightLabel);
weightPanel.add(weightField);
weightPanel.add(kgButton);
weightPanel.add(lbButton);
ButtonGroup weightGroup = new ButtonGroup();
weightGroup.add(kgButton);
weightGroup.add(lbButton);
kgButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
weightSelection = "kg";
}
});
lbButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
weightSelection = "lb";
}
});
// tdee JComponents
tdeeQuestionLabel = new JLabel("Calculate TDEE Also?");
tdeeYes = new JRadioButton("Yes");
tdeeNo = new JRadioButton("No", true);
ButtonGroup tdeeButton = new ButtonGroup();
tdeeButton.add(tdeeYes);
tdeeButton.add(tdeeNo);
tdeePanel.add(tdeeQuestionLabel);
tdeePanel.add(tdeeYes);
tdeePanel.add(tdeeNo);
// activitylevel JComponents
activityLevelLabel = new JLabel("Activity Level: ");
activityLevelBox = new JComboBox(activityLevels);
activityLevelBox.setSelectedIndex(0);
activityLevelPanel.add(activityLevelLabel);
activityLevelPanel.add(activityLevelBox);
activityLevelPanel.add(activityLevelHelp);
activityLevelBox.setEnabled(false);
activityLevelHelp
.setToolTipText("<html><b>Sedentary:</b> little or no exercise, deskjob<<br /><b>Lightly Active:</b> little exercise/sports 1-3 days/week<br /><b>Moderately active:</b> moderate exercise/sports 3-5 days/week<br /><b>Very active:</b> hard exercise or sports 6-7 days/week<br /><b>Extra active:</b> hard daily exercise or sports & physical labor job </html>");
tdeeYes.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
tdeeSelection = "yes";
activityLevelBox.setEnabled(true);
}
});
tdeeNo.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
tdeeSelection = "no";
activityLevelBox.setEnabled(false);
}
});
// tdee and BMR value components
bmrValue = calcBmr();
bmrLabel = new JLabel("<html><br /><br /><font size=4>You have a <i><font color=red>BMR</font></i> of: " + bmrValue + "<font></html>");
tdeeLabel = new JLabel("<html><br /><font size=4>You have a <i><font color=red>TDEE</font></i> of: " + tdeeValue + "<font></html>");
calculate = new JButton("Calculate");
bmrTDEEValuesPanel.add(calculate, BorderLayout.NORTH);
bmrTDEEValuesPanel.add(bmrLabel, BorderLayout.CENTER);
bmrTDEEValuesPanel.add(tdeeLabel, BorderLayout.SOUTH);
// Debugging panels for buttons (remove when complete)
calculate.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println("Male:" + genderMale.isSelected());
System.out.println("Female:" + genderFemale.isSelected() + "\n");
System.out.println("Kg:" + kgButton.isSelected());
System.out.println("LB:" + lbButton.isSelected() + "\n");
System.out.println("CM:" + cmButton.isSelected());
System.out.println("Feet:" + feetButton.isSelected() + "\n");
System.out.println("TDEE Yes:" + tdeeYes.isSelected());
System.out.println("TDEE No:" + tdeeNo.isSelected());
System.out.println("-------------------------------------");
}
});
// Adding sub JPanels to main JPanel
mainPanel.add(imgPanel);
combinedGAHWpanel.add(agePanel, BorderLayout.NORTH); // Combine genderPanel and agePanel (which are both flowLayouts) into a
// single BorderLayout panel where agePanel is given the Northern spot and
// genderPanel is given the center spot in the panel
weightHeightPanel.add(weightPanel, BorderLayout.NORTH); // Nested borderlayouts, the weightHeightPanel is another borderLayout which is nested
// into the southern position of the combinedGAHW border layout.
weightHeightPanel.add(heightPanel, BorderLayout.CENTER);
weightHeightPanel.add(tdeeBMRPanel, BorderLayout.SOUTH);
combinedGAHWpanel.add(genderPanel, BorderLayout.CENTER);
combinedGAHWpanel.add(weightHeightPanel, BorderLayout.SOUTH);
mainPanel.add(combinedGAHWpanel);
// adding to tdeeBMRPanel
tdeeBMRPanel.add(tdeePanel, BorderLayout.NORTH);
tdeeBMRPanel.add(activityLevelPanel, BorderLayout.CENTER);
tdeeBMRPanel.add(bmrTDEEValuesPanel, BorderLayout.SOUTH);
// Adding main JPanel and menubar to JFrame
setJMenuBar(menuBar);
add(mainPanel);
}
public static String calcBmr() {
return bmrValue;
}
public static String calcTDEE() {
return tdeeValue;
}
public static void main(String[] args) {
BmrCalcv2 gui = new BmrCalcv2("BMR/TDEE Calculator");
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setSize(330, 500);
gui.setResizable(false);
}
}
Thanks.