Im trying to insert the Jcombobox value into my sqlite database but whenever I run the program, it only inserts '9' in to my database. Please advise. I am trying to import the integer that the user picks into my sqlite database. For some reason, even with the action listener, the default value, 9, is still being inputed into the table and im not sure why. Here is the full code, not including the connection and the Jtable.
public class create extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
create frame = new create();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connect = null;
private JTextField textField_2;
String uniqueString = UUID.randomUUID().toString();
private JTextField textField_3;
/**
* Create the frame.
*/
public create() {
connect = connection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBackground(new Color(204, 204, 204));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblStudentName = new JLabel("Student ID:");
lblStudentName.setBounds(96, 69, 72, 16);
contentPane.add(lblStudentName);
textField = new JTextField();
textField.setBounds(173, 64, 216, 26);
contentPane.add(textField);
textField.setColumns(10);
JLabel lblGrade = new JLabel("Grade:");
lblGrade.setBounds(125, 107, 47, 16);
contentPane.add(lblGrade);
JComboBox comboBox = new JComboBox();
comboBox.addItem(9);
comboBox.addItem(10);
comboBox.addItem(11);
comboBox.addItem(12);
comboBox.setBounds(173, 102, 72, 29);
contentPane.add(comboBox);
comboBox.setSelectedItem(9);
comboBox.addActionListener(comboBox);
int selectedNumber = (int)comboBox.getSelectedItem();
JLabel lblInputBookOver = new JLabel("Teacher:");
lblInputBookOver.setBounds(111, 146, 61, 21);
contentPane.add(lblInputBookOver);
textField_1 = new JTextField();
textField_1.setBounds(173, 143, 216, 26);
contentPane.add(textField_1);
textField_1.setColumns(10);
JButton button = new JButton("<");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int count = 0; count <= 0; count++) {
//dispose();
options sc = new options();
sc.setVisible(true);
}
}
});
button.setBounds(6, 6, 30, 29);
contentPane.add(button);
JLabel lblStudentname = new JLabel("Student Name:");
lblStudentname.setBounds(74, 31, 99, 16);
contentPane.add(lblStudentname);
textField_2 = new JTextField();
textField_2.setBounds(173, 26, 216, 26);
contentPane.add(textField_2);
textField_2.setColumns(10);
JLabel lblEmail = new JLabel("Email:");
lblEmail.setBounds(125, 180, 42, 26);
contentPane.add(lblEmail);
textField_3 = new JTextField();
textField_3.setBounds(173, 180, 216, 26);
contentPane.add(textField_3);
textField_3.setColumns(10);
JButton btnCheckout = new JButton("Checkout");
btnCheckout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final String uniqueString = UUID.randomUUID().toString().replace("-", "");
try {
String query = "insert into data ('Name', 'Student ID', 'Teacher', 'Grade', 'Email', 'Ebook') values (?,?,?,?,?,?)";
PreparedStatement pst = connect.prepareStatement(query);
pst.setString(1,textField_2.getText() );
pst.setString(2,textField.getText() );
pst.setString(3,textField_1.getText() );
pst.setInt(4, selectedNumber);
pst.setString(5,textField_3.getText() );
pst.setString(6, uniqueString);
for (int count = 0; count <= 0; count++) {
//dispose();
confirm sc = new confirm();
sc.setVisible(true);
count = 0;
}
pst.execute();
pst.close();
}
catch (Exception w){
w.printStackTrace();
}
}
});
btnCheckout.setBounds(173, 218, 117, 29);
contentPane.add(btnCheckout);
}
}
It inserts 9 to your database because the selected item is always 9, and this because you add it first to your combobox. In order to insert the selected value, you will have to use an ActionListener. Then you can take user's selection and do whatever you want.
An example of its usage:
import java.awt.FlowLayout;
import java.io.FileNotFoundException;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class ComboBox extends JFrame {
public ComboBox() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
getContentPane().setLayout(new FlowLayout());
Integer[] numbers = { 4, 5, 8, 123, 42, 634 };
JComboBox<Integer> comboBox = new JComboBox<>(numbers);
comboBox.setSelectedItem(42); // The initial selection is 42.
comboBox.addActionListener(e -> {
int selectedNumber = (int) comboBox.getSelectedItem();
System.out.println("Selected number: " + selectedNumber);
// Do whatever with selected number
});
add(comboBox);
}
public static void main(String[] args) throws FileNotFoundException {
SwingUtilities.invokeLater(() -> new ComboBox().setVisible(true));
}
}
Related
I'm creating a little program for my self to learn Java now I did make a GUI with 12 JTextFields and now I want to use the text that's in the text fields in another class where I print them out.
When I press the button class print is successful, summand I get the last System.out.println("Test if class is triggerd") in my console but I don't get the JTextFields output in the console
Class Frame1
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class Frame1 {
public JFrame frmCratingRecipieGenerator;
public JTextField txtSlot;
public JTextField textField_1;
public JTextField textField_2;
public JTextField textField_3;
public JTextField textField_4;
public JTextField textField_5;
public JTextField textField_6;
public JTextField textField_7;
public JTextField textField_8;
public JTextField textField_9;
public JTextField textField_10;
public JTextField textField_11;
public JLabel lblNewLabel;
public String slot1;
public String slot2;
public String slot3;
public String slot4;
public String slot5;
public String slot6;
public String slot7;
public String slot8;
public String slot9;
public String output;
public String output_count;
public String file_num;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame1 window = new Frame1();
window.frmCratingRecipieGenerator.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Frame1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
public void initialize() {
frmCratingRecipieGenerator = new JFrame();
frmCratingRecipieGenerator.setResizable(false);
frmCratingRecipieGenerator.setTitle("Crating Recipie Generator Alpha 1");
frmCratingRecipieGenerator.getContentPane().setBackground(new Color(192, 192, 192));
frmCratingRecipieGenerator.setBounds(100, 100, 452, 248);
frmCratingRecipieGenerator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmCratingRecipieGenerator.getContentPane().setLayout(null);
txtSlot = new JTextField();
txtSlot.setBounds(10, 19, 86, 20);
frmCratingRecipieGenerator.getContentPane().add(txtSlot);
txtSlot.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(106, 19, 86, 20);
frmCratingRecipieGenerator.getContentPane().add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(202, 19, 86, 20);
frmCratingRecipieGenerator.getContentPane().add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(10, 50, 86, 20);
frmCratingRecipieGenerator.getContentPane().add(textField_3);
textField_3.setColumns(10);
textField_4 = new JTextField();
textField_4.setBounds(106, 50, 86, 20);
frmCratingRecipieGenerator.getContentPane().add(textField_4);
textField_4.setColumns(10);
textField_5 = new JTextField();
textField_5.setBounds(202, 50, 86, 20);
frmCratingRecipieGenerator.getContentPane().add(textField_5);
textField_5.setColumns(10);
textField_6 = new JTextField();
textField_6.setBounds(10, 81, 86, 20);
frmCratingRecipieGenerator.getContentPane().add(textField_6);
textField_6.setColumns(10);
textField_7 = new JTextField();
textField_7.setBounds(106, 81, 86, 20);
frmCratingRecipieGenerator.getContentPane().add(textField_7);
textField_7.setColumns(10);
textField_8 = new JTextField();
textField_8.setBounds(202, 81, 86, 20);
frmCratingRecipieGenerator.getContentPane().add(textField_8);
textField_8.setColumns(10);
textField_9 = new JTextField();
textField_9.setBounds(351, 19, 86, 20);
frmCratingRecipieGenerator.getContentPane().add(textField_9);
textField_9.setColumns(10);
textField_10 = new JTextField();
textField_10.setBounds(351, 81, 46, 20);
frmCratingRecipieGenerator.getContentPane().add(textField_10);
textField_10.setColumns(10);
textField_11 = new JTextField();
textField_11.setText("1");
textField_11.setBounds(351, 50, 46, 20);
frmCratingRecipieGenerator.getContentPane().add(textField_11);
textField_11.setColumns(10);
JLabel lblFileId = new JLabel("File ID");
lblFileId.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblFileId.setHorizontalAlignment(SwingConstants.LEFT);
lblFileId.setBounds(298, 82, 86, 14);
frmCratingRecipieGenerator.getContentPane().add(lblFileId);
JLabel lblOutput = new JLabel("Output");
lblOutput.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblOutput.setBounds(298, 20, 58, 14);
frmCratingRecipieGenerator.getContentPane().add(lblOutput);
JLabel lblCount = new JLabel("Count");
lblCount.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblCount.setBounds(298, 51, 52, 14);
frmCratingRecipieGenerator.getContentPane().add(lblCount);
JLabel lblThisJavaProgram = new JLabel("This Java program is coded by Jason");
lblThisJavaProgram.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblThisJavaProgram.setBounds(10, 179, 270, 20);
frmCratingRecipieGenerator.getContentPane().add(lblThisJavaProgram);
JLabel TestLabel = new JLabel("");
TestLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
TestLabel.setBounds(391, 179, 46, 19);
frmCratingRecipieGenerator.getContentPane().add(TestLabel);
JButton btnNewButton = new JButton("Generate the McFunction File's");
btnNewButton.setBounds(10, 108, 427, 60);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
TestLabel.setText(textField_10.getText());
print name = new print();
name.Print();
}
});
frmCratingRecipieGenerator.getContentPane().add(btnNewButton);
lblNewLabel = new JLabel("Last File num");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblNewLabel.setBounds(287, 182, 110, 14);
frmCratingRecipieGenerator.getContentPane().add(lblNewLabel);
this.slot1 = txtSlot.getText();
this.slot2 = textField_1.getText();
this.slot3 = textField_2.getText();;
this.slot4 = textField_3.getText();;
this.slot5 = textField_4.getText();;
this.slot6 = textField_5.getText();;
this.slot7 = textField_6.getText();;
this.slot8 = textField_7.getText();;
this.slot9 = textField_8.getText();;
this.output = textField_9.getText();
this.output_count = textField_11.getText();
this.file_num = textField_10.getText();
}
}
Class print
package example;
public class print {
public void Print() {
Frame1 slots = new Frame1();
String slot1 = slots.slot1;
String slot2 = slots.slot2;
String slot3 = slots.slot3;
String slot4 = slots.slot4;
String slot5 = slots.slot5;
String slot6 = slots.slot6;
String slot7 = slots.slot7;
String slot8 = slots.slot8;
String slot9 = slots.slot9;
String output = slots.output;
String output_count = slots.output_count;
String file_num = slots.file_num;
System.out.println(slot1);
System.out.println(slot2);
System.out.println(slot3);
System.out.println(slot4);
System.out.println(slot5);
System.out.println(slot6);
System.out.println(slot7);
System.out.println(slot8);
System.out.println(slot9);
System.out.println(output);
System.out.println(output_count);
System.out.println(file_num);
System.out.println("Test if class is triggerd");
}
}
This is happening because you create on the print class a new Object of frame1 so the variables by default are null. You can add on the Print method a list parameter that stores all the Strings in that list.
public void Print(List<String> slots) {
System.out.println(slots.get(0));
System.out.println(slots.get(1));
System.out.println(slots.get(2));
System.out.println(slots.get(3));
System.out.println(slots.get(4));
System.out.println(slots.get(5));
System.out.println(slots.get(6));
System.out.println(slots.get(7));
System.out.println(slots.get(8));
System.out.println(slots.get(9));
System.out.println(slots.get(10));
System.out.println(slots.get(11));
}
and redefine before the method call all the variables and store them in the list.
You can learn some things about Java's lists here
If you are struggling finding the code I made it for you
slot1 = txtSlot.getText();
slot2 = textField_1.getText();
slot3 = textField_2.getText();;
slot4 = textField_3.getText();;
slot5 = textField_4.getText();;
slot6 = textField_5.getText();;
slot7 = textField_6.getText();;
slot8 = textField_7.getText();;
slot9 = textField_8.getText();;
output = textField_9.getText();
List<String> slots = new ArrayList<String>();
slots.add(slot1);
slots.add(slot2);
slots.add(slot3);
slots.add(slot4);
slots.add(slot5);
slots.add(slot6);
slots.add(slot7);
slots.add(slot8);
slots.add(slot9);
slots.add(output);
slots.add(output_count);
slots.add(file_num);
output_count = textField_11.getText();
file_num = textField_10.getText();
TestLabel.setText(textField_10.getText());
print name = new print();
name.Print(slots);
and Print class:
public void Print(List<String> slots) {
System.out.println(slots.get(0));
System.out.println(slots.get(1));
System.out.println(slots.get(2));
System.out.println(slots.get(3));
System.out.println(slots.get(4));
System.out.println(slots.get(5));
System.out.println(slots.get(6));
System.out.println(slots.get(7));
System.out.println(slots.get(8));
System.out.println(slots.get(9));
System.out.println(slots.get(10));
System.out.println(slots.get(11));
System.out.println("Test if class is triggerd");
}
Im trying to sort my GUI so it will be able to use the methods from the other classes
in the JProject i also want to call it from the main.
The action listeners i had just learnt today so i need feedback on what to do there as well.
Any Ideas??
It would be a great help to get some insight on this!
(I am new to stack so my code posted in the explanation and in the actual script idk
why).
package test;
import javax.swing.JPanel;
import javax.swing.JLabel;
import com.jgoodies.forms.factories.DefaultComponentFactory;
import java.awt.Container;
import java.awt.SystemColor;
import java.awt.Color;
import javax.swing.JRadioButton;
import java.awt.Font;
import java.io.File;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JComboBox;
import javax.swing.JButton;
import java.util.ArrayList;
import java.util.Scanner;
//Main Method
public class TextUI{
protected StormTracker var;
public TextUI(StormTracker var)
{
this.var=var;
}
public static void main(String[] args)
{
ShowGUI gui = new SHOWGUI();
while(gui.running)
if(gui.buttonPress == -1)
continue;
StormTracker obj = new StormTracker("config.txt");
WeatherAuthority wa = new WeatherAuthority("stormfile.txt");
int xcoord=0;
int ycoord=0;
TextUI uiobj = new TextUI(obj);
Scanner scan = new Scanner(System.in);
while(true){
System.out.println("---------------------------------------------------------------");
System.out.println("Welcome to the StormTracker Application.");
System.out.println("Type the following commands to carry out the associated actions.");
System.out.println("\n");
System.out.println("----------------------{Commands Menu}---------------------
-------");
System.out.println("(1) NEW STORM x y");
System.out.println("(2) UPGRADE <name of storm>");
System.out.println("(3) DOWNGRADE <name of storm>");
System.out.println("(4) TICK");
System.out.println("(5) EXIT");
System.out.println("----------------------------------------------------------------");
String option=scan.nextLine();
if (option.substring(0,4).equals("TICK")){
obj.tick();
continue;
}
if (option.substring(0,9).equals("NEW STORM")){
if(option.length()==13){
xcoord = Integer.parseInt(option.substring(10,11));
ycoord = Integer.parseInt(option.substring(12,13));
}
else if (option.length()==14){
if (option.substring(11,12).equals(" ")){
xcoord = Integer.parseInt(option.substring(10,11));
ycoord = Integer.parseInt(option.substring(12,14));
}
else{
xcoord = Integer.parseInt(option.substring(10,12));
ycoord = Integer.parseInt(option.substring(13,14));
}
}
else if (option.length()==15){
xcoord = Integer.parseInt(option.substring(10,12));
ycoord = Integer.parseInt(option.substring(13,15));
}
obj.newstorm(xcoord,ycoord);
}
if (option.substring(0,7).equals("UPGRADE")){
String storm_name = option.substring(8);
obj.upgrade(storm_name);
}
if (option.substring(0,9).equals("DOWNGRADE")){
String storm_name = option.substring(10);
obj.downgrade(storm_name);
}
}
}
//GUI Class
public ShowGUI extends JPanel {
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
System.out.println("GUI Successfully Loaded");
createAndShow();
setToolTipText("Select Storm");
setBackground(Color.WHITE);
}
private void createAndShow(){
JPanel mainFrame = new JPanel("Storm Tracker V1.0");
}
private void addComponents(Container pane){
pane.setLayout(null);
JLabel lblStormTrackerV = DefaultComponentFactory.getInstance().createTitle("
Storm Tracker V1.0");
lblStormTrackerV.setBackground(SystemColor.activeCaption);
lblStormTrackerV.setFont(new Font("Calibri", Font.PLAIN, 22));
lblStormTrackerV.setBounds(162, 11, 430, 41);
add(lblStormTrackerV);
JRadioButton rdbtnMap = new JRadioButton("MAP");
rdbtnMap.setBounds(283, 59, 72, 23);
add(rdbtnMap);
JRadioButton rdbtnBulletin = new JRadioButton("Bulletin");
rdbtnBulletin.setBounds(406, 60, 72, 23);
add(rdbtnBulletin);
textField = new JTextField();
textField.setBounds(61, 103, 72, 20);
add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(61, 134, 72, 20);
add(textField_1);
textField_1.setColumns(10);
JTextPane txtpnX = new JTextPane();
txtpnX.setText("X:");
txtpnX.setBounds(23, 103, 28, 20);
add(txtpnX);
JTextPane txtpnY = new JTextPane();
txtpnY.setText("Y:");
txtpnY.setBounds(23, 134, 12, 20);
add(txtpnY);
JTextPane txtpnSpeed = new JTextPane();
txtpnSpeed.setText("Speed:");
txtpnSpeed.setBounds(10, 165, 41, 20);
add(txtpnSpeed);
textField_2 = new JTextField();
textField_2.setBounds(61, 165, 72, 20);
add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(61, 196, 72, 20);
add(textField_3);
textField_3.setColumns(10);
JTextPane txtpnSpeed_1 = new JTextPane();
txtpnSpeed_1.setText("Speed:");
txtpnSpeed_1.setBounds(10, 196, 41, 20);
add(txtpnSpeed_1);
JTextPane txtpnBearing = new JTextPane();
txtpnBearing.setText("Bearing:");
txtpnBearing.setBounds(10, 227, 41, 20);
add(txtpnBearing);
textField_4 = new JTextField();
textField_4.setBounds(61, 227, 72, 20);
add(textField_4);
textField_4.setColumns(10);
File input = new File(new
FileReader("C:\\Users\\620086793\\Documents\\test\\src\\test"));
List<String> strings = new ArrayList<String>();
try {
String line = null;
while (( line = input.readLine()) != null){
strings.add(line);
}
}
catch (FileNotFoundException e) {
System.err.println("Error, file " + "C:\\Users\\620086793\\Documents\\test\\src\\test" + " didn't exist.");
}
finally {
input.close();
}
String[] lineArray = strings.toArray(new String[]{});
JComboBox comboBox = new JComboBox(lineArray);
JComboBox comboBox = new JComboBox();
comboBox.setToolTipText("Select Storm");
comboBox.setEditable(true);
comboBox.setBounds(20, 60, 113, 20);
add(comboBox);
JButton btnUpdate = new JButton("UPDATE");
btnUpdate.setFont(new Font("Calibri", Font.BOLD, 11));
btnUpdate.setBounds(10, 273, 110, 28);
add(btnUpdate);
JButton btnNewButton = new JButton("NEW STORM\r\n");
btnNewButton.setFont(new Font("Calibri", Font.BOLD, 11));
btnNewButton.setBounds(10, 312, 110, 28);
add(btnNewButton);
addActionListeners();
pane.add(rdbtnMap);
pane.add(rdbtnBulletin);
pane.add(textField);
pane.add(textField_1);
pane.add(textField_2);
pane.add(textField_3);
pane.add(textField_4);
pane.add(comboBox);
pane.add(btnUpdate);
pane.add(btnNewButton);
}
//Im not sure how to properly add the action listeners i first learned about them
today.
private void addActionListeners(){
rdbtnMap.addActionListener(new ActionListener){
public void actionPerformed(ActionEvent ){
}
}
rdbtnBulletin.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField_2.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField_3.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField_4.addActionListener(){
public void actionPerformed(ActionEvent ){
stormTracker.tick = textField_4;
}
}
comboBox.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
btnUpdate.addActionListener(){
public void actionPerformed(ActionEvent ){
obj.upgrade() = btnUpdate;
return btnUpdate;
}
}
btnNewButton.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
}
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.
So i have a bit of a weird issue, i just posted and fixed my other error, but that seems to have created this one, and it makes no sense.
Basically, the user presses a button, this window opens, then whether he presses cancel, or register, this window should setVisible to false. but when this code gets executed, it says my window is null.
package frontend;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Registration extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private static boolean ranOnce = false;
private JPanel contentPane;
private Registration reg;
private JTextField userTF;
private JTextField passTF;
private JTextField emailTF;
private LoginProcess lp = new LoginProcess();
private JLabel error;
private JButton cancelBtn;
/**
* Create the frame.
*/
public Registration() {
if (!ranOnce) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
reg = new Registration();
reg.setVisible(true);
ranOnce = true;
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 245, 212);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(10, 11, 75, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(10, 36, 75, 14);
contentPane.add(lblPassword);
JLabel lblEmail = new JLabel("Email:");
lblEmail.setBounds(10, 61, 75, 14);
contentPane.add(lblEmail);
userTF = new JTextField();
userTF.setBounds(95, 8, 130, 20);
contentPane.add(userTF);
userTF.setColumns(10);
passTF = new JTextField();
passTF.setColumns(10);
passTF.setBounds(95, 33, 130, 20);
contentPane.add(passTF);
emailTF = new JTextField();
emailTF.setColumns(10);
emailTF.setBounds(95, 58, 130, 20);
contentPane.add(emailTF);
error = new JLabel("");
error.setBounds(10, 154, 215, 14);
contentPane.add(error);
JButton regBtn = new JButton("Register");
regBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!userTF.getText().equals("") || !passTF.getText().equals("") || !emailTF.getText().equals("")) {
try {
if (lp.newUser(userTF.getText(), passTF.getText(), emailTF.getText())) {
// THIS IS LINE 117 reg.setVisible(false);
Main.mainFrame.setVisible(true);
} else {
if (lp.duplicateAccount) {
error.setText("Error: Username already in use.");
}
}
} catch (SQLException e) {
}
}
}
});
regBtn.setBounds(10, 120, 215, 23);
contentPane.add(regBtn);
cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
reg.setVisible(false);
Main.mainFrame.setVisible(true);
}
});
cancelBtn.setBounds(10, 86, 215, 23);
contentPane.add(cancelBtn);
}
}
this is the abnormal error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at frontend.Registration$3.actionPerformed(Registration.java:117)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
i really have no clue as to why it's saying my window is null, when it's not. it has to be something i've done when initialising the window.
Why is it not working ?
You are not using Singleton design pattern correctly. Did you notice that you have two JFrame popping up ?
if (!ranOnce)
{
EventQueue.invokeLater(new Runnable()//this call the run method in a separate thread
{
public void run()
{
try
{
// for the current instance of Registration, you are setting
// the reg variable by calling another instance of Registration => thats not the correct way to do a Singleton
reg = new Registration();
reg.setVisible(true);
ranOnce = true;
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
So, let's assume you are calling new Registration() in your main method, you will enter the public Registration() constructor (let's call it instance1) and set the variable reg by calling one more time the constructor new Registration() (instance2) but by this time, ranOnce will be true and so EventQueue.invokeLater will not be called => reg will not be set in instance2 => NullPointerException when clicking on Jbutton in the second frame (the one on the top) (instance2). Clicking on first frame (instance1) button's will hide the second frame (instance2).
How to fix it ?
Use a proper Singleton :
private static final long serialVersionUID = 1L;
private static boolean ranOnce = false;
private JPanel contentPane;
private static Registration reg;
private JTextField userTF;
private JTextField passTF;
private JTextField emailTF;
private LoginProcess lp = new LoginProcess();
private JLabel error;
private JButton cancelBtn;
public static synchronized Registration getRegistration()
{
if(reg == null)
reg = new Registration();
return reg;
}
/**
* Create the frame.
*/
private Registration()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 245, 212);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(10, 11, 75, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(10, 36, 75, 14);
contentPane.add(lblPassword);
JLabel lblEmail = new JLabel("Email:");
lblEmail.setBounds(10, 61, 75, 14);
contentPane.add(lblEmail);
userTF = new JTextField();
userTF.setBounds(95, 8, 130, 20);
contentPane.add(userTF);
userTF.setColumns(10);
passTF = new JTextField();
passTF.setColumns(10);
passTF.setBounds(95, 33, 130, 20);
contentPane.add(passTF);
emailTF = new JTextField();
emailTF.setColumns(10);
emailTF.setBounds(95, 58, 130, 20);
contentPane.add(emailTF);
error = new JLabel("");
error.setBounds(10, 154, 215, 14);
contentPane.add(error);
JButton regBtn = new JButton("Register");
regBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!userTF.getText().equals("") || !passTF.getText().equals("") || !emailTF.getText().equals("")) {
try {
if (lp.newUser(userTF.getText(), passTF.getText(), emailTF.getText())) {
setVisible(false);
Main.mainFrame.setVisible(true);
} else {
if (lp.duplicateAccount) {
error.setText("Error: Username already in use.");
}
}
} catch (SQLException e) {
}
}
}
});
regBtn.setBounds(10, 120, 215, 23);
contentPane.add(regBtn);
cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
setVisible(false);
}
});
cancelBtn.setBounds(10, 86, 215, 23);
contentPane.add(cancelBtn);
}
public static void main(String[] args)
{
Registration registration = Registration.getRegistration();
registration.setVisible(true);
}
Try setVisible(fasle) instead of reg.setVisible(false)
I have created this Automated Library. And I need to know how to connect my Database per each JFrame.
This is my main method:
package com.Student.GUI;
public class Student_HomePage extends JFrame {
private JPanel contentPane;
private JTextField searchBox;
private static String results[];
private static Connection conn;
private static String searchText;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DBConnect db = new DBConnect();
conn = db.openConnection();
Student_HomePage frame = new Student_HomePage();
frame.setVisible(true);
frame.setBounds(400,150,599,489);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Student_HomePage() {
setBackground(Color.WHITE);
setIconImage(Toolkit.getDefaultToolkit().getImage("D:\\ITC302-Core Java\\java_workspace\\Pictures\\lala.png"));
setTitle("LookBook");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 599, 489);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnHome = new JButton("Home");
btnHome.setFont(new Font("Plantagenet Cherokee", Font.PLAIN, 16));
btnHome.setEnabled(false);
btnHome.setContentAreaFilled(false);
btnHome.setBorder(null);
btnHome.setBounds(144, 24, 95, 25);
contentPane.add(btnHome);
JButton btnAuthors = new JButton("Authors");
btnAuthors.setFont(new Font("Plantagenet Cherokee", Font.PLAIN, 16));
btnAuthors.setContentAreaFilled(false);
btnAuthors.setBorder(null);
btnAuthors.setBounds(241, 24, 95, 25);
contentPane.add(btnAuthors);
JButton btnBooks = new JButton("Books");
btnBooks.setFont(new Font("Plantagenet Cherokee", Font.PLAIN, 16));
btnBooks.setContentAreaFilled(false);
btnBooks.setBorder(null);
btnBooks.setBounds(338, 24, 95, 25);
contentPane.add(btnBooks);
JTextArea textArea = new JTextArea();
textArea.setText("|");
textArea.setFont(new Font("Monospaced", Font.PLAIN, 35));
textArea.setEditable(false);
textArea.setBounds(227, 11, 26, 57);
contentPane.add(textArea);
JTextArea textArea_1 = new JTextArea();
textArea_1.setText("|");
textArea_1.setFont(new Font("Monospaced", Font.PLAIN, 35));
textArea_1.setEditable(false);
textArea_1.setBounds(325, 11, 26, 57);
contentPane.add(textArea_1);
searchBox = new JTextField();
searchBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String temp = new String(searchBox.getText());
searchText = temp;
}
});
searchBox.setColumns(10);
searchBox.setBounds(37, 210, 148, 25);
contentPane.add(searchBox);
JTextArea textArea_2 = new JTextArea();
textArea_2.setText("Search title of books,\r\nauthors or genre");
textArea_2.setFont(new Font("Plantagenet Cherokee", Font.PLAIN, 14));
textArea_2.setBounds(37, 248, 188, 40);
contentPane.add(textArea_2);
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String temp = new String(searchBox.getText());
btnSearchActionPerformed(e, temp);
}
});
btnSearch.setIcon(new ImageIcon("D:\\ITC302-Core Java\\java_workspace\\Pictures\\searchIcon.png"));
btnSearch.setContentAreaFilled(false);
btnSearch.setBorder(null);
btnSearch.setBackground(Color.WHITE);
btnSearch.setBounds(185, 210, 87, 25);
contentPane.add(btnSearch);
JLabel label = new JLabel("");
label.setIcon(new ImageIcon("D:\\ITC302-Core Java\\java_workspace\\Pictures\\download.jpg"));
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setBounds(270, 202, 290, 215);
contentPane.add(label);
JLabel bookIcon = new JLabel("");
bookIcon.setIcon(new ImageIcon("D:\\ITC302-Core Java\\java_workspace\\Pictures\\BookIcon.png"));
bookIcon.setBounds(101, 78, 116, 90);
contentPane.add(bookIcon);
JLabel lookBookIcon = new JLabel("");
lookBookIcon.setIcon(new ImageIcon("D:\\ITC302-Core Java\\java_workspace\\Pictures\\image.png"));
lookBookIcon.setBounds(213, 74, 290, 135);
contentPane.add(lookBookIcon);
}
public void btnSearchActionPerformed (ActionEvent e, String searchText) {
DBConnect db = new DBConnect();
results = db.selectMatchedData(searchText, conn);
//if (results.length != 0) {
this.dispose();
Student_SearchList window = new Student_SearchList();
window.setVisible(true);
//}
//else {
//Student_Warning window = new Student_Warning();
//window.setVisible(true);
//}
}
}
And this is where I want to connect my Database:
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String temp = new String(searchBox.getText());
btnSearchActionPerformed(e, temp);
}
});
This whole code is my Main.java.