How can I simplify this module? - java

I have some method which looks awful(especially number of parameters). I wonder how can I make this code cleaner.
The method works with JLists and setting a new model(DefaultListModel). So it just swaps items between two JLists and deletes swapped item in list where was the item taken.
Сriticism and advice are welcome.
Call the method example:
moveToOtherJList(newOrdersModel, newOrdersJList, inProcessOrdersModel, inProcessOrdersJList);
The method:
private void moveToOtherJList(DefaultListModel firstModel, JList firstJList, DefaultListModel secondModel, JList secondJList)
{
int selectedIndex = firstJList.getSelectedIndex();
secondModel.addElement(firstJList.getSelectedValue());
secondJList.setModel(secondModel);
firstModel.remove(selectedIndex);
}

I have some method which looks awful(especially number of parameters).
Well there is no need to pass either ListModel, since you can get the ListModel from the JList.
So I would define the method as:
public void moveToOtherJList(JList fromJList, JList toJList)
{
int selectedIndex = fromJList.getSelectedIndex();
DefaultListModel fromModel = (DefaultListModel)fromJList.getModel();
DefaultListModel toModel = (DefaultListModel)toJList.getModel();
toModel.addElement(fromJList.getSelectedValue());
fromModel.remove(selectedIndex);
}

Related

Extending JComboBox

I am having trouble extending JComboBox. Mainly, I want to add a method that returns the selected Item into String. But since I might want to add more methods later on, I decided it would be better to create a child class.
import javax.swing.JComboBox;
public class ComboBox extends JComboBox{
public ComboBox(Integer[] items) {
super();
}
public ComboBox(String[] items) {
super();
}
public String getSelectedItemInString() {
return super.getSelectedItem().toString();
}
}
Above is my attempt but it wouldn't work this way. It would only create ComboBoxes that look like this, and I am not able to see the items even if I click on the drop down button result
I want to be able to create ComboBox that could take in both String[] or Integer[] in different instances.. just like how JComboBox allows to do this:
String [] groups = {null, "Zombies","Instigators","Fantastic Beasts","Stranger Things"};
JComboBox<String> groupSelector = new JComboBox<String>(groups);
totalNum = new JComboBox<Integer>();
totalNum.addItem(null);
totalNum.addItem(0); totalNum.addItem(1);
totalNum.addItem(2); totalNum.addItem(3);
totalNum.addItem(4);
The array that you are passing into the constructor of your ComboBox-class needs to be passed on to the constructor of the JComboBox.
public ComboBox(E[] items) {
super(items);
}
The reason your code is not throwing an error is because JComboBox also has another constructor which does not require any parameters (you are currently calling the constructor https://docs.oracle.com/javase/7/docs/api/javax/swing/JComboBox.html#JComboBox() but want to call https://docs.oracle.com/javase/7/docs/api/javax/swing/JComboBox.html#JComboBox(E[])). However, you want to call the constructor which takes an Array as the parameter. That's why you have to pass the parameter on to the super()-methid you're calling.

Getting Components by name not support all actions?

I have jTextField named "p0_1000"
And i use below methods can call it by name;
Creating Hashmap in class.
private HashMap componentMap;
Fill hashmap with components name.
private void createComponentMap() {
componentMap = new HashMap<String,Component>();
Component[] components = jDesktopPane1.getComponents();
for (int i=0; i < components.length; i++) {
componentMap.put(components[i].getName(), components[i]);
}
}
For call components by their names.
public Component getComponentByName(String name) {
if (componentMap.containsKey(name)) {
return (Component) componentMap.get(name);
}
else return null;
}
If i use directly p0_1000.setToolTipText("trying"); succesfully appear tooltiptext when mouse on releated textfield.
But if i use getComponentByName("p0_1000").setToolTipText("trying"); setToolTipText not recognized.
getComponentByName("p0_1000") succesfully working i tested. Because if i type "." after method name, avaliable action list come and i can use them (example .setVisible(false) working succesfully)
Some add, set or get commands not in avaliable action list when i call componen by name.
Any advice, idea, comments are appreciated.
Regards.
---SOLVED---
public JComponent getComponentByName(String name) {
if (componentMap.containsKey(name)) {
return (JComponent) componentMap.get(name);
}
else return null;
}
Above changes solve my problem.
You probably should be using JComponent which is has setToolTipText. If that's not what you want, you can check if the java.awt.Component is a JComponent and cast:
if (components[i]) instanceof JComponent) {
JComponent jc = (JComponent) components[i];
// now you can use setToolTipText
}
Your problem is that your method is declared to return Component type, and if you look in the API for this class, you'll see that it does not have a setToolTipText(...) method. This method begins in the JComponent class. One solution is to have the Map only collect JComponents and have the method declared to return this type. Incidentally, if you declare your Map with generic parameters, you won't have to do your cast.
i.e., rather than this declaration,
private HashMap componentMap;
use,
private HashMap<String, Component> componentMap;
or if again if this will work for you:
private HashMap<String, JComponent> componentMap;

how to retrieve the value of a component of a panel in java

