Dynamic child communication - java

Background: I have a JPanel (PanelCarga extends JPanel) that displays as many sub-JPanels (DatosArchivo extends JPanel) as files I wish to open (n DatosArchivo panels) in my program for diferent purposes. This DatosArchivos contains a "X" button that I wish it to closes this DatosArchivos panel and then informs to the corresponding PanelCarga that it have been closed so that can reorganize in his grid the remaining n-1 DatosArchivo panels.
Tha PanelCarga Class:
package gui;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.sql.SQLException;
import java.util.LinkedList;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import logica.Cargador;
public class PanelCarga extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextField textField;
private final JPanel panel = new JPanel();
/**
* Create the panel.
*/
public PanelCarga() {
JLabel lblArchivosA = new JLabel("Archivo (-s) a cargar");
textField = new JTextField();
textField.setEditable(false);
textField.setColumns(10);
final JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(panel);
panel.setLayout(new GridLayout(0, 2, 0, 0));
JButton btnAbrir = new JButton("Abrir");
btnAbrir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser escoger = new JFileChooser();
escoger.setMultiSelectionEnabled(true);
int resultado = escoger.showOpenDialog(null);
File[] archivos = null;
String nombres = "";
if (resultado == JFileChooser.APPROVE_OPTION) {
archivos = escoger.getSelectedFiles();
for (int i = 0; i<archivos.length;i++){
if (i==0){
nombres = nombres + archivos [i].getName() ;
}else{
nombres = nombres + "; " +archivos [i].getName() ;
}
DatosArchivo datos = null;
try {
datos = new DatosArchivo();
} catch (SQLException e) {
JDialog error = new JDialog ();
error.setTitle("error");
JLabel mensaje = new JLabel(e.getMessage());
error.getContentPane().add(mensaje);
error.validate();
}
datos.textField_Ruta.setText(archivos[i].toString());
JTextField texto = new JTextField ();
texto.setBounds(10, 10, 100, 100);
panel.add(datos);
}
textField.setText(nombres);
panel.validate();
scrollPane.validate();
}
}
});
GroupLayout groupLayout = new GroupLayout(this);
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(scrollPane, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 430, Short.MAX_VALUE)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblArchivosA)
.addGap(18)
.addComponent(textField, GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnAbrir)))
.addContainerGap())
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(6)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblArchivosA)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(btnAbrir))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 423, Short.MAX_VALUE)
.addContainerGap())
);
setLayout(groupLayout);
}
public LinkedList <Cargador> getCargadores (){
LinkedList <Cargador> cargadores = new LinkedList <Cargador> ();
for (int i = 0; i < panel.getComponentCount(); i++){
cargadores.add(((DatosArchivo) panel.getComponent(i)).getCargador());
}
return cargadores;
}
public JPanel getPanel (){
return this.panel;
}
}
And the DatosArchivo Class:
package gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.BevelBorder;
import logica.Cargador;
import logica.Conector;
public class DatosArchivo extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
public JTextField textField_Ruta;
private JTextField textField_Anio;
private JTextField textField_UbicacionNueva;
private String usuario = "rpatrizio";
private final JComboBox comboBox_Ubicacion ;
private JComboBox comboBox_Dia;
private JComboBox comboBox_mes;
/**
* Create the panel.
* #throws SQLException
*/
public DatosArchivo() throws SQLException {
setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
JPanel panel = new JPanel();
JLabel lblArchivo = new JLabel("Archivo:");
textField_Ruta = new JTextField();
textField_Ruta.setEditable(false);
textField_Ruta.setColumns(10);
GroupLayout gl_panel = new GroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addContainerGap()
.addComponent(lblArchivo)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(textField_Ruta, GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
.addContainerGap())
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(5)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblArchivo)
.addComponent(textField_Ruta, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panel.setLayout(gl_panel);
JPanel panel_1 = new JPanel();
JLabel lblUbicación = new JLabel("Ubicaci\u00F3n");
textField_UbicacionNueva = new JTextField();
textField_UbicacionNueva.setEditable(false);
textField_UbicacionNueva.setColumns(10);
String [] ubicaciones = Conector.getUbicacion();
comboBox_Ubicacion = new JComboBox(ubicaciones);
comboBox_Ubicacion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (comboBox_Ubicacion.getSelectedItem().toString().equals("Agregar Nueva")){
textField_UbicacionNueva.setEditable(true);
}else {
textField_UbicacionNueva.setEditable(false);
}
}
});
String [] dias = {"","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"};
String [] meses = {"","enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"};
JPanel panel_2 = new JPanel();
GroupLayout groupLayout = new GroupLayout(this);
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(panel, GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE)
.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 296, Short.MAX_VALUE)
.addComponent(panel_2, GroupLayout.PREFERRED_SIZE, 296, Short.MAX_VALUE))
.addContainerGap())
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(8)
.addComponent(panel, GroupLayout.PREFERRED_SIZE, 31, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 32, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(panel_2, GroupLayout.PREFERRED_SIZE, 34, GroupLayout.PREFERRED_SIZE)
.addGap(16))
);
JLabel lblFecha = new JLabel("Fecha");
comboBox_Dia = new JComboBox(dias);
JLabel lblDe = new JLabel("de");
comboBox_mes = new JComboBox(meses);
JLabel lblDe_1 = new JLabel("de");
textField_Anio = new JTextField();
textField_Anio.setColumns(10);
JButton btnX = new JButton("X");
btnX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
GroupLayout gl_panel_2 = new GroupLayout(panel_2);
gl_panel_2.setHorizontalGroup(
gl_panel_2.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_2.createSequentialGroup()
.addContainerGap()
.addComponent(lblFecha)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(comboBox_Dia, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(lblDe)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(comboBox_mes, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(lblDe_1)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(textField_Anio, GroupLayout.PREFERRED_SIZE, 38, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnX)
.addGap(49))
);
gl_panel_2.setVerticalGroup(
gl_panel_2.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_2.createSequentialGroup()
.addGap(5)
.addGroup(gl_panel_2.createParallelGroup(Alignment.BASELINE)
.addComponent(lblFecha)
.addComponent(comboBox_Dia, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblDe)
.addComponent(comboBox_mes, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblDe_1)
.addComponent(textField_Anio, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(btnX))
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panel_2.setLayout(gl_panel_2);
JButton button = new JButton("+");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (textField_UbicacionNueva.getText().equals("") || !textField_UbicacionNueva.isEnabled() || !comboBox_Ubicacion.getSelectedItem().equals("Agregar Nueva")){
String message = "Ubicación nueva no disponible";
JOptionPane.showMessageDialog(new JFrame(), message, "Dialog", JOptionPane.ERROR_MESSAGE);
}else{
}
}
});
GroupLayout gl_panel_1 = new GroupLayout(panel_1);
gl_panel_1.setHorizontalGroup(
gl_panel_1.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_1.createSequentialGroup()
.addGap(6)
.addComponent(lblUbicación)
.addGap(5)
.addComponent(comboBox_Ubicacion, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(11)
.addComponent(textField_UbicacionNueva, GroupLayout.PREFERRED_SIZE, 91, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(button)
.addContainerGap())
);
gl_panel_1.setVerticalGroup(
gl_panel_1.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_1.createSequentialGroup()
.addGap(9)
.addComponent(lblUbicación))
.addGroup(gl_panel_1.createSequentialGroup()
.addGap(5)
.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
.addComponent(comboBox_Ubicacion, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textField_UbicacionNueva, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(button)))
);
panel_1.setLayout(gl_panel_1);
setLayout(groupLayout);
}
public Cargador getCargador(){
return new Cargador (this.getRuta(),this.getUbicacion(),this.getFecha(),this.getUsuario());
}
public String getFecha (){
return this.getAnio()+"-"+this.getMes()+"-"+this.getDia().toString()+" 00:00:00.000";
}
public String getUsuario (){
return this.usuario;
}
public String getRuta (){
return this.textField_Ruta.getText();
}
public String getAnio(){
return this.textField_Anio.getText();
}
public String getMes(){
String mes = null;
if (this.comboBox_mes.getSelectedItem().toString().equals("enero")){
mes = "01";
}else if (this.comboBox_mes.getSelectedItem().toString().equals("febrero")){
mes = "02";
}else if (this.comboBox_mes.getSelectedItem().toString().equals("marzo")){
mes = "03";
}else if (this.comboBox_mes.getSelectedItem().toString().equals("abril")){
mes = "04";
}else if (this.comboBox_mes.getSelectedItem().toString().equals("mayo")){
mes = "05";
}else if (this.comboBox_mes.getSelectedItem().toString().equals("junio")){
mes = "06";
}else if (this.comboBox_mes.getSelectedItem().toString().equals("julio")){
mes = "07";
}else if (this.comboBox_mes.getSelectedItem().toString().equals("agosto")){
mes = "08";
}else if (this.comboBox_mes.getSelectedItem().toString().equals("septiembre")){
mes = "09";
}else if (this.comboBox_mes.getSelectedItem().toString().equals("octubre")){
mes = "10";
}else if (this.comboBox_mes.getSelectedItem().toString().equals("noviembre")){
mes = "11";
}else if (this.comboBox_mes.getSelectedItem().toString().equals("diciembre")){
mes = "12";
}
return mes;
}
public String getDia(){
return this.comboBox_Dia.getSelectedItem().toString();
}
public String getUbicacion(){
if (this.comboBox_Ubicacion.getSelectedItem().toString().equals("Agregar Nueva")){
if (this.textField_UbicacionNueva.getText().equals("")){
return null;
}else {
return this.textField_UbicacionNueva.getText();
}
}else if (this.comboBox_Ubicacion.getSelectedItem().toString().equals("")){
return null;
}else {
return this.comboBox_Ubicacion.getSelectedItem().toString();
}
}
}
Thanks in advance

