Combobox doesn't show ArrayList on Java GUI - java

I'm new to swing, and I'm trying to show an Array data on a ComboBox, but for some reason whenever I add data to it, the ComboBox doesn't seem to refresh with the data inserted, even though if I run a test on console using a system.out inside the forEach, the data inserted on the ArrayList (it also shows on debug). Here's the mainMenu class:
package com.gui.main;
/* imports */
public class mainMenu {
ArrayList<Instituicao> instituicoes = new ArrayList<Instituicao>();
private JFrame frame;
public static void main(String[] args) {
/*...*/
}
public mainMenu() {
initialize();
}
public void setComboboxInstituicao(JComboBox comboBox) {
comboBox.removeAllItems();
Vector<String> inst = new Vector<String>();
if(!instituicoes.isEmpty()) {
for(Instituicao i : instituicoes) {
inst.add(i.getNomeInstituicao());
}
} else {
inst.add("Select...");
}
comboBox.setModel(new DefaultComboBoxModel<String>(inst));
comboBox.setBounds(22, 120, 600, 33);
frame.getContentPane().add(comboBox);
}
private void initialize() {
/*...*/
// ComboBox
JComboBox<String> comboBox = new JComboBox<String>();
setComboboxInstituicao(comboBox);
JLabel lblSelecioneUmaInstituio = new JLabel("Select an institution:");
lblSelecioneUmaInstituio.setBounds(22, 93, 206, 15);
frame.getContentPane().add(lblSelecioneUmaInstituio);
// Calls another window for data insert
JButton btnNovaInstituio = new JButton("New Institution");
btnNovaInstituio.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
adicionaInstituicao window = new adicionaInstituicao();
window.frame.setVisible(true);
}
});
/*...*/
}
}
I used a setCombobox function to run each time the framework reloads, but it still not working.

Related

Create object on Jbutton click

I am trying to create an object when the user presses the button.So far, I've come up with the implementation bellow, but it does not seem to work.I haven't been dealing with Swing and Java UI at all so I am guessing it might be an amateur mistake.
The object I am trying to create is from another type called DebitCard.
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GenerateCard window = new GenerateCard();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GenerateCard() {
}
{
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Generate card");
btnNewButton.setBounds(112, 213, 216, 41);
frame.getContentPane().add(btnNewButton);
}
private class buttonEvent implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Generate card")) {
DebitCard a = new DebitCard();
}
}
}
Based on your available code, you seem to have forgotten to register buttonEvent with btnNewButton
btnNewButton.addActionListener(new buttonEvent());
You might want to take a closer look at:
How to Use Buttons, Check Boxes, and Radio Buttons
How to Write an Action Listener
Laying Out Components Within a Container
Code Conventions for the Java TM Programming Language (this will make your code easier to read and it easier for you to read others)

Stop code execution until button is pressed

After choose.setVisible(true) I would like first
to be able to choose and after pressing the ok button
to continue execution.
The below code shows the chooser and continues
without waiting.
static class box extends JFrame {
Checkbox cboxtps = new Checkbox("Grf1", false);
Checkbox cboxrspt = new Checkbox("Grf2", false);
JLabel lblQts = new JLabel("Please select graphs");
JButton btn1 = new JButton("Go");
public box(String str) {
super(str);
setLayout(new GridLayout(4, 1));
add(lblQts);
add(cboxtps);
add(cboxrspt);
add(btn1);
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the button");
}
});
}
}
public static void main(String args[]) {
box choose = new box("Select Graphs");
choose.setSize(300, 150);
choose.pack();
choose.setVisible(true);
List<File> filepaths = fileselect();
list = Splitter(filepaths);
}
Since you are working asynchronously here, you would have to put the code after choose.setVisible(true) into the actionPerformed callback like so:
public void actionPerformed(ActionEvent e)
{
System.out.println("You clicked the button");
List<File> filepaths = fileselect();
list = Splitter(filepaths);
}
In general, when working with a lot of callbacks it is the best to define helper functions to avoid deep nesting.

Pass a String to another class

