我用
Java创建了一个简单的菜单,但我无法弄清楚如何更改按钮的大小.
我的菜单看起来像这样:
我的菜单看起来像这样:
我希望最后一个按钮与其他按钮一样大小.
tlacTisk.setSize(10,10); tlacTisk.setPreferredSize(10,10);
不起作用.
代码,我创建按钮和框:
JButton tlacSVG = new JButton(); tlacSVG.setText("Export do SVG"); tlacSVG.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { exportujSVG(); } }); JButton tlacPNG = new JButton(); tlacPNG.setText("Export do PNG"); tlacPNG.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { exportujPNG(); } }); JButton tlacTisk = new JButton(); tlacTisk.setText("Tisk..."); tlacTisk.setPreferredSize(new Dimension(50,25)); tlacTisk.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { tiskni(); } }); Box BoxTlacitek = Box.createVerticalBox(); BoxTlacitek.add(Box.createVerticalStrut(5)); BoxTlacitek.add(tlacSVG); BoxTlacitek.add(Box.createVerticalStrut(10)); BoxTlacitek.add(tlacPNG); BoxTlacitek.add(Box.createVerticalStrut(10)); BoxTlacitek.add(tlacTisk); BoxTlacitek.setBorder(BorderFactory.createTitledBorder("Menu")); okno.add(BoxTlacitek,BorderLayout.EAST);
你能告诉我如何改变尺寸吗?谢谢.
解决方法
不同的布局管理器以不同方式处理首选大另外,使用setSize()设置大小不是一个好主意.让布局管理器为您做布局.有关更多详细信息和示例,请参见
A Visual Guide to Layout Managers.
例如,您可以创建一个包含按钮的单独面板.将其布局设置为GridLayout.在此布局中,组件占用其单元中的所有可用空间,并且每个单元的大小完全相同.将此面板添加到容器中.有关示例,请参见How to Use GridLayout.
这是GridLayout和GridBagLayout的简单演示:
import java.awt.*; import javax.swing.*; public class DemoButtons { public DemoButtons() { final JFrame frame = new JFrame("Demo buttons"); frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); JPanel buttonPanel = new JPanel(new GridLayout(3,1)); buttonPanel.add(new JButton("Export do SVG")); buttonPanel.add(new JButton("Export do PNG")); buttonPanel.add(new JButton("Tisk...")); JPanel east = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.NORTH; gbc.weighty = 1; east.add(buttonPanel,gbc); JPanel center = new JPanel(){ @Override public Dimension getPreferredSize() { return new Dimension(200,200); } }; center.setBorder(BorderFactory.createLineBorder(Color.BLACK)); frame.add(east,BorderLayout.EAST); frame.add(center); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new DemoButtons(); } }); } }