Up/Down Write a WidgetView GUI that has the following widgets: a button labeled
ID: 3778491 • Letter: U
Question
Up/Down
Write a WidgetView GUI that has the following widgets:
a button labeled "go up/down"
a label initialized to 0 (we'll call this the left label)
a label initialized to 0 (we'll call this the right label)
a button labeled "go down/up"
When the "go up/down" button is pushed, a random number between 1 and 10 (inclusive) is generated and added to the left label, and another random number between 1 and 10 (inclusive) is generated and subtracted from the right label.
When the "go down/up" button is pushed, a random number between 1 and 10 (inclusive) is generated and subtracted from the left label, and another random number between 1 and 10 (inclusive) is generated and added to the right label.
Explanation / Answer
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class UpDown{
private static JFrame mainFrame;
private static JLabel leftLabel;
private static JLabel rightLabel;
private static JButton downupButton;
private static JButton updownButton;
private static JPanel controlPanel;
static int leftval=0;
static int rightval=0;
public static void main(String[] args) {
mainFrame = new JFrame("Up/Down");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
leftLabel = new JLabel("", JLabel.CENTER);
rightLabel = new JLabel("", JLabel.CENTER);
leftLabel.setSize(350,100);
rightLabel.setSize(350,100);
downupButton = new JButton("go down/up");
downupButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Random random = new Random();
int rand = random.nextInt(10) + 1;
leftval -= rand;
String val = Integer.toString(leftval);
leftLabel.setText(val);
rand = random.nextInt(10) + 1;
rightval += rand;
val = Integer.toString(rightval);
rightLabel.setText(val);
}
});
updownButton = new JButton("go up/down");
updownButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Random random = new Random();
int rand = random.nextInt(10) + 1;
leftval += rand;
String val = Integer.toString(leftval);
leftLabel.setText(val);
rand = random.nextInt(10) + 1;
rightval -= rand;
val = Integer.toString(rightval);
rightLabel.setText(val);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(leftLabel);
mainFrame.add(controlPanel);
mainFrame.add(rightLabel);
mainFrame.setVisible(true);
controlPanel.add(updownButton);
controlPanel.add(downupButton);
mainFrame.setVisible(true);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.