如何在JavaSwing中用图像替换字符串?

时间:2018-04-18 20:47:06

标签: java swing user-interface

有没有办法在JavaSwing中用image / sprite替换字符串?例如,对于字符串"r",我想用Pokemon Silver的培训师图像替换它。

我这样做是因为"r"代表一个roomba,GUI将显示由roomba映射的字符映射。我只想用精灵替换"r",使GUI不仅仅是字符。现在我能够将ImageIcon显示在JTextPane上,我无法在那里选择位置。如果我能够在JTextPane上选择该位置并将其重叠到"r"所在的位置,因为"r"保持不变,这也是另一种解决方案。

这是否可能,或者我应该只使用"r"作为roomba而不是图像?

以下是现在的代码。我正在使用Intellij和它的UI设计师。我的一个合作伙伴目前正在编写代码以使其打印出网格,但我们已经确定"r"将成为roomba,所以如果我能够获得图标替换"r",我很高兴。

public class ObstacleMap extends JFrame{
    private JComboBox controllerselect;
    private JPanel panel;
    private JButton button;
    private JLabel silvergif;
    private JLabel battle;
    private JTextPane textPane1;
    int manual = 1;

    public ObstacleMap() {
        setTitle("Control Center");
        setContentPane(panel);
        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        textPane1.setVisible(false);
        battle.setVisible(false);
        textPane1.setEditable (false); //Make text area uneditable

        //System.out.println now prints to GUI text area
        PrintStream ps = new PrintStream(
            new OutputStream() {
                public void write(int c){
                    textPane1.setText(textPane1.getText() + (char) c);
                }
            }
        );

        System.setOut(ps);

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                textPane1.setVisible(true);
                silvergif.setVisible(false);
                textPane1.insertIcon(new ImageIcon("src/trainer.gif"));
            }
        });

        controllerselect.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (controllerselect.getSelectedItem() == "Autonomous"){
                    manual = 0;
                }
                else if (controllerselect.getSelectedItem() == "PS4 Controller"){
                    manual = 1;
                }
            }
        });
    }

    public static void main(String[] args){
        ObstacleMap o = new ObstacleMap();
    }
}

以下是GUI的屏幕截图:
Here is a screenshot of the GUI.

图标应放在JTextPane的底部中心区域,而不是左上角。

0 个答案:

没有答案