I can open the function from another class but no effect ... Why? - java

this my code .....
public class A {
JLabel A = new JLabel() ;
public JLabel newform(){
A.setBounds(0 , 197, 409, 245);
A.setIcon(createImageIcon("/Pictures/BG.png"));
return A; }
public void swinginDown_NF ( ){
AnimationClass AC = new AnimationClass();
AC.jLabelYDown(A.getY(), 270, 6, 1,A);
}
class B ....
public class B {
JLabel B = new JLabel() ;
public JLabel Box(){
B.setBounds(170 , 197, 409, 245);
B.setIcon(createImageIcon("/Pictures/BBD.png"));
B.addMouseListener(new java.awt.event.MouseAdapter() {
public final void mouseClicked(java.awt.event.MouseEvent evt) {
A a_class = new A();
a_class.swinginDown_NF();
} });
return B; }
Main...
JFrame frame = new JFrame(" AA ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
JLabel Label = new JLabel() ;
A a = new A();
B b = new B() ;
Label.add(B.Box());
Label.add(A.newform());
frame.getContentPane().add( Label , BorderLayout.CENTER);
My problem when I click in label Box nothing happen in label newform ...
when I click in label Box function swingDown_NF its open but the label doesnt go down ...... Why ???

You're creating a new A object within the swinging down method, one that is completely separate and unique from the displayed object, and so changing the state of the new object will have no effect on the displayed one. You'll have to pass in a reference of the displayed one to where it's needed. For example you could have the B class accept an A parameter in its constructor.
Some side recommendations:
Please learn and follow Java naming and formatting conventions as your code is very difficult to follow.
You have class and field with the same names, A and B. Again, this will only confuse us and the future you -- never do this.
Avoid null layouts and setBounds if at all possible as it leads to very rigid and hard to debug GUI's. Instead use layout managers.
Your posted code won't compile. It looks like you've tried to simplify your real code for this post which is fine, but in the process you've posted bad non-compilable code including calling an instance method as if it were static. Yes, do simplify your code, but please don't post bad code in the process since you want us to understand your code and your problem well.

Related

I need to set the JButton color almost in this way, Help:

I am very new and I have no idea how to set the color in this same line of code, I need it to be this line because it is covered by a loop while or if there are other ways, I would appreciate it if you told me, thanks.
add(new JButton(new PersonAction(new Person(miResultSet.getString("name"), miResultSet.getString("identification"))),setBackground(Color.yellow)));
If you want to do it in an uncluttered way, use more lines than one and create every object needed in a single statement:
while (someConditionIsTrue) {
// create a Person passing some parameters
Person p = new Person(miResultSet.getString("name"),
miResultSet.getString("identification"));
// create a PersonAction with the recently created person as parameter
PersonAction pa = new PersonAction(p);
// create the JButton passing the PersonAction as parameter
JButton jb = new JButton(pa);
// set the background of the JButton
jb.setBackground(Color.YELLOW)));
// add it to wherever it is to be added
someThing.add(jb);
}
This will make it much easier to read and debug…
Try this
add(new JButton(new PersonAction(new Person(miResultSet.getString("name"), miResultSet.getString("identification")))).setBackground(Color.yellow));
You have not constructed jbutton properly, more over you have used comma to access property instead of dot operator.
Or you can try this...
while (miResultSet.next()) {
Person person = new Person(miResultSet.getString("name"), miResultSet.getString("identification"));
PersonAction action = new PersonAction(person);
JButton actionButton = new JButton(action);
actionButton.setBackground(Color.yellow);
// set other properties if you need
add(actionButton);
}
P.S. I guess condition in while loop. Really - I don't know exacly.

Java, reference variables that point to the same object in the memory

I'm developing a GUI program, where I have made classes, that cluster ActionListeners, by functionality. My question is regarding how the JVM handles jButtons, that has the same ActionListener added to them.
First; I am aware that the JVM can save memory, by letting two reference variables that point to an identical string (for instance), point to the same string object in the memory.
public class Example {
String str1 = "SomeString";
String str2 = "SomeString";
}
Now, my question is this: If I have, say, 5 jButtons. All buttons have the same ActionListener added to them. When the program is run, will they have 5 seperate, identical, instaces of the same class added to them? Or will the JVM do something similar (to the above mentioned) ?
Thanks in advance :)
Well, it really depends on how you created the ActionListeners. If you did
button1.addActionListener(new ActionListener() {
....
});
....
button5.addActionListener(new ActionListener() {
....
});
Or
ActionListener al= new ActionListener() {
....
};
button1.addActionListener(al);
....
button5.addActionListener(al);
In the first case you, true, have 5 different action listeners. But in the second you have only one. When can you have only one? When it does exactly the same and on the same objects.
It depends.
This will give them the same instance.
ActionListener al = new ActionListener() { ... };
button.addActionListener(al);
button2.addActionListener(al);
...
while this will give them their own.
button.addActionListener(new ActionListener() { ... });
button2.addActionListener(new ActionListener() { ... });
I believe it would pass the same ActionListener object to all 5 buttons.
If you want to know the truth, I suggest you test it for yourself