i have jdialog. and i have added 50 buttons inside a jpanel in the jdialog.
Now i want to get the values of the buttons which is set by button.setText()
now my code looks like this
Component[] all_comp=mydialog.getComponents();
for(int i=0;i<=all_comp.length;i++)
{
Container ct=all_comp[i].getParent();
String panel_name=ct.getName();
}
i tried my best to find out all possible ways like taking all other functions of the component class.
but no result.
now i want to get the value of the buttons.(like button.getText).
how to do that??
You have to check whether current component is a button. If it is, cast it to button and call its getText():
Component[] all_comp=mydialog.getComponents();
for(int i=0;i<=all_comp.length;i++) {
if (all_comp[i] instanceof Button) {
String text = ((Button)all_comp[i]).getText();
// this is the text. Do what you want with it....
}
}
What you really want to do is pass mydialog into a method that will find all of the JButtons that are contained in it. Here is a method where if you pass in a Container (JDialog is a Container) and a List it will fill up the List with all of the JButtons the JDialog contains regardless of how you added the JButtons.
private void getJButtons(Container container, List<JButton> buttons) {
if (container instanceof JButton) {
buttons.add((JButton) container);
} else {
for (Component component: container.getComponents()) {
if (component instanceof Container) {
getJButtons((Container) component, buttons);
}
}
}
}
Basically this method looks to see if the Container passed in is a JButton. If it is then it adds it to the List. If it isn't then it looks at all the children of the Container and recursively calls getJButtons with the Container. This will search the entire tree of UI components and fill up the List with all JButtons it finds.
This is kind of ugly to have to create a List and pass it into the getButtons method so we will create a wrapper method that looks nicer
public List<JButton> getJButtons(Container container) {
List<JButton> buttons = new ArrayList<JButton>();
getJButtons(container, buttons);
return buttons;
}
This convenience method simply creates your List for you, passes it to our recursive method and then returns the List.
Now that we have the recursive method and the convenience method we can call the convenience method to get a list of all of our JButtons. After that we just loop over the items in the list and call getText() or whatever else you want to do with your buttons:
for (JButton button: getJButtons(mydialog)) {
String text = button.getText();
...
}

How to handle multiple jLists with one ListSelectionEvent

I have three jLists in my class frmMain. I have created a class called ListActions. The code below is working for one jList. It returns the value clicked for one jList.
How do I distinguish between the three other jList? Or do I need to create a seperate class for each listener?
I need to perform an action based on which jList was clicked. I attempted to see if I could access the variable name of the jList that was clicked, but couldn't find a way to do this...
class ListActions implements ListSelectionListener {
public void valueChanged(ListSelectionEvent evt) {
if (!evt.getValueIsAdjusting()) {
JList list = (JList) evt.getSource();
int iSelectedDatabase = list.getSelectedIndex();
Object objSelectedDatabase = list.getModel().getElementAt(iSelectedDatabase);
String sSelectedDatabase = objSelectedDatabase.toString();
JOptionPane.showConfirmDialog(null, sSelectedDatabase);
}
}
}
Thanks,
- Jason
JList inherits from Component.
Therefore, you can use the getName() method to get the name of your Component and know which one has been called.

Removing an item from the JList using ListModel as model type

I have the JList which is using ListModel and not the DefaultListModel. I don't want to change the type now because I am using this in many places. I want to remove a selected item from the same list. How do i do this? I am using the following code but its not working for me.
made_list.removeSelectionInterval(
made_list.getSelectedIndex(), made_list.getSelectedIndex());
--EDIT--
I am using the following code when I create my list:
made_list = new javax.swing.JList();
made_list.setModel(new DefaultListModel());
And then in the JButton mouseclick event, I am using the following code to remove the selected item from the list when the button is pressed
private void removeActionPerformed(java.awt.event.ActionEvent evt) {
//made_list.removeSelectionInterval(made_list.getSelectedIndex(),
//made_list.getSelectedIndex());
System.out.println(made_list.getModel());
DefaultListModel model = (DefaultListModel)made_list.getModel();
model.remove(1);
}
removeSelectionInterval removes nothing from the model or the list except the selection interval. The list items remain unscathed. I'm afraid that you're either going to have to extend your ListModel and give it a removeItem(...) method as well as listeners and the ability to fire notifiers, etc... a la AbstractListModel -- quite a lot of work! If it were my money, though, I'd go the easy route and simply use a DefaultListModel for my model as it is a lot safer to do it this way, a lot easier, and will take a lot less time. I know you state that you don't want to use these, but I think you'll find it a lot easier than your potential alternatives.
An example of an SSCCE is something like this:
import java.awt.event.*;
import javax.swing.*;
public class Foo1 {
private String[] elements = {"Monday", "Tueday", "Wednesday"};
private javax.swing.JList made_list = new javax.swing.JList();
public Foo1() {
made_list.setModel(new DefaultListModel());
for (String element : elements) {
((DefaultListModel) made_list.getModel()).addElement(element);
}
JButton removeItemBtn = new JButton("Remove Item");
removeItemBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
removeActionPerformed(e);
}
});
JPanel panel = new JPanel();
panel.add(new JScrollPane(made_list));
panel.add(removeItemBtn);
JOptionPane.showMessageDialog(null, panel);
}
private void removeActionPerformed(ActionEvent e) {
System.out.println("made_list's model: " + made_list.getModel());
System.out.println("Model from a fresh JList: " + new JList().getModel());
DefaultListModel model = (DefaultListModel) made_list.getModel();
if (model.size() > 0) {
model.remove(0);
}
}
public static void main(String[] args) {
new Foo1();
}
}
You've been given a link to different sections of the Swing tutorial in the past to help solve problems. This was done for a reason. It helps solve your current problem. It gives you a reference for future problems.
All you need to do is look at the Table of Contents for the Swing tutorial and you will find a section on "How to Use Lists" which has a working example that adds/removes items from a list. Please read the tutorial first.
Or if you can't remember how to find the Swing tutorial then read the JList API where you will find a link to the same tutorial.
//First added item into the list
DefaultListModel dlm1=new DefaultListModel();
listLeft.setModel(dlm1);
dlm1.addElement("A");
dlm1.addElement("B");
dlm1.addElement("C");
// Removeing element from list
Object[] temp=listRight.getSelectedValues();
if(temp.length>0)
{
for(int i=0;i<temp.length;i++)
{
dlm1.removeElement(temp[i]);
}
}

Categories