我完全新的在Java中使用的图形用户界面,所以我有一点麻烦搞清楚如何使我需要的一切。我要在我的JFrame面板,我需要对齐(其中一个向左,一个向右)和我需要在面板为中心的面板之一几个按钮。这是我的代码。我该如何调整在JPanels/JFrames元素?
package application;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.nio.*;
import java.util.*;
public class Main extends JPanel
{
public static void main(String[] args)
{
//set the ui to the native OS
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e)
{
}
JFrame frame = new JFrame("Application Name");
Menu menu = new Menu();
JPanel iconPanel = new JPanel();
final JPanel grid = new JPanel(new FlowLayout());
JButton firewallButton = new JButton("Firewall");
JButton networkButton = new JButton("Network");
JButton printerButton = new JButton("Printer");
int iconPanelSizeX;
int iconPanelSizeY;
int gridSizeX;
int gridSizeY;
int gridPosition;
//frame setting
frame.setSize(800, 600);
frame.setMinimumSize(new Dimension(800, 600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
//add grid and iconPanel JPanels to the frame
frame.add(iconPanel);
iconPanel.add(firewallButton);
iconPanel.add(networkButton);
iconPanel.add(printerButton);
frame.add(grid);
//iconPanel settings
iconPanel.setBorder(BorderFactory.createLoweredSoftBevelBorder());
iconPanel.setBackground(Color.gray);
iconPanel.setLayout(new FlowLayout());
iconPanel.setSize(new Dimension(100, 600));
iconPanel.setVisible(true);
//grid setting
grid.setBackground(Color.red);
grid.setSize(new Dimension(700, 600));
grid.setVisible(true);
//this is for resizing components when the user resizes the window
int counter = 0;
while(counter == 0)
{
firewallButton.setSize(new Dimension(iconPanel.getWidth(), 50));
networkButton.setSize(new Dimension(iconPanel.getWidth(), 50));
printerButton.setSize(new Dimension(iconPanel.getWidth(), 50));
iconPanelSizeX = frame.getWidth()/10;
iconPanelSizeY = frame.getHeight();
gridSizeX = (frame.getWidth()/10) * 9;
gridSizeY = frame.getHeight();
iconPanel.setSize(new Dimension(iconPanelSizeX, iconPanelSizeY));
grid.setSize(new Dimension(gridSizeX, gridSizeY));
}
}
}
正如你可以看到,第二的JPanel(网格)不与帧的右侧排队,和内部iconTray的按钮不能任一中心。我意识到这些都可能是简单的布局修复,但我不知道从哪里开始。
谢谢,这帮助了很多。实际上有一件事我忘了问,那就是如何垂直对齐按钮 - 我必须稍后添加一些按钮。 – user2067364 2013-02-17 23:07:33
用于'pack()'的+1;更多[这里](http://stackoverflow.com/a/14927280/230513)。 – trashgod 2013-02-17 23:21:01
您将不得不使用其他布局管理器。对于非常基本的对齐,你可以使用'GridLayout'或'BoxLayout',但对于更复杂的东西,我建议使用'GridBadLayout'或'MiGLayout'。只是谷歌。 – 2013-02-17 23:21:07