I have got this bit so far but I keep getting errors. I don't now what is happening, I have looked for tutorials online, but I don't now how to fix my problem.
JComboBox<String> cmdChoose = new JComboBox<String>();
cmdChoose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (cmdChoose.getSelectedItem() == "Json Sign") {
/* I am getting the error here it is below it says mDataone
cannot be resolved so please help me! */
mDataone.setVisible(true);
}
if (cmdChoose.getSelectedItem() == "Summon") {
}
}
});
cmdChoose.setBounds(149, 11, 181, 27);
mainPage.getContentPane().add(cmdChoose);
cmdChoose.addItem("Json Sign");
cmdChoose.addItem("Summon");
cmdChoose.setSelectedItem(null);
Label cglbl = new Label("Command Generators:");
cglbl.setBounds(10, 16, 133, 22);
mainPage.getContentPane().add(cglbl);
JPanel mDataone = new JPanel();
mDataone.setBounds(10, 74, 324, 209);
mainPage.getContentPane().add(mDataone);
mDataone.setLayout(new GridLayout(1, 0, 0, 0));
You have created an inner class for handling the action and the mDataone is declared after it, so create it before handling the action event, but the best way is to make it static.
One more thing that you should do in your code is that you should use equals() or equalsIgnoreCase(), cmdChoose.getSelectedItem().equalsIgnoreCase("Json Sign"). Hope it helps...
You are making the JPanel mdataone to be visible before attaching it to your JFrame. You have put the declaration of the JPanel at the end of the code, so when the setVisible() method is called in ActionPerformed() method then you get an error saying that mdataone is not defined. So to resolve this error you need to place the below code from its actual place (i.e. from the end) to the above of the actionPerformed() method.
JPanel mDataone = new JPanel();
mDataone.setBounds(10, 74, 324, 209);
mainPage.getContentPane().add(mDataone);
mDataone.setLayout(new GridLayout(1, 0, 0, 0));
Like this?
JPanel mDataone = new JPanel();
mDataone.setBounds(10, 74, 324, 209);
mainPage.getContentPane().add(mDataone);
mDataone.setLayout(new GridLayout(1, 0, 0, 0));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
mDataone.add(tabbedPane);
JPanel first_line = new JPanel();
tabbedPane.addTab("1st Line", null, first_line, null);
JPanel second_line = new JPanel();
tabbedPane.addTab("2nd Line", null, second_line, null);
JPanel third_line = new JPanel();
tabbedPane.addTab("3rd Line", null, third_line, null);
JPanel forth_line = new JPanel();
tabbedPane.addTab("4th Line", null, forth_line, null);
JComboBox<String> cmdChoose = new JComboBox<String>();
cmdChoose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (cmdChoose.getSelectedItem() == "Json Sign") {
mDataone.setVisible(true);
}
if (cmdChoose.getSelectedItem() == "Summon") {
}
}
});
cmdChoose.setBounds(149, 11, 181, 27);
mainPage.getContentPane().add(cmdChoose);
cmdChoose.addItem("Json Sign");
cmdChoose.addItem("Summon");
cmdChoose.setSelectedItem(null);
Related
I want when you click to button it adds a label on a panel. Outside of the Action Listener works fine, but inside doesn't do anything, nothing error code or anything.
(Some parts of the code missing, I deleted because I think there isn't relevant that)
JPanel panel1 = new JPanel();
panel1.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
panel1.setBounds(60, 80, 128, 128);
frmmain.getContentPane().add(panel1);
JLabel label1 = new JLabel ();
JButton btnTest = new JButton("Test");
btnTest.setFont(new Font("Bahnschrift", Font.PLAIN, 21));
btnTest.setBounds(240, 367, 121, 57);
btnTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
panel1.add(label1);
}
catch (Exception e2)
{
System.err.println(e2);
}
}
});
public class Mdiag extends JDialog implements ActionListener {
private static final long serialVersionUID = 1L;
public JButton btnClose,ok ;
public JLabel lblImgErr = new JLabel(new ImageIcon("err.png"));
public JLabel title = new JLabel(), message = new JLabel();
private static Mdiag mInstance;
public Mdiag(JFrame parent, String title,String message) {
super(parent, true);
setUndecorated(true);
getContentPane().setLayout(new GridLayout(1, 1));
setPreferredSize(new Dimension(444, 155));
setBounds(((int) getToolkit().getScreenSize().getWidth() - 444) / 2,
((int) getToolkit().getScreenSize().getHeight() - 155) / 2,
444, 155);
JPanel mainDgPanel = new JPanel();
mainDgPanel
.setBorder(new LineBorder(new Color(255, 255, 255), 3, true));
mainDgPanel.setBounds(0, 0, 444, 155);
getContentPane().add(mainDgPanel);
mainDgPanel.setLayout(null);
mainDgPanel.setBackground(Color.decode("#C7AA5"));
//add Title
JLabel lblTitle = new JLabel(title);
lblTitle.setBounds(190, 0, 80, 25);
panel.add(lblTitle);
//add Message
JTextArea txtrTextarea = new JTextArea(message);
txtrTextarea.setRows(2);
txtrTextarea.setBounds(76, 62, 336, 80);
txtrTextarea.setFont(new Font("Iskoola Pota", Font.PLAIN, 18));
txtrTextarea.setEditable(false);
txtrTextarea.setFocusable(false);
txtrTextarea.setOpaque(false);
txtrTextarea.setBorder(null);
txtrTextarea.setWrapStyleWord(true);
txtrTextarea.setLineWrap(true);
txtrTextarea.setForeground(Color.decode("#FFFFFF"));
mainDgPanel.add(txtrTextarea);
//add ok button
JPanel panelButtons = new JPanel();
panelButtons.setBounds(43, 115, 336, 30);
panelButtons.setBackground(Color.decode("#C7AA5"));
panelButtons.setBorder(new EmptyBorder(0, 0, 0, 0));
mainDgPanel.add(panelButtons);
JLabel lblNewLabel = lblImgErr;
lblNewLabel.setBounds(10, 62, 45, 43);
mainDgPanel.add(lblNewLabel);
ok=new JButton("OK");
panelButtons.add(ok);
ok.addActionListener(this);
//add close button
JPanel panel = new JPanel();
panel.setBounds(1, 1, 440, 27);
mainDgPanel.add(panel);
panel.setBackground(Color.WHITE);
panel.setLayout(null);
btnClose=new JButton(new ImageIcon("close.gif"));
btnClose.setBounds(406, 0, 39, 25);
panel.add(btnClose);
btnClose.addActionListener(this);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object source = e.getSource();
if (source == ok || source == btnClose) {
this.dispose();
}
}
}
In this customized JDialog, close button is active/focused by default and I can switch to OK button using Tab.
At any moment if the buton is active then I can click it either using the space bar or the mouse, but if the button is not active, I can not click it by the mouse, it does not respond, I have to make it active first, and this is what I do not understand.
Thank you.
I have my ProfileInput class to store a JTextField input from a Dialog box. Then I transfer that to the setter and getter methods. From there I am calling the setter and getter methods in my AppFrame class.
The the problem that I am having is when I want the input to be displayed as a JLabel on the GUI nothing is showing up. I have no errors that are displayed when I run the code either. Any ideas as to what I have done wrong.
Please note that I am new to Java and am trying to learn. Any ideas/help to improve anything is also great.
ProfileInput Class
package GUI;
//Library imports
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ProfileInput extends Dialog {
//array for the active drop down box
String[] activeLabels = {"Select One", "Not Active", "Slightly Active", "Active", "Very Active"};
public String firstNameString;
//intilizing aspects used in the user profile dialog box
JPanel Panel = new JPanel();
JButton saveButton = new JButton("Save");
JLabel firstName = new JLabel("First Name: ");
JLabel lastName = new JLabel("Last Name: ");
JLabel age = new JLabel("Age: ");
JLabel weight = new JLabel("Weight: ");
JLabel height = new JLabel("Height: ");
JLabel weightGoal = new JLabel("Weight Goal: ");
JLabel activeLevel = new JLabel("Active Level: ");
JLabel completion = new JLabel("Completion By: ");
JTextField firstNameInput = new JTextField();
JTextField lastNameInput = new JTextField();
JTextField ageInput = new JTextField();
JTextField weightInput = new JTextField();
JTextField heightInputFeet = new JTextField();
JTextField heightInputInches = new JTextField();
JTextField weightGoalInput = new JTextField();
JComboBox activeCombo = new JComboBox(activeLabels);
JTextField completionInput = new JTextField();
//setup of the dialog panel
public ProfileInput(Frame parent) {
super(parent,true);
userProfileInput();
setSize(315, 380);
setTitle("Profile Creator");
setLocationRelativeTo(null);
}
public void userProfileInput() {
//sets up the main panel for the dialog box (only panel to add to)
Panel.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
Panel.setLayout(null);
//sets the location of the aspects inside the panel
firstName.setBounds(35, 15, 150, 20);
lastName.setBounds(35, 50, 150, 20);
firstNameInput.setBounds(115, 15, 150, 20);
lastNameInput.setBounds(115, 50, 150, 20);
age.setBounds(35, 85, 120, 20);
ageInput.setBounds(115, 85, 150, 20);
weight.setBounds(35, 115, 150, 20 );
weightInput.setBounds(115, 115, 150, 20);
height.setBounds(35, 150, 150, 20);
heightInputFeet.setBounds(115, 150, 72, 20);
heightInputInches.setBounds(193, 150, 72, 20);
weightGoal.setBounds(35, 185, 150, 20);
weightGoalInput.setBounds(115, 185, 150, 20);
activeLevel.setBounds(35, 220, 150, 20);
activeCombo.setBounds(115,220, 150, 20);
completion.setBounds(35, 255, 150, 20);
completionInput.setBounds(130, 255, 120, 20);
saveButton.setBounds(135, 310, 65, 20);
saveButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
//converts the inputs to a string
firstNameString = firstNameInput.getText();
System.out.println(firstNameString);
}
});
//adds the items to the main panel on the dialog box
Panel.add(firstName, null);
Panel.add(lastName, null);
Panel.add(firstNameInput, null);
Panel.add(lastNameInput, null);
Panel.add(age, null);
Panel.add(ageInput, null);
Panel.add(weight, null);
Panel.add(weightInput, null);
Panel.add(height, null);
Panel.add(heightInputFeet, null);
Panel.add(heightInputInches, null);
Panel.add(weightGoal, null);
Panel.add(weightGoalInput, null);
Panel.add(activeLevel, null);
Panel.add(activeCombo, null);
Panel.add(completion, null);
Panel.add(completionInput, null);
Panel.add(saveButton, null);
//adds the panel to the dialog frame
add(Panel);
}//end of userProfileInput method
public String getFirstName() {
return this.firstNameString;
}
public void setFirstName(String firstNameString) {
this.firstNameString = firstNameString;
}
}
AppFrame Class
public class AppFrame extends JFrame {
private static final long serialVersionUID = 1L;
ProfileInput profileInput = new ProfileInput(null);
String firstNameTest = profileInput.getFirstName();
/**
* Starts the frame from AppFrame method below.
*
* #param args
*/
public static void main(String[] args) {
new AppFrame().setVisible(true);
}//end of main Method
/**
*
*
*/
private AppFrame() {
//Initialization of panels and bars used in the main app
JMenuBar menuBar = new JMenuBar();
JPanel contentPane = new JPanel(new BorderLayout());
JPanel rightPanel = new JPanel();
JPanel profileInfo = new JPanel();
//aspects used in the left toolbar panel
JToolBar toolBarPanel = new JToolBar();
JButton bloodPressureTool = new JButton();
JButton heartRateTool = new JButton();
JButton weightTool = new JButton();
JButton bmiTool = new JButton();
JButton medicationTool = new JButton();
JButton appointmentTool = new JButton();
JButton noteTool = new JButton();
JButton profileTool = new JButton();
Border etched = BorderFactory.createEtchedBorder();
Icon bloodPIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/BloodPressure.png");
Icon heartRateIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/HeartRate.png");
Icon weightIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/Weight.png");
Icon bmiIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/BMI.png");
Icon medicationIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/Medications.png");
Icon appointmentIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/DoctorAppointment.png");
Icon noteIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/Notes.png");
Icon profileIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/Profile.png");
//aspects of the user profile panel
JLabel firstName = new JLabel("First Name: ");
JLabel lastName = new JLabel("Last Name: ");
JLabel height = new JLabel("Height: ");
JLabel weight = new JLabel("Weight: ");
JLabel age = new JLabel("Age: ");
JLabel weightGoal = new JLabel("Weight Goal: ");
JLabel activeLevel = new JLabel("Active Level: ");
JLabel completion = new JLabel("Completion Date: ");
//Menu Bar Headers
JMenu file = new JMenu("File");
JMenu go = new JMenu("Go");
JMenu help = new JMenu("Help");
//file drop down
JMenuItem newEntry = new JMenuItem("Profile Creator");
JMenuItem exportReport = new JMenuItem("Export Report");
JMenuItem exportNotes = new JMenuItem("Export Notes");
JMenuItem preferences = new JMenuItem("Preferences");
JMenuItem exit = new JMenuItem("Exit");
file.add(newEntry);
file.addSeparator();
file.add(exportReport);
file.addSeparator();
file.add(exportNotes);
file.addSeparator();
file.add(preferences);
file.addSeparator();
file.add(exit);
//action used when the user presses the enter profile input button
newEntry.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
profileInput.setVisible(true);
}
});
//allows for the program to exit when exit is clicked
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
exitDialog();
}
});
//go drop down
JMenuItem bloodPressure = new JMenuItem("Blood Pressure");
JMenuItem heartRate = new JMenuItem("Heart Rate");
JMenuItem medication = new JMenuItem("Medication");
JMenuItem weightDisplay = new JMenuItem("Weight");
JMenuItem bmi = new JMenuItem("BMI");
JMenuItem docAppoints = new JMenuItem("Doctor's Appointments");
JMenuItem notes = new JMenuItem("Notes");
JMenuItem resources = new JMenuItem("Profile");
go.add(bloodPressure);
go.addSeparator();
go.add(heartRate);
go.addSeparator();
go.add(medication);
go.addSeparator();
go.add(weight);
go.addSeparator();
go.add(bmi);
go.addSeparator();
go.add(docAppoints);
go.addSeparator();
go.add(notes);
go.addSeparator();
go.add(resources);
//help drop down
JMenuItem usersGuide = new JMenuItem("Users Guide");
JMenuItem about = new JMenuItem("About Personal Health Application");
help.add(usersGuide);
help.addSeparator();
help.add(about);
//adds Items to Frame
menuBar.add(file);
menuBar.add(go);
menuBar.add(help);
setJMenuBar(menuBar);
//Panel that allows for all GUI to be ad added here
contentPane.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
contentPane.setBackground(Color.WHITE);
contentPane.add(toolBarPanel, BorderLayout.WEST);
contentPane.add(rightPanel);
//stores the buttons for application (left)
toolBarPanel.setOrientation(JToolBar.VERTICAL);
toolBarPanel.setBackground(Color.white);
toolBarPanel.setFloatable(false);;
toolBarPanel.setBorder(etched);
//sets the large panel on the right side of the frame.
rightPanel.setBackground(Color.WHITE);
rightPanel.setBorder(etched);
rightPanel.setLayout(null);
rightPanel.add(profileInfo, null);
//adds the user profile info to the main screen
profileInfo.setBounds(0, 0, 1104, 100);
profileInfo.setBackground(Color.WHITE);
profileInfo.setLayout(null);
profileInfo.setBorder(etched);
firstName.setBounds(80, 10, 80, 20);
firstName.setFont(new java.awt.Font("Dialog", 1, 11));
lastName.setBounds(80, 50, 80, 20);
lastName.setFont(new java.awt.Font("Dialog", 1, 11));
weightDisplay.setBounds(310, 10, 80, 20);
weightDisplay.setFont(new java.awt.Font("Dialog", 1, 11));
height.setBounds(330, 50, 80, 20);
height.setFont(new java.awt.Font("Dialog", 1, 11));
age.setBounds(550, 10, 80, 20);
age.setFont(new java.awt.Font("Dialog", 1, 11));
weightGoal.setBounds(550, 50, 80, 20);
weightGoal.setFont(new java.awt.Font("Dialog", 1, 11));
activeLevel.setBounds(780, 10, 80, 20);
activeLevel.setFont(new java.awt.Font("Dialog", 1, 11));
completion.setBounds(780, 50, 120, 20);
completion.setFont(new java.awt.Font("Dialog", 1, 11));
//test to see if first name displays
JLabel firstNameInputTest = new JLabel(firstNameTest);
firstNameInputTest.setBounds(160, 10, 80, 20);
profileInfo.add(firstName);
profileInfo.add(lastName);
profileInfo.add(weightDisplay);
profileInfo.add(height);
profileInfo.add(age);
profileInfo.add(weightGoal);
profileInfo.add(completion);
profileInfo.add(activeLevel);
//part of test to see of first name displays
profileInfo.add(firstNameInputTest);
//blood pressure button
bloodPressureTool.setMaximumSize(new Dimension(90, 80));
bloodPressureTool.setMinimumSize(new Dimension(30, 30));
bloodPressureTool.setFont(new java.awt.Font("Dialog", 1, 10));
bloodPressureTool.setPreferredSize(new Dimension(90, 50));
bloodPressureTool.setBorderPainted(false);
bloodPressureTool.setContentAreaFilled(false);
bloodPressureTool.setVerticalTextPosition(SwingConstants.BOTTOM);
bloodPressureTool.setHorizontalTextPosition(SwingConstants.CENTER);
bloodPressureTool.setText("Blood Pressure");
bloodPressureTool.setOpaque(false);
bloodPressureTool.setMargin(new Insets(0, 0, 0, 0));
bloodPressureTool.setSelected(true);
bloodPressureTool.setIcon(bloodPIcon);
//heart rate button
heartRateTool.setMaximumSize(new Dimension(90, 80));
heartRateTool.setMinimumSize(new Dimension(30, 30));
heartRateTool.setFont(new java.awt.Font("Dialog", 1, 10));
heartRateTool.setPreferredSize(new Dimension(90, 50));
heartRateTool.setBorderPainted(false);
heartRateTool.setContentAreaFilled(false);
heartRateTool.setVerticalTextPosition(SwingConstants.BOTTOM);
heartRateTool.setHorizontalTextPosition(SwingConstants.CENTER);
heartRateTool.setText("Heart Rate");
heartRateTool.setOpaque(false);
heartRateTool.setMargin(new Insets(0, 0, 0, 0));
heartRateTool.setSelected(true);
heartRateTool.setIcon(heartRateIcon);
//weight button
weightTool.setMaximumSize(new Dimension(90, 80));
weightTool.setMinimumSize(new Dimension(30, 30));
weightTool.setFont(new java.awt.Font("Dialog", 1, 10));
weightTool.setPreferredSize(new Dimension(90, 50));
weightTool.setBorderPainted(false);
weightTool.setContentAreaFilled(false);
weightTool.setVerticalTextPosition(SwingConstants.BOTTOM);
weightTool.setHorizontalTextPosition(SwingConstants.CENTER);
weightTool.setText("Weight");
weightTool.setOpaque(false);
weightTool.setMargin(new Insets(0, 0, 0, 0));
weightTool.setSelected(true);
weightTool.setIcon(weightIcon);
//BMI button
bmiTool.setMaximumSize(new Dimension(90, 80));
bmiTool.setMinimumSize(new Dimension(30, 30));
bmiTool.setFont(new java.awt.Font("Dialog", 1, 10));
bmiTool.setPreferredSize(new Dimension(90, 50));
bmiTool.setBorderPainted(false);
bmiTool.setContentAreaFilled(false);
bmiTool.setVerticalTextPosition(SwingConstants.BOTTOM);
bmiTool.setHorizontalTextPosition(SwingConstants.CENTER);
bmiTool.setText("BMI");
bmiTool.setOpaque(false);
bmiTool.setMargin(new Insets(0, 0, 0, 0));
bmiTool.setSelected(true);
bmiTool.setIcon(bmiIcon);
//medication button
medicationTool.setMaximumSize(new Dimension(90, 80));
medicationTool.setMinimumSize(new Dimension(30, 30));
medicationTool.setFont(new java.awt.Font("Dialog", 1, 10));
medicationTool.setPreferredSize(new Dimension(90, 50));
medicationTool.setBorderPainted(false);
medicationTool.setContentAreaFilled(false);
medicationTool.setVerticalTextPosition(SwingConstants.BOTTOM);
medicationTool.setHorizontalTextPosition(SwingConstants.CENTER);
medicationTool.setText("Medication");
medicationTool.setOpaque(false);
medicationTool.setMargin(new Insets(0, 0, 0, 0));
medicationTool.setSelected(true);
medicationTool.setIcon(medicationIcon);
//appointment button
appointmentTool.setMaximumSize(new Dimension(90, 80));
appointmentTool.setMinimumSize(new Dimension(30, 30));
appointmentTool.setFont(new java.awt.Font("Dialog", 1, 10));
appointmentTool.setPreferredSize(new Dimension(90, 50));
appointmentTool.setBorderPainted(false);
appointmentTool.setContentAreaFilled(false);
appointmentTool.setVerticalTextPosition(SwingConstants.BOTTOM);
appointmentTool.setHorizontalTextPosition(SwingConstants.CENTER);
appointmentTool.setText("Appointments");
appointmentTool.setOpaque(false);
appointmentTool.setMargin(new Insets(0, 0, 0, 0));
appointmentTool.setSelected(true);
appointmentTool.setIcon(appointmentIcon);
//note button
noteTool.setMaximumSize(new Dimension(90, 80));
noteTool.setMinimumSize(new Dimension(30, 30));
noteTool.setFont(new java.awt.Font("Dialog", 1, 10));
noteTool.setPreferredSize(new Dimension(90, 50));
noteTool.setBorderPainted(false);
noteTool.setContentAreaFilled(false);
noteTool.setVerticalTextPosition(SwingConstants.BOTTOM);
noteTool.setHorizontalTextPosition(SwingConstants.CENTER);
noteTool.setText("Notes");
noteTool.setOpaque(false);
noteTool.setMargin(new Insets(0, 0, 0, 0));
noteTool.setSelected(true);
noteTool.setIcon(noteIcon);
//profile button
profileTool.setMaximumSize(new Dimension(90, 80));
profileTool.setMinimumSize(new Dimension(30, 30));
profileTool.setFont(new java.awt.Font("Dialog", 1, 10));
profileTool.setPreferredSize(new Dimension(90, 50));
profileTool.setBorderPainted(false);
profileTool.setContentAreaFilled(false);
profileTool.setVerticalTextPosition(SwingConstants.BOTTOM);
profileTool.setHorizontalTextPosition(SwingConstants.CENTER);
profileTool.setText("Profile");
profileTool.setOpaque(false);
profileTool.setMargin(new Insets(0, 0, 0, 0));
profileTool.setSelected(true);
profileTool.setIcon(profileIcon);
//adding buttons to toolBarPanel
toolBarPanel.add(bloodPressureTool);
toolBarPanel.add(heartRateTool);
toolBarPanel.add(weightTool);
toolBarPanel.add(bmiTool);
toolBarPanel.add(medicationTool);
toolBarPanel.add(appointmentTool);
toolBarPanel.add(noteTool);
toolBarPanel.add(profileTool);
//sets up the actual frame
setSize(1200,800);
setResizable(false);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
add(contentPane);
//allows for the program to shut down by using x and then using the dialog
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
exitDialog();
}
});
}//end of appFrame Method
You've got several problems with the above code, but most important, you're using a modeless dialog when you absolutely need to use a modal one. Since it is modeless, program flow in the calling code does not halt when the dialog is made visible, and so you're calling getFirstName() on the dialog immediately after it is opened, before it has been closed, and well before the user has had a chance to input any information whatsoever. A modal dialog on the other hand will freeze program flow in the calling code, and program flow will not resume until the dialog is no longer visible.
Problems and suggestions:
First and foremost, make sure the dialog window is a modal dialog.
But even before this, don't use Dialog, Panel and other AWT component classes, but rather use Swing classes -- JDialog, JPanel, etc.
You can set the JDialog to be modal with either the proper constructor, passing in ModalityType.APPLICATION_MODAL as a parameter within the appropriate constructor (see the API), or you can set it via a method.
Either way, make sure that it's set before setting the dialog visible.
Do this, and when you query the state of the dialog, you can be assured that the user has at least had a chance to interact with the dialog before you try to extract information from it.
Be sure to query the dialog and assign the results after setting it visible.
Edit, I see now that you're calling String firstNameTest = profileInput.getFirstName(); even before setting the dialog visible, as if the firstNameTest String, which is obviously null at this stage, will magically update once the dialog has been visualized and dealt with, but sorry, there's no magic in Java, and fields will not update by themselves. Again, do not set the firstNameTest field at that point, but rather only after the dialog has been displayed and then dealt with.
Next we'll need to talk about null layouts and setBounds. You really don't want to go this route, trust me.
For example:
public class AppFrame extends JFrame {
private static final long serialVersionUID = 1L;
// !! the JLabel needs to be a field so it can be set in the ActionListener
private JLabel firstNameInputTest = new JLabel("");
private ProfileInput profileInput = null; //!! let this start out as null
// !! worthless code, get rid of
// String firstNameTest = profileInput.getFirstName();
public static void main(String[] args) {
// .... etc
And the ActionListener where we create/display the dialog:
newEntry.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//!! create JDialog in a lazy fashion
if (profileInput == null) {
// create dialog, passing in the JFrame
profileInput = new ProfileInput(AppFrame.this);
}
profileInput.setVisible(true); // display the *modal* dialog
// program flow is frozen here until JDialog is no longer visible
// query dialog for its contents
String firstNameTxt = profileInput.getFirstName();
// and use in GUI
firstNameInputTest.setText(firstNameTxt);
}
});
We don't want to declare the JLabel within a method or constructor since in doing so, it will not be visible throughout the class. So...
private AppFrame() { // ??? private ???
// .....
// test to see if first name displays
// !! JLabel firstNameInputTest = new JLabel(firstNameTest); // No!!!
Finally, a very simple example JDialog to demonstrate what I'm discussing:
#SuppressWarnings("serial")
public class ProfileInput extends JDialog {
private JTextField firstNameField = new JTextField(10);
public ProfileInput(JFrame frame) {
// make it modal!
super(frame, "Profile Input", ModalityType.APPLICATION_MODAL);
JPanel panel = new JPanel();
panel.add(new JLabel("Enter First Name:"));
panel.add(firstNameField);
panel.add(new JButton(new SubmitAction("Submit", KeyEvent.VK_S)));
add(panel);
pack();
setLocationRelativeTo(frame);
}
public String getFirstName() {
return firstNameField.getText();
}
private class SubmitAction extends AbstractAction {
public SubmitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
ProfileInput.this.dispose();
}
}
}
enter code hereHi I'm new developer in Java I want to put a JComboBox in a public class to get the selected item but Java don't recognize it for example i want to do this.
myComboBox.getSelectedItem().toString()
and when i try to put a JTextField it works fine.
Sorry for my expression I'm not speak English very well
Thats my code
package guarderia;
import java.awt.BorderLayout;
public class enfermedades extends JFrame {
private JPanel contentPane;
private JTextField txtid;
private JTextField textField_1;
private JTextField txtnom;
private static JTable table;
//VARIABLES PARA CONEXION A MYSQL
static Connection con;
static CallableStatement ps;
static ResultSet rs;
static DefaultTableModel tm;
static Statement sql;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
enfermedades frame = new enfermedades();
frame.setVisible(true);
llenar();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public enfermedades() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1211, 663);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 255, 255));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBackground(new Color(0, 0, 0));
panel.setBounds(0, 0, 1624, 53);
contentPane.add(panel);
JLabel lblEnfermedades = new JLabel("ENFERMEDADES");
lblEnfermedades.setForeground(Color.WHITE);
lblEnfermedades.setFont(new Font("Dialog", Font.BOLD, 19));
lblEnfermedades.setBounds(12, 12, 231, 41);
panel.add(lblEnfermedades);
JPanel panel_1 = new JPanel();
panel_1.setLayout(null);
panel_1.setBounds(10, 102, 426, 510);
contentPane.add(panel_1);
JLabel lblIdNio = new JLabel("ID NiƱo");
lblIdNio.setBounds(12, 30, 70, 15);
panel_1.add(lblIdNio);
txtid = new JTextField();
txtid.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
int c = e.getKeyChar();
if (c < '0' || c > '9') e.consume();
}
#Override
public void keyReleased(KeyEvent e) {
con= (Connection) conexion.conectar();
try {
if (txtid.getText().equals(""))
{
txtnom.setText("");
}
ps = (CallableStatement) con.prepareCall("{call select_nin (?) }");
ps.setLong(1, Integer.parseInt(txtid.getText()));
ResultSet res = ps.executeQuery();
if (res.next())
{
String tipo = res.getString("Nombre");
txtnom.setText(tipo);
llenar();
}
else
{
txtnom.setText(null);
}
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null, e1 );
}
}
});
txtid.setColumns(10);
txtid.setBounds(120, 28, 146, 19);
panel_1.add(txtid);
JLabel cbi = new JLabel("Enfermedad");
cbi.setBounds(12, 95, 194, 15);
panel_1.add(cbi);
JLabel lblTratamiento = new JLabel("Tratamiento");
lblTratamiento.setBounds(12, 130, 194, 15);
panel_1.add(lblTratamiento);
JButton btnNueva = new JButton("Nueva");
btnNueva.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnNueva.setBounds(282, 90, 88, 25);
panel_1.add(btnNueva);
JTextPane textPane = new JTextPane();
textPane.setBounds(12, 157, 402, 118);
panel_1.add(textPane);
JLabel lblFechaDeteccion = new JLabel("Fecha Deteccion");
lblFechaDeteccion.setBounds(12, 299, 194, 15);
panel_1.add(lblFechaDeteccion);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(135, 297, 95, 19);
panel_1.add(textField_1);
JLabel lblNombre = new JLabel("Nombre");
lblNombre.setBounds(12, 61, 70, 15);
panel_1.add(lblNombre);
txtnom = new JTextField();
txtnom.setEditable(false);
txtnom.setColumns(10);
txtnom.setBounds(120, 56, 294, 19);
panel_1.add(txtnom);
JLabel lblMedidadRecomendadas = new JLabel("Medidas recomendadas");
lblMedidadRecomendadas.setBounds(12, 330, 194, 15);
panel_1.add(lblMedidadRecomendadas);
JTextPane textPane_1 = new JTextPane();
textPane_1.setBounds(12, 355, 402, 93);
panel_1.add(textPane_1);
JButton btnGuardar = new JButton("Guardar");
btnGuardar.setBounds(297, 470, 117, 25);
panel_1.add(btnGuardar);
JComboBox cbx = new JComboBox();
cbx.setBounds(120, 90, 146, 24);
panel_1.add(cbx);
JPanel panel_2 = new JPanel();
panel_2.setLayout(null);
panel_2.setBackground(new Color(220, 20, 60));
panel_2.setBounds(10, 65, 426, 32);
contentPane.add(panel_2);
JLabel lblRegistrarEnfermedad = new JLabel("Registrar enfermedad");
lblRegistrarEnfermedad.setForeground(Color.WHITE);
lblRegistrarEnfermedad.setFont(new Font("Dialog", Font.BOLD, 19));
lblRegistrarEnfermedad.setBounds(12, 5, 401, 23);
panel_2.add(lblRegistrarEnfermedad);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(448, 102, 751, 510);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
JPanel panel_3 = new JPanel();
panel_3.setLayout(null);
panel_3.setBackground(new Color(128, 0, 128));
panel_3.setBounds(448, 65, 751, 32);
contentPane.add(panel_3);
JLabel lblEnfermedades_1 = new JLabel("Enfermedades");
lblEnfermedades_1.setForeground(Color.WHITE);
lblEnfermedades_1.setFont(new Font("Dialog", Font.BOLD, 19));
lblEnfermedades_1.setBounds(12, 5, 401, 23);
panel_3.add(lblEnfermedades_1);
}
public static void llenar()
{
try
{
con = (Connection) conexion.conectar();
String[]titulos={"ID", "ENFERMEDAD", "DESCRIPCION", "RIESGO CONTAGIO", "TIPO"};
String cmd = "select * from enfermedades";
tm = new DefaultTableModel(null,titulos);
sql = (Statement) con.createStatement();
ResultSet rs = sql.executeQuery(cmd);
String[]fila = new String[5];
while(rs.next())
{
fila[0]= rs.getString("id");
fila[1]= rs.getString("enfermedad");
fila[2]= rs.getString("descripcion");
fila[3]= rs.getString("riesgo");
fila[4]= rs.getString("tipo");
tm.addRow(fila);
}
table.setModel(tm);
TableColumnModel columnModel = table.getColumnModel();
columnModel.getColumn(0).setPreferredWidth(3);
columnModel.getColumn(1).setPreferredWidth(50);
columnModel.getColumn(2).setPreferredWidth(290);
}
catch(Exception d)
{
JOptionPane.showMessageDialog(null, d + " No se pudo conectar.");
}
}
public void ns()
{
cbx. //this is where not recognize the jcombobox
}
}
Your problem appears to be one simply of variable scope. When you declare the cbx variable within your constructor, it is visible only within the constructor. If you move the declaration to the class, then the variable becomes visible throughout the class.
So if you move JComboBox cbx = new JComboBox(); to the class level, in other words if you move this statement to just below your private JTextField txtnom; statement, then the cbx field will be visible within the ns method.
So in other words, make these changes:
public class enfermedades extends JFrame {
private JPanel contentPane;
private JTextField txtid;
private JTextField textField_1;
private JTextField txtnom;
private static JTable table;
// !! added
private JComboBox cbx = new JComboBox();
// ...... code removed for brevity's sake
public enfermedades() {
// ...... code removed for brevity's sake
panel_1.add(btnGuardar);
// !! JComboBox cbx = new JComboBox(); // ***** Don't declare this here ****
// ...... code removed for brevity's sake
}
// ...... code removed for brevity's sake
public void ns() {
// cbx field is now visible here
}
}
Other unrelated problems within your code:
Avoid using null layouts and setBounds. While this might seem to newbies the easiest way to create GUI's, believe me, it's not. Much better to learn how to use the layout managers and use them.
None of the mysql fields or the JTable table field should be static. They should be instance (non-static) fields only. This means that you shouldn't try to access them in a static way.
the llenar method shouldn't be static, and you should call it off of the instance that you've created.
Learn and follow Java naming conventions so that others (we) can better understand your code. Class names begin with an upper-case letter and variable and method names begin with a lower-case letter.
Your sql code should be located in its own class and not within the GUI class's code.
You will want to make sql calls in a separate thread off of the GUI's main event thread, the "EDT".
Making it public magically won't make you access it anywhere from world.
You need to have that instance in order to access that.
Getting a bit into GUIs and trying to make something simple. However, I seem to be getting stuck on just making a simple "Exit" button. I am using the WindowsBuilder plugin for Eclipse to help me.
private void initialize()
{
mainWindowFrame = new JFrame();
mainWindowFrame.setTitle("Lock and Log");
mainWindowFrame.setIconImage(Toolkit.getDefaultToolkit().getImage(MainWindow.class.getResource("/lockandlog/main/resources/icon.png")));
mainWindowFrame.setResizable(false);
mainWindowFrame.setBounds(100, 100, 854, 480);
mainWindowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindowFrame.getContentPane().setLayout(null);
final JTextArea logDisplay = new JTextArea();
logDisplay.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
logDisplay.setEditable(false);
logDisplay.setBounds(259, 11, 579, 250);
mainWindowFrame.getContentPane().add(logDisplay);
JLabel viewCmdDisplayLbl = new JLabel("View Command Display:");
viewCmdDisplayLbl.setFont(new Font("Tahoma", Font.BOLD, 11));
viewCmdDisplayLbl.setBounds(259, 272, 133, 14);
mainWindowFrame.getContentPane().add(viewCmdDisplayLbl);
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
textArea.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
textArea.setBounds(259, 297, 579, 104);
mainWindowFrame.getContentPane().add(textArea);
JToolBar toolBar = new JToolBar();
toolBar.setBounds(0, 412, 848, 16);
mainWindowFrame.getContentPane().add(toolBar);
JPanel manualGrp = new JPanel();
manualGrp.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
manualGrp.setBounds(10, 11, 239, 72);
mainWindowFrame.getContentPane().add(manualGrp);
manualGrp.setLayout(null);
manualTxt = new JTextField();
manualTxt.setBounds(10, 7, 219, 20);
manualGrp.add(manualTxt);
manualTxt.setColumns(10);
JButton manualBtn = new JButton("Manual Override");
manualBtn.setFont(new Font("Tahoma", Font.BOLD, 12));
manualBtn.setBounds(10, 38, 219, 23);
manualGrp.add(manualBtn);
JMenuBar menuBar = new JMenuBar();
mainWindowFrame.setJMenuBar(menuBar);
final JMenu fileBtn = new JMenu("File");
fileBtn.addMouseListener(new MouseAdapter() //This works
{
#Override
public void mouseEntered(MouseEvent e)
{
fileBtn.setSelected(true);
}
#Override
public void mouseExited(MouseEvent e)
{
fileBtn.setSelected(false);
}
});
menuBar.add(fileBtn);
JMenuItem exitBtn = new JMenuItem("Exit");
//Code is definitely passing through here.
exitBtn.addMouseListener(new MouseAdapter() //This doesn't work?
{
#Override
public void mouseClicked(MouseEvent e)
{
logDisplay.setText("Test"); //This isn't even being called!
System.exit(0);
}
});
//Definitely adds the button so code is passing through here.
fileBtn.add(exitBtn);
}
That's the whole initialize class for now. But if you would note near the bottom I have an event for the Exit button to where if you click on it the program should close. Except, when I click on the button nothing happens. Trying out other events like that in the fileBtn that works great. So what am I doing wrong?
Don't use mouseListeners, use ActionListeners.
import java.awt.event.*;
public class SOQ3
{
JFrame mainWindowFrame;
public static void main(String[] args)
{
SOQ3 s = new SOQ3();
}
public SOQ3()
{
initialize();
}
private void initialize()
{
mainWindowFrame = new JFrame();
mainWindowFrame.setTitle("Lock and Log");
mainWindowFrame.setIconImage(Toolkit.getDefaultToolkit().getImage(MainWindow.class.getResource("/lockandlog/main/resources/icon.png")));
mainWindowFrame.setResizable(false);
mainWindowFrame.setBounds(100, 100, 854, 480);
mainWindowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindowFrame.getContentPane().setLayout(null);
final JTextArea logDisplay = new JTextArea();
logDisplay.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
logDisplay.setEditable(false);
logDisplay.setBounds(259, 11, 579, 250);
mainWindowFrame.getContentPane().add(logDisplay);
JLabel viewCmdDisplayLbl = new JLabel("View Command Display:");
viewCmdDisplayLbl.setFont(new Font("Tahoma", Font.BOLD, 11));
viewCmdDisplayLbl.setBounds(259, 272, 133, 14);
mainWindowFrame.getContentPane().add(viewCmdDisplayLbl);
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
textArea.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
textArea.setBounds(259, 297, 579, 104);
mainWindowFrame.getContentPane().add(textArea);
JToolBar toolBar = new JToolBar();
toolBar.setBounds(0, 412, 848, 16);
mainWindowFrame.getContentPane().add(toolBar);
JPanel manualGrp = new JPanel();
manualGrp.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
manualGrp.setBounds(10, 11, 239, 72);
mainWindowFrame.getContentPane().add(manualGrp);
manualGrp.setLayout(null);
manualTxt = new JTextField();
manualTxt.setBounds(10, 7, 219, 20);
manualGrp.add(manualTxt);
manualTxt.setColumns(10);
JButton manualBtn = new JButton("Manual Override");
manualBtn.setFont(new Font("Tahoma", Font.BOLD, 12));
manualBtn.setBounds(10, 38, 219, 23);
manualGrp.add(manualBtn);
JMenuBar menuBar = new JMenuBar();
mainWindowFrame.setJMenuBar(menuBar);
final JMenu fileBtn = new JMenu("File");
fileBtn.addMouseListener(
new MouseAdapter() //This works
{
#Override
public void mouseEntered(MouseEvent e)
{
fileBtn.setSelected(true);
}
#Override
public void mouseExited(MouseEvent e)
{
fileBtn.setSelected(false);
}
});
menuBar.add(fileBtn);
JMenuItem exitBtn = new JMenuItem("Exit");
//Code is definitely passing through here.
exitBtn.addActionListener(
new ActionListener() //This doesn't work?
{
#Override
public void actionPerformed(ActionEvent e)
{
logDisplay.setText("Test"); //This isn't even being called!
System.exit(0);
}
});
//Definitely adds the button so code is passing through here.
fileBtn.add(exitBtn);
}
}
Now as for the reason behind this, you were trying to use MouseListeners, while MouseListeners are good, you need to GET THE SOURCE of what you are listening to. Simply adding a listener will now do anything like it would if it was an ActionListener, part of the reason why I chose to use one. Also, tip for you, using ActionListeners listen for an Action done by the object it is attached to, MouseListeners listen to your and everything it does, whether or not it even has anything to do with your program. In the future, when using listeners, ensure that they listen only to what is absolutely necessary to your program. If you don't need to know the position of the mouse, don't follow it.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Typically this is how you would capture the exit event.
For your custom Exit button, instead of a MouseListener, try just a plain 'ol ActionListener
Any event on the button will then be captured, and your code gracefully exited.