Perché setPreferredSize non cambia le dimensioni del pulsante?
-
23-09-2019 - |
Domanda
Ecco il codice:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class TestGrid {
public static void main(String[] args) {
JFrame frame = new JFrame("Colored Trails");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 9));
panel.setMaximumSize(new Dimension(9*30-20,4*30));
JButton btn;
for (int i=1; i<=4; i++) {
for (int j=1; j<=4; j++) {
btn = new JButton();
btn.setPreferredSize(new Dimension(30, 30));
panel.add(btn);
}
btn = new JButton();
btn.setPreferredSize(new Dimension(30, 10));
panel.add(btn);
for (int j=1; j<=4; j++) {
btn = new JButton();
btn.setPreferredSize(new Dimension(30, 30));
panel.add(btn);
}
}
mainPanel.add(panel);
frame.add(mainPanel);
frame.setSize(450,950);
frame.setVisible(true);
}
}
Suppongo di avere una tabella di pulsanti con 4 righe e 9 colonne. E la colonna centrale dovrebbe essere più stretta che altre colonne. Provai Dimension(30, 10)
e Dimension(30, 10)
Entrambi non hanno alcun effetto sulla larghezza della colonna centrale. Come mai?
Soluzione
I gestori di layout sono liberi di ignorare la dimensione preferita. In particolare, GridLayout
Farà sempre ogni cella nella griglia esattamente delle stesse dimensioni (per questo motivo è un gestore di layout piuttosto inutile).
Dovrai utilizzare un gestore di layout diverso, come nidificato BoxLayout
o a GroupLayout
.
Altri suggerimenti
Per utilizzare i colori del web host dovrai caricare dinamicamente il foglio di stile del web dell'host con alcuni JavaScript.Se stai usando JQuery nella pagina, puoi utilizzare il seguente blocco di JavaScript per iniettare il foglio di stile del web host sulla tua pagina.
(function () {
// Retrieve the host web's URL from the query string
var scriptbase = $.queryString('SPHostUrl') + '/_layouts/15/';
// Create a <link> tag for the style sheet
var $doclink = $('link').attr('rel', 'stylesheet');
// The style sheet is loaded through an ASP.NET HTTP handler (defaultcss.ashx)
$doclink.attr('href', scriptbase + 'defaultcss.ashx');
// Add the style sheet link to the
$('head').append($doclink);
})();
.
Se ciò non funziona, è anche possibile controllare l'articolo di Microsoft Come: Utilizzare il foglio di stile del sito Web di SharePoint in app per SharePoint per un esempio che non richiede jQuery.
setPreferredSize
Non cambierà la dimensione del pulsante fino a quando la dimensione non viene impostata utilizzando la dimensione.
Esempio:-
Dimension dim = new Dimension(20,20), then use setPerferredSize(dim).
Ho trovato questa versione del metodo, che si adatta perfettamente alla tua soluzione:
.addComponent(<<a jButton instance>>, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, <<put here an integer to set you max width button size>>)