单击按钮后将对象添加到JPanel [英] Add Object to JPanel after button click
问题描述
我创建了一个内部带有JPanel的JScrollPane,我想在按下按钮后添加JPanel/JLabel/Other对象.例如,在按下三个按钮之后,我想要得到类似以下内容的东西:
I have created a JScrollPane with a JPanel inside it and I want to add JPanel/JLabel/Other objects after pressing the button. For example after three button presses I want to get something like this:
我尝试将myJPane.add(testLabel)
与testlabel.setBounds()
一起使用,但是没有结果,由于大小不变,我不想使用GridLayout.我希望添加的对象具有不同的大小-调整为文本内容.
I tried myJPane.add(testLabel)
with testlabel.setBounds()
but no result, I don't want to use GridLayout because of the unchangeable sizes. I would like it if the added objects had different sizes - adjusted to the text content.
我应该使用它什么以及如何使用?
What should I use for it and how?
先谢谢了. 最好的祝福, 汤姆.
Thanks in advance. Best regards, Tom.
推荐答案
这是JScrollPane
内的JPanel
,当按下按钮时会在其中添加JLabel
:
Here is a JPanel
inside a JScrollPane
that adds JLabel
s to it when pressing the button:
public class Example extends JFrame {
public Example() {
JPanel boxPanel = new JPanel();
boxPanel.setLayout(new BoxLayout(boxPanel, BoxLayout.PAGE_AXIS));
JTextField textField = new JTextField(20);
JButton sendButton = new JButton("Send");
sendButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JLabel label = new JLabel(textField.getText());
label.setOpaque(true);
label.setBackground(Color.RED);
boxPanel.add(label);
boxPanel.add(Box.createRigidArea(new Dimension(0,5)));
textField.setText("");
boxPanel.revalidate();
// pack();
}
});
JPanel southPanel = new JPanel();
southPanel.add(textField);
southPanel.add(sendButton);
add(new JScrollPane(boxPanel));
add(southPanel, BorderLayout.PAGE_END);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new Example();
}
}
BoxLayout
将标签堆叠在一起.
注释:
-
必须在
-
setOpaque(true)
才能使用背景色. -
Box.createRigidArea
用于创建间隙.随心所欲地使用它. - 必须立即调用
revalidate()
,以便立即显示新组件. - 每次调用
pack()
(在JFrame
上)都会调整其大小,以适应所有新组件.我只是将其放在此处进行演示,因为初始帧大小太小,无法显示添加的初始组件.
label
上调用setOpaque(true)
must be called onlabel
for it to honor the background color.Box.createRigidArea
is used for creating gaps. Use it as you wish.- The call to
revalidate()
is imperative in order to display the new components immediately. - Calling
pack()
(on theJFrame
) will resize it each time to fit all the new components. I just put it there for demonstration since the initial frame size is too small to display the initial components added.
这篇关于单击按钮后将对象添加到JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!