Come aggiungere JButton a GridLayout?
-
26-09-2019 - |
Domanda
Se ho il codice in questo modo:
class X extends JFrame
{
X()
{
setLayout(new GridLayout(3,3));
JButton b = new JButton("A-ha");
/*I would like to add this button in the center of this grid (2,2)*/
//How can I do it?
}
};
Soluzione
Come quello che so, è necessario compilare tutte le celle precedenti prima. Quindi è necessario aggiungere 4 componenti prima di poter aggiungere il componente centrale. Hmm, potrebbe essere un LayoutManager migliore.
Che cosa stai cercando di fare? Forse BorderLayout è quello che stai cercando?
Altri suggerimenti
Si potrebbe desiderare di dare un'occhiata alla GridBag layout
Questa centri verticalmente e orizzontalmente
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class centerbutton extends JFrame{
public centerbutton(){
setLayout(new BorderLayout());
JPanel panel = new JPanel();
JButton button = new JButton("A-ha!");
button.setAlignmentX(
Component.CENTER_ALIGNMENT);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(Box.createVerticalGlue());
panel.add(button);
panel.add(Box.createVerticalGlue());
getContentPane().add(panel);
setVisible(true);
}
public static void main(String[] args) {
new centerbutton();
}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow