简体   繁体   English

如何从Jbutton actionlistener创建JLabel实例?

[英]How to create a JLabel instance from Jbutton actionlistener?

I'm trying to create a JLabel WITHIN the actionlistener event so please don't post any new jlabel(); 我试图创建一个JLabel ActionListener的事件,所以请不要发布任何新的JLabel(); instances outside of the actionlistener event. actionlistener事件之外的实例。 Main is the JFrame and Credits is the Jbutton and Oracle is the instance Jlabel i want to create. Main是JFrame,Credits是Jbutton,Oracle是我要创建的实例Jlabel。

Here is the code: 这是代码:

 Credits.addActionListener(new ActionListener() {
    public  void actionPerformed (ActionEvent e)
    { 
      JLabel Oracle = new JLabel();
      Oracle.setBounds(100,300,300,300);
      Oracle.setText("HI");
     Main.add(Oracle);
     }
 });

Suggestions: 意见建议:

  • First and foremost, don't set the bounds of anything. 首先,不要设定任何界限。 Using setBounds(...) suggests that you're using null layouts, often a sign of a newbie Swing program, and those programs are very rigid, hard to update, enhance and debug. 使用setBounds(...)表示您使用的是空布局,通常是新手Swing程序的标志,并且这些程序非常严格,难以更新,增强和调试。 Use the layout managers instead. 请改用布局管理器。
  • Next the layout manager of the container (here "Main") that is accepting the JLabel is key. 接下来,接受JLabel的容器(这里是“ Main”)的布局管理器是关键。 Some don't take too well to added components, for example GroupLayout, while others do better, such as BoxLayout. 有些组件不能很好地添加组件,例如GroupLayout,而其他组件则更好,例如BoxLayout。
  • Call revalidate() and repaint() on your container after adding or removing components. 添加或删除组件后,在容器上调用revalidate()repaint()
  • As a side recommendation (one not directly affecting your problem), to help us now and to help yourself in the future, please edit your code and change your variable names to conform with Java naming conventions : class names all start with an upper-case letter and method/variable names with a lower-case letter. 作为辅助建议(一个不直接影响您的问题的建议),为了现在对我们有所帮助,并在将来对您有所帮助,请编辑代码并更改变量名以符合Java命名约定 :类名均以大写字母开头字母和带有小写字母的方法/变量名称。
  • If you still need more help, consider creating and posting a minimal example program . 如果您仍然需要更多帮助,请考虑创建并发布一个最小的示例程序

For example, code with explanatory comments: 例如,带有解释性注释的代码:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class AddALabel extends JPanel {
   private static final int PREF_W = 300;
   private static final int PREF_H = 300;

   // The JPanel that gets the JLabels. GridLayout(0, 1) will stack them
   // in a single column
   private JPanel receivingPanel = new JPanel(new GridLayout(0, 1));

   // wrap the above JPanel in the below one, and add it 
   // BorderLayout.PAGE_START so that the newly added JLabels 
   // bunch to the top
   private JPanel wrapPanel = new JPanel(new BorderLayout());

   // put the outer JPanel, the wrapPanel into a JScrollPane
   private JScrollPane scrollpane = new JScrollPane(wrapPanel);

   // Holds text that goes into the newly created JLabel
   private JTextField textField = new JTextField("Foo", 10);

   public AddALabel() {
      // wrap the receiving panel.
      wrapPanel.add(receivingPanel, BorderLayout.PAGE_START);
      scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

      JPanel northPanel = new JPanel();
      northPanel.add(textField);
      // add a JButton that does our work. Give it an Action/ActionListener
      northPanel.add(new JButton(new AddLabelAction("Add a Label")));

      setLayout(new BorderLayout());
      add(northPanel, BorderLayout.PAGE_START);
      add(scrollpane, BorderLayout.CENTER);
   }

   @Override
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   // the code for our Action/ActionListener
   private class AddLabelAction extends AbstractAction {
      public AddLabelAction(String name) {
         super(name);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         // get text from JTextField
         String text = textField.getText();

         // create JLabel and insert above text
         JLabel label = new JLabel(text);

         // add JLabel to receiving JPanel
         receivingPanel.add(label);

         // revalidate and repaint receiving JPanel
         receivingPanel.revalidate();
         receivingPanel.repaint();
      }
   }

   // create our GUI in a thread-safe way
   private static void createAndShowGui() {
      AddALabel mainPanel = new AddALabel();

      JFrame frame = new JFrame("AddALabel");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

I think all you were missing was a call to the pack method, here how I was able to get your wanted result : 我认为您所缺少的只是对pack方法的调用,这是我如何能够获得所需结果的方法:

public class Main extends JFrame {

    final JButton credits;

    public Main()
    {
        super("JLabel from JButton actionlistener");
        setSize(100, 100);        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationByPlatform(true);

        credits = new JButton("Credits");

        credits.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                JLabel oracle = new JLabel();
                oracle.setText("Oracle licenses are out of price");
                Main.this.add(oracle);
                Main.this.pack();
            }
        });

        getContentPane().setLayout(new FlowLayout());
        add(credits);
        setVisible(true);
    }

    public static void main(String[] args) {
        new Main();
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM