How to delete button after clicking on "delete" button? - java

My program seems to run fine, except for the delete part. Every time I click on the 'delete' button, it deletes itself. So my question is, how would I delete a selected button after I clicked on the "delete" button?
Here is a snippet of my code:
public class DeleteButton extends JFrame implements ActionListener
{
JButton b18a = new JButton("Delete");
JPanel panel = new JPanel();
panel.add(b18);
class ClickListenerTwo implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton buttonThatWasClicked = (JButton) e.getSource();
Container parent = buttonThatWasClicked.getParent();
parent.remove(buttonThatWasClicked);
parent.revalidate();
parent.repaint();
}
}
}
ActionListener b18aClicked = new ClickListenerTwo();
b18a.addActionListener(b18aClicked);
P.S - This selected button that I'm talking about is made during run time, so I want to delete it during run time too, if that would be possible. Thanks!

So, assuming that you need to click the "other" button first, you could use an instance field to maintain a reference to the "last" clicked button and then use that when the delete button is clicked
For example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JButton lastButton;
public TestPane() {
JPanel grid = new JPanel(new GridLayout(8, 8));
for (int index = 0; index < 8 * 8; index++) {
JButton btn = new JButton(Integer.toString(index + 1));
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lastButton = btn;
}
});
grid.add(btn);
}
JButton delete = new JButton("Delete");
delete.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (lastButton != null) {
lastButton.getParent().remove(lastButton);
grid.revalidate();
grid.repaint();
}
lastButton = null;
}
});
setLayout(new BorderLayout());
add(grid);
add(delete, BorderLayout.SOUTH);
}
}
}
Personally, a JToggleButton would give a better user experience

You have to find the Component from the Top Frame.
May be this code will help you.
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if (source instanceof Component) {
Window w = findWindow((Component) source);
//Find your component and remove it from this window.
} else {
System.out.println("source is not a Component");
}
}
public static Window findWindow(Component c) {
System.out.println(c.getClass().getName());
if (c instanceof Window) {
return (Window) c;
} else if (c instanceof JPopupMenu) {
JPopupMenu pop = (JPopupMenu) c;
return findWindow(pop.getInvoker());
} else {
Container parent = c.getParent();
return parent == null ? null : findWindow(parent);
}
}

Related

parent dialog state is changed to invisible but child dialog still stays visible

