JTable and JPanel - java

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.

Related

Getting InvalidateStateException when using GroupLayout

I am getting the message Baseline must be used along vertical axis. I've tried using all the enums for alignment, to no avail and made sure that all components have been added to both horizontal and vertical axes.
Here is the exception chain
at javax.swing.GroupLayout$BaselineGroup.checkAxis(GroupLayout.java:2926)
at javax.swing.GroupLayout$BaselineGroup.calculateSize(GroupLayout.java:2706)
at javax.swing.GroupLayout$Group.calculatePreferredSize(GroupLayout.java:1602)
at javax.swing.GroupLayout$Spring.getPreferredSize(GroupLayout.java:1346)
at javax.swing.GroupLayout$Group.getSpringSize(GroupLayout.java:1638)
at javax.swing.GroupLayout$Group.calculateSize(GroupLayout.java:1624)
at javax.swing.GroupLayout$Group.calculatePreferredSize(GroupLayout.java:1602)
at javax.swing.GroupLayout$Spring.getPreferredSize(GroupLayout.java:1346)
at javax.swing.GroupLayout$Group.getSpringSize(GroupLayout.java:1638)
at javax.swing.GroupLayout$Group.calculateSize(GroupLayout.java:1625)
at javax.swing.GroupLayout$Group.calculatePreferredSize(GroupLayout.java:1602)
at javax.swing.GroupLayout$Spring.getPreferredSize(GroupLayout.java:1346)
at javax.swing.GroupLayout$SequentialGroup.setValidSize(GroupLayout.java:2017)
at javax.swing.GroupLayout$Group.setSize(GroupLayout.java:1587)
at javax.swing.GroupLayout.calculateAutopadding(GroupLayout.java:1079)
at javax.swing.GroupLayout.layoutContainer(GroupLayout.java:918)
at java.awt.Container.layout(Container.java:1513)
at java.awt.Container.doLayout(Container.java:1502)
at java.awt.Container.validateTree(Container.java:1698)
at java.awt.Container.validateTree(Container.java:1707)
at java.awt.Container.validateTree(Container.java:1707)
at java.awt.Container.validateTree(Container.java:1707)
at java.awt.Container.validateTree(Container.java:1707)
at java.awt.Container.validate(Container.java:1633)
at java.awt.Container.validateUnconditionally(Container.java:1670)
at java.awt.Window.pack(Window.java:818)
at resumebuilder.ResumeBuilder.(ResumeBuilder.java:32)
at resumebuilder.program.main(program.java:15)
Here is the code
private void initComponents() {
GroupLayout groupLayout = new GroupLayout(this);
groupLayout.setAutoCreateGaps(true);
groupLayout.setAutoCreateContainerGaps(true);
jLabel1 = new JLabel("Name");
jLabel1.setHorizontalAlignment(SwingConstants.RIGHT);
firstName = new JTextField(50);
firstName.setToolTipText("First Name");
lastName = new JTextField(50);
lastName.setToolTipText("Last Name");
jLabel2 = new JLabel("Address");
jLabel2.setHorizontalAlignment(SwingConstants.RIGHT);
address1 = new JTextField(50);
address1.setToolTipText("Address 1");
address2 = new JTextField(50);
address2.setToolTipText("Address 2");
add(address2);
toggleAddress3 = new javax.swing.JCheckBox();
toggleAddress3.setText("Show third address");
toggleAddress3.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
setToggle();
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
address3 = new JTextField(50);
address3.setToolTipText("Address 3");
address3.setVisible(false);
city = new JTextField(50);
city.setToolTipText("City");
state = new JTextField(10);
state.setToolTipText("State");
postalCode = new JTextField(25);
postalCode.setToolTipText("Postal Code");
jLabel3 = new JLabel("Gender");
jLabel3.setHorizontalAlignment(SwingConstants.RIGHT);
add(jLabel3);
String[] items = {"", "Male", "Female"};
gender = new JComboBox<String>(items);
gender.setToolTipText("Gender");
jLabel4 = new JLabel("Date of Birth");
jLabel4.setHorizontalAlignment(SwingConstants.RIGHT);
dateOfBirth = new JSpinner();
groupLayout.setHorizontalGroup(groupLayout.createParallelGroup()
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(firstName)
.addComponent(lastName))
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(address1))
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(toggleAddress3)
.addComponent(address2))
.addComponent(address3)
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(city)
.addComponent(state)
.addComponent(postalCode))
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(gender))
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(dateOfBirth))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(firstName, GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lastName, GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(
GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(address1)
)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(address2, GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(toggleAddress3))
.addComponent(address3, GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(city, GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(state, GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(postalCode, GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(gender))
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(dateOfBirth))
);
setLayout(groupLayout);
}

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?

JSplitPane setOneTouchExpandable(true) is not shown

I'm using nested JSplitPane...
I want to use OneTouchExpandable, but running the code is not shown...
But in preview mode I can see it.
Here complete code:
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import java.awt.Dimension;
import java.util.logging.Level;
import java.util.logging.Logger;
package splitpane;
public class JFr_SplitPane extends JFrame {
private JButton jbLeftRight;
private JButton jbRightLeft;
private JButton jbRightRight;
private JLabel jlLeftLeft;
private JPanel jpLeftLeft;
private JPanel jpLeftRight;
private JPanel jpMain;
private JPanel jpRightLeft;
private JPanel jpRightRight;
private JSplitPane jspLeft;
private JSplitPane jspMain;
private JSplitPane jspRight;
private JTextField jtfLeftLeft;
private JTextField jtfLeftRight;
private JTextField jtfRightLeft;
private JTextField jtfRightRight;
public JFr_SplitPane() {
initComponents();
}
private void initComponents() {
jpMain = new JPanel();
jspMain = new JSplitPane();
jspLeft = new JSplitPane();
jpLeftLeft = new JPanel();
jlLeftLeft = new JLabel();
jtfLeftLeft = new JTextField();
jpLeftRight = new JPanel();
jbLeftRight = new JButton();
jtfLeftRight = new JTextField();
jspRight = new JSplitPane();
jpRightLeft = new JPanel();
jbRightLeft = new JButton();
jtfRightLeft = new JTextField();
jpRightRight = new JPanel();
jbRightRight = new JButton();
jtfRightRight = new JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jpMain.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jpMain.setPreferredSize(new Dimension(692, 36));
jspMain.setDividerLocation(344);
jspMain.setMinimumSize(new Dimension(276, 28));
jspMain.setOneTouchExpandable(true);
jspMain.setPreferredSize(new Dimension(688, 34));
jspLeft.setDividerLocation(169);
jspLeft.setMinimumSize(new Dimension(132, 25));
jspLeft.setOneTouchExpandable(true);
jspLeft.setPreferredSize(new Dimension(338, 30));
jpLeftLeft.setMinimumSize(new Dimension(60, 25));
jpLeftLeft.setPreferredSize(new Dimension(320, 25));
jlLeftLeft.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jlLeftLeft.setPreferredSize(new Dimension(24, 18));
jtfLeftLeft.setPreferredSize(new Dimension(6, 25));
GroupLayout jpLeftLeftLayout = new GroupLayout(jpLeftLeft);
jpLeftLeft.setLayout(jpLeftLeftLayout);
jpLeftLeftLayout.setHorizontalGroup(
jpLeftLeftLayout.createParallelGroup(Alignment.LEADING)
.addGroup(jpLeftLeftLayout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jlLeftLeft, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(2, 2, 2)
.addComponent(jtfLeftLeft, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jpLeftLeftLayout.setVerticalGroup(
jpLeftLeftLayout.createParallelGroup(Alignment.LEADING)
.addGroup(jpLeftLeftLayout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(jlLeftLeft, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jtfLeftLeft, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
);
jspLeft.setLeftComponent(jpLeftLeft);
jpLeftRight.setMinimumSize(new Dimension(60, 25));
jpLeftRight.setPreferredSize(new Dimension(320, 25));
jbLeftRight.setPreferredSize(new Dimension(30, 21));
jtfLeftRight.setPreferredSize(new Dimension(6, 25));
GroupLayout jpLeftRightLayout = new GroupLayout(jpLeftRight);
jpLeftRight.setLayout(jpLeftRightLayout);
jpLeftRightLayout.setHorizontalGroup(
jpLeftRightLayout.createParallelGroup(Alignment.LEADING)
.addGroup(jpLeftRightLayout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jbLeftRight, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(2, 2, 2)
.addComponent(jtfLeftRight, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jpLeftRightLayout.setVerticalGroup(
jpLeftRightLayout.createParallelGroup(Alignment.LEADING)
.addGroup(jpLeftRightLayout.createParallelGroup(Alignment.CENTER)
.addComponent(jbLeftRight, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(jtfLeftRight, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
);
jspLeft.setRightComponent(jpLeftRight);
jspMain.setLeftComponent(jspLeft);
jspRight.setDividerLocation(169);
jspRight.setMinimumSize(new Dimension(132, 25));
jspRight.setOneTouchExpandable(true);
jspRight.setPreferredSize(new Dimension(338, 30));
jpRightLeft.setMinimumSize(new Dimension(60, 25));
jpRightLeft.setPreferredSize(new Dimension(320, 25));
jbRightLeft.setPreferredSize(new Dimension(30, 21));
jtfRightLeft.setPreferredSize(new Dimension(6, 25));
GroupLayout jpRightLeftLayout = new GroupLayout(jpRightLeft);
jpRightLeft.setLayout(jpRightLeftLayout);
jpRightLeftLayout.setHorizontalGroup(
jpRightLeftLayout.createParallelGroup(Alignment.LEADING)
.addGroup(jpRightLeftLayout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jbRightLeft, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(2, 2, 2)
.addComponent(jtfRightLeft, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jpRightLeftLayout.setVerticalGroup(
jpRightLeftLayout.createParallelGroup(Alignment.LEADING)
.addGroup(jpRightLeftLayout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(jbRightLeft, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jtfRightLeft, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
);
jspRight.setLeftComponent(jpRightLeft);
jpRightRight.setMinimumSize(new Dimension(60, 25));
jpRightRight.setPreferredSize(new Dimension(320, 25));
jbRightRight.setPreferredSize(new Dimension(30, 21));
jtfRightRight.setPreferredSize(new Dimension(6, 25));
GroupLayout jpRightRightLayout = new GroupLayout(jpRightRight);
jpRightRight.setLayout(jpRightRightLayout);
jpRightRightLayout.setHorizontalGroup(
jpRightRightLayout.createParallelGroup(Alignment.LEADING)
.addGroup(jpRightRightLayout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jbRightRight, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(2, 2, 2)
.addComponent(jtfRightRight, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jpRightRightLayout.setVerticalGroup(
jpRightRightLayout.createParallelGroup(Alignment.LEADING)
.addGroup(jpRightRightLayout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(jbRightRight, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jpRightRightLayout.createSequentialGroup()
.addComponent(jtfRightRight, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jspRight.setRightComponent(jpRightRight);
jspMain.setRightComponent(jspRight);
GroupLayout jpMainLayout = new GroupLayout(jpMain);
jpMain.setLayout(jpMainLayout);
jpMainLayout.setHorizontalGroup(
jpMainLayout.createParallelGroup(Alignment.LEADING)
.addComponent(jspMain, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jpMainLayout.setVerticalGroup(
jpMainLayout.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, jpMainLayout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jspMain, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
);
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGap(0, 702, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jpMain, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
layout.setVerticalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGap(0, 54, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jpMain, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
pack();
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(JFr_SplitPane.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(JFr_SplitPane.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(JFr_SplitPane.class.getName()).log(Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
Logger.getLogger(JFr_SplitPane.class.getName()).log(Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JFr_SplitPane().setVisible(true);
}
});
}
}
In preview mode:
Running is not shown...
What's the problem?
How can I to solve it?
Testing Look And Feel
Windows
Nimbus
Windows Classic
CDE/Motif
Metal
Probably you are looking for SplitPane.oneTouchButtonOffset:
import java.awt.*;
import javax.swing.*;
public class OneTouchButtonOffsetTest {
public JComponent makeUI() {
System.out.println(UIManager.getInt("SplitPane.oneTouchButtonOffset"));
UIManager.put("SplitPane.oneTouchButtonOffset", 0);
UIDefaults d = new UIDefaults();
d.put("SplitPane:SplitPaneDivider[Enabled+Vertical].foregroundPainter",
new Painter<JComponent>() {
#Override public void paint(Graphics2D g, JComponent c, int w, int h) {
/* empty */
}
});
JSplitPane splitPane = new JSplitPane();
splitPane.putClientProperty("Nimbus.Overrides", d);
splitPane.setLeftComponent(makePanel());
splitPane.setRightComponent(makePanel());
splitPane.setOneTouchExpandable(true);
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
p.add(splitPane, BorderLayout.NORTH);
return p;
}
private static JComponent makePanel() {
JPanel p = new JPanel(new BorderLayout());
p.add(new JButton(), BorderLayout.WEST);
p.add(new JTextField("aaaaaaaa"));
return p;
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
try {
for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(laf.getName())) {
UIManager.setLookAndFeel(laf.getClassName());
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new OneTouchButtonOffsetTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}

MySQL Java Use a JComboBox to set a second JComboBox

I am using MySQL server 5.6 to host a database that I am using to manage part number records. I have a Java client front end. My connections between the client and database are all good. In my panel to create parts, I have a JComboBox-typeComboBox that is populated by querying the database for all possible part types and displaying their type numbers in the drop down menu. Depending on the selection from that JComboBox the tdescripTextField and seqTextField are filled with the the appropriate information but I can not get the JComboBox-matComboBox to be populated by the appropriate results that are queried using the selected PartType number.
I have used a number of System.out.println(); to debug the part of the code where the issue is happening, and from what I can tell the String[] mats does contain the correct information, but it just wont assign it to the matComboBox. I notifced if I don't initialize matComboBox = new JComboBox(); right after the typeComboBox I get a compilation error saying that matComboBox is null.
Thanks in advance for any help.
p.s. all of my query methods return JSONArrays from the database.
class CreatePanel extends JPanel{
//JButtons
private JButton saveButton;
private JButton backButton;
//JComboBox
private JComboBox<?> typeComboBox;
private JComboBox<?> matComboBox;
//JTextField
private JTextField tdescripTextField;
private JTextField mdescripTextField;
private JTextField descripTextField;
private JTextField seqTextField;
private JTextField bpartTextField;
private JTextField cpartTextField;
private JTextField spartTextField;
//JLabel
private JLabel lblSeq;
private JLabel lblDescription;
private JLabel lblMatterialDescription;
private JLabel lblTypeDescription;
private JLabel lblType;
private JLabel lblMatterial;
private JLabel lblBosalPartNumber;
private JLabel lblCustomerPartNumber;
private JLabel lblSupplierPartNumber;
private JLabel lblCreateAPart;
private JLabel Bosal;
JPanel contentPane;
//StringPanel
public CreatePanel(final JPanel create)
{
//TextFields
tdescripTextField = new JTextField();
tdescripTextField.setEditable(false);
mdescripTextField = new JTextField();
mdescripTextField.setEditable(false);
descripTextField = new JTextField();
seqTextField = new JTextField();
seqTextField.setEditable(false);
bpartTextField = new JTextField();
bpartTextField.setEditable(false);
cpartTextField = new JTextField();
spartTextField = new JTextField();
//ComboBoxes
typeComboBox = new JComboBox<Object>();
matComboBox = new JComboBox<Object>();
JSONArray temp1 = new JSONArray();
String[] types = null;
try{
temp1 = con.queryReturnAllTypes();
types = new String[temp1.length()];
for(int i = 0; i < temp1.length(); i++){
types[i] = temp1.getJSONObject(i).get("PartType").toString();
}
}catch(Exception ex){/*ignore*/}
typeComboBox = new JComboBox<Object>(types);
typeComboBox.setEditable(true);
typeComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
int partType = Integer.valueOf((String) typeComboBox.getSelectedItem());
/*Debug*/System.out.println(partType);
JSONArray temp1 = new JSONArray();
JSONArray temp2 = new JSONArray();
String typeDescrip = null;
String seqNum = null;
String[] mats = null;
try{
temp1 = con.queryPartType(partType);
/*Debug*/System.out.println(temp1);
temp2 = con.queryMaterialPartType(partType);
/*Debug*/System.out.println(temp2);
mats = new String[temp2.length()];
/*Debug*/System.out.println(temp2.length());
typeDescrip = temp1.getJSONObject(0).get("TypeDescription").toString();
tdescripTextField.setText(typeDescrip);
seqNum = temp1.getJSONObject(0).get("SeqNumber").toString();
seqTextField.setText(seqNum);
for(int i = 0; i < temp2.length(); i++){
/*Debug*/System.out.println(i);
/*Debug*/System.out.println(temp2.getJSONObject(i).get("Material").toString());
mats[i] = temp2.getJSONObject(i).get("Material").toString();
/*Debug*/System.out.println(mats[i]);
}
for(int i = 0; i<mats.length; i++){
/*Debug*/System.out.println(mats[i]);
}
}catch(Exception ex){/*ignore*/}
for(int i = 0; i<mats.length; i++){
/*Debug*/System.out.println(mats[i]);
}
matComboBox = new JComboBox<Object>(mats);
matComboBox.setEditable(true);
}
});
//Labels
lblType = new JLabel("Type");
lblMatterial = new JLabel("Material");
lblTypeDescription = new JLabel("Type Description");
lblMatterialDescription = new JLabel("Material Description");
lblSeq = new JLabel("Seq");
lblDescription = new JLabel("Description");
lblBosalPartNumber = new JLabel("Bosal Part Number");
lblCustomerPartNumber = new JLabel("Customer Part Number");
lblSupplierPartNumber = new JLabel("Supplier Part Number");
lblCreateAPart = new JLabel("Create a Part Number");
ImageIcon bosal = new ImageIcon(getClass().getResource("/Images/bosal.jpg"));
Bosal = new JLabel(bosal);
setBackground(Color.DARK_GRAY);
//Buttons
ImageIcon save = new ImageIcon(getClass().getResource("/images/save1.jpg"));
saveButton = new JButton(save);
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == saveButton){
int n = JOptionPane.showConfirmDialog(
frame,
"Are you sure you want to save part data?",
"Save:",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
}}});
add(saveButton);
ImageIcon back = new ImageIcon(getClass().getResource("/images/back1.jpg"));
backButton = new JButton(back);
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == backButton)
{
setVisible(false);
frame.setLocation(550,220);
frame.setSize(700, 580);
main.setVisible(true);
}}});
add(backButton);
setupPanel();
};
private void setupPanel()
{
//Label Fonts
lblType.setFont(new Font("Tahoma", Font.BOLD, 14));
lblType.setForeground(Color.BLACK);
lblMatterial.setFont(new Font("Tahoma", Font.BOLD, 14));
lblMatterial.setForeground(Color.BLACK);
lblTypeDescription.setFont(new Font("Tahoma", Font.BOLD, 14));
lblTypeDescription.setForeground(Color.BLACK);
lblMatterialDescription.setFont(new Font("Tahoma", Font.BOLD, 14));
lblMatterialDescription.setForeground(Color.BLACK);
lblDescription.setFont(new Font("Tahoma", Font.BOLD, 14));
lblDescription.setForeground(Color.BLACK);
lblSeq.setFont(new Font("Tahoma", Font.BOLD, 14));
lblSeq.setForeground(Color.BLACK);
lblSupplierPartNumber.setFont(new Font("Tahoma", Font.BOLD, 14));
lblSupplierPartNumber.setForeground(Color.BLACK);
lblCreateAPart.setFont(new Font("EucrosiaUPC", Font.BOLD, 64));
lblCreateAPart.setForeground(Color.BLACK);
lblCustomerPartNumber.setFont(new Font("Tahoma", Font.BOLD, 14));
lblCustomerPartNumber.setForeground(Color.BLACK);
lblBosalPartNumber.setFont(new Font("Tahoma", Font.BOLD, 14));
lblBosalPartNumber.setForeground(Color.BLACK);
//Group Layout
GroupLayout groupLayout = new GroupLayout(this);
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(24)
.addComponent(Bosal, GroupLayout.PREFERRED_SIZE, 199, GroupLayout.PREFERRED_SIZE)
.addGap(6)
.addComponent(lblCreateAPart, GroupLayout.PREFERRED_SIZE, 434, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(50)
.addComponent(lblType)
.addGap(121)
.addComponent(lblTypeDescription)
.addGap(163)
.addComponent(lblBosalPartNumber))
.addGroup(groupLayout.createSequentialGroup()
.addGap(50)
.addComponent(typeComboBox, GroupLayout.PREFERRED_SIZE, 79, GroupLayout.PREFERRED_SIZE)
.addGap(76)
.addComponent(tdescripTextField, GroupLayout.PREFERRED_SIZE, 211, GroupLayout.PREFERRED_SIZE)
.addGap(67)
.addComponent(bpartTextField, GroupLayout.PREFERRED_SIZE, 156, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(50)
.addComponent(lblMatterial)
.addGap(101)
.addComponent(lblMatterialDescription)
.addGap(143)
.addComponent(lblCustomerPartNumber))
.addGroup(groupLayout.createSequentialGroup()
.addGap(50)
.addComponent(matComboBox, GroupLayout.PREFERRED_SIZE, 79, GroupLayout.PREFERRED_SIZE)
.addGap(76)
.addComponent(mdescripTextField, GroupLayout.PREFERRED_SIZE, 211, GroupLayout.PREFERRED_SIZE)
.addGap(67)
.addComponent(cpartTextField, GroupLayout.PREFERRED_SIZE, 156, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(50)
.addComponent(lblSeq)
.addGap(129)
.addComponent(lblDescription)
.addGap(201)
.addComponent(lblSupplierPartNumber))
.addGroup(groupLayout.createSequentialGroup()
.addGap(331)
.addComponent(backButton, GroupLayout.PREFERRED_SIZE, 157, GroupLayout.PREFERRED_SIZE)
.addGap(41)
.addComponent(saveButton, GroupLayout.PREFERRED_SIZE, 156, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(50)
.addComponent(seqTextField, GroupLayout.PREFERRED_SIZE, 58, GroupLayout.PREFERRED_SIZE)
.addGap(97)
.addComponent(descripTextField, GroupLayout.PREFERRED_SIZE, 211, GroupLayout.PREFERRED_SIZE)
.addGap(67)
.addComponent(spartTextField, GroupLayout.PREFERRED_SIZE, 156, GroupLayout.PREFERRED_SIZE)))
.addContainerGap(36, Short.MAX_VALUE))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(32)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(Bosal, GroupLayout.PREFERRED_SIZE, 42, GroupLayout.PREFERRED_SIZE)
.addComponent(lblCreateAPart, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE))
.addGap(6)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(lblType)
.addComponent(lblTypeDescription)
.addComponent(lblBosalPartNumber))
.addGap(6)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(typeComboBox, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
.addGroup(groupLayout.createSequentialGroup()
.addGap(3)
.addComponent(tdescripTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(3)
.addComponent(bpartTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.addGap(6)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(lblMatterial)
.addComponent(lblMatterialDescription)
.addComponent(lblCustomerPartNumber))
.addGap(6)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(matComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(mdescripTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(cpartTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(9)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(lblSeq)
.addComponent(lblDescription)
.addComponent(lblSupplierPartNumber))
.addGap(6)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(seqTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(descripTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(spartTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(37)
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
.addComponent(saveButton, 0, 0, Short.MAX_VALUE)
.addComponent(backButton, Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 51, GroupLayout.PREFERRED_SIZE))
.addContainerGap(135, Short.MAX_VALUE))
);
setLayout(groupLayout);
}}
You already have a combo box, which is already displayed in the panel. What you want is to popule this already existing combo box.
But your code does
matComboBox = new JComboBox<Object>(mats);
So it creates another JComboBox, populated with the mats that you retrieved. That won't popukate your existing, displayed combo box. What you need to do is to change the data inside the combo box:
matComboBox.setModel(new DefaultComboBoxModel(mats));

Dynamic child communication

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

Categories

Resources