英文:
How to apply Java Swing in a different class?
问题
我有两个不同的类,
主窗口:
```java
package opdracht4;
public class Opdracht4 {
public static void main(String[] args) {
new App();
}
}
而这个类是
package opdracht4;
import javax.swing.*;
public class App() {
JFrame app = new JFrame();
JPanel paneel = new JPanel();
paneel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
}
我不太确定我在这里做错了什么,因为我在Java方面不是很擅长,所以有谁能告诉我第二个类中第5行是什么问题吗?
<details>
<summary>英文:</summary>
I have 2 different classes,
Main window:
package opdracht4;
public class Opdracht4 {
public static void main(String[] args) {
new App();
}
}
And this class
package opdracht4;
import javax.swing.*;
public class App() {
JFrame app = new JFrame();
JPanel paneel = new JPanel();
paneel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
}
I'm not quite sure what I am doing wrong here, as I'm not the best in Java, so could anyone tell me whats wrong at line 5 in the second class?
</details>
# 答案1
**得分**: 2
paneel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
这行代码位于任何方法之外,您需要向类App
添加一个构造函数,例如:
public App(){
paneel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
app.setVisible(true);// 用于显示JFrame
}
<details>
<summary>英文:</summary>
The line `paneel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));` is out of any method, you need to add a constructor to the class `App`, for example:
public App(){
paneel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
app.setVisible(true);// to display the JFrame
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论