[英]Cannot add JLabel or JButton to a JFrame. The frame won't show it
我是 Java 的新手。 我正在嘗試將JLabel
添加到JFrame
但它沒有顯示。 我也嘗試過添加JButton
,但它似乎不起作用。 在過去的幾天里,我嘗試了很多東西。
我的代碼有什么問題嗎?
public class F2 extends JPanel implements ActionListener {
JFrame frame = new JFrame();
JLabel label = new JLabel();
int j = 2;
ArrayList<Person> people = new ArrayList<>();
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
F2 f = new F2();
}
public F2() {
j++;
frame = new JFrame();
frame.setSize(1380, 728);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Timer t = new Timer(20, this);
t.restart();
label.setText("Test");
add(label);
frame.pack();
frame.add(this);
frame.setVisible(true);
for (int i = 0; i < 100; i++) {
people.add(new Person(0));
}
}
public void paint(Graphics g) {
super.paintComponent(g);
Places p1 = new Places(g);
for (Person p : people) {
p.paint(g); //recall that each Person object has a paint method. We're passing g as the argument
}
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
復制 Alex Rudenko 的回答:
您應該已將 label 添加到您的面板,然后將您的面板添加到框架中。 現在您的空面板替換了 label。
this.add(label)
frame.add(this)
也許讓它也可見並使用坐標和大小......或者只是從互聯網上復制預制代碼......您在主要 class 中使用 jpanel 的方式可能會讓您感到困惑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.