how to update comboBox while using glazedList..evenlist - java

alright.,ive already tried every trick off my sleeves..but couldnt figure out how to update the comboBox w/glazedList..if the input is coming from other class..ive tried passing the value to the methods,declaring it first to a string..and such..but none has work..tho it does work if the new item will just gonna come from same class..via click of a button..
so far ive got this code..
values = GlazedLists.eventListOf(auto);//auto is an array..
AutoCompleteSupport.install(comboSearch,values);//comboSearch is the comboBox
//"x" is the value coming from another class.
public void updateCombo(String x){
List<String> item = new ArrayList<>();
item.add(x)
value.addAll(item);
}
i hope this codes are enough to interpret what im trying to ask..

It's not possible to see how you've created your combobox and your eventlist. Therefore I'll just create a simple example application from scratch that shows you the essentials.
Just in case you're not familiar the general concepts the main take home points are:
Try and avoid using standard Java collections (eg ArrayList, Vector) and use the EventList class as soon as possible. All the goodness that comes with sorting/filtering/auto-complete relies on the EventList foundation so set one up asap and then simply manipulate (add/remove/etc) and then the GlazedLists plumbing will take care of the rest.
Once you've got your collection of objects in an EventList and you want to leverage a swing component then look in the ca.odell.glazedlists.swing module which contains everything you need. In this instance you can use an EventListComboBoxModel - pass in your eventlist, and then set your JComboBox model to use the newly created EventListComboBoxModel and from that point GlazedLists will take care of ensuring your list data structure and combobox stay in sync.
So in my example I create an empty combobox and an button. Clicking the button will add an item per click into the combobox. The magic is simply the creation of the EventList and the use of EventListComboBoxModel to link the list to the combobox.
Please note that the code below was only tested against GlazedLists 1.8. But I'm pretty sure it'll work fine with 1.9 or 1.7 too.
public class UpdateComboBox {
private JFrame mainFrame;
private JComboBox cboItems;
private EventList<String> itemsList = new BasicEventList<String>();
public UpdateComboBox() {
createGUI();
}
private void createGUI() {
mainFrame = new JFrame("GlazedLists Update Combobox Example");
mainFrame.setSize(600, 400);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton addButton = new JButton("Add Item");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
itemsList.add("Item " + (itemsList.size()+1));
}
});
// Use a GlazedLists EventComboBoxModel to connect the JComboBox with an EventList.
EventComboBoxModel<String> model = new EventComboBoxModel<String>(itemsList);
cboItems = new JComboBox(model);
JPanel panel = new JPanel(new BorderLayout());
panel.add(cboItems, BorderLayout.NORTH);
panel.add(addButton, BorderLayout.SOUTH);
mainFrame.getContentPane().add(panel);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new UpdateComboBox();
}
});
}
}

Related

How to change icon in JLabel with JButton

