How can I remove JButton from JFrame? - java

I want to remove JButton when user click JButton.
I know that I should use remove method, but it did not work.
How can I do this?
Here is my code:
class Game implements ActionListener {
JFrame gameFrame;
JButton tmpButton;
JLabel tmpLabel1, tmpLabel2, tmpLabel3, tmpLabel4;
public void actionPerformed(ActionEvent e) {
gameFrame.remove(tmpLabel1);
gameFrame.getContentPane().validate();
return;
}
Game(String title) {
gameFrame = new JFrame(title);
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setBounds(100, 100, 300, 500);
gameFrame.setResizable(false);
gameFrame.getContentPane().setLayout(null);
tmpLabel4 = new JLabel(new ImageIcon("./images/bomber.jpg"));
tmpLabel4.setSize(200, 200);
tmpLabel4.setLocation(50, 100);
tmpButton = new JButton("Play");
tmpButton.setSize(100, 50);
tmpButton.setLocation(100, 350);
tmpButton.addActionListener(this);
gameFrame.getContentPane().add(tmpLabel4);
gameFrame.getContentPane().add(tmpButton);
gameFrame.setVisible(true);
}
}

If hiding the button instead of removing works for your code then you can use:
public void actionPerformed(ActionEvent event){
tmpButton.setVisible(false);
}
for the button.But the button is just hidden not removed.

The simplest solution might be to...
Attach an ActionListener to the button, see How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners for more details
When the ActionListener is clicked, extract the source of the event, JButton buttonThatWasClicked = (JButton)actionEvent.getSource()
Remove it from it's parent...
For example...
Container parent = buttonThatWasClicked.getParent();
parent.remove(buttonThatWasClicked);
parent.revaidate();
parent.repaint();
As some ideas...

First of all in your actionPerformed method you need to check that the button is clicked or not. And if the button is clicked, remove it. Here's how :
if(e.getSource() == tmpButton){
gameFrame.getContentPane().remove(tmpButton);
}
add this to your actionPerformed Method

don't add your button to jframe but add each component you want!
public void actionPerformed(ActionEvent event)
{
//gameFrame.getContentPane().add(tmpButton); -=> "Commented Area"
gameFrame.getContentPane().validate();
}
or hide your button like this
public void actionPerformed(ActionEvent event)
{
tmpButton.setVisible(false);
}

Related

How to add mouse listener to JOptionPane button?

