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.
Related
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));
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
having problems with the code mentioned below. the eclipse error code is as follows ::
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at gui.PassengerGui$2.actionPerformed(PassengerGui.java:139)
Any recommendations would be very much appreciated? I have have been pulling my hair out for almost one hour trying to figure out what the problem is..
private JPanel contentPane;
private JFileChooser fileChooser;
private PassengerController controller;
private PassengerTabelPanel tabelPanel;
private JTextField nameField;
private JTextField cityField;
private JTable passengerTable;
private JRadioButton standardRadio;
private JRadioButton businessRadio;
private ButtonGroup classGroup;
private PassengerFormListener formListener;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PassengerGui frame = new PassengerGui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public PassengerGui() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 584, 368);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenuItem importDataItem = new JMenuItem("Import Data");
menuBar.add(importDataItem);
JMenuItem exportDataItem = new JMenuItem("Export Data");
menuBar.add(exportDataItem);
fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new PassengerFileFilter());
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
classGroup = new ButtonGroup();
//set up class radio
classGroup.add(standardRadio);
classGroup.add(businessRadio);
JLabel nameLabel = new JLabel("Name: ");
nameLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
nameLabel.setBounds(12, 11, 69, 31);
contentPane.add(nameLabel);
JLabel cityLabel = new JLabel("City: ");
cityLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
cityLabel.setBounds(12, 47, 69, 31);
contentPane.add(cityLabel);
JLabel lblNewLabel_2 = new JLabel("Class: ");
lblNewLabel_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblNewLabel_2.setBounds(12, 89, 69, 31);
contentPane.add(lblNewLabel_2);
nameField = new JTextField();
nameField.setBounds(60, 18, 129, 20);
contentPane.add(nameField);
nameField.setColumns(10);
cityField = new JTextField();
cityField.setColumns(10);
cityField.setBounds(60, 53, 129, 20);
contentPane.add(cityField);
JRadioButton businessRadio = new JRadioButton("Business");
businessRadio.setBounds(58, 95, 109, 23);
contentPane.add(businessRadio);
JRadioButton standardRadio = new JRadioButton("Standard");
standardRadio.setBounds(60, 127, 109, 23);
contentPane.add(standardRadio);
JButton btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String city = cityField.getText();
String passengerClass = classGroup.getSelection().getActionCommand();
PassengerFormEvent ev = new PassengerFormEvent(this, name, passengerClass, city);
You aren't instantiating ButtonGroup variable classGroup. You are using dot (.) operator on a null reference.
Do this:
ButtonGroup classGroup = new ButtonGroup();
and Somewhere in your code after this instantiation, do this:
String passengerClass = classGroup.getSelection().getActionCommand();
You are not instantiating classGroup. You need code such as:-
classGroup = new ButtonGroup();
before you can call methods on classGroup.
EDIT: In answer to the second problem, it's because the buttons you've added to the buttonGroup are also null. You need to create them before you add them.
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 am trying to create a paint component for the panel_1 JPanel, but I don't know how to do it. This is my class.
This code works, except that it does not paint the panel_1.
If I try and add it to the panel without painting it, it works just fine.
Also I need that panel to refresh (repaints) automatically at a given interval.
Please let help me. :D
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
public class GUI extends JFrame implements ActionListener {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JButton btnStop, btnStart;
private JComboBox comboBox_1, comboBox;
private Manager manager = new Manager();
private String arrMin, arrMax, svcMin, svcMax, simTime;
private JTextField textField_4;
private JPanel panel_1 = new JPanel(){
#Override
public void paintComponent(Graphics g){
paintComponents(g);
panel_1.setBackground(Color.orange);
panel_1.setVisible(true);
System.out.println("Just testing");
}
};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI frame = new GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public GUI() {
setResizable(false);
setForeground(Color.DARK_GRAY);
setBackground(Color.DARK_GRAY);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 700, 500);
contentPane = new JPanel();
contentPane.setForeground(Color.DARK_GRAY);
contentPane.setBackground(Color.DARK_GRAY);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(12, 12, 434, 346);
panel.setForeground(Color.LIGHT_GRAY);
contentPane.add(panel);
panel.setLayout(null);
JLabel lblArrivingTime = new JLabel("Arriving time");
lblArrivingTime.setBounds(12, 367, 94, 15);
lblArrivingTime.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblArrivingTime);
JLabel lblMin = new JLabel("Min");
lblMin.setBounds(12, 395, 70, 15);
lblMin.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblMin);
JLabel lblMax = new JLabel("Max");
lblMax.setBounds(12, 418, 70, 15);
lblMax.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblMax);
textField = new JTextField();
textField.setBounds(58, 394, 48, 16);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(58, 422, 48, 15);
contentPane.add(textField_1);
textField_1.setColumns(10);
JLabel lblServiceTime = new JLabel("Service Time");
lblServiceTime.setBounds(152, 367, 105, 15);
lblServiceTime.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblServiceTime);
JLabel lblMin_1 = new JLabel("Min");
lblMin_1.setBounds(152, 395, 51, 15);
lblMin_1.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblMin_1);
JLabel lblMax_1 = new JLabel("Max");
lblMax_1.setBounds(152, 418, 70, 15);
lblMax_1.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblMax_1);
textField_2 = new JTextField();
textField_2.setBounds(209, 393, 48, 17);
contentPane.add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(209, 417, 48, 17);
contentPane.add(textField_3);
textField_3.setColumns(10);
JLabel lblSimSetup = new JLabel("Sim. Setup");
lblSimSetup.setBounds(292, 367, 94, 15);
lblSimSetup.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblSimSetup);
JLabel lblQueue = new JLabel("Queue");
lblQueue.setBounds(292, 395, 70, 15);
lblQueue.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblQueue);
String[] numbers = { "1", "2", "3", "4" };
comboBox = new JComboBox(numbers);
comboBox.setBounds(345, 395, 75, 15);
contentPane.add(comboBox);
JLabel lblMode = new JLabel("Mode");
lblMode.setBounds(292, 418, 70, 15);
lblMode.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblMode);
String[] mode = { "Time", "Number" };
comboBox_1 = new JComboBox(mode);
comboBox_1.setBounds(345, 413, 75, 15);
contentPane.add(comboBox_1);
JLabel lblActions = new JLabel("Actions");
lblActions.setBounds(484, 367, 70, 15);
lblActions.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblActions);
btnStart = new JButton("Start");
btnStart.setBounds(482, 392, 81, 20);
contentPane.add(btnStart);
btnStop = new JButton("Stop");
btnStop.setBounds(482, 415, 81, 20);
contentPane.add(btnStop);
JLabel lblTime = new JLabel("Time");
lblTime.setBounds(292, 440, 70, 15);
lblTime.setForeground(Color.LIGHT_GRAY);
contentPane.add(lblTime);
textField_4 = new JTextField();
textField_4.setBounds(345, 438, 75, 17);
contentPane.add(textField_4);
textField_4.setColumns(10);
panel_1.setBounds(484, 12, 202, 346);
contentPane.add(panel_1);
panel_1.setLayout(null);
JTextArea textArea = new JTextArea();
textArea.setBounds(158, 12, -126, 322);
panel_1.add(textArea);
btnStop.addActionListener(this);
btnStart.addActionListener(this);
comboBox.addActionListener(this);
comboBox_1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnStop) {
this.dispose();
System.exit(NORMAL);
} else if (e.getSource() == btnStart) {
String nrQueues = (String) comboBox.getSelectedItem();
arrMin = textField.getText();
arrMax = textField_1.getText();
svcMin = textField_2.getText();
svcMax = textField_3.getText();
simTime = textField_4.getText();
int aMin = 0;
int aMax = 0;
int sMin = 0;
int sMax = 0;
int sTime = 0;
int nQueues = 1;
try {
nQueues = Integer.parseInt(nrQueues);
aMin = Integer.parseInt(arrMin);
aMax = Integer.parseInt(arrMax);
sMin = Integer.parseInt(svcMin);
sMax = Integer.parseInt(svcMax);
sTime = Integer.parseInt(simTime);
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String s = (String) comboBox_1.getSelectedItem();
System.out.println("Selected: " + s);
boolean mode = true;
if (s.equals("Time")) {
mode = true;
} else {
mode = false;
}
manager.startSimulation(aMin * 1000, aMax * 1000, sMin * 1000,
sMax * 1000, sTime * 1000, nQueues, mode);
}
}
}
Of course the handler is not relevant in this case since I am only interested in painting that panel.
First of all, this...
private JPanel panel_1 = new JPanel(){
#Override
public void paintComponent(Graphics g){
paintComponents(g);
panel_1.setBackground(Color.orange);
panel_1.setVisible(true);
System.out.println("Just testing");
}
};
Is not what custom painting is for. You should NEVER change the state of the component, or any component for that matter, from inside any paint method.
This could trigger a new repaint request which would put you into a never ending cycle of painting...
Calling paintComponents(g); is going to produce a StackOverflowException. You should not be calling paintComponents any way (note the s at the end) but you should be calling super.paintComponent(g);
JPanel is visible by default.
As it stands, you simply don't need to do anything that you are...
Don't use null layouts. Swing was designed to work with layout managers, you will have no end of issues getting the screen to update without them, besides, pixel perfect layouts are an illusion in modern user interface design, you don't control the fonts, rendering pipelines or other aspects of the target system that might effect how large elements like text are rendered.
Take a look at Laying Out Components Within a Container for more details
You're calling the super.paintComponents method inside of your paintComponent override. Yikes. You are also using null layout and shouldn't be.
You are setting background color but doing nothing with it. You should instead set the background color on your JPanel object, not in its paintComponent method.
i.e., here
panel_1.setBackground(Color.orange); // here
// !! panel_1.setBounds(484, 12, 202, 346); // you shouldn't need this!
contentPane.add(panel_1);
Edit
You state:
Is it enough to simply append a string to the text area, and it will be displayed on the screen automatically?
Yes, as long as you take Swing thread rules into consideration.
I am trying to create a register system for my MySQL database. I have a Java form that I created, in which the user inserts a username, password, and their email. I take that infromation and store it in a variable accordingly. The MySQL connection code works, and it does insert a new row, but the information is blank on the MySQL page. Am I doing someting wrong?
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private JPasswordField passwordField;
private static Connection con;
private static PreparedStatement st;
private static int rs;
String username;
String password;
String email;
private JTextField textField_1;
String insertTableSQL = "INSERT INTO `users`" + "(username, password, email) VALUES" + "(?,?,?)";
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Main() {
setResizable(false);
setTitle("Barrage : Login / Register");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 350, 200);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Username: ");
lblNewLabel.setBounds(60, 25, 68, 20);
contentPane.add(lblNewLabel);
JLabel lblPassword = new JLabel("Password: ");
lblPassword.setBounds(60, 59, 68, 20);
contentPane.add(lblPassword);
textField = new JTextField();
username = textField.getText();
textField.setBounds(138, 22, 120, 26);
contentPane.add(textField);
textField.setColumns(10);
passwordField = new JPasswordField();
password = passwordField.getText();
passwordField.setBounds(138, 56, 120, 26);
contentPane.add(passwordField);
JButton btnRegister = new JButton("Register");
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/barrage", "root", "");
st = con.prepareStatement(insertTableSQL);
st.setString(1, username);
st.setString(2, password);
st.setString(3, email);
st.executeUpdate();
} catch(Exception e) {
e.printStackTrace();
}
}
});
btnRegister.setBounds(119, 138, 89, 23);
contentPane.add(btnRegister);
JLabel lblEmail = new JLabel("E-mail: ");
lblEmail.setBounds(60, 96, 68, 20);
contentPane.add(lblEmail);
textField_1 = new JTextField();
email = textField_1.getText();
textField_1.setBounds(138, 93, 120, 26);
contentPane.add(textField_1);
textField_1.setColumns(10);
}
}
You need to call the various fields' getText() method in your ActionListener so that you get the values after the user has entered them.
As it stands now you get the initial values prior to any user interaction.
You need to set the values of username u.a. in the moment where you you call the actionPerformed method.
Right now you set the value when creating the GUI. At that moment they are null. They are not "linked", they just take the value that the controls return at that time. If the controls getText() result changes, your variables do not get updated.