I'm not sure if there is any one best way to do this, but I see two possible ways:
One way is to allow outside classes to add an ActionListener to the btnX held in DatosArchivo by giving this class a public method for doing this. Something like:
public void addbtnXActionListener(ActionListener listener) {
btnX.addActionListener(listener);
}
Then the outside class can delete that JPanel from its display if it wishes. The advantage of doing it this way is that the DatosArchivo need know nothing about the gui that's holding it. When I did it this way, I also gave the DatosArchivo a public getBtnX() method to return the btnX JButton. This is so I can match the JButton obtained from the ActionListener's actionPerformed method's getSource method to be able to decide which DatosArchivo object to dispose.
For example:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Foo002 {
private static void createAndShowUI() {
JFrame frame = new JFrame("Foo002");
frame.getContentPane().add(new PanelCarga2());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
#SuppressWarnings("serial")
class PanelCarga2 extends JPanel {
private static final Dimension PREF_SIZE = new Dimension(600, 400);
private JPanel datosArchivoContainer = new JPanel();
private BtnXListener btnXListener = new BtnXListener();
public PanelCarga2() {
JButton btnAbrir = new JButton("Abrir");
btnAbrir.addActionListener(new ActionListener() {
int index = 1;
public void actionPerformed(ActionEvent e) {
DatosArchivo2 datosArchivo2 = new DatosArchivo2(index);
datosArchivo2.addbtnXActionListener(btnXListener);
datosArchivoContainer.add(datosArchivo2);
datosArchivoContainer.revalidate();
index++;
}
});
JPanel topPanel = new JPanel();
topPanel.add(btnAbrir);
datosArchivoContainer.setLayout(new BoxLayout(datosArchivoContainer, BoxLayout.LINE_AXIS));
JScrollPane scrollPane = new JScrollPane(datosArchivoContainer);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
setPreferredSize(PREF_SIZE);
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
}
private class BtnXListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
Component[] components = datosArchivoContainer.getComponents();
for (int i = components.length - 1; i >= 0; i--) {
if (components[i] instanceof DatosArchivo2) {
DatosArchivo2 datoArchivo = (DatosArchivo2) components[i];
if (source.equals(datoArchivo.getBtnX())) {
datosArchivoContainer.remove(components[i]);
}
}
}
datosArchivoContainer.revalidate();
datosArchivoContainer.repaint();
}
}
}
#SuppressWarnings("serial")
class DatosArchivo2 extends JPanel {
private JButton btnX = new JButton("X");
public DatosArchivo2(int index) {
setPreferredSize(new Dimension(200, 200));
setBorder(BorderFactory.createEtchedBorder());
add(btnX);
add(new JLabel("Index: " + index));
}
public void addbtnXActionListener(ActionListener listener) {
btnX.addActionListener(listener);
}
public JButton getBtnX() {
return btnX;
}
}
Another way to do this is to give DatosArchivo a reference to its containing class and then having the DatosArchivo object handle its own deletion. The disadvantage to this is I believe that there is some increased cohesion. For this to work, I passed a reference of the containing PanelCarga into the DatosArchivo's constructor, and then gave PanelCarga a public removeDatosArchivo that the DatosArchivo method will call, passing itself as a parameter:
public void removeDatosArchivo(DatosArchivo3 datosArchivo) {
datosArchivoContainer.remove(datosArchivo);
datosArchivoContainer.revalidate();
datosArchivoContainer.repaint();
}
This whole example program looks like:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Foo003 {
private static void createAndShowUI() {
JFrame frame = new JFrame("Foo002");
frame.getContentPane().add(new PanelCarga3());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
#SuppressWarnings("serial")
class PanelCarga3 extends JPanel {
private static final Dimension PREF_SIZE = new Dimension(600, 400);
private JPanel datosArchivoContainer = new JPanel();
public PanelCarga3() {
JButton btnAbrir = new JButton("Abrir");
btnAbrir.addActionListener(new ActionListener() {
int index = 1;
public void actionPerformed(ActionEvent e) {
DatosArchivo3 datosArchivo3 = new DatosArchivo3(index, PanelCarga3.this);
datosArchivoContainer.add(datosArchivo3);
datosArchivoContainer.revalidate();
index++;
}
});
JPanel topPanel = new JPanel();
topPanel.add(btnAbrir);
datosArchivoContainer.setLayout(new BoxLayout(datosArchivoContainer, BoxLayout.LINE_AXIS));
JScrollPane scrollPane = new JScrollPane(datosArchivoContainer);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
setPreferredSize(PREF_SIZE);
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
}
public void removeDatosArchivo(DatosArchivo3 datosArchivo) {
datosArchivoContainer.remove(datosArchivo);
datosArchivoContainer.revalidate();
datosArchivoContainer.repaint();
}
}
#SuppressWarnings("serial")
class DatosArchivo3 extends JPanel {
private PanelCarga3 panelCarga;
private JButton btnX = new JButton("X");
public DatosArchivo3(int index, PanelCarga3 panelCarga) {
this.panelCarga = panelCarga;
btnX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnXActionPerformed(e);
}
});
setPreferredSize(new Dimension(200, 200));
setBorder(BorderFactory.createEtchedBorder());
add(btnX);
add(new JLabel("Index: " + index));
}
private void btnXActionPerformed(ActionEvent e) {
panelCarga.removeDatosArchivo(this);
}
}