I'm making a simple conversion tool to convert dollars to euro's and vice versa.
The whole purpose is just to experiment and learn this cool tool, java.
I have a JLabel at the top with an icon of a euro to indicate the starting currency. I have a button bellow this that I want to use to change that icon to a dollar one.
I am currently plying around with an ActionListener and trying different variations of setIcon/setIconImage (every itteration I can think of seeing that nothing has worked thus far).
public class MoneyConverter extends JFrame implements ActionListener{
//add label and icon showing base conversion currency
JLabel startcur = new JLabel("<--- Starting Curency", new ImageIcon("C:\\Users\\Russel\\Desktop\\1euro.gif"), SwingConstants.CENTER);
JButton euro = new JButton("Swap to Euro");
JButton dollar = new JButton("Swap to Dollar");
I then set up a
public MoneyConverter(){}
method and add all my components to a grid layout and add ActionLister's to my convert buttons.
e.g.
dollar.addActionListener(this);
euro.addActionListener(this);
After the usual code (setVisible and the likes that I will omit for your sake as I don't see it interfering with this, please let me know if I should include it all)
public void ActionPerformed (ActionEvent e){
Object source = e.getSource();
if (source.equals(euro)){
startcur.setIcon(new ImageIcon("C:\\Users\\Russel\\Desktop\\1.gif"));
}
}
This part has been changed many times and is the main reason for this post, how do I change this icon in the JLabel? - I will also be setting the conversion rate in here depending if they choose to start with dollars or euros. (Rate won't be actual rate.)
First, create and store a new ImageIcon
ImageIcon image = new ImageIcon(getClass().getResource("/nameOfImage.jpg"));
Then put this in your Action Listener
label.setIcon(image);
label.setText("");
You have to make sure you have a resource folder set up for your project. You can read how to do that in IntelliJ or Eclipse
You are also declaring the actionPerformed() wrong. I suggest reading up on this You should be doing it like this.
#Override
public void actionPerformed(ActionEvent e)
{
}
Conventionally, in java, method names start with a lower case letter and Classes start with an upper case.
The whole purpose is just to experiment and learn this cool tool, java.
Then I'll show you how to improve this program in a number of ways.
//Don't make your Swing class implement Actionlistener and add it as a
//listener to itself in the constructor before it's fully initialized
public class MoneyConverter extends JFrame {
//These don't have to be loaded at runtime, so make them into constants
//Java variables and methods follow thisNamingConvention
private static final Icon euroIcon = new ImageIcon("C:\\Users\\Russel\\Desktop\\1euro.gif");
private static final Icon dollarIcon = new ImageIcon("C:\\Users\\Russel\\Desktop\\1dollar.gif");
//These you probably want to use later so save them as private class variables
//Make them final so you can access them in the ActionListeners below
private final JLabel currencyLabel;
private final JButton euroButton;
private final JButton dollarButton;
public MoneyConverter() {
//These are declared final and are are therefore usually set first in constructor
this.currencyLabel = new JLabel("<--- Starting Curency", euroIcon, SwingConstants.CENTER);
this.euroButton = new JButton("Swap to Euro");
this.dollarButton = new JButton("Swap to Dollar");
//Write your own separate ActionListener for each button
euroButton.addActionListener(new ActionListener() {
#Override
public void run() {
currencyLabel.setIcon(euroIcon);
//These two are required for you to see the effect
//This should also be the solution to your initial problem
currencyLabel.revalidate();
currencyLabel.repaint();
}
});
dollarButton.addActionListener(new ActionListener() {
#Override
public void run() {
currencyLabel.setIcon(dollarIcon);
currencyLabel.revalidate();
currencyLabel.repaint();
}
});
//Add your components here using whatever layout manager you want.
}
public static void main(String []args){
//Start new Swing applications like this to prevent it from
//clogging the rest of the program
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MoneyConverter();
}
});
}
}

Passing JList value from JFrame to JDialog

I'm currently building an application and it has a JFrame and a JDialog. The JFrame has a JList called:
JList lstMainVenuesEvents = new JList();
And I'm trying to get the value of lstMainVenuesEvents by using:
lstMainVenuesEvents.getSelectedIndex();
I can get the value perfectly fine on my JFrame, but how do I pass it to my JDialog? I thought about creating a setter method in one of my class files and then just getting that value from my JDialog file, but surely there's an easy way? Is it possible to just have a method of some sort that passes the data from the JFrame to the JDialog like a POST request in PHP?
Apologies if I've missed anything crucial out.
Update: here's the code for my JList and JDialog show.
JList lstMainVenuesEvents = new JList();
lstMainVenuesEvents
.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
// stop from firing twice
if (e.getValueIsAdjusting()) {
EventModify evtWindow = new EventModify();
evtWindow.setVisible(true);
}
}
});
I can't be confident it's "right" but an inversion of control sort of approach usually reduces passing values around.
Assuming the value lstMainVenuesEvents.getSelectedIndex() is used on a particular action/event in the JDialog you could set an ActionListener from the JFrame.
// some where in the JFrame
jDialog.setButtonPressed(new ActionListener() {
public void actionPerformed(ActionEvent evt)
{
// lstMainVenuesEvents.getSelectedIndex() is accessible in this block
// put code logic here where
}
});

Assign function to Jbutton