In my project code, we are using custom dialogs. I am facing some weird issues with them.
I have a child dialogue and a parent dialogue.
Ideally a child dialogue goes to invisible state when we invoke parent.setVisible(false).
But I am seeing some strange behaviour.
When I make parent.setVisible(false) then still my child dialog remains visible but when I try to get child.isVisible() : it gives me false.
Also when I try to invoke child.setVisible(false), again it has no effect in visiblity of parent dialog .
NOTE: I cannot show any code sample due to too much complexity, lenght and other external API issues. Also I tried replicating this using external programs but it works as expected and no issues seen.
I just want to know does anybody knows any scenario in which a child dialog control get loosen up when we make parent.setVisible(false)?
I just want to know does anybody knows any scenario in which a child
dialog control get loosen up when we make parent.setVisible(false)?
for parent is called setVisible(false) too,
be sure that you to reuse reduced number of childs, to set DefaultCloseOparation to HIDE or DISPOSE_ON_CLOSE (by defasult the last container turn off light, but hasn't effect if is there modality between containers)
for example
import java.awt.BorderLayout;
import java.awt.Dialog.ModalityType;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
/**
*
* #author user
*/
public class ModalityAndJDialog {
private JFrame frame = new JFrame();
private JDialog dialog1;
private JDialog dialog2;
private JButton button = new JButton("Start Swing Timer");
private JButton button1 = new JButton();
private JButton button01 = new JButton();
private JButton button02 = new JButton();
private Timer timer;
public ModalityAndJDialog() {
button.setAction(updateCol());
frame.setTitle("JFrame");
frame.add(button, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(400, 300);
frame.setLocation(150, 150);
frame.setVisible(true);
timer = new javax.swing.Timer(500, updateCol());
timer.setRepeats(false);
timer.start();
}
private Action updateCol() {
return new AbstractAction("Show JDialog") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
if (dialog1 == null) {
dialog1 = new JDialog(dialog1, ModalityType.APPLICATION_MODAL);
dialog1.setTitle("1st. JDialog");
dialog1.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
button1.setAction(updateCol1());
button01.setAction(updateCol01());
dialog1.add(button1, BorderLayout.SOUTH);
dialog1.add(button01, BorderLayout.NORTH);
dialog1.pack();
dialog1.setSize(400, 300);
dialog1.setLocation(250, 250);
dialog1.setVisible(true);
} else {
EventQueue.invokeLater(() -> {
dialog1.setVisible(true);
});
}
}
};
}
private Action updateCol01() {
return new AbstractAction("Hide JDialog") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
if (dialog1 != null) {
dialog1.setVisible(false);
}
}
};
}
private Action updateCol1() {
return new AbstractAction("Show Child JDialog") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
if (dialog2 == null) {
dialog1.setTitle("2nd. JDialog");
dialog2 = new JDialog(frame, ModalityType.APPLICATION_MODAL);
dialog2.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
button02.setAction(updateCol02());
dialog2.add(button02, BorderLayout.SOUTH);
dialog2.pack();
dialog2.setSize(400, 300);
dialog2.setLocation(350, 350);
dialog2.setVisible(true);
} else {
EventQueue.invokeLater(() -> {
dialog2.setVisible(true);
if (!frame.isVisible()) {
frame.setVisible(true);
}
});
}
}
};
}
private Action updateCol02() {
return new AbstractAction("Hide JDialog") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
if (frame != null) {
frame.setVisible(false);
}
/*if (dialog1 != null) {
dialog1.setVisible(false);
}*/
}
};
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
/*UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());*/
} catch (UnsupportedLookAndFeelException | ClassNotFoundException | IllegalAccessException | InstantiationException ex) {
System.out.println("[L&F][Exception] " + ex.getMessage());
}
EventQueue.invokeLater(() -> {
new ModalityAndJDialog();
});
}
}

Accumulating getClickCount()

good day!
I'm making an attendance-checking program that displays an orange button when clicked once, red button, for two clicks and black button for 3. I'm having problem as to how to accumulate getClickCount() values, because for the buttons to register 3 clicks, the buttons have to be clicked at 3 times quickly.
Here's the code
button1.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent a){
if (a.getClickCount() == 1){
button1.setBackground(Color.ORANGE);
}
else if (a.getClickCount() == 2){
button1.setBackground(Color.RED);
}
else if (a.getClickCount() == 3){
button1.setBackground(Color.BLACK);
}
}
});
frame.setVisible(true);
frame.pack();
}
}
If I understand correctly, basically you want to change the color each time the button is pressed, based on the number of times the button has previously been pressed.
MouseListener is not a good choice for JButton, as buttons can be activated by the keyboard (via short cuts or focus activity) and programically, none of which the MouseListener will detect.
Instead, you should use a ActionListener
This example will change the color each time the button is clicked. I've used an array of Colors to make life simpler, but the general concept should work for if-else statements, you just need to reset the counter when it reaches its limit
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ButtonClicker {
public static void main(String[] args) {
new ButtonClicker();
}
public ButtonClicker() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class TestPane extends JPanel {
private static final Color[] COLORS = new Color[]{Color.ORANGE, Color.RED, Color.BLACK};
private int clickCount;
public TestPane() {
setLayout(new GridBagLayout());
JButton clicker = new JButton("Color Changer");
clicker.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
clickCount++;
setBackground(COLORS[Math.abs(clickCount % COLORS.length)]);
}
});
setBackground(COLORS[clickCount]);
add(clicker);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Take a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners for more details
Step 1: Create your own MouseListener class. In this case, I chose to create an external class that extends MouseAdapter.
public class MyMouseListener extends MouseAdapter
{
public void mousePressed(MouseEvent event)
{
Object obj = event.getSource();
if (obj instanceof JButton)
{
if JButton btn = (JButton)obj;
if (a.getClickCount() == 1)
{
btn.setBackground(Color.ORANGE);
}
else if (a.getClickCount() == 2)
{
btn.setBackground(Color.RED);
}
else if (a.getClickCount() == 3)
{
btn.setBackground(Color.BLACK);
}
}
}
}
Step 2: Add independent instances of this listener to each button
button1.addMouseListener(new MyMouseListener());
button2.addMouseListener(new MyMouseListener());
button3.addMouseListener(new MyMouseListener());
button4.addMouseListener(new MyMouseListener());
button5.addMouseListener(new MyMouseListener());
button6.addMouseListener(new MyMouseListener());
button7.addMouseListener(new MyMouseListener());
button8.addMouseListener(new MyMouseListener());
button9.addMouseListener(new MyMouseListener());
button10.addMouseListener(new MyMouseListener());
button11.addMouseListener(new MyMouseListener());
button12.addMouseListener(new MyMouseListener());
That should work for you. However, as I mentioned, this works OK, but not great.

