我在 Java Swing 中编码,出于某种原因,当我将两个元素添加到网格布局时,它们都假定相同的位置。我曾尝试将其简化为不会失败的东西,然后从那里开始构建,但是唉,它仍然无法正常工作。
程序中的行为不端代码是:
bodyPanelMain.setLayout(new GridLayout(4, 1, 10, 10));
JTextArea one = new JTextArea("Hi");
one.setLineWrap(true);
one.setSize(100, 100);
JTextArea two = new JTextArea("Goodbye");
two.setLineWrap(true);
two.setSize(100, 100);
bodyPanelMain.add(one);
bodyPanelMain.add(two);
bodyPanelMain.repaint();
如果我将 JTextArea 的宽度设置为 200 并将背景设置为不同的颜色,很明显它在它后面是可见的,所以它肯定是添加了所有正确的元素,它们的位置是错误的。
编辑:这是我正在尝试做的一个非常非常简短的版本。
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class minimessageboard extends Applet implements ActionListener {
JPanel mainPanel;
JPanel buttonPanel;
JButton announcements, websites;
JPanel bodyPanel, bodyPanelMain;
public minimessageboard() {
this.setSize(600, 400);
mainPanel = new JPanel(new BorderLayout());
mainPanel.setPreferredSize(new Dimension(this.getWidth(), this.getHeight()));
this.add(mainPanel);
buttonPanel = new JPanel(new GridLayout(6, 1, 10, 10));
mainPanel.add(buttonPanel, BorderLayout.WEST);
announcements = new JButton("Announcements");
this.formatButton(announcements);
announcements.setActionCommand("announcements");
buttonPanel.add(announcements);
websites = new JButton("Websites");
this.formatButton(websites);
websites.setActionCommand("websites");
buttonPanel.add(websites);
bodyPanel = new JPanel(new BorderLayout());
bodyPanel.setSize(200, 500);
bodyPanel.setPreferredSize(new Dimension(200, 500));
mainPanel.add(bodyPanel, BorderLayout.CENTER);
bodyPanelMain = new JPanel(new BorderLayout());
bodyPanel.add(bodyPanelMain, BorderLayout.CENTER);
bodyPanelMain.setLayout(new GridLayout(4, 1, 10, 10));
JButton one = new JButton("Roar");
bodyPanelMain.add(one);
bodyPanelMain.revalidate();
bodyPanelMain.repaint();
}
public static void main(String args[]) {
JFrame overall = new JFrame();
overall.pack();
overall.setVisible(true);
overall.add(new minimessageboard());
}
public void formatButton(JButton b){
b.setPreferredSize(new Dimension(150, 33));
b.addActionListener(this);
}
public void actionPerformed(ActionEvent arg0) {
String action = arg0.getActionCommand();
bodyPanelMain.removeAll();
if (action.equals("websites")){
System.out.println("Fires!");
bodyPanelMain.setLayout(new GridLayout(4, 1, 10, 10));
JButton one = new JButton("Hi");
JButton two = new JButton("Goodbye");
bodyPanelMain.add(one);
bodyPanelMain.add(two);
bodyPanelMain.revalidate();
}
bodyPanelMain.repaint();
}
}
基本上,当您点击网站时,应该会出现“Hi”和“Bye”。如果我将网站 if 语句 (if (action.equals("websites")) 中的代码块内的代码移动到原始构造函数,它看起来非常好。代码输出“Fires!”,所以我 100% 确定它到达那部分。注意,我将它从 JTextArea 更改为 JButton,因为我将使用 JButtons,而不是 JTextArea。