Related

Counter reset not working in Java

In my program it has two JButton with name Start and Reset to 0 and one JTextField and one JLabel. When I click to Start JButton number of times its show the result in JTextField.
If count number is equal to 1 it show message Start in JLabel and when count is greater than 1 it show the Reset to 0 in JLabel. But the problem is when I click on Reset to 0 JButton it reset to 1 but it not showing message Reset to 0 in JLabel?
Program is here:
import java.awt.EventQueue;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import com.alee.laf.rootpane.WebFrame;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
public class Search {
private WebFrame frame;
private JTextField textField;
private JButton btnResetTo;
private JButton btnNewButton;
private int count;
private JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Search window = new Search();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Search() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new WebFrame();
frame.setBounds(100, 100, 296, 374);
frame.setDefaultCloseOperation(WebFrame.EXIT_ON_CLOSE);
btnNewButton = new JButton("Start");
btnNewButton.addMouseListener(new MouseAdapter() {
private int Qnty;
#Override
public void mouseClicked(MouseEvent e) {
count=e.getClickCount();
textField.setText(Integer.toString(count));
Qnty=Qnty+count;
if(Qnty==1)
lblNewLabel.setText("Start");
else if(Qnty>1)
{
lblNewLabel.setText("Reset");
}
}
});
textField = new JTextField();
textField.setFont(new Font("Tahoma", Font.BOLD, 40));
textField.setHorizontalAlignment(SwingConstants.CENTER);
textField.setColumns(10);
btnResetTo = new JButton("Reset to 0");
btnResetTo.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
count=e.getClickCount();
count=0;
}
});
lblNewLabel = new JLabel("");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 15));
GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
.addComponent(lblNewLabel, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)
.addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
.addComponent(btnNewButton, GroupLayout.PREFERRED_SIZE, 88, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED, 36, Short.MAX_VALUE)
.addComponent(btnResetTo, GroupLayout.PREFERRED_SIZE, 136, GroupLayout.PREFERRED_SIZE))
.addComponent(textField, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE))
.addContainerGap())
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(25)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
.addComponent(btnResetTo, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnNewButton, GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, 69, GroupLayout.PREFERRED_SIZE)
.addGap(31)
.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 45, GroupLayout.PREFERRED_SIZE)
.addGap(73))
);
frame.getContentPane().setLayout(groupLayout);
}
}
Use a ActionListener instead of MouseListener on your buttons - buttons can be trigged in more ways then just clicking on them. See How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener for more details
When reset is called, you actually need to change the components, like you did with btnNew - the variables aren't magically linked to the components
Maybe like
btnResetTo = new JButton("Reset to 0");
btnResetTo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
count = 0;
textField.setText(Integer.toString(count));
lblNewLabel.setText("Start");
}
});

