问题
I'm trying to do a program in Java that will make a button appears in a JPanel where and when it's clicked. To do that, I have the method run, with the following code:
public void run(){
panel.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e){
JButton button = new JButton();
button.setVisible(true);
button.setAlignmentX(e.getXOnScreen());
button.setAlignmentY(e.getYOnScreen());
panel.add(button);
panel.revalidate();
panel.repaint();
}
});
}
The problem is, nevermind where I click, the buttons never appears.
回答1:
This code should make a button appear when the panel is clicked. It will not make it appear at the cursor but that should be easy to add. It will also make a new button every time you click the panel. If you only want one button simply move this line JButton button = new JButton();
, outside of the mousePressed event
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 500);
JPanel panel = new JPanel();
panel.setSize(500, 500);
frame.add(panel);
frame.show();
run(panel);
}
public static void run(JPanel panel){
panel.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e){
JButton button = new JButton();
button.setVisible(true);
panel.add(button);
panel.revalidate();
}
});
}
回答2:
a button appears in a JPanel where and when it's clicked.
button.setAlignmentX(e.getXOnScreen());
button.setAlignmentY(e.getYOnScreen());
You are using a couple of incorrect methods.
To position a component in a panel you need to use:
button.setLocation(...);
However, you can't use the getXOnScreen() method because that is relative to the screen. You need to position the component relative to the panel. So instead you need to use:
button.setLocation(e.getX(), e.getY());
That is still not enough because when you use a null layout you also are responsible for determining the size of the component. So you would also need to use:
button.setSize( button.getPreferredSize() );
You also need to make sure the panel is using a null layout, otherwise the layout manager will override the size/location.
回答3:
This worked for me (even whithout adding buttons labels)
public static void main(String[] args) {
final JPanel panel = new JPanel();
JFrame frame = new JFrame("test swing");
frame.setAlwaysOnTop(true);
frame.setSize(400, 200);
frame.add(panel);
frame.setVisible(true);
panel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e){
JButton button = new JButton();
button.setVisible(true);
button.setAlignmentX(e.getXOnScreen());
button.setAlignmentY(e.getYOnScreen());
panel.add(button);
panel.revalidate();
panel.repaint();
}
});
}
来源:https://stackoverflow.com/questions/30465297/add-dynamic-buttons-to-jpanel-in-java