I want to code a little tool that simulates a deterministic, finite automaton (like JFLAP) for myself.
My JFrame
is just blank. How can I let the user place buttons on left click? And how do I assign the right values to that button (like which function to call when pressed).
I know I can place a button with
JButton button = new JButton("Press me");
frame.add(button);
But I don't know how I could dynamically code that.
Any help is welcome. Also if you think it's stupid to solve my problem with buttons, I'd like to hear suggestions for improvement.
The following code will add a JButton
to a "blank" JFrame
every time the mouse is clicked inside the JFrame
. The JButton
will be placed where the mouse click occurred. The JButton
text will be a number. Each JButton
will display a different number.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class AdButton extends MouseAdapter implements Runnable {
private int counter;
private JFrame frame;
private JPanel contentPane;
public void mouseClicked(MouseEvent event) {
int x = event.getX();
int y = event.getY();
JButton button = new JButton(String.valueOf(++counter));
Dimension dim = button.getPreferredSize();
button.setBounds(x, y, dim.width, dim.height);
contentPane.add(button);
contentPane.revalidate();
contentPane.repaint();
}
@Override
public void run() {
showGui();
}
private void showGui() {
frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
contentPane = (JPanel) frame.getContentPane();
contentPane.setLayout(null);
contentPane.addMouseListener(this);
frame.setSize(400, 450);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new AdButton());
}
}