【发布时间】:2014-03-23 15:59:30
【问题描述】:
我正在尝试使用 GridBagLayout 定位多个组件,但我有点困惑。当我尝试定位它们时,它们不会移动,只会创建几列。我尝试过使用空布局,但每次都会受到惩罚。
这是我的代码:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
public class Main
{
JFrame window = new JFrame("PE Fixture"); //JFrame variables
JPanel container = new JPanel();
JPanel guestFixturesPanel = new JPanel();
JLabel guestFixturesTitle = new JLabel("FIXTURES");
JButton loginButton = new JButton("Login");
JSeparator southBar1 = new JSeparator(JSeparator.HORIZONTAL);
JSeparator southBar2 = new JSeparator(JSeparator.HORIZONTAL);
JTable listTable = new JTable();
CardLayout cardLayout = new CardLayout();
GridLayout layout = new GridLayout();
public Main()
{
container.setLayout(cardLayout);
guestFixturesPanel.setLayout(layout); //GUEST FIXTURES PANEL COMPONENTS
GridBagConstraints c = new GridBagConstraints();
guestFixturesTitle.setBounds(120, 20, 500, 50);
guestFixturesTitle.setFont(new Font("TimesRoman", Font.PLAIN, 50));
guestFixturesTitle.setForeground(Color.WHITE);
c.fill = GridBagConstraints.PAGE_START;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
guestFixturesPanel.add(guestFixturesTitle, c);
southBar1.setBounds(0, 760, 500, 10);
northBar1.setBounds(0, 80, 500, 10);
listTable = new JTable(data, columns)
{
public boolean isCellEditable(int data, int columns) //Makes cells editable false by anyone
{
return false;
}
};
listTable.setPreferredScrollableViewportSize(new Dimension(450, 750));
listTable.setFillsViewportHeight(false);
listTable.setBounds(22, 100, 450, 640);
JScrollPane scroll = new JScrollPane(listTable);
listTable.setBackground(Color.LIGHT_GRAY);
c.fill = GridBagConstraints.CENTER;
guestFixturesPanel.add(scroll, c);
loginButton.setBounds(330, 770, 150, 50);
c.fill = GridBagConstraints.LAST_LINE_END;
guestFixturesPanel.add(loginButton, c);
container.add(guestFixturesPanel, "2");
cardLayout.show(container, "1");
window.add(container); //Creates the frame of the program.
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(500, 860);
window.setResizable(false);
window.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Main();
}
});
}
}
【问题讨论】:
-
您的代码不完整。请提供实际代码。告诉您问题出在哪里会更容易。
-
这应该可以了,我刚刚删除了与问题相关的所有不必要的代码
-
southBar1、northBar1、listTable 和 loginButton 缺少它们的声明。代码不会编译。
-
我很困惑:1)你不使用 GridBagLayout(至多是一个完全不同的动物的 GridLayout)2)你的很多代码都没有让它编译(我们不讨论关于运行它) 3)您调用 setBounds 但将所有内容放入具有 LayoutManager 的容器中(即,您正试图与 LayoutManager 对抗)。尝试做一个更一致的例子,并从停止调用 setBounds 开始:放弃那个糟糕、不健康和讨厌的习惯。
-
忘记使用所谓的“空布局”吧,你应该总是,我的意思是总是,使用 LayoutManager。您的代码中还有其他问题,但 GridLayout 肯定看起来像一个。我不确定您要做什么,所以我现在无法给出更好的答案。确保如果您回答某人的评论,则在您的评论中添加“@somebody”之类的内容。人们不会经常轮询您的帖子以查看您是否更新了它。
标签: java swing jframe layout-manager