我有一台JScrollPane。但默认情况下,它显示JTextArea。
JTextArea jTextArea = new JTextArea();
JScrollPane pane = new JScrollPane(jTextArea);所以在这里一切都很好。但现在我想通过用户操作来更改JScrollPane组件:
pane.remove(jTextArea);
pane.add(new JTable(data[][], columns[]));
pane.revalidate();
frame.repaint();在我的主窗口中设置框架。使用GridBagLayout将JScrollPane添加到主窗口。但这不管用。运行操作后,JScrollPane变为灰色。
发布于 2012-01-27 18:44:53
jScrollPane.getViewport().remove/add发布于 2012-01-27 19:55:09
在收到@camickr国王的一个宝贵建议后编辑了我的答案,setViewportView(componentObject);已经习惯于做这样的事情了。
以下是帮助您实现目标的示例代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ScrollPaneExample extends JFrame
{
private JPanel panel;
private JScrollPane scrollPane;
private JTextArea tarea;
private JTextPane tpane;
private JButton button;
private int count;
public ScrollPaneExample()
{
count = 0;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
panel = new JPanel();
panel.setLayout(new BorderLayout());
tarea = new JTextArea();
tarea.setBackground(Color.BLUE);
tarea.setForeground(Color.WHITE);
tarea.setText("TextArea is working");
scrollPane = new JScrollPane(tarea);
tpane = new JTextPane();
tpane.setText("TextPane is working.");
button = new JButton("Click me to CHANGE COMPONENTS");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (count == 0)
{
scrollPane.setViewportView(tpane);
count++;
}
else if (count == 1)
{
scrollPane.setViewportView(tarea);
count--;
}
}
});
setContentPane(panel);
panel.add(scrollPane, BorderLayout.CENTER);
panel.add(button, BorderLayout.PAGE_END);
pack();
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ScrollPaneExample();
}
});
}
}希望这能在某些方面对你有所帮助。
问候
https://stackoverflow.com/questions/9031963
复制相似问题