How can I make this JButton work
I am working on a code that will generate a random number when you click a button and output that number. I wrote this code and it compiles, but when I click the button, nothing works. Can help someone. Here is my code.
public class slotmachine extends JApplet {
JButton b1 = new JButton("START");
JPanel p;
int Int1;
public slotmachine() {
init();
}
public void init() {
this.setLayout(null);
this.setSize(1000, 1000);
JButton b1 = new JButton("START");
b1.setBounds(100, 100, 100, 100);
getContentPane().add(b1);
repaint();
}
public void run() {
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Random random1 = new Random();
int Int1 = random1.nextInt(11);
}
});
}
public void paint(Graphics g) {
g.drawString("Your number is" + Int1, 30, 30);
}
}
source to share
- Avoid using layouts
null
, pixel perfect layouts are an illusion in modern ui design. There are too many factors that affect the individual size of components, none of which you can control. Swing was designed to work with layout managers in the kernel, dropping them away, there will be no end to problems and problems that you will spend more and more time fixing. - You are creating a local variable
Int1
within limitsActionListener
for the button. It has nothing to do withInt1
class. - You will never tell the UI to update
- You smash the paint chain without causing
super.paint
(be prepared for some serious weird and wonderful graphical glitches). - You made the same mistake with
b1
as you did withInt1
. You are creating an instance level field, but shading it to a local variable ininit
, which means when calledstart
,b1
-null
which will result inNullPointerxception
Add JLabel
to your applet instead , use it setText
to display a random value
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Random random1 = new Random();
int Int1 = random1.nextInt(11);
lable.setText(Integer.toString(Int1));
}
});
Also, if possible I would avoid using JApplet
, they have their own set of problems that can make life harder than it should be when learning the Swing API. Try using JPanel
for the main container instead and then add it to the instance JFrame
.
Also, take a look at:
- Understanding Class Members for more information on local and class / instance context for variables
- How to use shortcuts
- Why is he unhappy with the use of blank layout in SWING? and Stacking Components Inside a Container
- And if you're really curious about how painting works, Performing Custom Painting and Painting in AWT and Swing
for more details
source to share