我是 Swing 新手,谁能帮我解决这个问题...
它没有显示我的“标签”,而是仅显示“面板”类中的组件。
还有一个问题,谁能帮我解释一下 LayoutManagers 吗? 一个框架中可以使用 2 个或更多 LayoutManager 吗?就像我将使用 FlowLayout 的框架一样,我将一个 JPanel 添加到我将使用 BoxLayout 的框架中......首先有可能吗?
import javax.swing.*;
import java.awt.event.*;
import java.awt.Graphics;
public class JForm1 extends JFrame
{
public JForm1()
{
init();
}
public static void main(String[] args)
{
JForm1 form = new JForm1();
}
public void init()
{
JFrame frame = new JFrame("My Form 1");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
JLabel label = new JLabel("Enter your Name : ");
panel MyPanel = new panel();
frame.getContentPane().add(label);
frame.getContentPane().add(MyPanel);
frame.setVisible(true);
}
}
class panel extends JPanel implements ActionListener
{
JButton submitButton;
JTextField text;
panel()
{
this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
}
public void paintComponent(Graphics g)
{
text = new JTextField("Enter Name here");
text.setSize(100,25);
submitButton = new JButton("Submit");
submitButton.setSize(50,90);
submitButton.setBounds(200, 0, 80, 80);
submitButton.addActionListener(this);
this.add(text);
this.add(submitButton);
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==submitButton)
{
System.out.println("The Entered Name is : "+text.getText());
}
}
}
最佳答案
这是什么?:
public void paintComponent(Graphics g)
{
text = new JTextField("Enter Name here");
text.setSize(100,25);
submitButton = new JButton("Submit");
submitButton.setSize(50,90);
submitButton.setBounds(200, 0, 80, 80);
submitButton.addActionListener(this);
this.add(text);
this.add(submitButton);
}
这段代码与paintComponent
无关。 paintComponent
是关于“绘制组件”,即绘制一个矩形、绘制一条线、填充一个椭圆形等...这绝对不是添加组件的地方。相反,请在构造函数中调用该代码。
此外,如果您正在使用 LayoutManager(您应该这样做),则调用 setSize/setBounds/setLocation
是没有用的(隐含地删除这些调用)。
还有一些事情:
- 如果您重写
paintComponent
,请确保调用super
方法 - 如果不需要,就不要扩展
JFrame
(这里显然不需要) - 遵循 Java 命名约定(类名应以大写字母开头,变量和方法应以小写字母开头)
- 所有与 Swing 相关的代码都必须在 EDT 上调用。在
SwingUtilities.invokeLater()
block 中启动您的 UI。
关于java - 为什么它没有显示我的标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16790662/