2014-12-07 39 views
1

我已经为JPanel构建了一个包含多个JButton的类。在这个类中,我想构造另一个JPanel,JLabel将根据actionPerformed第一个JPanel的JButtons。最后,我想在同一个Jframe上添加这两个面板。所有这些都可以在第一个面板的类中完成吗?否则,对于这个问题,这是一个更好的方法吗?更改面板的JLabel取决于同一个Jframe中另一个面板的Jbutton

+1

当然。我不知道为什么这不应该工作。 因为我不知道你真正的问题在哪里答案只是:是的,这可以在你的第一类 – 2014-12-07 23:24:52

+0

所有内容完成是的,但问题变成了,如果你... – MadProgrammer 2014-12-07 23:46:05

+0

谢谢你们。我只是对报表的编写顺序感到好奇。 – 2014-12-09 08:29:55

回答

0

是的,你可以。一种方法,你可以做到这一点是与匿名内部类(节省击键):

import java.awt.BorderLayout; 
import java.awt.event.*; 
import javax.swing.*; 

public class Foo { 
    JLabel one; 
    JLabel two; 

    public static void main(String[] args) { 
     (new Foo()).go(); 
    } 

    public void go() { 
     JFrame frame = new JFrame("Test"); 

     // Panel with buttons 
     JPanel buttonPanel = new JPanel(); 
     JButton changeOne = new JButton("Change One"); 
     changeOne.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent event) { 
       one.setText("New text for one"); 
      } 
     } 
     buttonPanel.add(changeOne); 
     JButton changeTwo = new JButton("Change Two"); 
     changeTwo.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent event) { 
       two.setText("New text for two"); 
      } 
     } 
     buttonPanel.add(changeTwo); 
     frame.add(buttonPanel, BorderLayout.NORTH); 

     // Panel with labels 
     JPanel labelPanel = new JLabel(); 
     one = new JLabel("One"); 
     labelPanel.add(one); 
     two = new JLabel("Two"); 
     labelPanel.add(two); 

     // Set up the frame 
     frame.add(labelPanel, BorderLayout.SOUTH); 
     frame.setBounds(50, 50, 500, 500); 
     frame.setDefaultCloseAction(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
    } 
} 
相关问题