JTextfield not focusable/editable on Mac

We are making a project in OpenGL using lwjgl3. Our application has a button 'Add Cube' which opens a new JFrame containing 4 JTextFields and 2 JButtons, the layout for this JFrame is made using GroupLayout. My friends who are running our project on Windows/Linux can select and edit these JTextFields without any problem, yet me, using MacOS High Sierra, can't.
When I open the JFrame none of the textfields are selected, they do register clicks (textField.setText when mouse clicked works), but they never grab focus, the flashing |-beam never appears, despite all my best efforts (it's been weeks now). When I try to type something in the fields (neglecting the absence of the |-beam) the text appears in my current project file instead (where my cursor last was before running the project). I added other classes who use JTextField's, when I run their main method they work fine yet when I instantiate these classes somewhere in our project the frame does open but the textfields are yet again not selectable.
Here I provide the CubeAdderPanel class, I have trimmed it down a bit.
Updated according to replies
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import sourcecode.visualization.objects.Cube;
import java.util.HashMap;
import java.util.Map;
public class CubeAdderPanel extends JFrame {
private JTextField textFieldX;
private JTextField textFieldY;
private JTextField textFieldZ;
private JTextField textFieldSize;
private SolidButton addButton;
private SolidButton backButton;
private JLabel lblX;
private JLabel lblY;
private JLabel lblZ;
private JLabel lblSize;
private Font font = new Font("Open Sans Light", Font.PLAIN, 13);
private Map<JTextField, Double> textInput = new HashMap<>();
private final MenuHandler handler;
public CubeAdderPanel(MenuHandler handler){
this.handler = handler;
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
setType(Type.UTILITY);
setResizable(false);
setUndecorated(true);
setBounds(1370, 130, 280, 210);
String osName = System.getProperty("os.name");
if (osName.contains("Mac")) {
setBounds(1130, 40, 280, 240);
}
initTextFields();
initButtons();
initLabels();
//initFocusTraversal();
initTextInputMap();
initTextActions();
//Creates JFrame layout
JSeparator separator = new JSeparator();
GroupLayout gl_panel = new GroupLayout(getContentPane());
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, gl_panel.createSequentialGroup()
.addGap(47)
.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_panel.createSequentialGroup()
.addComponent(addButton, GroupLayout.PREFERRED_SIZE, 76, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addComponent(backButton, GroupLayout.PREFERRED_SIZE, 76, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addComponent(lblX)
.addComponent(lblY, GroupLayout.PREFERRED_SIZE, 8, GroupLayout.PREFERRED_SIZE)
.addComponent(lblZ)
.addComponent(lblSize))
.addPreferredGap(ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addComponent(textFieldSize, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textFieldX, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textFieldY, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textFieldZ, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))))
.addGap(42))
.addGroup(gl_panel.createSequentialGroup()
.addComponent(separator, GroupLayout.PREFERRED_SIZE, 279, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(35)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblX)
.addComponent(textFieldX, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(textFieldY, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblY))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(textFieldZ, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblZ))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblSize)
.addComponent(textFieldSize, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18)
.addComponent(separator, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addGap(15)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(backButton, GroupLayout.PREFERRED_SIZE, 27, GroupLayout.PREFERRED_SIZE)
.addComponent(addButton, GroupLayout.PREFERRED_SIZE, 27, GroupLayout.PREFERRED_SIZE))
.addContainerGap(46, Short.MAX_VALUE))
);
getContentPane().setLayout(gl_panel);
}
private void initTextInputMap() {
double empty = Double.POSITIVE_INFINITY;
textInput.put(textFieldX, empty);
textInput.put(textFieldY, empty);
textInput.put(textFieldZ, empty);
textInput.put(textFieldSize, empty);
}
private void saveTextInput(JTextField textField) {
try {
textInput.put(textField, Double.parseDouble(textField.getText()));
getFocusOwner().transferFocus();
} catch (NumberFormatException e) {
Toolkit.getDefaultToolkit().beep();
textField.setText("");
textInput.put(textField, Double.POSITIVE_INFINITY);
} finally {
boolean validInputs = hasValidInputs();
if (! hasValidInput(textField)) {
Toolkit.getDefaultToolkit().beep();
}
addButton.setEnabled(validInputs);
}
}
private void saveTextInputs() {
for (JTextField textField : textInput.keySet()) {
saveTextInput(textField);
}
}
private void initTextActions() {
for (JTextField textField : textInput.keySet()) {
textField.addActionListener((ActionEvent a) -> {
saveTextInput(textField);
});
}
}
private void initFocusTraversal() {
getContentPane().setFocusTraversalPolicy(
new SimpleFocusTraversalPolicy(
textFieldX, textFieldY, textFieldZ,
textFieldSize));
}
private void initTextFields() {
textFieldX = new JTextField();
textFieldX.setColumns(10);
textFieldX.setName("X");
textFieldY = new JTextField();
textFieldY.setColumns(10);
textFieldY.setName("Y");
textFieldZ = new JTextField();
textFieldZ.setColumns(10);
textFieldZ.setName("Z");
textFieldSize = new JTextField();
textFieldSize.setColumns(10);
textFieldSize.setName("Size");
}
private void initButtons() {
addButton = new SolidButton("add");
addButton.addActionListener((ActionEvent a) -> {
saveTextInputs();
if (!hasValidInputs()) {
Toolkit.getDefaultToolkit().beep();
cleanInvalidInputs();
} else {
float x = textInput.get(textFieldX).floatValue();
float y = textInput.get(textFieldY).floatValue();
float z = textInput.get(textFieldZ).floatValue();
float size = textInput.get(textFieldSize).floatValue();
Cube cube = new Cube(x, y, z, size, 360, 1);
handler.addCube(cube);
resetInputs();
}
});
addButton.setFont(font);
backButton = new SolidButton("back");
backButton.addActionListener((ActionEvent a) -> {
setVisible(false);
handler.restoreMenu();
});
backButton.setFont(font);
}
private void initLabels() {...}
private int counter = 1;
#Override
public void setVisible(boolean state) {
super.setVisible(state);
addButton.setEnabled(!state);
if (state) {
if (counter == 1) {
counter = 0;
super.setVisible(true);
}
textFieldX.requestFocus();
}
}
public void terminate() {
dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}
private boolean hasValidInputs() {...}
private void cleanInvalidInputs() {...}
private boolean hasValidInput(JTextField textField) {...}
public void resetInputs() {...}
Thank you!! If any additional information is required I'll be happy to provide!
EDIT:
This simple TextField class provides a perfectly editable/focusable JTextField when I run JTextField.main().
package sourcecode.visualization.GUI;
import javax.swing.*;
public class TextField {
JFrame frame = new JFrame("Jtextfield demo");
JTextField textField = new JTextField("Hello from JTextField", 10);
public TextField() {
frame.add(textField);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TextField();
}
});
}
Yet when I call the TextField from anywhere inside our project it never is editable/focusable when I run Main.main(), despite trying all focus related functions etc, e.g. here I added a TextField object to our Pilot class.
....
import sourcecode.visualization.GUI.TextField;
public class Pilot implements ILogic {
TextField textField = new TextField();
....}
So this makes me believe the problem originates from an other class, not the CubeAdderPanel class, interfering with the JTextFields/swing, yet I don't know which one could cause this problem, we have looked in all of them, because all our code seems correct as it runs fine on Windows and Linux. Could it be the Shader, Mesh, Window, Renderer... class? What can cause this problem?

