Abh*_*era 2 java swing jscrollpane jtextarea absolutelayout
我正在编辑.我正在使用Java swing.我已经嵌入JTextArea带JScrollPane.我想把jtextarea特定尺寸放在中间位置JScrollPane.为此,我使用了setLocation函数.但这不起作用?
public class ScrollPaneTest extends JFrame {
private Container myCP;
private JTextArea resultsTA;
private JScrollPane scrollPane;
private JPanel jpanel;
public ScrollPaneTest() {
resultsTA = new JTextArea(50,50);
resultsTA.setLocation(100,100);
jpanel=new JPanel(new BorderLayout());
jpanel.add(resultsTA,BorderLayout.CENTER);
scrollPane = new JScrollPane(jpanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(800, 800));
scrollPane.setBounds(0, 0, 800, 800);
setSize(800, 800);
setLocation(0, 0);
myCP = this.getContentPane();
myCP.setLayout(new BorderLayout());
myCP.add(scrollPane);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new ScrollPaneTest();
}
}
Run Code Online (Sandbox Code Playgroud)
您只需添加JTextArea到JScrollPane,并将其添加到CENTER了的JPanel有BorderLayout.
不要使用AbsolutePositioning.添加一个合适的LayoutManager,让LayoutManager完成剩下的工作,以便在屏幕上定位和调整组件大小.
为了使用该setBounds(...)方法,您必须使用不null适合使用的组件的布局,前提是透视,如AbsolutePositioning第一段中所述.虽然在你提供的代码示例中,你正在同时做两件事,即使用Layout和使用AbsolutePositioning,这在各方面都是错误的.我的建议停止做它 :-)
在所提供的示例ROWS,并COLUMNS提供由你足以大小JTextArea由布局的关注.
代码示例:
import java.awt.*;
import javax.swing.*;
public class Example
{
private JTextArea tarea;
private void displayGUI()
{
JFrame frame = new JFrame("JScrollPane Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
JScrollPane textScroller = new JScrollPane();
tarea = new JTextArea(30, 30);
textScroller.setViewportView(tarea);
contentPane.add(textScroller);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
new Example().displayGUI();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)