I have a few classes to create a very simple GUI (JFrame) with a few objects like a JTabbedPanel and a JTree. And one of the classes that creates a ribbon in the JTabbedPanel creates a JButton, that should have a function that updates the JTree.
I do have some getter, but I have no idea how to use the JButton to update something on an object that gets created in the main method (the GUI object, from where I would be able to get to the JTree).
How do I update something on an object that gets created in the main method in the actual class of the JButton?
I might have to change the structure of my project.
public class Gui extends JFrame{
private Ribbon ribbon;
private Status status;
public Panel panel;
public Gui(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("INIT TITLE");
setExtendedState(Frame.MAXIMIZED_BOTH);
setMinimumSize(new Dimension(600,400));
setVisible(true);
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
ribbon = new Ribbon();
add(ribbon, BorderLayout.NORTH);
status = new Status();
add(status, BorderLayout.SOUTH);
panel = new Panel();
add(panel, JSplitPane.HORIZONTAL_SPLIT);
//panel.setLeftComponent(panel.getTree());
//panel.openProject();
setVisible(true);
panel.loadProject();
}
The Ribbon doesnt do a lot:
public class Ribbon extends JTabbedPane {
public Ribbon(){
addTab("Home", null, new RibbonHome());
addTab("Import", null, new RibbonImport());
addTab("Options", null, new RibbonOptions());
}
}
But the Ribbon-Tab creates some buttons:
public class RibbonHome extends JPanel{
private JButton b1, b2, b3;
public RibbonHome(){
b1 = new JButton("test1");
b2 = new JButton("test2");
b3 = new JButton("test3");
add(b1);
add(b2);
add(b3);
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//UPDATE the JTree
}
});
}
}
button.addActionListener( main );
main implements ActionListener and provides the method actionPerformed()
A code sample of what you are doing would make things easier, but anyway.
Probably you want to make the component you are planning to update a class member. This way, you can initialize it where it is initialized now, but still reach it from your ActionListener.
Again, this is a bit a guess on how you structured things, so if you can post a code sample, I am sure you can get a much more detailed answer.
EDIT after code sample:
You could give RibbonHome an additional private member of type Gui. I usually call it parent, so it becomes: private Gui parent;
In the constructor of RibbonHome, you add Gui as a parameter, this way, RibbonHome will always have access to its parent.
Also add it to the constructor of Ribbon, because you will want to pass it through there.
As a last step, you will always have to construct Ribbon with Gui as a parameter, so in Gui it will become: ribbon = new Ribbon(this);
As soon as you have done all of this, you can reach the JTree by the getter of you JTree on parent.
There are better solutions, since this will have as a drawback that you will never be able to construct a new Ribbon from another component than a Gui, but if you want that, you can work with interfaces.
The most obvious answer is of course to pass the reference of your Gui class to your Ribbon class, which in turn can pass it to the RibbonHome class.
public Gui{
//...
ribbon = new Ribbon( this );
//...
}
public Ribbon ( Gui gui ){
//...
addTab("Home", null, new RibbonHome( gui ));
//...
}
public RibbonHome( Gui gui){
//...
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//UPDATE the JTree
}
});
//...
}
However, this ensures a very tight coupling between your different classes. I do not know what exactly you want to update on that JTree but the more fundamental solution might be to share a model between your different views. Your JTree would update itself when the model changes, and the button just updates the model.

Swing GUI Factory Method Pattern

I am looking to use the Factory Method Pattern in order to make the development of my Swing UI quicker and more manageable.
In general, its an MDI application using JInternalFrames. I have a lot of settings, types as I call them, in the system (Eg. userTypes, accountTypes, etc.) I have a fixed UI which I've decided to use. Thing is, there are over 50 of these types in the system, so the factory method pattern seems to be the most manageable solution. Below are two screenshots of a working app.
I was looking at [this example][3] but since I wont be able to estimate the number of tabs I would require to store all info in a record, I would need to be able to add multiple tabs and controls (labels, textboxes, tables, comboboxes, etc.) within these tabs.
Based on the example, is it possible to create a JTabbedPane in the abstract class and modify and add to it in the subclasses? I tried the following and am a bit lost:
public AbstractTypeInternalFrame(String title) {
setBounds(100, 100, 808, 589);
JToolBar toolBar = new JToolBar();
getContentPane().add(toolBar, BorderLayout.NORTH);
JButton btnAdd = new JButton("Add");
toolBar.add(btnAdd);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
toolBar.add(btnSave);
JButton btnDelete = new JButton("Delete");
toolBar.add(btnDelete);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
toolBar.add(btnCancel);
JTabbedPane recordTabs = new JTabbedPane(makeRecordTabPane());
getContentPane().add(recordTabs, BorderLayout.NORTH);
JSeparator recordSearchSeparator = new JSeparator();
getContentPane().add(recordSearchSeparator, BorderLayout.NORTH);
}
protected abstract int makeRecordTabPane();
with the method makeRecordTabPane() require to return an int.
As you can see, I'm a little lost and just need some direction as to how to proceed with such a pattern. If any has any advice or even examples/links, it would be much appreciated.
I realize my question is vague, so if any clarification is required on my side, please feel free to ask.
Best regards.
Here is the question in more detail.
So, I am looking to build a simple JInternalFrame for CRUD operations on records on the system. Records such as users, usertypes, accounts, accountypes, etc. There are more than 50 of these types in the system, so I figure using the factory method pattern would make all these JInternalFrames more manageable.
Here is an example of a user record:
Link1
Link2
The top half constitutes of the details of a record, which are split into tabs depending on the contents of the record. Some records may have just one tab, while other larger ones will have multiple. Therefore, the contents of the JTabbedPane should be instantiated at the subclass level and per this example.
The bottom part is where we would search for records of that type. Say for example, in the links posted, the User Manager JInternalFrame is opened. We then would search for users according to username and/or userID. Results are displayed in the table below and on double-clicking a search result, the record is displayed above in the JTabbedPane.
Add, Save, Delete and Cancel buttons are then used to perform CRUD operations on whatever is entered into the record.
From this, we can say that the aspects of the design than need to be instantiated by subclasses are:
1) Size of the JInternaFrame
2) All contents of the JTabbedPane: no of tabes, tables, labels, textboxes, etc.
3) The number of columns in the search result JTable: which we can change by instantiating the JTable Header.
As a start, I was trying to just create an Abstract class with a JTabbedPane, and add components to the JTabbedPane to see how I could go about it. This is the code I posted earlier. This file was generated using WindowBuilder, which I later then modified:
package zm.co.freight.fpsManagementGUI.view;
import java.awt.EventQueue;
public abstract class AbstractTypeInternalFrame extends JInternalFrame {
/**
* Launch the application.
*/
// public static void main(String[] args) {
// EventQueue.invokeLater(new Runnable() {
// public void run() {
// try {
// AbstractTypeInternalFrame frame = new AbstractTypeInternalFrame();
// frame.setVisible(true);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// });
// }
/**
* Create the frame.
*/
public AbstractTypeInternalFrame(String title) {
setBounds(100, 100, 808, 589);
JToolBar toolBar = new JToolBar();
getContentPane().add(toolBar, BorderLayout.NORTH);
JButton btnAdd = new JButton("Add");
toolBar.add(btnAdd);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
toolBar.add(btnSave);
JButton btnDelete = new JButton("Delete");
toolBar.add(btnDelete);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
toolBar.add(btnCancel);
JTabbedPane recordTabs = new JTabbedPane(makeRecordTabPane());
getContentPane().add(recordTabs, BorderLayout.NORTH);
JSeparator recordSearchSeparator = new JSeparator();
getContentPane().add(recordSearchSeparator, BorderLayout.NORTH);
}
protected abstract int makeRecordTabPane();
}
The question is, am I on the right track? How should I approach it using the factory method pattern as I don't seem to grasp it very well. I've seen simpler examples, with shapes and drawings, but am a bit lost with Swing interfaces. Is there a good example you could direct me to or a simple example just to point me in the right direction ... thats all I was asking for. Sorry if it was vague ...