JTree refresh without collapsing

I have a problem when refreshing a JTree instance. See the following code:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
public class ItemTest {
private JFrame frame;
private DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
private JTree tree = new JTree(root);
private JButton button = new JButton("Rebuild");
private String[] array = new String[] { "name", "first_name", "middle_name", "last_name"};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
ItemTest window = new ItemTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ItemTest() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 523, 349);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollBar = new JScrollPane();
GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(scrollBar, GroupLayout.PREFERRED_SIZE, 200, GroupLayout.PREFERRED_SIZE)
.addComponent(button, GroupLayout.PREFERRED_SIZE, 85, GroupLayout.PREFERRED_SIZE)
.addContainerGap(412, Short.MAX_VALUE))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(22)
.addComponent(scrollBar, GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
.addComponent(button, GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
.addContainerGap())
);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
root.add(new DefaultMutableTreeNode("Row 4"));
((DefaultTreeModel) tree.getModel()).nodeChanged(root);
}
});
for(String string : array) {
root.add(new DefaultMutableTreeNode(string));
}
scrollBar.setViewportView(tree);
frame.getContentPane().setLayout(groupLayout);
}
}
If we run this code, and expand the "Root" node. We will see 4 nodes in it. If we click the button "Rebuild", the tree won't update it's self. The weird thing is, if we don't expand the "Root" node at the begin (so just start the application) and click the button, and after that we expand the "Root" node, the new row is added. Does anyone knows how to refresh this tree without collapsing, because nodeChanged doesn't seem to work when you expand the "Root" node at the begin.
Note: I have to accomplish this without using insertNodeInto.
You must notify the listeners that a node was inserted:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
root.add(new DefaultMutableTreeNode("Row 4"));
((DefaultTreeModel) tree.getModel()).nodesWereInserted(
root, new int[]{root.getChildCount()-1});
}
});

