英文:
Cannot add JLabel or JButton to a JFrame. The frame won't show it
问题
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();
}
}
英文:
I'm new to Java. I'm trying to add JLabel
to a JFrame
but it doesn't show. I've tried adding JButton
also but it does't seem to work. I've tried so many things over the past few days.
Anything wrong with my code?
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();
}
}
</details>
# 答案1
**得分**: 0
复制Alex Rudenko的回答:
您应该将标签添加到面板,然后将面板添加到框架中。现在您的空面板替代了标签。
```java
this.add(label);
frame.add(this);
也许还可以使其可见,并调整坐标和大小... 或者直接从互联网上复制预先制作好的代码... 您在主类中使用jpanel的方式可能会让您感到困惑。
英文:
Copying Alex Rudenko answer:
You should have added the label to your panel and then add your panel to the frame. Now your empty panel replaces the label.
this.add(label)
frame.add(this)
Maybe make it also visible and play with the coordinates and the size... or just copy a premade code from the internet... the way you are using the jpanel in the main class is maybe confusing you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论