我正在编写一些实验性 GUI 代码。我正在尝试对其进行设置,以便调用 main
生成两个窗口,每个窗口都有一个按钮和一个标签。标签显示按钮被单击的次数。但是,我希望这样,如果您单击一个窗口中的按钮,其他窗口中的标签就会更新。我该怎么做?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
@SuppressWarnings("serial")
public class TestGUI extends JFrame {
private static int count;
private JButton button = new JButton("odp");
private JLabel label = new JLabel();
public TestGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(button);
setLayout(new FlowLayout(FlowLayout.RIGHT));
labelUpdateText();
add(label);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
count++;
labelUpdateText();
}
});
pack();
setVisible(true);
}
private void labelUpdateText() {
label.setText("Count: " + count);
}
public static void main(String[] args) {
new TestGUI();
new TestGUI();
}
}
最佳答案
1 - 我宁愿避免扩展 JFrame,因为您并没有真正创建一个新的 JFrame 类。
因此,您可以创建它们的实例,而不需要添加更多行为,而不是将整个类作为 JFrame 的子类(这不是)。
2 - 如果您想让两个标签反射(reflect)同一“事物”的值,您必须在它们之间共享该事物(或者让某人为您更新该值)
所以,使用著名的MVC你需要。
对您想要在两个标签中显示的计数器进行建模。
查看将显示模型的标签
Controller 在它们之间进行交易的东西。
它们都属于一个应用程序,它们是应用程序的实例属性。
为了了解它们如何组合在一起,我将代码粘贴到此处:
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.*;
// TwoWindows is the Application
public class TwoWindows {
// shared state ( model )
private int clickCount = 0;
// UI
private List<JLabel> toUpdate = new ArrayList<JLabel>();
// listener ( listens for clicks on buttons kind of controller )
private ActionListener actionListener = new ActionListener() {
// Each time update the UI
public void actionPerformed( ActionEvent e ) {
clickCount++;
for( JLabel label : toUpdate ) {
label.setText( "Count: " + ( clickCount ) );
}
}
};
// Createsa winddow with a label and a button
public void showWindow( String named ) {
JFrame f = new JFrame( named );
f.add( createButtonAndLabel() );
f.pack();
f.setVisible( true );
}
// Creates the label and button and adds this.actionListener
// to each button.
private JComponent createButtonAndLabel() {
JPanel panel = new JPanel();
JLabel label = new JLabel("Count: 0");
JButton clickMe = new JButton("Click me");
// adding the label to a "view" list.
toUpdate.add( label );
// adding the listener to each button
clickMe.addActionListener( actionListener );
panel.add( label );
panel.add( clickMe );
return panel;
}
// Run the app
public static void main( String [] args ) {
TwoWindows t = new TwoWindows();
t.showWindow("A");
t.showWindow("B");
}
}
这样您就可以拥有共享模型并根据需要更新任意数量的 View 。
alt text http://img387.imageshack.us/img387/1106/capturadepantalla200910d.png
关于Java 图形用户界面 : Sharing values across different JFrames,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1574096/