单击按钮时滚动到文本区域中的某个位置。

时间:2014-05-10 12:05:26

标签: java swing

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

让我们假设我已经创建了5个JButtonfirstButtonsecondButtonthirdButtonfourthButtonfifthButton。 然后我将所有文本信息放在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的hightlight。

/*
 * 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                   
}

2 个答案:

答案 0 :(得分:2)

以下是您的代码,其中包含一些更改。按下按钮时,文本区域将滚动到文本的位置,将突出显示该文本。

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而不是使用构建器,那么您将获得很多收益。

答案 1 :(得分:-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();

}

}