java文本区添加滚动条,将滚动条添加到文本区域

I use Eclipse Window Builder. When I click the button, something will be written on the screen. But since my prints are long, I want to use a scroll pane.

public class uyg2 extends JFrame {

private JPanel contentPane;

/**

* Launch the application.

*/

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

public void run() {

try {

uyg2 frame = new uyg2();

frame.setVisible(true);

} catch (Exception e) {

e.printStackTrace();

}

}

});

}

/**

* Create the frame.

*/

public uyg2() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setBounds(100, 100, 450, 300);

contentPane = new JPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

setContentPane(contentPane);

contentPane.setLayout(null);

JButton btnNewButton = new JButton("New button");

btnNewButton.setBounds(32, 29, 89, 23);

contentPane.add(btnNewButton);

JTextArea textArea = new JTextArea();

textArea.setBounds(10, 63, 233, 173);

contentPane.add(textArea);

ScrollPane scrollPane = new ScrollPane();

scrollPane.setBounds(249, 10, 173, 118);

contentPane.add(scrollPane);

}

解决方案

So, based on...

public class uyg1 extends JFrame {

private JPanel contentPane;

/**

* Launch the application.

*/

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

public void run() {

try {

uyg1 frame = new uyg1();

frame.setVisible(true);

} catch (Exception e) {

e.printStackTrace();

}

}

});

}

/**

* Create the frame.

*/

public uyg1() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setBounds(100, 100, 450, 300);

contentPane = new JPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

contentPane.setLayout(new BorderLayout(0, 0));

setContentPane(contentPane);

JTextArea textArea = new JTextArea("Test");

textArea.setSize(400, 400);

JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

frame.getContentPane().add(scroll);

frame.setVisible(true);

}

}

textArea.setSize(400, 400); is irrelevant as the layout manager will deal with it. You can provide sizing hints via the JTextArea(String, int, int) constructer, but remember, this is the number of characters in width/height, not pixels.

The following are giving you issues...

frame.getContentPane().add(scroll);

frame.setVisible(true);

because frame is undefined. Since the class extends from JFrame, they are pointless, it should just be

getContentPane().add(scroll);

setVisible(true);

but, I'd add...

pack();

setLocationRelativeTo(null);

before it, as it will give you a generally better experience

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值