我对在java中操作UI有点陌生,所以请原谅我的这个问题--我在任何地方都找不到答案。
Description我正在尝试做一个纸牌游戏,我有一个引擎类,可以操纵所有的卡片和游戏,我希望引擎告诉UI更新分数、卡片位置或卡片图像。
这是我如何启动UI的一个例子,这里的问题是,我没有任何实例可以使用我在Board类中创建的实例方法来操作JLabels,而且我无法在EventQueue之外创建一个实例,因为我违反了“永远不要在UI线程之外操作/创建UI”
public class Engine {
public StartUp(){
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (UnsupportedLookAndFeelException e) {
}
new Board().setVisible(true);
}
});
}
}Board类扩展了JPanel,并在构造函数中向ui中添加了一些JLabels,并且有几种方法来更改文本和imgs。
我的问题是如何正确地调用这些方法(我创建这些方法是为了修改文本和img),对于如何处理这个问题,我也公开了任何其他建议。
*编辑:
下面是我的董事会类的简单示例:
public class Board extends JFrame{
public JLabel img1;
public Board(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 265);
JPanel body = new JPanel(new GridBagLayout());
getContentPane().add(body);
img1 = new JLabel();
body.add(img1);
}
public void setImg1(String s){
img1.setIcon(new ImageIcon(s));
}
}我希望能够从引擎访问位于板内的setImg1(String s)方法,以便能够在运行时更改当前映像
如果我说错了问题,很抱歉
最后编辑:
解决了把引擎合并到董事会的问题。
感谢每一个帮助你的人和你的时间
发布于 2011-08-04 18:01:48
public class MainFrame extends JFrame {
public MainFrame() {
super("Demo frame");
// set layout
// add any components
add(new Board()); // adding your board component class
frameOptions();
}
private void frameOptions() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack(); // or setSize()
setVisible(true);
}
public static void main(String[] a) {
JFrame.setDefaultLookAndFeelDecorated(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
new MainFrame();
} catch (Exception exp) {
exp.printStackTrace();
}
}
});
}
}发布于 2011-08-04 17:34:06
获得GUI的基本成语是:
SwingUtilities.invokeLater(new Runnable() {
JFrame frame = new JFrame("My Window Title");
frame.setSize(...);
frame.add(new Board()); // BorderLayout.CENTER by default
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); // center on main screen
frame.setVisible(true);
});https://stackoverflow.com/questions/6945830
复制相似问题