Desktop application - how do I dynamically create and destroy forms

I'm creating a small crypto app for the desktop using java.
I'm using JFrames (import javax.swing.JFrame) with Oracle
JDeveloper 11g under Linux.
I want to have a "welcome" form/frame where users can choose
their encryption method, and then on choosing the method,
I want to dynamically create the appropriate form for the
chosen encryption method and also destroy/free/dispose() of
the welcome form. When the user has finished their encrypting,
they should close the frame/form (either by clicking on the
x at the top right - or using the Exit button or by any
method) and the welcome frame should be dynamically recreated
and appear.
I've tried various things - btnEncode_actionPerformed(ActionEvent e)
then this.dispose() - and I've fiddled with this_windowClosed(WindowEvent e)
and dispose(), but nothing seems to work.
Even a workaround using setVisibl(true/false) would be acceptable at
this stage - this has been wrecking my head all day. It's very
easy to do in Delphi!
TIA and rgs,
Paul...
something like this usually does the trick: (Note I haven't tested this)
public class WelcomeMsg extends JFrame
.
.
.
public void btnContinue_actionPerformed(ActionEvent e)
{
this.dispose();
SwingUtilities.invokeLater(new Runnable(){ new JFrameAppropriateWindow(args) });
}
where btnContinue is the Continue button on your welcome form and JFrameAppropriateWindow is the next frame you would like to show depending on the user's choice. Args are any arguments you need to pass.
When you are ready, you can simply dispose the current frame and relaunch an instance of WelcomeMsg
I put together this simple example for creating and displaying a panel depending on a user choice.
public class Window extends JFrame {
public Window() {
this.setLayout(new BorderLayout());
JComboBox encryptionCombobox = new JComboBox();
encryptionCombobox.addItem("foo");
encryptionCombobox.addItem("bar");
//...
encryptionCombobox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// find choices and the correct panel
JPanel formPanel = new JPanel();
formPanel.setOpaque(true);
formPanel.setBackground(Color.RED);
//...
Window.this.add(formPanel, BorderLayout.CENTER);
Window.this.validate();
Window.this.repaint();
}
});
add(encryptionCombobox, BorderLayout.NORTH);
}
public static void main(String[] args) {
new Window().setVisible(true);
}
}
When I come to think about it, you should probably use a CardLayout instead, which allows you to switch between different panels (cards).

Categories

Resources