如何在另一个类中应用Java Swing?

huangapple go评论105阅读模式
英文:

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&#39;m not quite sure what I am doing wrong here, as I&#39;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>



huangapple
  • 本文由 发表于 2020年10月27日 18:47:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64552780.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定