我正在尝试制作一个"句子随机器",当按下按钮时,通过循环来自单独文件夹和单独文件的不同类型的单词,生成语法正确的句子,这可能没有任何意义。它还可以在每个面板上更换颜色。到目前为止,我能够让JButton显示,但我似乎不知道如何让面板显示?下面是我到目前为止编写的UI代码:
package user_interface;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import code.sentence;
import user_interface.RandomButtonListener;
public class sentenceUI {
private sentence _s;
private JButton _rando;
public sentenceUI() {
_s = new sentence(this);
JFrame f = new JFrame("Ryan Ellis' Lab 9");
f.setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));
JPanel topPanel = new JPanel();
f.add(topPanel);
JPanel lowerPanel = new JPanel();
f.add(lowerPanel);
_rando = new JButton("Random Sentence");
_rando.addActionListener(new RandomButtonListener(_s, this));
lowerPanel.add(_rando);
Color c1 = Color.BLUE;
Color c2 = new Color( 255 - c1.getRed(), 255 - c1.getGreen(), 255 - c1.getBlue());
for(int i = 0; i < 8; i++){
JLabel _l = new JLabel();
_l.setBackground(c1);
_l.setForeground(c2);
Color temp = c1;
c1 = c2;
c2 = temp;
_l.setBorder(BorderFactory.createEmptyBorder(0,0,8,5));
_l.setFont(new Font("Comic Sans", Font.BOLD, 18));
topPanel.add(_l);
}
ArrayList<String> _slst = new ArrayList<String>();
_slst.add("WordLists/adjectives.txt");
_slst.add("WordLists/adverbs.txt");
_slst.add("WordLists/determiners.txt");
_slst.add("WordLists/nouns.txt");
_slst.add("WordLists/verbs.txt");
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
list.add(_slst);
int i = 0;
list.get(i % 5);
f.add(topPanel, BorderLayout.PAGE_START);
f.add(lowerPanel, BorderLayout.PAGE_END);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
}
private void createRButton(String string, JPanel lowerPanel) {
createRButton("Random", lowerPanel);
}
你在JFrame中添加了两次topPanel,这里
JPanel topPanel = new JPanel();
f.add(topPanel);
和这里:
f.add(topPanel, BorderLayout.PAGE_START);
f.add(lowerPanel, BorderLayout.PAGE_END);
,在第二次添加,你添加它,如果JFrame当前使用的是一个BorderLayout,但它不是,因为你给了它一个BoxLayout。
相反,只添加一次topPanel,并以逻辑的方式。也考虑给你的JLabel一些虚拟文本,比如" "
,这样当你第一次pack()
你的GUI时,它们有一些大小。
同样,你的标签正在添加,但它们没有大小,并且是非不透明的,因此无法看到。例如,在For循环中试试下面的代码:
JLabel _l = new JLabel("Label " + i); // to give labels size
_l.setOpaque(true); // so you can see the background color
_l.setBackground(c1);
_l.setForeground(c2);