implementing a copy/paste action in java

Im having some issues getting the copy and paste methods from JTextComponent working
for my program i have an array of strings that will be the menu choices. "Copy" and "Paste" are two of these.
else if (e.getActionCommand().equalsIgnoreCase("Copy"))
{
JTextArea a = new JTextArea();
a.setEditable(true);
a.copy();
}
else if (e.getActionCommand().equalsIgnoreCase("Paste"))
{
JTextArea a = new JTextArea();
a.setEditable(true);
a.getSelectedText();
a.paste();
}
im getting no error messages but its not working. any help would be appreciated
You're creating a new instance of JTextArea each time your want to perform an action.
These won't represent what is actually on the screen. Instead, interact with a instance variable or pass the instance of the JTextArea that is on the screen in as a parameter
You are declaring a local object whose scope is limited only in an if condition:
else if (e.getActionCommand().equalsIgnoreCase("Copy"))
{
JTextArea a = new JTextArea(); // CREATING A NEW OBJECT
a.setEditable(true);
a.copy();
} // AS Soon as the code comes HERE THE Instance IS LOST with the data
Declare;
JTextArea a = new JTextArea(); outside the if condition, maybe in the class before main(){}
Create an private instance variable of the same.
Hope this helps. Let me know, if you have any questions.
class TEST{
public JTextArea a = new JTextArea();
TEST objectOfTEST = new TEST():
publis static String someText = "";
public static void main(String[] args){
if(e.getActionCommand().equalsIgnoreCase("Copy")){
someText = objectOfTEST.a.getText();
}
else if(e.getActionCommand().equalsIgnoreCase("Paste")){
// PERFORM SOME OPERATION
someText = "Paste this";
objectOfTEST.a.setText("Some TEXT that you want to set here");
}
}
}

How can I make an upside-down list in Java?

