我試圖做一個「句子隨機數發生器」,當按下按鈕時,通過從單獨的文件夾和單獨的文件中循環不同類型的單詞來製作語法正確的句子,這可能沒有任何意義。它也改變每個面板的顏色。我到目前爲止能夠讓JButton出現,但我似乎無法弄清楚如何讓面板出現?這是到目前爲止我的代碼的用戶界面:如何讓這些JLabel顯示在我的JFrame中?
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);
}
請不要命名您的變量是這樣的...你會後悔讓這個習慣,我保證 – nhouser9
見編輯回答 –