سؤال

JPanel droppan = new JPanel ();

droppan.setLayout (new FlowLayout ());


bi1 = new ImageIcon ("");
b1 = new JButton (bi1);
//b1.setBorderPainted (false);
b1.setBorder (BorderFactory.createEmptyBorder (2,3,2,3));
b1.setContentAreaFilled (false);
b1.setSize (100,38);
//b1.setBounds(3,3,100,38);

droppan.add(b1);
b1.addMouseListener (this);

add(droppan);

This is actually a row of buttons but the code above is just a snippet of the first button. Initially, the first button has a border unless I click on another button and then that button now has the border, as if it "transfers" if you get what I mean.

What am I doing wrong? the setborderpainted is a comment because even if it's not in a comment the border is still there

This is a panel inside a frame

هل كانت مفيدة؟

المحلول

I "think" what your talking about is the focus border used to show which button has focus...

Try using b1.setFocusPainted(false); instead

For example...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ButtonRows {

    public static void main(String[] args) {
        new ButtonRows();
    }

    public ButtonRows() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new FlowLayout());

                for (int index = 0; index < 10; index++) {
                    JButton b1 = new JButton(Integer.toString(index));
                    b1.setFocusPainted(false);
                    b1.setBorder(BorderFactory.createEmptyBorder(2, 3, 2, 3));
                    b1.setContentAreaFilled(false);

                    frame.add(b1);
                }

                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

Also, the use of setSize and setBounds is scary, you should be letting the layout manager deal with these details.

I don't know why you're using a MouseListener on button, but the prefered method for gaining notification for when a button is triggered is through the ActionListener interface, as a button my a triggered via a number means, not just the mouse click

Take a closer look at How to Use Buttons for more details

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top