Repaint only a specific JPanel inside a JFrame - java

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.

Related

Jcombobox not selecting item

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));
}
}

JComboBox in a public class

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.

Frame active, but setting visible to false = nullpointer

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)

Why isn't my JScrollPane working?

I'm trying to make my JPanel scrollable but it's not working. I made a JPanel, added components to it, then added my JPanel to a JScrollPane. This is what you're supposed to do, right? What am I doing wrong?
import java.awt.Dimension;
import java.awt.Font;
import java.awt.SystemColor;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneLayout;
import javax.swing.SwingConstants;
public class RegisterPane extends JPanel {
private JTextField txtJohnDoe;
private JTextField txtExampledomaincom;
private JPasswordField passwordField;
private JPasswordField passwordField_1;
/**
* Create the panel.
*/
public RegisterPane() {
setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(6, 36, 300, 450);
panel.setLayout(null);
JLabel lblFirstName = new JLabel("First Name");
lblFirstName.setBounds(28, 6, 92, 16);
panel.add(lblFirstName);
txtJohnDoe = new JTextField();
txtJohnDoe.setText("John Doe");
txtJohnDoe.setBounds(124, 0, 251, 28);
panel.add(txtJohnDoe);
txtJohnDoe.setColumns(10);
txtExampledomaincom = new JTextField();
txtExampledomaincom.setText("Example#domain.com");
txtExampledomaincom.setColumns(10);
txtExampledomaincom.setBounds(124, 40, 251, 28);
panel.add(txtExampledomaincom);
JLabel lblEmail = new JLabel("Email");
lblEmail.setBounds(28, 46, 92, 16);
panel.add(lblEmail);
JLabel lblGender = new JLabel("Gender");
lblGender.setBounds(28, 89, 55, 16);
panel.add(lblGender);
JRadioButton rdbtnMale = new JRadioButton("Male");
rdbtnMale.setBounds(124, 85, 92, 23);
panel.add(rdbtnMale);
JRadioButton rdbtnFemale = new JRadioButton("Female");
rdbtnFemale.setBounds(283, 85, 92, 23);
panel.add(rdbtnFemale);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(28, 157, 55, 16);
panel.add(lblPassword);
JLabel passDirections = new JLabel();
passDirections.setHorizontalAlignment(SwingConstants.CENTER);
passDirections.setFont(new Font("Lucida Grande", Font.PLAIN, 10));
passDirections.setBackground(SystemColor.window);
passDirections.setText("Password's Must be at Least 6 characters long and contain 1 non letter character");
passDirections.setBounds(29, 117, 346, 28);
panel.add(passDirections);
passwordField = new JPasswordField();
passwordField.setBounds(124, 151, 251, 28);
panel.add(passwordField);
passwordField_1 = new JPasswordField();
passwordField_1.setBounds(124, 195, 251, 28);
panel.add(passwordField_1);
JLabel lblRetypePassword = new JLabel("Password Again");
lblRetypePassword.setBounds(28, 201, 92, 16);
panel.add(lblRetypePassword);
JCheckBox chckbxSubscribeToNews = new JCheckBox("Subscribe to News Letter");
chckbxSubscribeToNews.setSelected(true);
chckbxSubscribeToNews.setHorizontalAlignment(SwingConstants.CENTER);
chckbxSubscribeToNews.setBounds(29, 244, 346, 23);
panel.add(chckbxSubscribeToNews);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(28, 280, 55, 16);
panel.add(lblNewLabel);
JScrollPane scroll = new JScrollPane(panel);
scroll.setSize(new Dimension(450,300));
panel.setAutoscrolls(true);
add(scroll);
}
}
Here's my JFrame class
import java.awt.BorderLayout;
public class MainFrame extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(0, 0));
setResizable(false);
setContentPane(new RegisterPane());
//RegisterPane isn't scrolling ^
}
}
Thanks in Advance for your help!
I'm seeing setLayout(null) alot in your code.
The JViewport uses the component's/view's preferred size as a bases for determining if the view expands beyond the visible bounds of the JScrollPane, because you've seen fit to ignore this feature, the components have begun to break down.
Swing is designed to work layout managers and it makes it much easier to develop complex user interfaces that can work across a multitude of platforms and environments

How do I remove a component from a JPanel? and then redisplay the frame?

Some context for this code,
what I am trying to do is create a validation warning if the input containts "" as a value,
so if an error is displayed it displays the message.
If it is valid it does not display a message,
so how do I remove the message when the textField is valid?
The message is a JPanel that contains a JLabel with the text in it,
I add this this JPanel to the frame when it is not valid,
and I am trying to remove it when it is valid.
So what am I doing wrong here?
I am at a basic level with Swing.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Test {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 401, 232);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 330, 94);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Firstname :");
lblNewLabel.setBounds(10, 11, 104, 14);
panel.add(lblNewLabel);
textField = new JTextField();
textField.setBounds(76, 8, 244, 20);
panel.add(textField);
textField.setColumns(10);
JLabel lblLastname = new JLabel("Lastname :");
lblLastname.setBounds(10, 42, 78, 14);
panel.add(lblLastname);
textField_1 = new JTextField();
textField_1.setBounds(76, 39, 244, 20);
panel.add(textField_1);
textField_1.setColumns(10);
JButton btnValidate = new JButton("Validate");
btnValidate.addMouseListener(new MouseAdapter() {
#SuppressWarnings("deprecation")
#Override
public void mousePressed(MouseEvent arg0) {
JPanel panel_1 = new JPanel();
JPanel panel_2 = new JPanel();
if(textField.getText().equals("")) {
panel_1.setBackground(new Color(30, 144, 255));
panel_1.setBounds(100, 116, 330, 26);
JLabel lblMessage = new JLabel("0 :");
lblMessage.setForeground(new Color(255, 255, 255));
lblMessage.setFont(new Font("Tahoma", Font.BOLD, 13));
panel_1.add(lblMessage);
frame.getContentPane().add(panel_1);
frame.revalidate();
frame.repaint(10);
frame.revalidate();
}
else if(textField_1.getText().equals("")) {
panel_2.setBackground(new Color(50, 200, 255));
panel_2.setBounds(10, 134, 330, 26);
JLabel lblMessage = new JLabel("1 :");
lblMessage.setBounds(50, 50, 50, 50);
lblMessage.setAlignmentX(50);
lblMessage.setForeground(new Color(255, 255, 255));
lblMessage.setFont(new Font("Tahoma", Font.BOLD, 13));
panel_2.add(lblMessage);
frame.getContentPane().add(panel_2);
frame.remove(panel_1);
frame.revalidate();
frame.repaint(10);
frame.revalidate();
}
}
});
btnValidate.setBounds(231, 71, 89, 23);
panel.add(btnValidate);
}
}
The easiest way is to simply adjust the visibility (JComponent#setVisible( false ) ).
If you really want to remove the component completely, you have to remove and revalidate, as documented in the Container#remove method
This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to reflect the changes.
which results in code like
panel.remove( componentToRemove );
panel.revalidate();
panel.repaint();
As a side note: please replace the null layout and those setBounds call by a proper LayoutManager. You might want to take a look excellent 'Nested layout example' available on SO to see what is possible with layout managers. The Swing tag info on SO contains some extra useful links when starting to work with layout managers
yourpanel.setVisible(false); should hide your panel, where "yourPanel" is your JPanel instance

Categories

Resources