[英]How to Get these JLabels to be Displayed in my JFrame?
我試圖制作一個“句子隨機化器”,通過按下一個單獨的文件夾和單獨的文件中的不同類型的單詞,使按下按鈕時的語法正確的句子變得毫無意義。 它還在每個面板中交替顯示顏色。 到目前為止,我可以顯示JButton,但似乎無法弄清楚如何顯示面板? 到目前為止,這是我的用戶界面代碼:
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);
}
您要將topPanel兩次添加到JFrame,在這里
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.