【问题标题】:Scroll to a position in a text area when the button clicked.单击按钮时滚动到文本区域中的某个位置。
【发布时间】:2014-06-28 03:38:58
【问题描述】:

创建像this sample 这样的HTML 链接位置很容易,但现在我要讨论的是Java swing。

假设我创建了 5 个JButtons:firstButtonsecondButtonthirdButtonfourthButtonfifthButton。 然后我把所有的文字信息放在一个JTextArea txtInform

当我单击firstButton 时,firstButton 的信息将显示在txtInform 的顶部。

当我单击secondButton 时,secondButton 的信息将显示在txtInform 的顶部。

等下一个按钮。所有按钮都必须像this sample 一样工作。 我该怎么做?

注意: 我知道如何在 java swing 中创建组件(如 JButton、JTextArea 等)。请不要告诉我只看Swing Class API 或其他java docs 的教程。我已经阅读了 Swing Class API 教程和java docs,但我还没有找到任何针对这个问题的具体教程。如果您曾经阅读过像我在这里问的那样的特定教程,请告诉我。

编辑:

更新:我真正需要的是在单击按钮时滚动到文本区域中的某个位置。

以下是我目前的代码,我是在 netbeans 中创建的。我使用来自here 的高光。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package gui_001;

import java.awt.Color;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;

/**
 *
 * @author MyScript
 */
public class sampleFrame extends javax.swing.JFrame {

