我的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);
}
}
请尝试按左下角的小按钮。您应该在两个文本区域中都看到文本,但是只有一个可以工作。
这是一个常见的错误。因此,让Reimeus进一步详细说明解决方案:
该JScollPane
是一个复杂的组件,它包含几个子组件。它可能包含Viewport
与可能JScrollBar
s ^,如图这一形象从如何使用滚动窗格教程。这些组件通过特殊的布局管理器(尤其是使用ScrollPaneLayout
)进行排列。
当您仅致电时scrollPane.add(componentThatShouldBeScrolled)
,新组件可能会替换现有组件之一,或者使整个布局变幻莫测。
通常,您无需将其手动添加到滚动窗格中,而是将其传递给JScollPane
构造函数:
JScrollPane scrollPane = new JScrollPane(componentThatShouldBeScrolled);
另外,如果您必须替换“应该滚动的组件”,则可以调用
scrollPane.setViewportView(componentThatShouldBeScrolled);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句