[英]unable to get java swing components
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import java.awt.BorderLayout;
public class Fram {
public static void main(String[] args) {
JTextArea map;
JButton btn;
map= new JTextArea();
btn= new JButton("hello");
JFrame frame= new JFrame("jarvis");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,600);
frame.setLayout(new BorderLayout());
frame.add(map, BorderLayout.CENTER);
frame.add(btn, BorderLayout.SOUTH);
}
}
我正在使用此代码来获取文本区域,但我只获得没有任何文本区域或按钮的框架。
你的代码对我有用。 我添加了一些你遗漏的东西。
首先,您必须通过调用 SwingUtilities invokeLater 来启动所有 Swing 应用程序。 这可确保您的 Swing 组件在事件调度线程(EDT) 上定义和执行。
其次,我最后移动了框架 setVisible 方法。 在使其可见之前,您需要完全设置 JFrame。
这是修改后的代码:
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class Fram implements Runnable {
@Override
public void run() {
JTextArea map;
JButton btn;
map = new JTextArea();
btn = new JButton("hello");
JFrame frame = new JFrame("jarvis");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setLayout(new BorderLayout());
frame.add(map, BorderLayout.CENTER);
frame.add(btn, BorderLayout.SOUTH);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Fram());
}
}
你没有设置按钮的大小。它可以在中心或南方,但你应该声明它的大小。 所以我更喜欢你btn.setBounds(0,0,100,20)
如果那不起作用你可以删除 BorderLayour.CENTER 并设置边界 200,280
你的代码对我来说也很好。 您提到you can not see swing component
我认为您没有按预期看到文本区域的原因是因为该文本区域占据了边框布局中的完整空间,因此您无法辨别是否有文本区域。 因此,我在您的代码中添加了 JPanel 和 JscrollPane 以改进行为。 我还想调用 setVisible 作为最后一个方法,正如 Gilbert 所提到的,您必须通过调用 SwingUtilities invokeLater 来启动所有 Swing 应用程序。
package stackOverFlow;
import java.awt.BorderLayout;
public class Frame implements Runnable {
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Frame());
}
@Override
public void run() {
JTextArea map;
JButton btn;
JLabel lbl;
map = new JTextArea(10, 50);
final JScrollPane scrollPanel = new JScrollPane(map);
btn = new JButton("hello");
lbl = new JLabel("Text Area: ");
final JPanel actionPanel = new JPanel(
new FlowLayout(FlowLayout.LEADING));
actionPanel.add(lbl);
actionPanel.add(scrollPanel);
final JFrame frame = new JFrame("jarvis");
frame.setLayout(new BorderLayout());
frame.add(actionPanel, BorderLayout.CENTER);
frame.add(btn, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setVisible(true);
}
}
程序的输出是
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.