Java JDialogs How To Pass Information Between?

after looking for an answer for 3 hours, I am just about to give up on this idea:
I am making an application that displays the followers of a Twitch streamer.
A couple of features i am trying to add:
the display frame is a separate window from the controls frame.
I am trying to use (JFrame as display window) (JDialog as controls frame)
And furthermore: Settings is in another JDialog (this one has Modal(true))
Settings needs to be able to send the JFrame information such as: "username" and "text color"
And the settings JDialog will only pop up from clicking "settings" on the controls JDialog.
It will setVisible(false) when you click "save settings" or the X.
On the controls JDialog (b_console) needs to receive error messages and info like that.
And on the same JDialog, "filler" needs to receive follower count and things like that.
Here follows my code involving the transfers listed above:
package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics.*;
import javax.swing.*;
import java.io.*;
import java.net.URL;
public class JavaFollowerNotifier extends JFrame implements ComponentListener
{
Settings settings = new Settings();
ControlPanel ctrlPnl = new ControlPanel();
public JavaFollowerNotifier()
{
try
{
settings.readSettings();
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void grabFollower()
{
ctrlPnl.b_console.setText("Retrieving Info...");
try
{
URL twitch = new URL("https://api.twitch.tv/kraken/channels/" + savedSettings[1] + "/follows?limit=1&offset=0");
ctrlPnl.b_console.setText("Retrieved");
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void grabStats()
{
ctrlPnl.b_console.setText("Retrieving Info...");
try
{
URL twitch = new URL("https://api.twitch.tv/kraken/channels/" + savedSettings[1] + "/follows?limit=1&offset=0");
ctrlPnl.filler.setText("Followers: " + totalFollowers + "\nLatest: " + lastFollower);
ctrlPnl.b_console.setText("Retrieved");
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void componentMoved(ComponentEvent arg0)
{
//this is only to *attach this JDialog to the JFrame and make it move together my plan is to have it undecorated as well
int x = this.getX() + this.getWidth();
int y = this.getY();
ctrlPnl.movePanel(x, y);
}
public void paint(Graphics g)
{
if(clearPaint == false)
{
//any "savedSettings[n]" are saved in Settings.java (just not in this version)
g.setColor(Color.decode(savedSettings[3]));
scaledFont = scaleFont(follower + " followed!", bounds, g, new Font(savedSettings[2], Font.PLAIN, 200));
}
}
}
package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Settings extends JDialog implements ActionListener
{
JavaFollowerNotifier jfollow = new JavaFollowerNotifier();
ControlPanel ctrlPnl = new ControlPanel();
//here are the settings mention above
String[] savedSettings = {"imgs/b_b.jpg","username","font","color","Nightbot"};
public Settings()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void saveSettings()
{
savedSettings[4] = jfollow.lastFollower;
try
{
PrintWriter save = new PrintWriter("config.cfg");
ctrlPnl.b_console.setText("Saving...");
for(int i = 0; i < 5; i++)
{
save.println(savedSettings[i]);
}
save.close();
ctrlPnl.b_console.setText("Saved");
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
canClose = false;
}
readSettings();
this.repaint();
}
public void readSettings()
{
ctrlPnl.b_console.setText("Loading...");
try
{
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
jfollow.lastFollower = savedSettings[4];
try
{
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
ctrlPnl.b_console.setText("Loaded Settings");
}
}
package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ControlPanel extends JDialog implements ActionListener
{
public ControlPanel()
{
try
{
}
catch (Exception e)
{
b_console.setText("Error");
System.out.println(e);
}
}
public void movePanel(int x, int y)
{
//here is where i *attach the JDialog to the JFrame
controlPanel.setLocation(x, y);
}
public void actionPerformed(ActionEvent ie)
{
if(ie.getSource() == b_settings)
{
settings.frame.setVisible(true);
}
}
}
I tried to fix your program, but I wasn't too sure about its flow. So I created another simple one. What I did was pass the labels from the main frame to the dialogs' constructors. In the dialog, I took those labels and changed them with text entered in their text fields. If you hit enter after writing text from the dialog, you'll see the text in the frame change
public class JavaFollowerNotifier1 extends JFrame{
private JLabel controlDialogLabel = new JLabel(" ");
private JLabel settingDialogLabel = new JLabel(" ");
private ControlDialog control;
private SettingsDialog settings;
public JavaFollowerNotifier1() {
control = new ControlDialog(this, true, controlDialogLabel);
settings = new SettingsDialog(this, true, settingDialogLabel);
....
class ControlDialog extends JDialog {
private JLabel label;
public ControlDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
....
class SettingsDialog extends JDialog {
private JLabel label;
public SettingsDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
Test it out and let me know if you have any questions
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class JavaFollowerNotifier1 extends JFrame{
private JLabel controlDialogLabel = new JLabel(" ");
private JLabel settingDialogLabel = new JLabel(" ");
private JButton showControl = new JButton("Show Control");
private JButton showSetting = new JButton("Show Settings");
private ControlDialog control;
private SettingsDialog settings;
public JavaFollowerNotifier1() {
control = new ControlDialog(this, true, controlDialogLabel);
settings = new SettingsDialog(this, true, settingDialogLabel);
showControl.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
control.setVisible(true);
}
});
showSetting.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
settings.setVisible(true);
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(showControl);
buttonPanel.add(showSetting);
add(buttonPanel, BorderLayout.SOUTH);
add(controlDialogLabel, BorderLayout.NORTH);
add(settingDialogLabel, BorderLayout.CENTER);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JavaFollowerNotifier1();
}
});
}
}
class ControlDialog extends JDialog {
private JLabel label;
private JTextField field = new JTextField(15);
private JButton button = new JButton("Close");
private String s = "";
public ControlDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
setLayout(new BorderLayout());
add(field, BorderLayout.NORTH);
add(button, BorderLayout.CENTER);
pack();
setLocationRelativeTo(frame);
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
s = field.getText();
label.setText("Message from Control Dialog: " + s);
}
});
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
ControlDialog.this.setVisible(false);
}
});
}
}
class SettingsDialog extends JDialog {
private JLabel label;
private JTextField field = new JTextField(15);
private JButton button = new JButton("Close");
private String s = "";
public SettingsDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
setLayout(new BorderLayout());
add(field, BorderLayout.NORTH);
add(button, BorderLayout.CENTER);
pack();
setLocationRelativeTo(frame);
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
s = field.getText();
label.setText("Message from Settings Dialog: " + s);
}
});
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
SettingsDialog.this.setVisible(false);
}
});
}
}
Typically when I build GUI's which use modal dialogs to gather user input, I build my own class, which extends the JDialog or in some cases a JFrame. In that class I expose a getter method for an object which I usually call DialgResult. This object acts as the Model for the input I gather from the user. In the class that has the button, or whatever control which triggers asking the user for the information, I create it, show it as a modal dialog, then when it is closed, I retrieve the object using that same getter.
This is a very primitive example:
package arg;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class asdfas extends JFrame {
public static void main(String[] args) {
asdfas ex = new asdfas();
ex.setVisible(true);
}
public asdfas() {
init();
}
private void init() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBounds(100,100,200,200);
final JButton button = new JButton("Show modal dialog");
button.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Dialog d = new Dialog();
d.setVisible(true);
button.setText(d.getDialogResult().value);
revalidate();
repaint();
}
});
this.add(button);
}
class DialogResult {
public String value;
}
class Dialog extends JDialog {
JTextField tf = new JTextField(20);
private DialogResult result = new DialogResult();
public Dialog() {
super();
init();
}
private void init() {
this.setModal(true);
this.setSize(new Dimension(100,100));
JButton ok = new JButton("ok");
ok.addActionListener( new ActionListener () {
#Override
public void actionPerformed(ActionEvent arg0) {
result = new DialogResult();
result.value = tf.getText();
setVisible(false);
}
});
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.add(tf);
p.add(ok);
this.add(p);
}
public DialogResult getDialogResult() {
return result;
}
}
}