    /**
     * Creates new form sampleFrame
     */
    public sampleFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        firstButton = new javax.swing.JButton();
        secondButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtInform = new javax.swing.JTextArea();
        thirdButton = new javax.swing.JButton();
        fourthButton = new javax.swing.JButton();
        fifthButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        firstButton.setText("First Button");
        firstButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                firstButtonActionPerformed(evt);
            }
        });

        secondButton.setText("Second Button");
        secondButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                secondButtonActionPerformed(evt);
            }
        });

        txtInform.setText("*First*");
        txtInform.append("\n");
        txtInform.append("All first information are here..");
        txtInform.append("\n\n\n\n");
        txtInform.append("**Second**");
        txtInform.append("\n");
        txtInform.append("All second information are here..");
        txtInform.append("\n\n\n\n");
        txtInform.append("***Third***");
        txtInform.append("\n");
        txtInform.append("All third information are here..");
        txtInform.append("\n\n\n\n");
        txtInform.append("****Fourth****");
        txtInform.append("\n");
        txtInform.append("All fourth information are here..");
        txtInform.append("\n\n\n\n");
        txtInform.append("*****Fifth*****");
        txtInform.append("\n");
        txtInform.append("All fifth information are here..");
        txtInform.setColumns(20);
        txtInform.setLineWrap(true);
        txtInform.setRows(5);
        txtInform.setWrapStyleWord(true);
        jScrollPane1.setViewportView(txtInform);

        thirdButton.setText("Third Button");
        thirdButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                thirdButtonActionPerformed(evt);
            }
        });

        fourthButton.setText("Fourth Button");
        fourthButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fourthButtonActionPerformed(evt);
            }
        });

        fifthButton.setText("Fifth Button");
        fifthButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fifthButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(76, 76, 76)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(secondButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(firstButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(thirdButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(fourthButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(fifthButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(64, 64, 64)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(71, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(76, 76, 76)
                .addComponent(firstButton, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(secondButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(thirdButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(fourthButton, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(fifthButton, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(44, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(90, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(595, 477));
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    private void secondButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
        String text = txtInform.getText();
        String second = "**Second**";
        int i = text.indexOf(second);
        int pos = txtInform.getCaretPosition(); 

        Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.BLUE );

        int offset = text.indexOf(second);
        int length = second.length();

        while ( offset != -1)
        {
            try
            {
                txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
                offset = text.indexOf(second, offset+1);
            }
            catch(BadLocationException ble) { System.out.println(ble); }
        }

    }                                            

    private void firstButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
        String text = txtInform.getText();
        String second = "*First*";
        int i = text.indexOf(second);
        int pos = txtInform.getCaretPosition(); 

        Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.BLUE );

        int offset = text.indexOf(second);
        int length = second.length();

        while ( offset != -1)
        {
            try
            {
                txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
                offset = text.indexOf(second, offset+1);
            }
            catch(BadLocationException ble) { System.out.println(ble); }
        }
    }                                           

    private void fifthButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
        String text = txtInform.getText();
        String second = "*****Fifth*****";
        int i = text.indexOf(second);
        int pos = txtInform.getCaretPosition(); 

        Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.BLUE );

        int offset = text.indexOf(second);
        int length = second.length();

        while ( offset != -1)
        {
            try
            {
                txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
                offset = text.indexOf(second, offset+1);
            }
            catch(BadLocationException ble) { System.out.println(ble); }
        }
    }                                           

    private void fourthButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
         String text = txtInform.getText();
        String second = "****Fourth****";
        int i = text.indexOf(second);
        int pos = txtInform.getCaretPosition(); 

        Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.BLUE );

        int offset = text.indexOf(second);
        int length = second.length();

        while ( offset != -1)
        {
            try
            {
                txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
                offset = text.indexOf(second, offset+1);
            }
            catch(BadLocationException ble) { System.out.println(ble); }
        }
    }                                            

    private void thirdButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
         String text = txtInform.getText();
        String second = "***Third***";
        int i = text.indexOf(second);
        int pos = txtInform.getCaretPosition(); 

        Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.BLUE );

        int offset = text.indexOf(second);
        int length = second.length();

        while ( offset != -1)
        {
            try
            {
                txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
                offset = text.indexOf(second, offset+1);
            }
            catch(BadLocationException ble) { System.out.println(ble); }
        }
    }                                           

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(sampleFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(sampleFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(sampleFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(sampleFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new sampleFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton fifthButton;
    private javax.swing.JButton firstButton;
    private javax.swing.JButton fourthButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton secondButton;
    private javax.swing.JButton thirdButton;
    private javax.swing.JTextArea txtInform;
    // End of variables declaration                   
}

【问题讨论】:

  • 你知道ActionListener是什么吗?
  • @kdgregory,我当然愿意。我只是混淆了单击按钮时如何将 txtInform 中的文本放在 txtInform 的顶部。好的,我可以在按钮的 ActionListener 中实现任何事件。我的问题:我必须在其中实施什么事件?
  • “我必须在其中实现的事件是什么?”在actionPerformed 中,使用textArea.setTexttextArea.append 将信息作为参数。我建议您发布一些到目前为止您尝试过的代码。
  • 好的,我会尽快发布答案,但请告诉我,您在问题的标题或正文中的哪个位置提到了“我想滚动到文本中的某个位置”之类的内容区域”?

标签: java swing


【解决方案1】:

这是您的代码,其中有一些更改。按下按钮时,文本区域将滚动到文本所在的位置,只有该文本会被突出显示。

public class SampleFrame extends JFrame {

    private static JTextArea txtInform = new JTextArea();
    private static final String TEXT = "*First*\nAll first information are here..\n\n\n\n" +
            "**Second**\nAll second information are here..\n\n\n\n" +
            "***Third***\nAll third information are here..\n\n\n\n" +
            "****Fourth****\nAll fourth information are here..\n\n\n\n" +
            "*****Fifth*****\nAll fifth information are here..";

    public SampleFrame() {

        initComponents();
    }

    private void initComponents() {

        JScrollPane jScrollPane1 = new JScrollPane(txtInform);
        JButton firstButton = new JButton("First Button");
        JButton secondButton = new JButton("Second Button");
        JButton thirdButton = new JButton("Third Button");
        JButton fourthButton = new JButton("Fourth Button");
        JButton fifthButton = new JButton("Fifth Button");

        firstButton.addActionListener(new MyActionListener("*First*"));
        secondButton.addActionListener(new MyActionListener("**Second**"));
        thirdButton.addActionListener(new MyActionListener("***Third***"));
        fourthButton.addActionListener(new MyActionListener("****Fourth****"));
        fifthButton.addActionListener(new MyActionListener("*****Fifth*****"));

        txtInform.setText(TEXT);
        txtInform.setColumns(20);
        txtInform.setRows(5);
        txtInform.setLineWrap(true);
        txtInform.setWrapStyleWord(true);

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(76, 76, 76)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
                    .addComponent(secondButton, GroupLayout.DEFAULT_SIZE,
                                GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(firstButton, GroupLayout.DEFAULT_SIZE,
                                GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(thirdButton, GroupLayout.DEFAULT_SIZE,
                                GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(fourthButton, GroupLayout.DEFAULT_SIZE,
                                GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(fifthButton, GroupLayout.DEFAULT_SIZE,
                                GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(64, 64, 64)
                .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 265,
                            GroupLayout.PREFERRED_SIZE).addContainerGap(71, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(76, 76, 76)
                .addComponent(firstButton, GroupLayout.PREFERRED_SIZE, 30,
                            GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(secondButton, GroupLayout.PREFERRED_SIZE, 31,
                            GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(thirdButton, GroupLayout.PREFERRED_SIZE, 31,
                            GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(fourthButton, GroupLayout.PREFERRED_SIZE, 32,
                            GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(fifthButton, GroupLayout.PREFERRED_SIZE, 32,
                            GroupLayout.PREFERRED_SIZE)
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(44, Short.MAX_VALUE)
                .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 305,
                            GroupLayout.PREFERRED_SIZE).addContainerGap(90, Short.MAX_VALUE)));

        setSize(new java.awt.Dimension(595, 477));
        setLocationRelativeTo(null);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    private class MyActionListener implements ActionListener {

        private int offset, length;
        private final Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.BLUE);

        private MyActionListener(String chapter) {

            offset = TEXT.indexOf(chapter);
            length = chapter.length();
        }

        public void actionPerformed(ActionEvent e) {

            txtInform.setCaretPosition(offset);
            txtInform.getHighlighter().removeAllHighlights();
            try {
                txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
            } catch (BadLocationException ble) {
                ble.printStackTrace();
            }
        }
    }

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {

                new SampleFrame().setVisible(true);
            }
        });
    }
}
  • 根据 Java 命名约定,类名以大写开头。
  • 使您的代码呈现出行的逻辑顺序。一个接一个地初始化所有按钮,而不是将滚动窗格初始化推到中间,这样会更清楚。
  • 当您可以创建局部变量时不要创建字段(所有按钮和滚动窗格)。
  • 使用应显示的文本准备一个字符串,而不是为每一行调用 append(如果您还没有这样做的话)。
  • 为所有按钮创建 1 个动作侦听器,因为它对所有按钮都有类似的功能 - 可重用代码。

如果您自己编写 GUI,而不是与构建器一起编写,您将受益匪浅。

【讨论】:

  • 这正是我所需要的。感谢您的 cmets,回答和编辑。我已经接受了这个作为答案。再次感谢。
【解决方案2】:

简单示例

public class Main extends JPanel implements ActionListener{
    JTextField textField = null;
public static void main(final String[] args) { 
Main main =  new Main();
main.textField= new JTextField("Sample");
JButton btn1 = new JButton("Button1");
btn1.addActionListener(main);
JButton btn2 = new JButton("Button2");
btn2.addActionListener(main);

main.add(main.textField);
main.add(btn1);
main.add(btn2);
JFrame frame = new JFrame();
frame.setTitle("Simple example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.add(main);
frame.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
    textField.setText(e.getActionCommand());
    repaint();

}

}

【讨论】:

  • -1 用于草率代码(除了缩进,repaint() 在做什么,为什么要修改主线程上的组​​件层次结构?),以及帮助和教唆复制和-粘贴编码器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-26
  • 2019-01-03
相关资源
最近更新 更多