I'm writing an application where I need to get two String objects from the GUI to the nullObject class.
I'm relatively new to programming, and am trying my best to learn. If you have any tips on how to make this better, I'd be really thankful!
My GUI class:
package com.giuly.jsoncreate;
public class GUI {
private JFrame startFrame;
private JFrame chkFrame;
private JFrame osFrame;
private JFrame appVFrame;
private JPanel controlPanel;
private JButton nextPage;
private JButton cancel;
private JButton save;
public GUI() {
generateGUI();
}
public static void main(String[]args) {
GUI gui = new GUI();
}
public void generateGUI() {
//Creation of the First Frame
startFrame = new JFrame("JSCON Creator");
startFrame.setSize(1000, 700);
startFrame.setLayout(new FlowLayout());
startFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//Panel Creation
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
//Button Creation
cancel = new JButton("Cancel");
cancel.setSize(100, 100);
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
nextPage = new JButton("Next");
nextPage.setSize(100, 100);
nextPage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startFrame.setVisible(false);
showText();
}
});
startFrame.add(controlPanel);
startFrame.add(cancel);
startFrame.add(nextPage);
startFrame.setVisible(true);
startFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void showText() {
JFrame textFrame = new JFrame();
textFrame.setSize(1000, 700);
textFrame.setTitle("Text");
textFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel textPanel = new JPanel();
JLabel titleLabel = new JLabel("Title");
textPanel.add(titleLabel);
JLabel descrLabel = new JLabel("Description");
JTextField tfTitle = new JTextField("",15);
tfTitle.setForeground(Color.BLACK);
tfTitle.setBackground(Color.WHITE);
JTextField tfDescr = new JTextField("",30);
tfDescr.setForeground(Color.BLACK);
tfDescr.setBackground(Color.WHITE);
textPanel.add(tfTitle);
textPanel.add(descrLabel);
textPanel.add(tfDescr);
JButton buttonOK = new JButton("OK");
textPanel.add(buttonOK);
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String jsonTitle = tfTitle.getText();
String jsonDescr = tfDescr.getText();
System.exit(0);
}
});
textFrame.add(textPanel);
textFrame.setVisible(true);
}
I want to get the Strings jsonTitle and jsonDescr into another class, so I can store them. In the end I will have some Strings and I need to save them in a JSON file. I need a way to get those two Strings, what advice do you guys have?
Erick is correct with his answer. Just thought I should add additional info. If you declare jstonTitle and jsonDescr like your other fields using private you still will not be able to access these fields from another class. Coding up a getter for the fields along with declaring them at the top of GUI should solve your problem. Then just create an instance of GUI in your other class and call the method.
public String getJsonTitle(){
return this.jsonTitle;
}
You're declaring jstonTitle and jsonDescr inside the actionPerformed() method. That means that as soon as actionPerformed() exits you'll lose those variables. You need to declare them in an enclosing context. For example, you could make them fields on the GUI class. Still assign them in actionPerformed(), but declare them up at the top of GUI where you're declaring startFrame, chkFrame, etc.
That will give you the ability to access those values from anywhere within GUI.
Oh, BTW, get rid of System.exit(0);. (Have you actually tried to run your program?)

How to dynamically create JPanel with given parameters?

I have main JFrame in my project. And one main JPanel with Y-AXIS BoxLayout which is used to contain another panels in it. This is the way i use my JFrame to show this JPanel by default (I'm not quite convinced if this is the right way):
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
mainPanel = new MainScreenPanel();
MainFrame mainFrame = new MainFrame();
mainFrame.setContentPane(mainPanel);
mainFrame.invalidate();
mainFrame.validate();
mainFrame.setVisible(true);
}
});
}
Next I add two JPanels into mainPanel like this:
public class MainScreenPanel extends javax.swing.JPanel {
public MainScreenPanel() {
StatusPanel sPanel = new StatusPanel();
LogPanel lPanel = new LogPanel();
add(sPanel);
add(lPanel);
}
}
lPanel has different gui elements on it. One of them is a button which opens another panel (addConnectionPanel), and replaces mainPanel in the jFrame Here is the way i do it:
private void addCnctButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
topFrame.setContentPane(new AddConnectionPanel());
topFrame.invalidate();
topFrame.validate();
}
AddConectionPanel has some labels and input text boxes. It has two buttons ok and cancel. Here is the code of cancel button:
private void cancelCnctBtnActionPerformed(java.awt.event.ActionEvent evt) {
JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
topFrame.setContentPane(new MainScreenPanel());
topFrame.invalidate();
topFrame.validate();
}
sPanel is empty. It must be empty until input boxes on AddConnectionPanel are not filled and 'ok' button is not pressed. When these actions are performed, I want to dynamically create JLabels which take parameters from inputs on sPanel. Labels should be grouped, so when the actions performed second time new group must be created. Can some one give me advice on how to do this? And show me my mistakes? Keep in mind I'm using NetBeans.
This would be my approach:
public interface ConnectionPanelListener{
void onOkButtonClicked(String... options);
void onCancelButtonClicked();
}
public class AddConnectionPanel extends JPanel {
private static final long serialVersionUID = 1L;
private ConnectionPanelListener listener;
public AddConnectionPanel(){
final Map<ConnectionOptions, JTextField> components = new HashMap<>(ConnectionOptions.values().length);
for(ConnectionOptions option:ConnectionOptions.values()){
this.add(new JLabel(option.labelCaption));
JTextField textField = new JTextField();
//setup textField;
this.add(textField);
components.put(option, textField);
}
JButton button = new JButton("OK");
button.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(final MouseEvent pE) {
super.mouseClicked(pE);
//TODO validate TextFields
Collection<String> inputs = new Stack<>();
for(Entry<?,JTextField> e : components.entrySet()){
String text = e.getValue().getText();
if(text==null || text.trim().isEmpty()){
//TODO improve input validation
System.out.println("Input text is empty for: "+e.getKey());
} else {
inputs.add(e.getKey() + ": " + text);
}
}
listener.onOkButtonClicked(inputs.toArray(new String[inputs.size()]));
}
});
this.add(button);
button = new JButton("cancel");
button.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(final MouseEvent pE) {
super.mouseClicked(pE);
listener.onCancelButtonClicked();
}
});
this.add(button);
}
public void setConnectionPanelListener(final ConnectionPanelListener l){
listener = l;
}
private enum ConnectionOptions{
IP_ADDRESS("IP-Address:"), PORT("Port:"), WHATEVER_ATTRIBUTE_YOU_NEED("Extras:");
private String labelCaption;
private ConnectionOptions(final String caption) {
labelCaption = caption;
}
}
}
As you can see, AddConnectionPanel expects a Listener to register for the case, that "OK" or "CANCEL" are clicked. So your adjusted implementation could be like:
private void addCnctButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
AddConnectionPanel panel = new AddConnectionPanel();
panel.setConnectionPanelListener(new ConnectionPanelListener(){
#Override
void onOkButtonClicked(String... options){ TODO: fill sPanel using the given Strings }
#Override
void onCancelButtonClicked(){ TODO }
});
topFrame.setContentPane(panel);
topFrame.invalidate();
topFrame.validate();
}

