Ada*_*yos 2 java user-interface swing jscrollpane jtextarea
我的GUI遇到了很大的问题.我的第一个问题是,当我按下导致我的JTextArea显示字符串的按钮时,他的文本区域会发生变化,从而推动我的GUI中的所有按钮和其他所有按钮.我尝试了很多解决方案,但没有任
我把我的文本区域放在一个可能有效或无效的滚动面板中.我不知道,因为滚动面板中没有显示任何文字.有人可以看看我的代码并告诉我我做错了什么吗?
谢谢
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class myClass extends JFrame implements ActionListener{
public JButton picture = new JButton();
public JTextArea description = new JTextArea(10,30);
public JButton B1 = new JButton();
public JTextArea C1 = new JTextArea();
public myClass (String STP){
super(STP);
makeGUI();
}
public static void main(String[] args){
myClass test = new myClass("story");
}
public void actionPerformed(ActionEvent event){
Object source = event.getSource();
if (source==B1){
description.setText("hello world");
C1.setText("hello world");
}
}
public void makeGUI(){
JScrollPane scroll = new JScrollPane(description);
JPanel pane = new JPanel(new GridBagLayout());
Container con = this.getContentPane();
setBounds(50,50,600,600); //(x,-y,w,h) from north west
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// picture
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill=GridBagConstraints.NONE;
gbc.ipadx=260;
gbc.ipady=310;
gbc.insets=new Insets(5,5,5,5);
gbc.gridx=0;
gbc.gridy=0;
gbc.gridwidth=2;
gbc.gridheight=3;
pane.add(picture,gbc);
// button 1
B1.addActionListener(this);
gbc.fill=GridBagConstraints.NONE;
gbc.ipadx=0;
gbc.ipady=10;
gbc.insets=new Insets(5,5,5,5);
gbc.gridx=0;
gbc.gridy=3;
gbc.gridwidth=1;
gbc.gridheight=1;
pane.add(B1,gbc);
//caption 1
gbc.fill=GridBagConstraints.HORIZONTAL;
gbc.ipadx=0;
gbc.ipady=30;
gbc.insets=new Insets(5,5,5,5);
gbc.gridx=1;
gbc.gridy=3;
gbc.gridwidth=3;
gbc.gridheight=1;
C1.setEditable(false);
C1.setLineWrap(true);
C1.setWrapStyleWord(true);
pane.add(C1,gbc);
// description !this is the part im having a problem with!
gbc.fill=GridBagConstraints.BOTH;
gbc.ipadx=100;
gbc.ipady=170;
gbc.insets=new Insets(10,10,10,0);
gbc.gridx=2;
gbc.gridy=0;
gbc.gridwidth=2;
gbc.gridheight=1;
description.setEditable(false);
description.setLineWrap(true);
description.setWrapStyleWord(true);
scroll.add(description);
pane.add(scroll,gbc);
con.add(pane);
setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
尝试按下左下角的小按钮.你应该看到两个文本区域中的文本,但只有一个有效.
删除这一说法被更换ViewPortView了的JScrollPane部件.
scroll.add(description);
Run Code Online (Sandbox Code Playgroud)
在JTextArea description已经被设置为口的视图.
这JScollPane是一个包含多个子组件的复杂组件.它可能包含Viewport和可能的JScrollBars,如" 如何使用滚动窗格"教程中的此图像所示.这些组件使用特殊的布局管理器(特别是带有a )进行排列.ScrollPaneLayout
当您刚刚调用时scrollPane.add(componentThatShouldBeScrolled),新组件可能会替换现有组件之一,或者无法预测地搞砸整个布局.
您通常将其传递给JScollPane构造函数,而不是手动添加滚动窗格的内容:
JScrollPane scrollPane = new JScrollPane(componentThatShouldBeScrolled);
Run Code Online (Sandbox Code Playgroud)
或者,如果必须替换"应滚动的组件",则可以调用
scrollPane.setViewportView(componentThatShouldBeScrolled);
Run Code Online (Sandbox Code Playgroud)