How to Close JInternalFrame when JButton click and show another JInternalFrame?

For Example:
When JButton1 click JInternalFrame1 Show on the JDesktopPane
And when JButton2 Click JInternalFrame1 Close and JInternalFrame2 Show on the JDesktopPane.
thx before
Edit: with code from comment
if (JInternalFrame1 == null) {
JInternalFrame1 = new FJInternalFrame();
Desktop.add(JInternalFrame1);
JInternalFrame1.toFront();
} else {
JInternalFrame1.dispose();
}
Take a look at this example. I created a custom JInternalFrame that has a different title every time you create a new frame. when you click on the button, a new one is created and the old one disapears
Here is the important code that may help you out. I add a new frame if the desktop size is equal to 0, other wise I remove the previous one, add a new frame, and revalidate
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (desktop.getAllFrames().length == 0) {
desktop.add(new MyInternalFrame());
} else {
desktop.remove(0);
desktop.add(new MyInternalFrame());
revalidate();
repaint();
}
}
});
Here is the complete code. It's two different files.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class InternalFrameDemo1 extends JPanel {
JDesktopPane desktop;
JButton button;
public InternalFrameDemo1() {
desktop = new JDesktopPane();
button = new JButton("Get Next Frame");
setLayout(new BorderLayout());
add(desktop, BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (desktop.getAllFrames().length == 0) {
desktop.add(new MyInternalFrame());
} else {
desktop.remove(0);
desktop.add(new MyInternalFrame());
revalidate();
repaint();
}
}
});
}
public static void createAndShowGui() {
JFrame frame = new JFrame();
frame.add(new InternalFrameDemo1());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
import javax.swing.JInternalFrame;
public class MyInternalFrame extends JInternalFrame {
static int openFrameCount = 0;
static final int xOffset = 30, yOffset = 30;
public MyInternalFrame() {
super("Document #" + (++openFrameCount),
true, //resizable
true, //closable
true, //maximizable
true);//iconifiable
setSize(300,300);
setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
setVisible(true);
}
}

Attach action Event on JComboBox arrow JButton

I try to attach action Events on the JCombobox arrow JButton.
So I make a custom ComboBoxUI:
public class CustomBasicComboBoxUI extends BasicComboBoxUI {
public static CustomBasicComboBoxUI createUI(JComponent c) {
return new CustomBasicComboBoxUI ();
}
#Override
protected JButton createArrowButton() {
JButton button=super.createArrowButton();
if(button!=null) {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// arrow button clicked
}
});
}
return button;
}
}
The problem with this is that the look of combobox is different, seem to be an old look.
Why? I only add a listener to the same arrow button...
Thank.
Perhaps the problem is due to your expecting a JComboBox isn't a BasicComboBoxUI but one of another look and feel, perhaps a MetalComboBoxUI.
Rather than create a new CustomBasicComboBoxUI object, could you extract the JButton component from an existing JComboBox object? i.e.,
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ComboBoxArrowListener {
private static void createAndShowUI() {
String[] data = {"One", "Two", "Three"};
JComboBox combo = new JComboBox(data);
JPanel panel = new JPanel();
panel.add(combo);
JButton arrowBtn = getButtonSubComponent(combo);
if (arrowBtn != null) {
arrowBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("arrow button pressed");
}
});
}
JFrame frame = new JFrame("ComboBoxArrowListener");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static JButton getButtonSubComponent(Container container) {
if (container instanceof JButton) {
return (JButton) container;
} else {
Component[] components = container.getComponents();
for (Component component : components) {
if (component instanceof Container) {
return getButtonSubComponent((Container)component);
}
}
}
return null;
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}

Categories