AWT-EventQueue-0

I have 4 classes
ui/ProductUI
controller/ProductController
project_package/Product
project_package/ProductRecords
When I try to push the button "add" it returns me an error, which if I run it through the controller doesn't show. and I put the two same identical requests.
UI:
package ui;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.UnsupportedLookAndFeelException;
import controller.ProductController;
public class ProductUI {
private JFrame f;
private JPanel page1, page2;
private JTabbedPane tp;
private JTextField addProductTextFieldName;
private JTextField addProductTextFieldPrice;
private JTextField addProductTextFieldDescription;
private JTextField addProductTextFieldDiscount;
private JTextField addProductTextFieldQuantity;
private ProductController productCtrl;
public void display()
{
f.getContentPane().add(tp);
tp.add("Add product", page1);
tp.add("Edit product", page2);
f.setSize(510,450);
f.setVisible(true);
f.setResizable(false);
}
public ProductUI()
{
f = new JFrame("Product UI");
tp = new JTabbedPane();
//**********************************
// PAGE 1
//**********************************
page1 = new JPanel();
JLabel addProductLabelName = new JLabel("Product Name");
JLabel addProductLabelPrice = new JLabel("Product Price");
JLabel addProductLabelDescription = new JLabel("Product Description");
JLabel addProductLabelDiscount = new JLabel("Product Discount");
JLabel addProductLabelQuantity = new JLabel("Product Quantity");
JLabel addProductLabelLocation = new JLabel("Product Location");
JCheckBox addProductCheckBoxAalborg = new JCheckBox("Aalborg");
JCheckBox addProductCheckBoxOdense = new JCheckBox("Odense");
JCheckBox addProductCheckBoxCopenhagen = new JCheckBox("Copenhagen");
JButton addProductButtonReset = new JButton("Reset");
JButton addProductButtonAdd = new JButton("Add");
JButton addProductButtonClose = new JButton("Close window");
JButton addProductButtonExit = new JButton("Exit");
addProductTextFieldName = new JTextField(10);
addProductTextFieldPrice = new JTextField(10);
addProductTextFieldDescription = new JTextField(10);
addProductTextFieldDiscount = new JTextField(10);
addProductTextFieldQuantity = new JTextField(10);
addProductButtonAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
/*double productPrice = Double.parseDouble(addProductTextFieldPrice.getText());
double productDiscount = Double.parseDouble(addProductTextFieldDiscount.getText());
int productQuantity = Integer.parseInt(addProductTextFieldQuantity.getText());
String productName = addProductTextFieldName.getText();
String productDescription = addProductTextFieldDescription.getText();
//productCtrl.createProduct(productName, productPrice, productDiscount, productDescription, productQuantity, "location");
*/
productCtrl.createProduct("Test", 20.0, 20.0, "haha", 20, "nqkude");
}
});
GroupLayout gl_page1 = new GroupLayout(page1);
gl_page1.setHorizontalGroup(
gl_page1.createParallelGroup(Alignment.LEADING)
.addGroup(gl_page1.createSequentialGroup()
.addGap(95)
.addGroup(gl_page1.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_page1.createSequentialGroup()
.addGroup(gl_page1.createParallelGroup(Alignment.LEADING)
.addComponent(addProductLabelName)
.addComponent(addProductLabelPrice)
.addComponent(addProductLabelDescription)
.addComponent(addProductLabelDiscount)
.addComponent(addProductLabelQuantity)
.addComponent(addProductLabelLocation))
.addGap(82))
.addGroup(gl_page1.createSequentialGroup()
.addGap(34)
.addGroup(gl_page1.createParallelGroup(Alignment.TRAILING)
.addComponent(addProductButtonAdd, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)
.addComponent(addProductButtonClose, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE))
.addGap(40)))
.addGroup(gl_page1.createParallelGroup(Alignment.LEADING, false)
.addComponent(addProductCheckBoxOdense)
.addComponent(addProductCheckBoxAalborg)
.addComponent(addProductTextFieldName, GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE)
.addComponent(addProductTextFieldPrice)
.addComponent(addProductTextFieldDescription)
.addComponent(addProductTextFieldDiscount)
.addComponent(addProductTextFieldQuantity)
.addGroup(gl_page1.createSequentialGroup()
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_page1.createParallelGroup(Alignment.TRAILING, false)
.addComponent(addProductButtonExit, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(addProductCheckBoxCopenhagen, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(addProductButtonReset, Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 96, GroupLayout.PREFERRED_SIZE))
.addGap(25)))
.addGap(100))
);
gl_page1.setVerticalGroup(
gl_page1.createParallelGroup(Alignment.LEADING)
.addGroup(gl_page1.createSequentialGroup()
.addGap(58)
.addGroup(gl_page1.createParallelGroup(Alignment.BASELINE)
.addComponent(addProductLabelName)
.addComponent(addProductTextFieldName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_page1.createParallelGroup(Alignment.BASELINE)
.addComponent(addProductLabelPrice)
.addComponent(addProductTextFieldPrice, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_page1.createParallelGroup(Alignment.BASELINE)
.addComponent(addProductLabelDescription)
.addComponent(addProductTextFieldDescription, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_page1.createParallelGroup(Alignment.BASELINE)
.addComponent(addProductLabelDiscount)
.addComponent(addProductTextFieldDiscount, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_page1.createParallelGroup(Alignment.BASELINE)
.addComponent(addProductLabelQuantity)
.addComponent(addProductTextFieldQuantity, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_page1.createParallelGroup(Alignment.BASELINE)
.addComponent(addProductLabelLocation)
.addComponent(addProductCheckBoxAalborg))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_page1.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_page1.createSequentialGroup()
.addComponent(addProductCheckBoxOdense)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(addProductCheckBoxCopenhagen)
.addGap(7)
.addComponent(addProductButtonReset))
.addComponent(addProductButtonAdd))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_page1.createParallelGroup(Alignment.BASELINE)
.addComponent(addProductButtonClose)
.addComponent(addProductButtonExit))
.addContainerGap(57, Short.MAX_VALUE))
);
page1.setLayout(gl_page1);
//**********************************
// PAGE 2
//**********************************
page2 = new JPanel();
GroupLayout gl_page2 = new GroupLayout(page2);
gl_page2.setHorizontalGroup(
gl_page2.createParallelGroup(Alignment.LEADING)
.addGap(0, 499, Short.MAX_VALUE)
);
gl_page2.setVerticalGroup(
gl_page2.createParallelGroup(Alignment.LEADING)
.addGap(0, 394, Short.MAX_VALUE)
);
page2.setLayout(gl_page2);
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
ProductUI productMenu = new ProductUI();
productMenu.display();
}
}
package controller;
import project_package.*;
public class ProductController {
ProductRecords productRecordsCtrl;
public ProductController()
{
productRecordsCtrl = ProductRecords.getInstance();
}
public void createProduct(String name, double price, double discount, String description, int quantity, String location)
{
productRecordsCtrl.createProduct(name, price, discount, description, quantity, location);
}
}
package project_package;
import java.util.ArrayList;
//import java.util.Arrays;
import java.util.List;
public class ProductRecords
{
private static ProductRecords instance = null;
ArrayList<Product> products = new ArrayList<Product>();
List<Integer> quantity = new ArrayList<Integer>();
List<String> location = new ArrayList<String>();
int productIndex = 0;
public static ProductRecords getInstance()
{
if(instance == null)
{
instance = new ProductRecords();
}
return instance;
}
// add a product to the list
public void addProduct(Product product, int quantity, String location)
{
products.add(product.getID(), product);
this.quantity.add(product.getID(), quantity);
this.location.add(product.getID(), location);
}
// create (add) a new product (to the shop list)
public void createProduct(String name, double price, double discount, String description, int quantity, String location)
{
Product newProduct = new Product(productIndex, price, discount, name, description);
addProduct(newProduct, quantity, location);
productIndex++;
}
}
package project_package;
public class Product {
int id;
double price;
double discount;
String name;
String description;
public Product(int id, double price, double discount, String name, String description)
{
this.id = id;
this.price = price;
this.discount = discount;
this.name = name;
this.description = description;
}
}
The full error is this
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
thrown on this line
productCtrl.createProduct("Test", 20.0, 20.0, "haha", 20,"nqkude");
due to the fact that productCtrl has not been instantiated. You could do:
productCtrl = new ProductController();

How to create a slide panel

I try to change a layout of the panel, but there are problems, because when I change layout the components remain on the panel and there are many bags.
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LayoutTest extends JFrame {
public LayoutTest() {
initComponents();
}
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton = new JButton();
jPanel1.setBackground(new java.awt.Color(204, 204, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LayoutManager tempGroupLayout = jPanel1.getLayout();
jPanel1.setLayout(layoutManager2);
jPanel1.getParent().validate();
layoutManager = layoutManager2;
layoutManager2 = tempGroupLayout;
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).
addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup().
addContainerGap(286, Short.MAX_VALUE).
addComponent(jButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)));
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).
addComponent(jButton, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE));
layoutManager = jPanel1Layout;
javax.swing.GroupLayout jPanel1Layout2 = new javax.swing.GroupLayout(jPanel1);
jPanel1Layout2.setHorizontalGroup(
jPanel1Layout2.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).
addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout2.createSequentialGroup().
addComponent(jButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)));
jPanel1Layout2.setVerticalGroup(
jPanel1Layout2.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).
addComponent(jButton, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE));
layoutManager2 = jPanel1Layout2;
getContentPane().add(jPanel1);
pack();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LayoutTest().setVisible(true);
}
});
}
private JButton jButton;
private JPanel jPanel1;
private LayoutManager layoutManager;
private LayoutManager layoutManager2;
}
Have a look at the JSplitPane component. You can nest a few of them.
splitPane.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, new SplitPanePropertyChangeListener());
private class SplitPanePropertyChangeListener implements PropertyChangeListener {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
int nv = ((Integer) evt.getNewValue()).intValue();
if (nv == 1) { //adjust this depending on your divider location
setSize(new Dimension(800, 560));
}
if (nv == 221) { //adjust this depending on your divider location
setSize(new Dimension(1000, 560));
}
}
}
Check with above code and remodel it for your requirement

Categories

Resources