Reputation: 105
I was able to create about 11 JButtons in a circle using this code......
public class Beginner extends JPanel {
private JButton quest;
public Beginner() {
int n = 10; //no of JButtons
int radius = 200;
Point center = new Point (250, 250);
double angle = Math.toRadians(360 / n);
List <Point> points = new ArrayList<Point> ();
points.add(center);
for (int i = 0; i < n; i++) {
double theta = i * angle;
int dx = (int) (radius * Math.sin(theta));
int dy = (int) (radius * Math.cos(theta));
Point p = new Point (center.x + dx , center.y + dy);
points.add(p);
}
draw (points);
}
public void draw (List<Point> points) {
JPanel panels = new JPanel();
SpringLayout spring = new SpringLayout();
int count = 1;
for (Point point: points) {
quest = new JButton("Question " + count); //JButton is drawn about 10 times in a circle arragement
quest.setForeground(Color.BLUE);
Font fonte = new Font("Script MT Bold", Font.PLAIN, 20);
quest.setFont(fonte);
add (quest);
count++;
;
spring.putConstraint(SpringLayout.WEST, quest, point.x, SpringLayout.WEST, panels );
spring.putConstraint(SpringLayout.NORTH, quest, point.y, SpringLayout.NORTH, panels );
setLayout(spring);
panels.setOpaque(false);
panels.setVisible(true);
panels.setLocation(10, 10);
add(panels);
}
}
}
Now, I have to create an actionListener for each JButton, and it is such each Button should be active only for one click, after which it changes its color to green!, I have no Idea on how to do that! Thanks for your help!
Upvotes: 1
Views: 4448
Reputation: 11
In the button's action listener try to do:
button.setEnabled(false);
It should work.
Upvotes: 1
Reputation: 1376
You should add a listener for all buttons:
METHOD 1:
quest.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
source.setEnabled(false);
source.setBackground(Color.GREEN);
}
});
METHOD 2:
quest.addActionListener(new DisableButtonActionListener());
...
private class DisableButtonActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
source.setEnabled(false);
source.setBackground(Color.GREEN);
}
}
METHOD 3 (my personal choise):
Beginner implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
source.setEnabled(false);
source.setBackground(Color.GREEN);
}
...
quest.addActionListener(this);
}
Upvotes: 3