I would like to use setAlwaysOnTop(boolean) in java.
I want to setAlwaysOnTop() when I click on a JButton and this JButton has its own actionListener
My Problem is I don't know how to set the JFrame on top at this situation, because it's not inside the constructor nor there is a method getFrame()
I tried creating a method inside the constructor but it does not work :S.
UPDATE:
private class optionAction implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource() == onTop) //onTop is a menuItem when I click it it should make the frame Always on top.
frame.setAlwaysOnTop(true); //This does not work of course just to demonstrat you what I want to do
}
}
The following code lines show you how it can be done with a direct implementation of ActionListener() assigned to a button declared inside the constructor. (You can also do this anywhere else in your class.)
class MyFrame extends JFrame {
public MyFrame() {
// ...
JButton button = new JButton("PRESS");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setAlwaysOnTop(true);
// Alternatively use MyFrame.this.setAlwaysOnTop(true);
}
});
add(button);
// ...
}
}
An idea might be to pass a reference to your JFrame to the constructor of your implementation of the ActionListener.
Maybe something like this:
class MyActionListener implements ActionListener {
private JFrame jFrame;
public MyActionListener(JFrame jFrame) {
this.jFrame = jframe;
}
public void onClick(Event event) {
jFrame.setAlwaysOnTop(true);
}
}
create a boolean called ontop
boolean ontop = false;
jbutton.addActionListener(new ActionListener()) {
public void actionPerformed(ActionEvent e){
if (ontop) {
frame.setAlwaysOnTop(false);
ontop = false;
}
else {frame.setAlwaysOnTop(true); ontop = true}
});
The correct working code for this question is below:
private class optionAction implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource() == onTop) //onTop is a menuItem
setAlwaysOnTop(true); //This does not work of course just to demonstrate you what I want to do
}
}
The reason this is does not work because I was setting the setAlwaysOnTop on a JFrame object, which it doesn't exists in that class.
To set the setALwaysOnTop on a JFrame you have to remove the frame. and just add `setAlwaysOnTop()
Related
Ok so I have 2 jPanels.
one of them has a number of buttons that when pressed should add text to the the textfield that is in the second jPanel.
I am brand spanking new to swing with previously only having to write back end code and web based code so I am having difficulty seeing how you would accomplish this.
I only have buttons created in one panel and a textfield in another so i suspect code would be irrelevant.
Any articles that someone could point me to or examples are greatly appreciated.
So I had this problem ones,
So Lets say you have two JFrame JFrame1 and JFrame2
In order to communicate with each other at runtime both has to have most recent initialized object of each individual frame.
Now lets say this is your first frame where is your textbox,
public class JFrame1 extends JFrame{
JTextField jTextField= null;
public JFrame1() throws HeadlessException {
super("JFrame");
setSize(200, 200);
jTextField = new JTextField();
add(jTextField);
setVisible(true);
}
public void setValueToText(String value){
jTextField.setText(value);
}
}
Then This is second and where is your Button,
public class JFrame2 extends JFrame{
JButton jButton= null;
JFrame1 frame1=null;
public JFrame2() throws HeadlessException {
super("JFrame");
frame1=new JFrame1();
jButton = new JButton("Clieck Me");
add(jButton);
setVisible(true);
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
frame1.setValueToText("Hi");
}
});
setVisible(true);
}
public static void main(String[] args) {
JFrame2 jf= new JFrame2();
jf.setSize(200, 200);
}
}
Now Just run second class file and click one button which will set hi on your textbox which is in second frame.
So As you see answer lay's in Initialized second object in frame.
My execution is like,
Run JFrame2
Initialized JFrame1 in JFame2 const.
you can make the JTextField an instance variable of the enclosing JFrame and make the two panels inner classes of it. By this, the two panels will have a reference to the same field which belongs to the outer class.
So, you will end up having something similar to:
public class Outer extends JFrame{
private JTextField text = new JTextField();
...
public Outer(){
this.add(new Inner1(), BorderLayout.NORTH);
this.add(new Inner2(), BorderLayout.SOUTH);
}
class Inner1 extends JPanel{
...
public Inner1(){
this.add(text);
}
}
class Inner2 extends JPanel implements ActionListener{
private JButton button = new JButton();
public Inner2(){
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == button)
text.setText("Hello StackOverFlow");
}
}
}
add your code to change the text in another panel, when a button clicked in the first panel.
mybutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//do your logic to change the text in another panel
}
});
I have class DnyMesice what creates many instances of JButton. Every instance contains variable poznamkaDne. This class DnyMesice contains actionListener to find poznamkaDne value of pushed JButton.
I have class Gui what creates one instance of mentioned class DnyMesice and one instance of JTextArea.
How can I refresh value of JTextArea (names poznamkovePole) if some JButton (in class DnyMesice) is pushed?
public class DnyMesice extends JPanel {
public String poznamkaDne="first note";
jButton tlacitkoDen;
public void zobrazMesic(Calendar kalendar){
for (c=1; c<30; c++){
tlacitkoDen = new JButton(Integer.toString(denvMesici));
tlacitkoDen.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
poznamkaDne="New note";
};
});
add(tlacitkoDen);
}
}
}
public class Gui extends JFrame {
...
public void zobrazKalendar(){
...
panel3 = new JPanel();
panel3.setLayout(new FlowLayout());
add(panel3);
JTextArea poznamkovePole;
poznamkovePole = new JTextArea();
poznamkovePole.setColumns(30);
poznamkovePole.setRows(5);
poznamkovePole.setText(panel2.poznamkaDne);
panel3.add(poznamkovePole);
}
Now the program shows in JTextArea only "first note" (which is defined during creating of instance JButton) but hot to refresh it after ActionListener action?
Maybe better if you will use:
Add to DnyMesice JTextArea link and in ActionListener change text.
public class DnyMesice extends JPanel {
private JTextArea poznamkaDne;
jButton tlacitkoDen;
public DnyMesice (JTextArea jTextArea){
this.poznamkaDne = jTextArea;
}
public void zobrazMesic(Calendar kalendar){
for (c=1; c<30; c++){
tlacitkoDen = new JButton(Integer.toString(denvMesici));
tlacitkoDen.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
poznamkaDne.setText("New note");
};
});
add(tlacitkoDen);
}
}
}
P.S. - And please don't forget to use Code Conventions for the Java
Modify as follows:
// add these methods
public void setPoznamkaDne(String s) {
poznamkaDne = s;
}
public String getPoznamkaDne() {
return poznamkaDne;
}
// CHANGE this method (KEEP the rest of the code!)
public void actionPerformed(ActionEvent evt) {
setPoznamkaDne("New note");
};
poznamkovePole.setText(panel2.getPoznamkaDne());
These changes should allow you to update the text. BUT you need to either call poznamekovePole.setText() somehow, or implement an advanced listener class. I recommend combining your class like #Too Strong Magic said, above.
I have a JPanel form which contains a JList and some JButton.
The JPanel looks like this
When I click the Add List button, a separate JFrame form is displayed.
The JFrame form will look like this
When the add button on the JFrame is clicked, I need to add the value of the JTextfield (named List Name) to the JList on the previous JPanel. I wonder how to pass the value from the JFrame to the JPanel? Any suggestion would be appreciated.
Here is a code of the JPanel form (using Designer GUI)
package multimediaproject;
public class musicPlayerPanel extends javax.swing.JPanel {
public musicPlayerPanel() {
initComponents();
}
private void initComponents() {
//...here is the generated code by using designer GUI
}
// Variables declaration - do not modify
//..generated code
// End of variables declaration
}
Here is the code of JFrame form (using Designer GUI)
package multimediaproject;
public class addListFrame extends javax.swing.JFrame {
public addListFrame() {
initComponents();
this.setLocation(515, 0);
setVisible(true);
}
private void initComponents() {
//..here is the generated code by using Designer GUI
}
private void addBtnActionPerformed(java.awt.event.ActionEvent evt){
//some validation
if(...)
{
//validation
}
else
{
//IF VALUE IS CORRECT, ADD the List Name JTextfield value to the JList on the previous JPanel
errorMessage.setText("");
}
}
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new addListFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
//....generated code
// End of variables declaration
}
UPDATE with your code.
You can take advantage of PropertyChangeListener and PropertyChangeSupport (This classes implements Observer Pattern).
I give you an example you for guidance:
public class MusicPlayerPanel extends JPanel {
private JList list;
private JButton addButton;
private PropertyChangeListener listener = new MyPropertyChangeListener();
//..in some place
addButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
JFrame form = new FrameForm();
form.addPropertyChangeListener(FrameForm.BUTTON_CLICKED,listener);
form.setVisible(true);
}
});
//in another place
private class MyPropertyChangeListener implements PropertyChangeListener{
#Override
public void propertyChange(PropertyChangeEvent evt){
if(evt == null)
return;
if(evt.getPropertyName().equals(FrameForm.BUTTON_CLICKED)){
String value = (String) evt.getNewValue();
((DefaultListModel)list.getModel()).addElement(value);
}
}
}
}
And the frame form like this:
public class AddListFrame extends JFrame{
private JTextField textfield;
private JButton submitButton;
public static final String BUTTON_CLICKED ="buttonClicked";
// in some place
submitButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
firePropertyChange(BUTTON_CLICKED,null,textfield.getText());
}
});
}
Note: In java by convention, classes start with uppercase and follow a camel style. This is very important for readability.
OK.This is easy if i understand your problem.
Step 1:Create setter and getter for your JList object reference.
Step 2:On button click , when you open new JFrame pass your panel reference in constructor of class which inherits JFrame.
Step 3:By doing this you are able to call getter method on panel reference.
Step 4:Now you have reference of JList,do what you want.
I hope this is best solution of your problem
"when I click the add button, a separate jFrame form is displayed. The jFrame contain a jTextfield and a submit button."
Did you seriously create an entirely new JFrame for a JTextField and a JButton?!
Have you not heard of JOptionPane? That's exactly what you are trying to replicate. The only code you need is this:
String s = JOptionPane.showInputDialog(component, message);
model.addElement(s);
The first line will cover all your code for your custom JFrame.
Take a look at this example
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JOPDemo extends JPanel {
JList list;
JButton button = new JButton("Add Name");
String name;
DefaultListModel model;
public JOPDemo() {
model = new DefaultListModel();
list = new JList(model);
setLayout(new BorderLayout());
add(list, BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
name = JOptionPane.showInputDialog(this, "Enter a name");
model.addElement(name);
}
});
}
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
private static void createAndShowGui() {
JFrame frame = new JFrame();
frame.add(new JOPDemo());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Edit
What you can do is have an inner class which is your JFrame. Personally, I'd go with a JDialog though.
From comment: Have your frame as an inner class of your main class. That way it can access all the variables from your main class. You can have a String listName also in the GUI class. From the other frame when you hit add, it sets the listName in GUI class, then adds to the list.
public class GUI {
String listName;
JList list;
InnerFrame inner = new InnerFrame();
private class InnerFrame extends JFrame {
JButton addButton;
}
}
I've been working on a program and my master class with the bulk of the code has over 20 different "addActionListener" methods. How can I instead create this actionListener, itemStateChanged etc etc in a separate class but still perform as it should the way it does now. Any tips would be most welcome as I have run over 4000 lines of code already in this class :( Thank you!
public class MyActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent evt) {
// actionPerformed here...
}
}
You would use it like:
JButton button = new JButton();
button.addActionListener(new MyActionListener());
// OR
MyActionListener listener = new MyActionListener();
JButton button = new JButton();
button.addActionListener(listener);
class Mylistener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e){
if (e.getSource() == someButton){
// do something
} else if (e.getSource() == someOtherButton){
// do something
}
// add more else if statements for other components
// e.getSource() is the component that fires the event e.g. someButton
}
}
Say you have two buttons
JButton someButton = new JButton("SOME BUTTON");
JButton someOtherButton = new JButtton("SOME OTHER BUTTON");
ActionListener listener = new MyListener();
someButton.addActionListener(listener);
someOtherButton.addActionListener(listener);
Edit:
public MyClass extends JFrame {
JButton someButton = new JButton("SOME BUTTON");
JButton someOtherButton = new JButtton("SOME OTHER BUTTON");
public MyClass(){
ActionListener listener = new MyListener();
someButton.addActionListener(listener);
someOtherButton.addActionListener(listener);
}
class Mylistener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e){
if (e.getSource() == someButton){
// do something
} else if (e.getSource() == someOtherButton){
// do something
}
// add more else if statements for other components
// e.getSource() is the component that fires the event e.g. someButton
}
}
You want to write a class which implements ActionListener.
I could give you some code here with very little explanation, but I think it is best that I point you to the documentation here: http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
This link will give you some examples, and it will explain in detail how it is working.
I hope this helps.
This question already has answers here:
Keyword for the outer class from an anonymous inner class [duplicate]
(2 answers)
Closed 9 years ago.
I am trying to create my own window class which extends JFrame. However, I am having a problem with the action listener for fullScreenBtn. When writing the ActionListener.actionPerformed funcion, I am unable to use the this keyword as it refers to new ActionListener. How do I refer to the instance of MyWindow instead?
public class MyWindow extends JFrame {
private static GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
private static GraphicsDevice gDev = gEnv.getDefaultScreenDevice();
private static JPanel toolbar = new JPanel();
private static JButton fullScreenBtn = new JButton("Show Full Screen");
private static boolean isFullScreen = false;
public MyWindow() {
toolbar.setLayout(new FlowLayout());
this.getContentPane().add(toolbar, BorderLayout.PAGE_START);
fullScreenBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Toggle full screen window
this.setUndecorated(!isFullScreen);
this.setResizable(isFullScreen);
gDev.setFullScreenWindow(this);
isFullScreen = !isFullScreen;
if (isFullScreen) {
fullScreenBtn.setText("Show Windowed");
} else {
fullScreenBtn.setText("Show Full Screen");
}
}
});
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
this.dispose();
System.exit(0);
}
});
}
}
In inner classes you will need to prepend your use of this with the class name of the outer class if you need to obtain a reference to the outer class: For example, use
MyWindow.this.setUndecorated(...)`
// etc...
As an aside, you really don't want to extend JFrame here, and in most situations.
Also, the ancestor Window that holds the JButton can be obtained in other ways such as via SwingUtilities.getWindowAncestor(theButton). i.e.,
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof JButton) {
JButton button = (button) source;
Window ancestorWin = SwingUtilities.getAncestorWindow(button);
ancestorWin.setUndecorated(!isFullScreen);
ancestorWin.setResizable(isFullScreen);
// etc...
Or if you know most definitely that the ancestor window is a JFrame:
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof JButton) {
JButton button = (button) source;
JFrame ancestorWin = (JFrame) SwingUtilities.getAncestorWindow(button);
ancestorWin.setUndecorated(!isFullScreen);
ancestorWin.setResizable(isFullScreen);
// etc...
This is the syntax of accessing the enclosing-class's instance from an inner-class or an anonymous-class:
OuterClass.this.foo();
Because you are using an anonymous class, this will refer to that class, in this case the ActionListener. Because your ActionListener doesn't have methods such as setUndecorated, this will give you a compile error.
What you want to do is use MyWindow.this, followed by any method of MyWindow.
You will need to access this by specifying the outer class too, in your case it has to be something like follows:
MyWindow.this