This is my code:
package saaaaaaaaaa;
public class xd {
public static JFrame frame = new JFrame("Halo");
public static JLabel lab = new JLabel("learning ",JLabel.CENTER);
public static JButton but = new JButton("but");
public static JButton but1 = new JButton("butt");
public static CustomAct act = new CustomAct(lab);
public static void main(String[] args) {
but.addMouseListener(act);
but1.addMouseListener(act);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(640, 480);
frame.setLayout(new BorderLayout());
frame.setResizable(false);
frame.add(lab, BorderLayout.CENTER);
frame.add(but, BorderLayout.SOUTH);
frame.add(but1, BorderLayout.NORTH);
}
}
This is extra class for mouse click, I need 2x mouse click for 2 buttons.
package saaaaaaaaaa;
public class CustomAct implements MouseListener {
private static final long serialVersionUID = 1L;
private String halo = "this is ";
private int getClickCount = 1;
private JLabel lab;
private JLabel lab1;
public CustomAct(JLabel lab) {
this.lab = lab;
}
public void mouseClicked(MouseEvent e) {
if(e.getSource()==but) {
lab.setText("cau"+getClickCount++);
}
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
}
How can I do a multiple buttons for each different mouse click action?
How can I get ID of button, which is used?
This is if(e.getSource()==but) --- but cannot be resolved to a variable
I really don't know how to do it.
First of all you don't use a MouseListener to listen for clicks on a button.
Instead you should be using an ActionListener.
If the Action for each button is unrelated, then you need to create a separate ActionListener for each button with each ActionListener containing the specific code for the button. For example the "Add" and "Subtract" methods of a simple calculator would require a separate Action.
If the Action is related, then you would create a generic ActionListener that can be shared by the buttons. For example, entering digits 0, 1, 2, ... could be a shared ActionListener. For a working example of this approach check out: How to add a shortcut key for a jbutton in java?
Also, you should NOT be using static variables. Instead you should be create a class that extends a JPanel where you define all your variables and Swing components. The ActionListeners would also be defined in that class so they can update the labels as required.
Related
Basically I have 1 main class which extends JFrame and implements ActionListener and i have created a window which is my main window. Now I wanted to make another window which opens when I click a button on the main window. So to do this I created another class which extends JFrame and created another window. Now I am unsure how to set it so that the new window I created opens when I click a button in the main window. I have my actionPerformed in that main class. Im not sure what statement would make my window pop up.
What you want to do is have a listener on the main window "Add credits" button. That is, you want to implement ActionListener in your SlotMachine class (that's the class containing the button, right?).
You will indeed want to add this code to your SlotMachine class, and not in the other one :
public void actionPerformed(ActionEvent e){
String butonCommand = e.getActionCommand();
if(butonCommand.equals("Add Credits")){
// The add credits button has been fired. Make the other window visible
}
}
You want to make the add credits window visible, that is, you want to do the following :
addCreditsFrame.setVisible(true);
If you add the listener in your main class, it needs to have access to the frame that has to be visible. You need to send a new AddCreditsClass to your SlotMachine constructor so he can set it visible. You can't use AddCreditsClass.setVisible(true) because you're setting a frame visible, not the entire class.
That is, something along the lines of :
public class SlotMachine {
AddCreditsClass otherframe;
public SlotMachine(AddCreditsClass otherFrame) {
this.otherFrame=otherFrame;
// ...
}
public void actionPerformed(ActionEvent e){
String butonCommand = e.getActionCommand();
if(butonCommand.equals("Add Credits")){
otherFrame.setVisible(true);
}
}
}
You would have the following code :
public static void main(String... args) {
SlotMachine mainFrame = new SlotMachine(new AddCreditsClass());
mainFrame.setVisible(true); // The main window has to be visible at the beginning
public class AddCreditsClass extends JFrame implements ActionListener{
public static final int WIDTH = 700;
public static final int HEIGHT = 500;
private static JLabel addCreditsLabel;
public AddCreditsClass(){
super("Add Credits");
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
// setVisible(true); Do _not_ do this! You want the window to be hidden until you set it visible by yourself.
}
// No listener here, the button listener should be in the main class
}
In your SlotMachine class, which contains the "add credits" button, you would add the listener I mentioned earlier :
public void actionPerformed(ActionEvent e){
String butonCommand = e.getActionCommand();
if(butonCommand.equals("Add Credits")){
addCreditsFrame.setVisible(true);
}
}
Duh! Sorry I hadn't seen you answered before me. Should I delete this answer?
Well, when the button is clicked you want actionPerformed() to be called. But the button is in SlotMachine so actionPerformed() needs to be in the SlotMachine class as well. You didn't post SlotMachine but it would look something like this:
public class SlotMachine extends JFrame implements ActionListener {
public static void main(String[] args) {
SlotMachine mainFrame = new SlotMachine();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(640, 480);
mainFrame.setLocationRelativeTo(null); // center on screen
mainFrame.setVisible(true);
}
public SlotMachine() {
setLayout(new BorderLayout());
JButton button = new JButton("Open new window");
button.setActionCommand("Add Credits");
button.addActionListener(this);
add(button, BorderLayout.CENTER);
}
#Override
public void actionPerformed(ActionEvent e) {
String butonCommand = e.getActionCommand();
if (butonCommand.equals("Add Credits")) {
AddCreditsClass addCredits = new AddCreditsClass();
addCredits.setLocationRelativeTo(this);
addCredits.setVisible(true);
}
}
}
In SlotMachine's constructor we add a button and add a listener to the button. So when that button is pressed actionPerformed() will be called. And as you can see in actionPerformed() we create a new instance of AddCreditsClass and make it visible.
We moved most code from AddCreditsClass to SlotMachine but what is left looks like this:
public class AddCreditsClass extends JFrame {
public static final int WIDTH = 700;
public static final int HEIGHT = 500;
private static JLabel addCreditsLabel;
public AddCreditsClass() {
super("Add Credits");
setSize(WIDTH, HEIGHT);
setLayout(null);
}
}
In the code I am designing, I have a JButton instantiated in the main JFrame of my application that is using an ActionListener referencing an actionPerformed method in another class/component. I'm wondering if there is a way to remove that button upon running said actionPerformed method (clicking on it). In other words, is it possible for the actionPerformed method to reference back to the button that is activating it?
Can you get a reference to the object that caused the ActionListener to activate? Yes via the ActionEvent parameter's getSource() method.
i.e.,
public void actionPerformed(ActionEvent evt) {
Object theSource = evt.getSource();
}
A warning though: if you use this ActionListener or Action in multiple settings, such as with menus, the source may not be a button at all.
As far as using this to "remove" the button, you would then need to get the component's container, something like:
public void actionPerformed(ActionEvent evt) {
JButton button = (JButton) evt.getSource(); // danger when casting!
Container parent = button.getParent();
parent.remove(button);
parent.revalidate();
parent.repaint();
}
but again, I have to warn that you'll be in trouble if the event was not caused by a JButton, or if the layout manager that the parent uses doesn't things being removed. I have to wonder if a CardLayout would be better to use here.
e.g.,
import java.awt.Container;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class RemoveButton extends JPanel {
private static final long serialVersionUID = 1L;
private static final int BUTTON_COUNT = 5;
private Action removeMeAction = new RemoveMeAction("Remove Me");
public RemoveButton() {
for (int i = 0; i < BUTTON_COUNT; i++) {
add(new JButton(removeMeAction));
}
}
private static void createAndShowGui() {
RemoveButton mainPanel = new RemoveButton();
JFrame frame = new JFrame("Remove Buttons");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class RemoveMeAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public RemoveMeAction(String name) {
super(name); // to set button's text and actionCommand
}
#Override
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
// AbstractButton is the parent class of JButton and others
if (source instanceof AbstractButton) {
AbstractButton button = (AbstractButton) source;
Container parent = button.getParent();
parent.remove(button);
parent.revalidate();
parent.repaint();
}
}
}
Ok. I'm not sure about the title of my question and whether I used the right words.
As I am a self taught total amateur I'm finding it hard to ask my question as I don't know the correct terms for things so I will write something in code and then ask my question. I've written it without import statements, setting up layouts and scrollbars and some other things just to keep it simpler.
public class Foo{
JTextArea text;
public static void main(String[] args){
Foo foo = new Foo;
foo.go();
}
public void go(){
JFrame frame = new JFrame();
JButton button = new JButton("One");
JButton button2 = new JButton("Two");
JPanel panel = new JPanel();
frame.setVisible(true);
frame.setSize(600, 300);
frame.getContentPane().add(BorderLayout.EAST, panel);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(button);
panel.add(button2);
text = new JTextArea(10, 20);
panel.add(text);
button.addActionListener(new ButtLis());
button2.addActionListener(new ButtLis());
}
class ButtLis implements ActionListener{
#override
// this is where I have the problem
text.append();
}
}
What I want is an if statement to go into my inner class (ButtLis) which will determine which of the buttons are pressed and then append certain text to the JTextArea based on that. But I don't know what to call to find out which button was pressed.
You have a couple options. In the current case you have, where the JButton objects are locally scoped within the constructor, you would need to check for actionCommmand because the objects are not accessible from the ActionListener with their current scope. So you could do this
class ButtLis implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ("One".equals(command)) {
// do something
}
}
}
If you wanted to compare object source, you would need to give your buttons a global scope
public class Foo {
JButton button = new JButton("One");
JButton button2 = new JButton("Two");
class ButtLis implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
}
}
}
}
A third option is to register the buttons individually
public void go() {
...
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
}
See more at How to use Common Button and How to Write ActionListeners
I think this is what you're looking for, although I would hardly recommend it:
class ButtLis implements ActionListener {
private JTextArea text;
public ButtLis(JTextArea text) {
this.text = text;
}
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource(); // Warning! This is not good coding practice, because you don't know that the source will be a button
text.append(button.getText());
}
}
Instead, I'd recommend:
JButton button1 = new JButton("One");
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
text.append("one");
}
});
That uses an "anonymous inner class" to define the action listener. For Button2, you'd say a similar thing. The benefits here are that the action listener is right next to the button that it works on, and it prevents you from having a single ActionListener that has to check where each event came from (using e.getSource()).
Inside your ButtLis, add this
class ButtLis implements ActionListener {
public void actionPerformed(ActionEvent e) {
e.getSource();
//Your implementation
}
}
Here the class that implements ActionListener:
class ButtLis implements ActionListener {
JTextArea text;
public ButtLis(JTextArea text) {
this.text = text;
}
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() instanceof JButton) {
JButton button = (JButton) ae.getSource();
if(text != null){
text.append(" " + button.getText());
}
}
}
}
And here how to add an action listener to the buttons:
button.addActionListener(new ButtLis(text));
button2.addActionListener(new ButtLis(text));
For a generale ActionListsner, i suggest a different customer ActionListener like this:
abstract class ButtLis implements ActionListener {
protected String sourceEvent; //or you can use a reference for the source object
public ButtLis(String sourceEvent) {
this.sourceEvent = sourceEvent;
}
public String getSourceEvent() {
return sourceEvent;
}
#Override
public void actionPerformed(ActionEvent ae) {
customer_actionPerformed(ae);
}
public abstract void customer_actionPerformed(ActionEvent ae);
}
And the adding of action listener for any component is the same as an ordinary ActionListener:
//for exemple button
button.addActionListener(new ButtLis(button.getText()) {
#Override
public void customer_actionPerformed(ActionEvent ae) {
text.append(getSourceEvent());
}
});
Ok, here is my problem. Class B is a class that build a GUI ,which has a textField and button. class A has an instance of class B.Now I enter some value in the textfield, when I click the button, in class A I want to print out the value I just enter in the textfield, how can I achieve that?
Code below may better explain what I want to achieve:
public class A
{
B myB = new B();
(when the JButton was clicked,
how can I get the new textfield value here?)
}
public class B
{
JLabel myLabel;
JButton myButton;
public B()
{
getContentPane().setLayout(null);
myLabel = new JLabel();
myLabel.setLocation(0,0);
myLabel.setSize(100,30);
myLabel.setBackground( new Color(-6710887) );
myLabel.setText("");
getContentPane().add(myLabel);
myButton = new JButton();
myButton.setLocation(0,50);
myButton.setSize(100,30);
myButton.setBackground( new Color(-16737895) );
myButton.setText("Submit");
getContentPane().add(myButton);
myButton.addActionListener(this);
setSize(400,400);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
(how can I pass this "myLabel.getText()" value to class A when
this action performed?)
}
}
Can anybody help me finish this little program? Thanks in advance!
You need to expose the value in text field with a method in class B. Then class A can call that method. What it actually sounds like though is that class A (or something else) should be a ActionListener for your button.
However, a bigger problem is that you don't have a text field you just have a label in class B. This code is a good reason why you shouldn't use a GUI builder, especially when learning Swing.
Some reading:
http://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html
http://docs.oracle.com/javase/tutorial/uiswing/events/
I often make an "App" class that ties all my GUI-builder-built components together. Any GUI builder worth anything lets you add getters to the generated source code. Add some getters to the GUI-built components to retrieve key elements of the GUI, then let the App class use the getters to interact with the components as necessary. This won't win any MVC/MVVM/MVP design awards, but it gets the job done, which ought to count for something.
public class App {
private B _b;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
App app = new App();
app.run();
}
});
}
void run() {
_b = new B();
_b.getMainButton().addActionListener(new MainButtonListener());
_b.setVisible(true);
}
private void handleMainButtonClicked() {
String mainText = _b.getMainTextArea().getText();
System.out.println("Button clicked; main text = " + mainText);
}
public class MainButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
handleMainButtonClicked();
}
}
}
public class B extends JFrame {
private JPanel _contentPane;
private JTextArea _jTextArea;
private JButton _jButton;
public B() {
initComponents();
}
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
_contentPane = new JPanel();
setContentPane(_contentPane);
_jTextArea = new JTextArea();
_contentPane.add(_jTextArea, BorderLayout.CENTER);
_jButton = new JButton("My Button");
_contentPane.add(_jButton, BorderLayout.SOUTH);
}
public JButton getMainButton() {
return _jButton;
}
public JTextComponent getMainTextArea() {
return _jTextArea;
}
}
I have a JPanel with n number of JXTitledPanels. The user should be able to click the JXTitledPanel and hit a remove button to remove it.
My question is how do I know what JXTitlePanel the user has selected.
here is a screen from my program basically I want a user to click "Hospitals", click remove and the Hospitals Table will disappear.
I'd probably add a "remove" control into the right decoration position. This way you could pass a reference to the control of the JXTiltedPane
titledPane.addRightDecoration(new MyRemoveControl(titkedPane));
Or such
#madprogrammer probably has the simplest answer, but if you don't want to change the look of the application, you could combine your button's actionListener with a mouseListener for the panels.
The mouseListener portion saves the last panel clicked, and the actionListener just removes the panel that was registered by the mouseListener.
Here's a quick sample I cooked up - it doesn't use JXTitledPane but that shouldn't matter because they're all in the same hierarchy.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TempProject extends JFrame{
public TempProject(){
Box mainContent = Box.createVerticalBox();
//Create Button
JButton removePanel = new JButton("RemovePanel");
RemoveListener listener = new RemoveListener(mainContent);
removePanel.addActionListener(listener);
mainContent.add(removePanel);
//Create Panels
mainContent.add(getPanel(Color.red, listener));
mainContent.add(getPanel(Color.orange, listener));
mainContent.add(getPanel(Color.pink, listener));
mainContent.add(getPanel(Color.magenta, listener));
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setContentPane(mainContent);
pack();
setVisible(true);
}
public JPanel getPanel(Color color, RemoveListener l){
JPanel result = new JPanel();
result.setBackground(color);
result.add(new JLabel(color.toString()));
result.addMouseListener(l);
return result;
}
public static void main(String args[])
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
new TempProject();
}
});
}
public static class RemoveListener extends MouseAdapter implements ActionListener{
Component lastSelectedComponent = null;
Container master; //The panel containing the ones being listened to
public RemoveListener(Container master){
this.master = master;
}
#Override
public void mouseClicked(MouseEvent arg0) {
lastSelectedComponent = (Component)arg0.getSource();
}
#Override
public void actionPerformed(ActionEvent e) {
if(lastSelectedComponent != null){
master.remove(lastSelectedComponent);
master.repaint();
}
}
}
}