如何从Jbutton actionlistener创建JLabel实例?

时间:2015-02-03 01:27:58

标签: java swing actionlistener

我正在尝试创建一个JLabel WITHIN actionlistener事件,所以请不要发布任何新的jlabel(); actionlistener事件之外的实例。主要是JFrame,而Credits是Jbutton,Oracle是我想创建的Jlabel实例。

以下是代码:

 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);
     }
 });

2 个答案:

答案 0 :(得分:4)

建议:

  • 首先,不要设置任何东西的界限。使用setBounds(...)表示您使用的是null布局,通常是新手Swing程序的标志,而且这些程序非常严格,难以更新,增强和调试。请改用布局管理器。
  • 接下来,接受JLabel的容器(此处为#34; Main")的布局管理器是关键。有些人不太喜欢添加组件,例如GroupLayout,而其他人则做得更好,例如BoxLayout。
  • 在添加或删除组件后,在您的容器上调用revalidate()repaint()
  • 作为一个侧面推荐(一个不直接影响您的问题),为了帮助我们现在并在将来帮助自己,请编辑您的代码并更改您的变量名称以符合Java naming conventions:类名称全部开始带有大写字母和带小写字母的方法/变量名称。
  • 如果您仍需要更多帮助,请考虑创建并发布minimal example program

例如,带有解释性注释的代码:

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();
         }
      });
   }
}

答案 1 :(得分:0)

我认为你所缺少的是对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();
    }

}