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();
Related
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?
I'm trying to make a program that uses Swing for the GUI, but the form that opens up when I run the code below is blank. I'm still able to get information regarding the objects that aren't seen, however (tested with getting btnLogin.getText()). Am I missing something, or am I doing something wrong?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class loginForm extends JFrame implements ActionListener{
public static void main(String[] args){
new loginForm();
}
public loginForm() {
System.out.println("Starting...");
pack();
initComponents();
System.out.println("Opened");
this.setVisible(true);
}
private void initComponents() {
loginForm = new JFrame();
lblUserID = new JLabel();
existingUserIDTextField = new JTextField();
lblPassword = new JLabel();
existingUserPasswordField = new JPasswordField();
btnLogin = new JButton();
btnLogin.addActionListener(this);
lblWelcome = new JLabel();
//======== loginForm ========
{
loginForm.setResizable(false);
loginForm.setTitle("Library Reservation System");
Container loginFormContentPane = loginForm.getContentPane();
//---- lblUserID ----
lblUserID.setText("User ID:");
lblUserID.setFont(new Font("Tahoma", Font.PLAIN, 16));
//---- lblPassword ----
lblPassword.setText("Password:");
lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 16));
//---- btnLogin ----
btnLogin.setText("Login");
//---- lblWelcome ----
lblWelcome.setText("Welcome to our Library Reservation System");
lblWelcome.setFont(new Font("Tahoma", Font.PLAIN, 16));
GroupLayout loginFormContentPaneLayout = new GroupLayout(loginFormContentPane);
loginFormContentPane.setLayout(loginFormContentPaneLayout);
loginFormContentPaneLayout.setHorizontalGroup(
loginFormContentPaneLayout.createParallelGroup()
.addGroup(loginFormContentPaneLayout.createSequentialGroup()
.addGroup(loginFormContentPaneLayout.createParallelGroup()
.addGroup(loginFormContentPaneLayout.createSequentialGroup()
.addGap(199, 199, 199)
.addComponent(btnLogin, GroupLayout.PREFERRED_SIZE, 145, GroupLayout.PREFERRED_SIZE))
.addGroup(loginFormContentPaneLayout.createSequentialGroup()
.addGap(72, 72, 72)
.addGroup(loginFormContentPaneLayout.createParallelGroup()
.addComponent(lblUserID, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)
.addComponent(lblPassword))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addGroup(loginFormContentPaneLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
.addComponent(existingUserIDTextField, GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)
.addComponent(existingUserPasswordField, GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)))
.addGroup(GroupLayout.Alignment.TRAILING, loginFormContentPaneLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lblWelcome, GroupLayout.PREFERRED_SIZE, 318, GroupLayout.PREFERRED_SIZE)))
.addContainerGap(118, Short.MAX_VALUE))
);
loginFormContentPaneLayout.setVerticalGroup(
loginFormContentPaneLayout.createParallelGroup()
.addGroup(loginFormContentPaneLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lblWelcome, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
.addGap(11, 11, 11)
.addGroup(loginFormContentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(lblUserID)
.addComponent(existingUserIDTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(loginFormContentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(lblPassword)
.addComponent(existingUserPasswordField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(btnLogin)
.addContainerGap(12, Short.MAX_VALUE))
);
loginForm.pack();
loginForm.setLocationRelativeTo(loginForm.getOwner());
}
}
private JFrame loginForm;
private JLabel lblUserID;
private JTextField existingUserIDTextField;
private JLabel lblPassword;
private JPasswordField existingUserPasswordField;
private JButton btnLogin;
private JLabel lblWelcome;
}
The frame containing the controls is never displayed.
loginForm.setVisible(true);
Instead of having an outer redundant frame class you could do
public class LoginFormApp extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
LoginFormApp loginFormApp = new LoginFormApp();
loginFormApp.initComponents();
}
});
.....
}
where initComponents makes the loginForm visible as previously stated.
My JTable doesn't display my column name, and I don't see why. Can anyone help me to tell me why? Thank you in advance.
package projet.ihm;
import java.awt.Color;
public class VueOccupations extends JPanel {
class MonModeleTableOccupation extends AbstractTableModel {
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
private JoursHoraire jours;
// initialise ma liste de joueurs
public MonModeleTableOccupation( JoursHoraire jour) {
super();
this.jours=jour;
///périodes = périodes;
//jours = JoursHoraire.valueOf(jour);
}
// #Override
// public void setValueAt(Object aValue, int l, int c) {
// JoursHoraire[] jours=JoursHoraire.values();
// Joueur j = joueurs.get(l);
// switch (c) {
//
// case 1:
// j.setPrenom((String) aValue);
// break;
//case 2:
// j.setDate((Date) aValue);
//}
//}
#Override
public Class<?> getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
#Override
public String getColumnName(int c) {
// TODO Auto-generated method stub
switch (c) {
case 0:
return "périodes";
case 1:
return "Jour";
case 2:
return "Heure Debut";
case 3:
return "Heure Fin";
case 4:
return "Local";
}
return "Vide";
}
#Override
public int getColumnCount() {
return 5;
}
#Override
public int getRowCount() {
return Periode.NB_PERIODES;
}
#Override
public Object getValueAt(int l, int c) {
JoursHoraire jour = jours.JEUDI;
// System.out.println(l+" "+c+" "+j);
switch (c) {
case 0:
return jour.values();
case 1:
return jour.values();
case 2:
// return sdf.format(j.getDate());
return jour.values();
}
return "Vide";
}
}
private ControleurJHOccupation ctrl;
private JTable table;
private JTable table_1;
private JComboBox cbModule;
private JComboBox cbPeriode;
private JComboBox<JoursHoraire> cbJour;
private JComboBox<HeureMinute> cbHeureD;
private JComboBox<HeureMinute> cbHeureFin;
private ModèleJHOccupation modèleJHOccupation;
public VueOccupations(ControleurJHOccupation ctrl)throws HeadlessException {
modèleJHOccupation = new ModèleJHOccupation(ctrl);
// super(new ModèleJHProfesseur(ctrl),
// ctrl.getFacade().getIdsProfesseurs());
this.ctrl=ctrl;
JLabel lblModule = new JLabel("Choix Module");
cbModule = new JComboBox();
table = new JTable(modèleJHOccupation);
cbPeriode = new JComboBox();
cbJour = new JComboBox();
cbHeureD = new JComboBox();
cbHeureFin = new JComboBox();
String[] listeModule = ctrl.getFacade().getIdsModules();
for (int p = 0; p < listeModule.length; p++)
cbModule.addItem(listeModule[p]);
HeureMinute[] listeHDeb=SlotsJour.getHeuresJournée();
for (int p = 0; p < listeHDeb.length ; p++)
cbHeureD.addItem(listeHDeb[p]);
HeureMinute[] listeHFin=SlotsJour.getHeuresJournée();
for (int p = 0; p < listeHFin.length ; p++)
cbHeureFin.addItem(listeHFin[p]);
JoursHoraire[] jour=JoursHoraire.values();
for (int p = 0; p < jour.length ; p++)
cbJour.addItem(jour[p]);
List<Periode> période =ctrl.getFacade().getListePériode();
for (int i = 0; i < période.size(); i++){
cbPeriode.addItem( période.get(i).getId());
}
initGui();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 500);
setVisible(true);
JButton btnAjoutOcc = new JButton("Ajout Occupation");
JScrollPane scrollPane = new JScrollPane();
GroupLayout groupLayout = new GroupLayout(this);
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(18)
.addComponent(lblModule)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(cbModule, 0, 466, Short.MAX_VALUE))
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap(44, Short.MAX_VALUE)
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(table_1, GroupLayout.PREFERRED_SIZE, 514, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(cbPeriode, GroupLayout.PREFERRED_SIZE, 79, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(cbJour, GroupLayout.PREFERRED_SIZE, 79, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(cbHeureD, GroupLayout.PREFERRED_SIZE, 79, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(cbHeureFin, GroupLayout.PREFERRED_SIZE, 81, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(btnAjoutOcc, GroupLayout.PREFERRED_SIZE, 168, GroupLayout.PREFERRED_SIZE)))))
.addGap(42))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblModule)
.addComponent(cbModule, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(table_1, GroupLayout.PREFERRED_SIZE, 161, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(42)
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.addGap(47)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(cbPeriode, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(cbJour, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(cbHeureD, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(cbHeureFin, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(btnAjoutOcc))
.addContainerGap(227, Short.MAX_VALUE))
);
setLayout(groupLayout);
}
private void initGui() {
//monModeleTableOccupation = new MonModeleTableOccupation(JoursHoraire jour);
table_1 = new JTable(monModeleTableOccupation);
//table.getColumnModel().getColumn(2).setCellRenderer(new Rend);
table_1.setAutoCreateRowSorter(true);
table_1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table_1.setBackground(Color.cyan);
table_1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged ( ListSelectionEvent evt ) {
if ( evt . getValueIsAdjusting ()) return ;
int i =table . getSelectedRow ();
if (i >= 0) {
i =table.convertRowIndexToModel (i);
System.out.println(i);
} else
{}}}
);
JScrollPane scp = new JScrollPane(table);
//getRootPane().getContentPane().add(scp);
add(scp, BorderLayout.CENTER);
//JPanel panelSud = new JPanel();
//getContentPane().add(panelSud, BorderLayout.NORTH);
}
private MonModeleTableOccupation monModeleTableOccupation;
private void setDefaultCloseOperation(int exitOnClose) {
// TODO Auto-generated method stub
}
}
A simple way to show the columns is to put the JTable into the viewport of a JScrollPane.
JScrollPane tablePane = new JScrollPane(jtable);
and add this JScrollPane to a JPanel.
As the javadoc of JTable states:
If this JTable is the viewportView of an enclosing JScrollPane (the usual situation), configure this ScrollPane by, amongst other things, installing the table's tableHeader as the columnHeaderView of the scroll pane.
....
I can't see that your table_1 is wrapped by a JScrollPane. I guess this causes the problem.
Ok, I have a program I am doing for class. I have to take the input form the text field, ad throw it into an overloaded constructor that takes a string as an argument. There are a few other things I have to do with constructors as well, so in my code you'll see some stuff that is outside of this question. also, I am not posting my methods because it's a big part of the homework, and those all work fine, (prior to my attempt at passing info to the constructor). What I would like to know is i there is a way to pass the text field info into the constructor, because I have been going at this for a couple hours now, but it's becoming plainly obvious that I don't understand this. If you just want to direct me to somewhere that I can learn how to do this I would appreciate it.
Code:
package lab4;
import java.awt.*;
import java.awt.List;
import javax.swing.*;
import java.awt.event.*;
import java.lang.Iterable.*;
import java.util.*;
public class Lab4 extends JFrame{
private JTextField jTextField1;
private JButton doSome;
private JLabel ansTxt;
private JLabel asciSum;
private JLabel jLabel1;
private JLabel jLabel3;
private JLabel jLabel4;
private JLabel jLabel5;
private JLabel jLabel6;
private JLabel lowCnt;
private JLabel numDigit;
private JLabel upCnt;
private JLabel vowelCnt;
private String userInput = jTextField1.getText();
public Lab4()
{
initComponents();
}
public Lab4(String x)
{
this.userInput = x;
}
public Lab4(char[] x)
{
}
public Lab4(byte[] x)
{
}
private void initComponents() {
jTextField1 = new JTextField();
jLabel1 = new JLabel();
doSome = new JButton();
ansTxt = new JLabel();
jLabel3 = new JLabel();
jLabel4 = new JLabel();
jLabel5 = new JLabel();
jLabel6 = new JLabel();
asciSum = new JLabel();
vowelCnt = new JLabel();
numDigit = new JLabel();
upCnt = new JLabel();
lowCnt = new JLabel();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setAutoRequestFocus(false);
setFont(new java.awt.Font("Comic Sans MS", 1, 12)); // NOI18N
jLabel1.setText("Enter a string Here and I'll show you some info about it!");
doSome.setToolTipText("This Will Do Something");
doSome.setInheritsPopupMenu(true);
doSome.setLabel("Click Me When Your Done!");
doSome.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
doSomeActionPerformed(evt);
}
});
ansTxt.setText("ASCII SUM:");
jLabel3.setText("Number of Vowels:");
jLabel4.setText("Number of Digits:");
jLabel5.setText("Number Of Uppercase:");
jLabel6.setText("Number Of Lowercase:");
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
.addComponent(ansTxt)
.addComponent(jLabel5, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel6, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(84, 84, 84)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(lowCnt)
.addComponent(vowelCnt)
.addComponent(asciSum)
.addComponent(numDigit)
.addComponent(upCnt)))
.addGroup(layout.createSequentialGroup()
.addGap(95, 95, 95)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1)
.addComponent(jLabel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(doSome, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap(239, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(jLabel1)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(doSome)
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(ansTxt)
.addComponent(asciSum))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(vowelCnt))
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(numDigit))
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(upCnt))
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(lowCnt))
.addContainerGap(157, Short.MAX_VALUE))
);
pack();
}
private void doSomeActionPerformed(ActionEvent evt)
{
String takeTfIn = this.jTextField1.getText();
this.asciSum.setText(getAsciiSum(takeTfIn));
this.vowelCnt.setText(getNumVowels(takeTfIn));
this.numDigit.setText(getNumDigits(takeTfIn));
this.upCnt.setText(getNumUpperCase(takeTfIn));
this.lowCnt.setText(getNumLowerCase(takeTfIn));
}
// Excluded methods go here...
public static void main(String[] args)
{
Lab4 test = new Lab4();
test.setVisible(true);
}
}
You'll need to create new instance of lab4 after you fill tex field value and click on submit. on click of submit you can do like this
this.setVisible(false);//Hide current instance
Lab4 test = new Lab4(this.jTextField1.getText()); // create new instance
test.setVisible(true); // set new instance visible
Don't forget to add following constructor:
public Lab4 (String value)
{
this.jTextField1.setText(value); // if you like to set value back to textbox
}
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);
}
}