【问题标题】:JTabbedPane not switching tab contentsJTabbedPane 不切换选项卡内容
【发布时间】:2012-04-04 16:19:48
【问题描述】:

我在使用 JTabbedPane 时遇到问题,因为单个选项卡的内容没有显示(每次我单击新选项卡时,活动选项卡都会更改,但内容不会,所以我看到的内容相同无论选择哪个选项卡。)。

我正在尝试为我自己的编程语言编写一个 IDE,但之前从未使用过 JTabbedPane。我的选项卡式窗格由 JScrollPanes 中的 JEditTextArea(用户编写的组件)组成。这是负责的类

package tide.editor;

import javax.swing.*;

import javax.swing.filechooser.FileNameExtensionFilter;

import java.awt.Toolkit;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

import org.syntax.jedit.*;
import org.syntax.jedit.tokenmarker.*;

@SuppressWarnings("serial")
public class Editor extends JFrame implements ActionListener {

//Version ID
final static String VERSION = "0.01a";

//The editor pane houses the JTabbedPane that allows for code editing
//JPanel editorPane;

JTabbedPane tabbedPanel;

//The JTextPanes hold the source for currently open programs
ArrayList<JEditTextArea> textPanes;

//The toolbar that allows for quick opening, saving, compiling etc
JToolBar toolBar;

//Buttons for the toolbar
JButton newButton, openButton, saveButton, compileButton, runButton;


public Editor()
{
    super("tIDE v" + VERSION);
    setSize(Toolkit.getDefaultToolkit().getScreenSize());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new BorderLayout());
    init();
    setVisible(true);
    textPanes.get(0).requestFocus();
}

public void init()
{
    //Initialise toolbar
    toolBar = new JToolBar();
    toolBar.setFloatable(false);

    newButton = new JButton("New");
    newButton.addActionListener(this);
    openButton = new JButton("Open");
    openButton.addActionListener(this);
    saveButton = new JButton("Save");
    saveButton.addActionListener(this);
    compileButton = new JButton("Compile");
    compileButton.addActionListener(this);
    runButton = new JButton("Run");
    runButton.addActionListener(this);

    toolBar.add(newButton);
    toolBar.add(openButton);
    toolBar.add(saveButton);
    toolBar.add(compileButton);
    toolBar.add(runButton);


    tabbedPanel = new JTabbedPane();

    textPanes = new ArrayList<JEditTextArea>();

    JEditTextArea initialProgram = createTextArea("program.t");

        tabbedPanel.addTab(initialProgram.getName(), new JScrollPane(initialProgram));


    getContentPane().add(tabbedPanel, BorderLayout.CENTER);
    add(toolBar, BorderLayout.NORTH);
}

public static void main(String[] args)
{
java.awt.EventQueue.invokeLater(new Runnable() {

    @Override
    public void run() {
        new Editor();
    }
});

}

JEditTextArea createTextArea(String name)
{
    JEditTextArea editPane = new JEditTextArea(name);
    editPane.setTokenMarker(new TTokenMarker());

    textPanes.add(editPane);

    return editPane;
}

public void actionPerformed(ActionEvent e) {

    if (e.getSource() == newButton)
    {
        String filename = "program2";
        boolean fileExists = true;

        //Ensures that no duplicate files are created
        while (fileExists)
        {
        fileExists = false;
        //Get new file name from user
        filename = JOptionPane.showInputDialog(null, "Enter a name for the file", "program.t");

        //Cancel was clicked in the new file dialog
        if (filename == null)
            return;

            for (JEditTextArea panes: textPanes)
            {
                if (panes.getName().equals(filename) || panes.getName().equals(filename.concat(".t")) || panes.getName().concat(".t").equals(filename))
                    fileExists = true;
            }
        }

        //add extension if it is missing
        if(!filename.endsWith(".t"))
            filename = filename.concat(".t");

        //Add the new "file" to the editor window in a new tab
        tabbedPanel.addTab(filename, new JScrollPane(createTextArea(filename)));
        tabbedPanel.setSelectedIndex(tabbedPanel.getSelectedIndex()+1);
    }

    if (e.getSource() == openButton)
    {
        File f = null;


        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Choose target file location");
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setAcceptAllFileFilterUsed(false);
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
                "t source or bytecode(.t, .tbc)", "t", "tbc");

        fileChooser.setFileFilter(filter);

        if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
        {
            f = fileChooser.getSelectedFile();
        }

        //Cancel button was clicked on the open file dialog
        if (f == null)
            return;

        //Load the contents of the selected file into the editor
        else
        {
            JEditTextArea textArea = null;
            StringBuilder inputText = null;

            try {
                Scanner sc = new Scanner(f);

                //Add a new text area to the editor
                textArea = createTextArea(f.getName());
                tabbedPanel.add(new JScrollPane(textArea), textArea.getName());

                //The newly added tab is set as the active tab
                tabbedPanel.setSelectedIndex(tabbedPanel.getTabCount()-1);
                textArea.requestFocus();

                inputText = new StringBuilder();
                while (sc.hasNext())
                {
                    inputText.append(sc.nextLine() + "\n");
                }

            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            }

            //Set the contents of the current text area to that of the opened file
            textArea.setText(inputText.toString());
        }
    }

}

}

【问题讨论】:

    标签: java swing file-io jtabbedpane


    【解决方案1】:

    1) 从FileIO 相关try - catch 块中删除代码行

    textArea = createTextArea(f.getName());
    tabbedPanel.add(new JScrollPane(textArea), textArea.getName());
    //The newly added tab is set as the active tab
    tabbedPanel.setSelectedIndex(tabbedPanel.getTabCount()-1);
    textArea.requestFocus();
    

    Input / OutputStreams之前或之后准备那些Object

    2) close() 来自 Input / OutputStreams 的所有 Objects,在 finally 块中 (try - catch - finally)

    3) JTextComponets 实现 read()write(),接受所有分隔符,那么就没有理由以编程方式调用“\n”

    4) 使用SwingWorker 代码为FileIO

    【讨论】:

    • 我已经尝试了你在这里建议的大部分内容(我不知道如何使用 SwingWorker),但仍然没有运气。
    • @Peter:请阅读教程中的 SwingWorker。我担心您的问题可能是并发问题。
    【解决方案2】:

    这可能不是根本原因的解决方案,但您的代码中可能存在一些不一致导致 TestAreas 上的绘制问题,因此我建议您注册一个 TabChageListener,然后为该特定选项卡重新绘制 ScrollPane,这应该工作:

    tabbedPanel.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
         int selectedIndex =   tabbedPane.getSelectedIndex();
      // get the ScrollPane for this selectedIndex and then repaint it.
    
        }
    });
    

    【讨论】:

    • 我试过了,但不幸的是它没有用。同样的问题仍然存在。
    【解决方案3】:

    在过去的几个小时里,我一直在努力解决这个问题。

    事实上,无论你实例化多少个JEditTextArea,它们都依赖于同一个SyntaxDocument,因此是相同的文本。这就是它在JEditTextArea 中的编码方式。

    在构造函数public JEditTextArea(TextAreaDefaults defaults) 中,您需要找到该行:

    setDocument(defaults.document);

    并将其替换为:

    setDocument(new SyntaxDocument());

    每次你创建一个新的JEditTextArea时,它都会实例化一个全新的Document

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多