I want to change appearance of Button on JOptionPane.ShowMessageDialog.
I have managed to change Button caption with
UIManager.put("OptionPane.okButtonText", "Text I want");
Now, my next goal is to make Button work same as buttons in rest of my app. That is, when hovering mouse over it, it changes background and font color.
On rest of my buttons I added mouse listener like this one:
//setting change color on hover
private final MouseListener mouseAction = new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
JButton rollOver = (JButton)e.getSource();
if (rollOver.isEnabled()) {
rollOver.setBackground(new Color(163, 184, 204));
rollOver.setForeground(Color.WHITE);
rollOver.setFont(b);
}
};
#Override
public void mouseExited(MouseEvent e) {
JButton rollOver = (JButton)e.getSource();
if (rollOver.isEnabled()) {
rollOver.setBackground(new Color(230, 230, 230));
rollOver.setForeground(Color.BLACK);
rollOver.setFont(f);
}
};
};
Previously in code I have Font varibles set:
Font f = new Font("System", Font.PLAIN, 12);
Font b = new Font("System", Font.BOLD, 12);
I could make new dialogs from scratch and implent this behaviour but that would be overkill.
Is there some way to access Button on JOptionPane and add mouse listener
to it?
UIManager.put("OptionPane.okButtonText", "Text I want");
The above will change the text for all "Ok" buttons on all JOptionPanes that you create.
If you want to change the text on an individual button on a specific JOptionPane then
read the section from the Swing tutorial on Customizing Button Text.
Is there some way to access Button on JOptionPane and add mouse listener to it?
When you use the static showXXX(...) methods a modal JDialog is created so you don't have access to the dialog or its components until the dialog is closed which is too late.
So instead you need to manually create the JOptionPane and add it to a JDialog. The basics of doing this can be found by reading the JOptionPane API and looking at the section titled "Direct Use".
Once you have created the JOptionPane (and before you make the dialog visible) you can then search the option pane for the buttons and add a MouseListener to each button. To help you with this you can use the Swing Utils class. It will do a recursive search of the option pane and return the buttons to you in a List. You can then iterate through the List and add the MouseListener.
The basic code using this helper class would be:
JOptionPane optionPane = new JOptionPane(
"Are you sure you want to exit the application",
JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_CANCEL_OPTION);
List<JButton> buttons = SwingUtils.getDescendantsOfType(JButton.class, optionPane, true);
for (JButton button: buttons)
{
System.out.println( button.getText() );
}
If you want to see the same effect inside all OptionPanels, I think the override BasicOptionPaneUI is a good solution
This is a minimal example
public class MyOptionPaneUI extends BasicOptionPaneUI {
#SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"})
public static ComponentUI createUI(JComponent c) {
return new MyOptionPaneUI();
}
private static final MyMouseListener m = new MyMouseListener();
#Override
public void update(Graphics g, JComponent c) {
super.update(g, c);
}
#Override
protected void installListeners() {
JButton button = (JButton) getButtons()[0];
button.addMouseListener(m);
super.installListeners();
}
#Override
protected void uninstallListeners() {
JButton button = (JButton) getButtons()[0];
button.removeMouseListener(m);
super.uninstallListeners();
}
public static class MyMouseListener extends MouseAdapter{
#Override
public void mouseEntered(MouseEvent e) {
JButton rollOver = (JButton)e.getSource();
if (rollOver.isEnabled()) {
rollOver.setBackground(new Color(163, 184, 204));
rollOver.setForeground(Color.WHITE);
}
};
#Override
public void mouseExited(MouseEvent e) {
JButton rollOver = (JButton)e.getSource();
if (rollOver.isEnabled()) {
rollOver.setBackground(new Color(230, 230, 230));
rollOver.setForeground(Color.BLACK);
}
};
}
}
inside your frame your main class you can add this code for load the class inside the UIDefoult
static{
UIManager.put("OptionPaneUI", MyOptionPaneUI.getClass().getCanonicalName());
}
Because getButtons()[0], because I see this code inside the BasicOptionPaneUI
else if (type == JOptionPane.OK_CANCEL_OPTION) {
defaultOptions = new ButtonFactory[2];
defaultOptions[0] = new ButtonFactory(
UIManager.getString("OptionPane.okButtonText",l),
getMnemonic("OptionPane.okButtonMnemonic", l),
(Icon)DefaultLookup.get(optionPane, this,
"OptionPane.okIcon"), minimumWidth);
defaultOptions[1] = new ButtonFactory(
UIManager.getString("OptionPane.cancelButtonText",l),
getMnemonic("OptionPane.cancelButtonMnemonic", l),
(Icon)DefaultLookup.get(optionPane, this,
"OptionPane.cancelIcon"), minimumWidth);
} else {
defaultOptions = new ButtonFactory[1];
defaultOptions[0] = new ButtonFactory(
UIManager.getString("OptionPane.okButtonText",l),
getMnemonic("OptionPane.okButtonMnemonic", l),
(Icon)DefaultLookup.get(optionPane, this,
"OptionPane.okIcon"), minimumWidth);
}
inside the method protected Object[] getButtons()
If you want the effect mouse hover on the button I'm working on this library and have the solution for the mouse over.
If you have a possibility to personalize the DefaoultButton inside the library with this constant
UIManager.put("Button[Default].background", new Color(163, 184, 204));
UIManager.put("Button[Default].foreground", Color.WHITE);
UIManager.put("Button[Default].mouseHoverColor", new Color(230, 230, 230));
ps: this is only information if you need to add the mouse hover inside the you project

Swing: How do I use multiple buttons?

