问题
I have a class named BoardGUI extended from JFrame, in a constructor I have made a JPanel with two buttons in it. I have added this panel into my frame. Whenever I run this program, buttons get invisible. As I bring my mouse cursor over the buttons they get visible. Code is as follows:
public class BoardGUI extends JFrame {
Play pieces;
JButton a=new JButton("Undo");
JButton r=new JButton("replay");
JPanel jp=new JPanel();
public BoardGUI() {
pieces = new Play();
setTitle("Checkers Game");
setSize(645, 700);
setVisible(true);
jp.setLayout(new FlowLayout());
jp.setPreferredSize(new Dimension(645,35));
a.setVisible(true);
r.setVisible(true);
jp.add(a);
jp.add(r);
add(jp,BorderLayout.SOUTH);
I am also using repaint method in my program. Can anybody point out my mistake and suggest any solution for this?
回答1:
I have a class named BoardGUI extended from JFrame, in a constructor i have made a JPanel with two buttons in it. I have added this panel into my frame. Whenever i run this program, buttons get invisible. As i bring my mouse cursor over the buttons they get visible.
setVisible(true);should be last code line in constructor, because you addedJComponentsto the already visibleJFrame,or to call
revalidate()andrepaint()in the case thatJComponentsare added to visible Swing GUIthere no reason to call
a.setVisible(true);orr.setVisible(true);for standardJComponents, becauseJComponentsarevisible(true)by default in comparing withTop Level Containers, there you need to callJFrame/JDialog/JWindow.setVisible(true);
EDIT
(i used the very first suggestion you gave. problem remains the same.) - for example
from code
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyGridLayout {
private JFrame frame = new JFrame("GridLayout, JButtons, etc... ");
private JPanel panel = new JPanel(new GridLayout(8, 8));
public MyGridLayout() {
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
JButton button = new JButton("(" + (row + 1) + " / " + (col + 1) + ")");
button.putClientProperty("column", col);
button.putClientProperty("row", row);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
System.out.println(
"clicked column : "
+ btn.getClientProperty("column")
+ ", row : " + btn.getClientProperty("row"));
}
});
panel.add(button);
}
}
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MyGridLayout myGridLayout = new MyGridLayout();
}
});
}
}
来源:https://stackoverflow.com/questions/21112572/how-to-set-a-jpanel-over-a-jframe