I'd like to be able to display a mutable list (using Swing) such that the first item is at the bottom in a fixed position, and subsequent items appear above it. Just the way a stack of stuff would appear in reality. The behavior is that of a FIFO queue (add to the top, remove from the bottom).
I can imagine a solution involving "padding" the list and then sorting it in reverse, or something like that, but I wondered if there might be a more direct way.
Example:
item[0]="Adam"
item[1]="Baker"
item[2]="Charlie"
should appear in 5-row list as:
+----------
|
|
| Charlie
| Baker
| Adam
+----------
If you don't want to create a custom model, then you can use the DefaultListModel. Then instead of using:
model.addElement( element );
you can use:
model.add(0, element);
and the elements will be displayed in the order you wish.
The following code also show how you might make the list look bigger than it really is:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class ListBottom2 extends JFrame
{
JList list;
JTextField textField;
public ListBottom2()
{
DefaultListModel model = new DefaultListModel();
model.add(0, "Adam");
model.add(0, "Baker");
model.add(0, "Charlie");
list = new JList(model);
list.setVisibleRowCount(5);
JPanel box = new JPanel( new BorderLayout() );
box.setBackground( list.getBackground() );
box.add(list, BorderLayout.SOUTH);
JScrollPane scrollPane = new JScrollPane( box );
scrollPane.setPreferredSize(new Dimension(200, 95));
add( scrollPane );
textField = new JTextField("Use Enter to Add");
getContentPane().add(textField, BorderLayout.NORTH );
textField.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JTextField textField = (JTextField)e.getSource();
DefaultListModel model = (DefaultListModel)list.getModel();
// model.addElement( textField.getText() );
model.add(0, textField.getText());
int size = model.getSize() - 1;
list.scrollRectToVisible( list.getCellBounds(size, size) );
textField.setText("");
}
});
}
public static void main(String[] args)
{
ListBottom2 frame = new ListBottom2();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
Provide an implementation of ListModel and that can wrap whatever data structure is appropriate.
Just reverse your array. In one line: (This isn't exactly efficient, but it'll work):
JList list = new JList(Collections.reverse(Arrays.asList(items)).toArray());
Note: It doesn't make sense to have a different UI component which reads the data differently. A ListModel holds the data according to the contract between itself and JList. Creating a new contract is pointless, when its trivial to reorganize the data based on how you want to visualize it, and more importantly, based on UI standards of the operating system.
If anything, you want a reverse ListModel, but, on the same note, it doesn't make sense to have a full implementation of ListModel that just goes in the opposite direction, when really, all you need to do is reverse the order of the backing data structure.
So, that's what you do.
Edit to add:
I read more of what you're trying to do and it looks like you want a fixed size list where data starts at the end (like a stack). In that case, what you really need to do is implement your own ListModel. Take a look at AbstractListModel and you should be able to extend it and provide your own data.
If you do that, your class will then be essentially (consider this p-code, this may not be 100% right):
class ReverseListModel extends AbstractListModel {
public Object getElementAt(int i) {
int dataIndex = fixedSize - i;
if(dataIndex > data.length)
return "";
else
return data[dataIndex];
}
public int getSize() {
return fixedSize;
}
}
Collections utility is enough to reverse a collections Collections.reverse(list)

set focus for all fields

I noticed I can use getName() as part of the trick.
What is java.awt.Component.getName() and setName() used for?
But I don't really have a clue where to start. What type of listener should I use (assuming the textfield / or box is currently blinking / selected)
This is my previous question, and thank you for the help guys.
How do I use requestFocus in a Java JFrame GUI?
I realize that for each component (Textfield) that I am creating, I have to insert a statement like requestFocus (or using transferFocus).
Is it possible to apply this policy to all the fields???
I have several textfields and ComboBox. The problem I hit is that I don't want to write methods for every single field / box.
For example, I write a method like this
private JTextField getFirstNameEntry() {
.... do something
}
because my instructor writes his program like this
private JPanel getJContentPane() {
jContentPane = new JPanel();
jContentPane.setLayout(new java.awt.FlowLayout(FlowLayout.LEADING));
jContentPane.add(makeLabel(" First Name *", 100, 20));
jContentPane.add(getFirstNameEntry(), null);
jContentPane.add(makeLabel(" Middle Initial", 100, 20));
jContentPane.add(getMiddleInitialEntry(), null);
// etc
return jContentPane;
However, to save redundancy (that was my motive at first), say I have a box, I can simply add the following code inside the method above: getJContentPane()
titleBox = new JComboBox(new String[]{"Mr.","Mrs.","Ms.","Dr.","Prof.","Rev."});
jContentPane.add(titleBox);
But doing this, I still need to create a method to do addItemListener
private void setComboBoxFocus() {
titleBox.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(e.getStateChange() == ItemEvent.SELECTED)
{
String titleSelected = titleBox.getSelectedItem().toString();
System.out.println(titleSelected);
titleBox.transferFocus();
}
}
});
}
However, this doesn't really save redundancy at all. If I have more than one ComboBox to be added, I would have to write another similar method. In fact, even in the case with one ComboBox (titleBox), I would still end up with writing a method for titleBox.
So my question is: is there a way to write a general method that can call focus to all (maybe one for ComboBox type)?
Thank you and sorry for the long post.
Why not take a JComboBox argument to your setComboBoxFocus() method, which allows you to set that listener to any JComboBox you may have? Like so:
private void setComboBoxFocus(JComboBox box) {
box.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(e.getStateChange() == ItemEvent.SELECTED)
{
String titleSelected = box.getSelectedItem().toString();
System.out.println(titleSelected);
box.transferFocus();
}
}
});
}

Categories

Resources