I created this little test program. It has 2 buttons and 2 labels. I want to know how I can use 2 buttons. So when I press button-1 then I change the text for text-1 and when I press button-2 then I change text for text-2. I just wanna get an idea of how I can use multiple buttons.
My code:
JLabel text1, text2;
JButton button1, button2;
public Game(String title) {
super(title);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout());
addComponents();
setSize(250, 250);
setResizable(false);
}
public void addComponents() {
text1 = new JLabel();
getContentPane().add(text1, text2);
text2 = new JLabel();
getContentPane().add(text2);
button1 = new JButton("Button");
getContentPane().add(button1);
button1.addActionListener(this);
button2 = new JButton("Button 2");
getContentPane().add(button2);
button2.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
}
I'm new to programming, so I would also like if someone could write some comments for the code. Just so I get an idea on how the code for multiple buttons work.
In your actionPerformed method you can get the source of the action
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1){
//Do Something
}else if(e.getSource() == button2){
//Do Something Else
}
There are various approaches to add listeners to buttons, here just a couple:
Inner
If you don't have to do much actions in each button you can add inner listener in each button
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// DO STUFF
}
});
Common Listener
If you have more than 2 buttons (i guess your app will be bigger) you can use your actionPerformed(ActionEvent e) and get source of the action
#Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
if(source.equals(button1)){
// DO STUFF
}
}
Use actionCommand to clarify
To clarify this approach I would reccommend to use JButton.setActionCommand(stringCommand) so after you can use a switch:
Declaring buttons:
button1.setActionCommand("command1");
button2.setActionCommand("command2");
In ActionListener::actionPerformed()
public void actionPerformed(ActionEvent e) {
String command = ((JButton) e.getSource()).getActionCommand();
switch (command) {
case "command1":
// DO STUFF FOR BUTTON 1
break;
case "command2":
// DO STUFF FOR BUTTON 2
break;
}
}
Using Java 8, its it much more concise to add ActionListeners:
button.addActionListener(ae -> System.out.println("foo"));
Using multiple statements:
button.addActionListener(ae -> {
System.out.println("foo");
System.out.println("bar");
});
You should not use setVisible(true) before the components are added.
There are a few ways to deal with more elements in an ActionEvent:
e.getSource() returns the object on which the event occurred. So, if button1 was pressed, e.getSource() will be the same as button1 (and e.getSource()==button1 will thus be true)
You can use separate classes for each ActionEvent. If you would add the ActionListener "Button1ActionEvent" [button1.addActionListener(new Button1ActionEvent());] you have to create this class, let it implement ActionListener and add the method actionPerformed as you had in your main class. Also, you can create a listener inside of the addActionListener-method [button1.addActionListener(new ActionListener() { // actionPerformed-method here });]

how to make JButton changes the location of the text inside JLabel

how can i set JButton that changes the JLabel location on the JPanel when it pressed?
how to implement the actionlistener for this on the JButton?
You want to add the action listener to the button first
button.addActionListener(new ButtonListener());
Next you want to create the custom class
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button) {
label.setLocation(xValue, yValue);
}
}
}
Change the xValue/yValue to the x and y values that you want the label to change to.
I hope this helps!

buttons resizing them selves?

Me and a friend are trying to make an mp3 player with buttons in java, however once the first button is clicked it resizes all butttons on the second menu.
Any information on how to keep the buttons from rezising would be greatly appreciated.
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Player extends JFrame {
class CustomPanel extends JPanel{ //create image
public void paintComponent (Graphics painter){
Image pic = Toolkit.getDefaultToolkit().getImage("playerBase.jpg");
if(pic != null) painter.drawImage(pic, 0, 0, this);
}
}
public static void main(String[] args) {
Player gui = new Player();
gui.go();
}
public void go() {
JFrame frame = new JFrame("MP3 Player."); //Creates window.
CustomPanel base = new CustomPanel(); //Makes the image into a panel.
JButton button1 = new JButton("Artists");
JButton button2 = new JButton("Genres");
JButton button3 = new JButton("Songs");
JButton button4 = new JButton("TEST");
JButton button5 = new JButton("TEST");
button1.setHorizontalAlignment(SwingConstants.LEFT);
button2.setHorizontalAlignment(SwingConstants.LEFT);
button3.setHorizontalAlignment(SwingConstants.LEFT);
button4.setHorizontalAlignment(SwingConstants.LEFT);
button5.setHorizontalAlignment(SwingConstants.LEFT);
button1.addActionListener(new Button1Listener());
button2.addActionListener(new Button2Listener());
button3.addActionListener(new Button3Listener());
button4.addActionListener(new Button4Listener());
button5.addActionListener(new Button5Listener());
base.add(button1);
base.add(button2);
base.add(button3);
base.add(button4);
base.add(button5);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(304, 360);
frame.setResizable(false);
frame.add(base);
frame.setVisible(true);
button1.setSize(280, 30);
button1.setLocation(10,10);
button1.setBackground(Color.BLACK);
button1.setForeground(Color.white);
button2.setSize(280, 30);
button2.setLocation(10,40);
button2.setBackground(Color.BLACK);
button2.setForeground(Color.white);
button3.setSize(280, 30);
button3.setLocation(10,70);
button3.setBackground(Color.BLACK);
button3.setForeground(Color.white);
button4.setSize(280, 30);
button4.setLocation(10,100);
button4.setBackground(Color.BLACK);
button4.setForeground(Color.white);
button5.setSize(280, 30);
button5.setLocation(10,130);
button5.setBackground(Color.BLACK);
button5.setForeground(Color.white);
}
//These are the actions for the 5 buttons.
//Need to get buttons straight once first button is clicked
class Button1Listener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() instanceof JButton) {
JButton clickedButton = (JButton) event.getSource();
clickedButton.setSize(280, 30);
clickedButton.setLocation(10,10);
clickedButton.setBackground(Color.BLACK);
clickedButton.setForeground(Color.white);
String buttonText = clickedButton.getText();
if (buttonText.equals("Artists")) {
System.out.println("Artists");
clickedButton.setText("Back");
}
else if (buttonText.equals("Back")) {
System.out.println("Back");
}
}
}
}
//these are just place holders for the other buttons.
class Button2Listener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("Genres");
}
}
class Button3Listener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("Songs");
}
}
class Button4Listener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("TEST");
}
}
class Button5Listener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("TEST");
}
}
}
Set the layout Manager to null on your CustomPanel base.
base.setLayout(null);
If you want to force the size and location of your components (using setBounds()), then you need to remove the layout manager.
However, LayoutManagers provide better UI experience across different platforms as they will adapt to differences. LayoutManager's perform the sizing and positionning of the components based on preferredSize and constraints. If you have never used them or heard from them, you should really consider looking into them: http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
well, I didn't see a menu code. However, by default, the Layout manager for Panel is Flow Layout. Since you did not specify any layout, Flow Layout is assumed, and any sizing you specify will largely be ignored.
So, as Guillaume suggests, set it to null, so you can position things absolutely. Or use more complex layouts depending on your needs. Have a look at how to use layout managers in the swing tutorial. GridBagLayout is the most complex (difficult to use), unless you use some sort of gui builder. Other candidates are BorderLayout, GridLayout among others. Read through the examples to see which one fits your case.

