Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my second button show in Java

Tags:

java

button

swing

I am having a problem with my code. For some reason, it won't show my second button b2, and I can't set the size for the first button. I want to have both buttons next to each other in the middle with some space around them.

import java.awt.*;
import java.awt.event.*;

import javax.swing.JFrame;

public class HW10{
    Button b1, b2;
    L1 l1;
    class L1 implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            int tmp = Integer.parseInt(b1.getLabel());
            tmp++;
            b1.setLabel(""+tmp);
        }
        
    }
    public HW10(){
        JFrame frame = new JFrame("Homework 15");
        l1 = new L1();
        b1 = new Button("0");
        b2 = new Button("KURAC");
        b1.addActionListener(l1);
        b1.setBounds(100, 100, 100, 80);
        frame.add(b1);
        frame.setBounds(200,200,400,400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        HW10 kk = new HW10();
    }

}
like image 592
iSoulFeed1g Avatar asked Sep 04 '26 18:09

iSoulFeed1g


1 Answers

The other answers are correct that you don't add the second button at all, however, you shouldn't add components to frames directly. What you want to do is

frame.getContentPane().add(button1);
frame.getContentPane().add(button2);

You should also probably be setting a layout manager to the pane.

like image 139
daniu Avatar answered Sep 07 '26 07:09

daniu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!