Change Swing L&F at command line not work well

I made an application with some widgets and at command line I want change their look and feel:
java -Dswing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel LookAndFeelAppl
but after invoked that command only a widget into the class constructor change its L&F but other that I created into a separate methods don't!!! Also tha JFrame itself not change.
public class LookAndFeelAppl extends JFrame
{
private JLabel label;
private JButton button;
public LookAndFeelAppl()
{
super("Look And Feel Demo");
setLayout(null);
final UIManager.LookAndFeelInfo plaf[] = UIManager.getInstalledLookAndFeels();
JLabel lable_laf = new JLabel("Choose L&F:");
final JComboBox cb = new JComboBox();
createOtherGUI();
cb.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
int ix = cb.getSelectedIndex();
try
{
UIManager.setLookAndFeel(plaf[ix].getClassName());
SwingUtilities.updateComponentTreeUI(LookAndFeelAppl.this);
}
catch (Exception ex)
{
}
}
});
// HERE IS THE PROBLEM!!!! THIS LOOP GOES BEFORE
// THE ITEMLISTENER BECAUSE WHEN I ADD ITEMS AN ITEMEVENT
// IS RAISED THAT SET AGAIN THE L&F WITH setLookAndFeel!!!
for (int i = 0, n = plaf.length; i < n; i++)
{
cb.addItem(plaf[i].getName());
}
//--------------------------------------------------------
add(lable_laf);
add(cb);
lable_laf.setBounds(10, 10, 150, 25);
cb.setBounds(10, 35, 150, 25);
}
public void createOtherGUI()
{
button = new JButton("BUTTON!!!!");
add(button);
button.setBounds(300, 45, 150, 35);
}
public static void main(String args[])
{
LookAndFeelAppl window = new LookAndFeelAppl();
window.setSize(1000, 700);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.setLocationRelativeTo(null);
}
}
I ran this in Eclipse (latest version) using JDK 1.6.0_13 on windows. In the run configuration (VM arguments) of Eclipse I used -Dswing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel
public class Test extends JFrame {
public Test() {
super("Test L&F");
JComboBox box = new JComboBox(new String[] {"One", "Two", "Three"});
getContentPane().add(box, BorderLayout.SOUTH);
createControls();
setSize(300, 300);
setVisible(true);
}
private void createControls() {
JComboBox box = new JComboBox(new String[] {"One", "Two", "Three"});
getContentPane().add(box, BorderLayout.NORTH);
}
public static void main(String[] args) {
new Test();
}
}
Sorry, formatting is weird but you get the idea...
Few things to try and questions:
I see you are setting the L&F for windows, so I'm assuming you are running this on a windows box? The reason I ask is I'm not sure what the JDK is supporting as far as cross-platform L&Fs, just something to think about.
Did you try other L&Fs with the same result? (e.g. Nimbus)
This may or may not do anything but where do you have main(...)? Try putting it in the JFrame and in a separate class that constructs the JFrame.
Worst comes to worse you could always pass the L&F classname in as an arg to main(...) (or a props file) then use the UIManager to set it BEFORE any swing components are created.
Good luck,
Dave

Categories