adding components in applet

I am making an applet and as part of my applet, I want this to happen: When the user presses "OK", the old components (some radio buttons) are removed, and a new JPanel is added, with a bunch of textfields.
However, I cannot figure out how to add a new component to the applet after it has started. I made the problem simpler by ignoring the removal part (Which I know how to do) and just adding a simple JLabel instead, but even that won't add!
Here is my code so far:
// imports omitted
public class Class extends Applet implements ActionListener
{
Button okButton;
CheckboxGroup radioGroup;
Checkbox radio1;
Checkbox radio2;
Checkbox radio3;
JLabel j;
public void init()
{
setLayout(new FlowLayout());
okButton = new Button("OK");
j = new JLabel("hello");
radioGroup = new CheckboxGroup();
radio1 = new Checkbox("Red", radioGroup,false);
radio2 = new Checkbox("Blue", radioGroup,true);
radio3 = new Checkbox("Green", radioGroup,false);
add(okButton);
add(radio1);
add(radio2);
add(radio3);
okButton.addActionListener(this);
}
public void repaint(Graphics g)
{
if (radio1.getState()) add(j);
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == okButton) repaint();
}
}
What am I doing wrong?
You shouldn't override the repaint method, and certainly not add a component in this method. Just remove the radio buttons from the applet (using its remove method) and add the label in the applet in your actionPerformed method, the same way you add them in the init method.
You might have to call validate after.
Add components and then call validate() of your container. In this case yourApplet.validate(). This will trigger repainting and rearranging of all elements.
you could do something like
JFrame fr= new JFrame(); // global variables
JPanel panelToBeAdded = new JPanel();
JPanel initialPanel = new JPanel();
JTextField fieldToBeAdded = new JTextField();
panelToBeAdded.setPreferredSize( new Dimension(400,400));
initialPanel.setPreferredSize( new Dimension(400,400));
initialPanel.setVisible(true);
fr.add(initialPanel);
fr.setVisible(true);
fr.pack();
public void actionPerformed(ActionEvent ae) {
initialPanel.setVisible(false);
//radiobuttons.setVisible(false);---> hide the radio buttons
panelToBeAddedd.add(fieldToBeAddedd);
panelToBeAddedd.setVisible(true);
fr.add(panelToBeAddedd);
}
public void repaint( Graphics g ) {
// do something
}
What am I doing wrong?
Your repaint(Graphics) method is not the same method you are calling in your actionPerformed method.
Also, repaint is a pretty bad name for a method which is adding a new component.
public void swapComponents()
{
if (radio1.getState()) {
remove(radio1);
remove(radio2);
remove(radio3);
add(j);
validate();
}
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == okButton) {
swapComponents();
}
}
When the user presses "OK", the old components (some radio buttons) are removed, and a new JPanel is added, with a bunch of textfields.
Use a CardLayout, as shown here. It is perfect for situations like this.

Categories