我有一個嵌入在JFrame上的面板(GridLayout(0,1))。如何限制JButton作爲重新驗證的結果來更改尺寸
按我的要求: -
- 我在上面定義面板上對加(JButton的,JTextArea中)。
- 現在,點擊任何一對JButton,它的JTextArea應該被刪除,並且在重新點擊JButton時,應該再次添加JTextArea。
一切工作正常,但低於兩家上市問題:
的JButton的- 尺寸都在重新驗證改變。
- 的JButton的初始尺寸非常大(如何限制的JButton的尺寸)
作爲參考,看看這個。
並請在下面找到修改的代碼清單: -
TestFrame.java
package com.test;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class TestFrame extends JFrame implements ActionListener{
final JPanel panel ;
private TestFrame() {
setExtendedState(JFrame.MAXIMIZED_BOTH) ;
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) ;
panel = new JPanel() ;
panel.setLayout(new GridLayout(0, 1)) ;
for(int i = 1 ; i <= 3 ; ++i){
TButton btn = new TButton("User " + i + " [Toggle Button for TextArea " + i + "] (Click)") ;
panel.add(btn) ; btn.addActionListener(this) ; panel.add(new JScrollPane(btn.getLoggingArea())) ;
}
add(panel, BorderLayout.CENTER) ;
setVisible(true) ;
setExtendedState(JFrame.MAXIMIZED_BOTH) ;
}
@Override
public void actionPerformed(ActionEvent e) {
TButton btn = (TButton) e.getSource() ;
JPanel parent = (JPanel) btn.getParent() ;
int index = getIndex(parent, btn) ;
if(btn.isLoggingAreaVisible()){
parent.remove(parent.getComponent(index + 1)) ;
btn.setLoggingAreaVisible(false) ;
}else{
parent.add(new JScrollPane(btn.getLoggingArea()), index + 1) ;
btn.setLoggingAreaVisible(true) ;
}
parent.revalidate() ;
parent.repaint() ;
}
private int getIndex(JComponent parent, Component btn) {
Component []comps = parent.getComponents() ;
for(int i = 0 ; i < comps.length ; ++i){
if(comps[i].equals(btn)){
return i ;
}
}
return -1 ;
}
public static void main(String[] args) {
new TestFrame() ;
}
}
TButton.java
package com.test;
import javax.swing.JButton;
import javax.swing.JTextArea;
public class TButton extends JButton{
private JTextArea loggingArea ;
private boolean loggingAreaVisible = true ;
public TButton(String threadName) {
super(threadName) ;
initComponents(threadName) ;
}
public void initComponents(String threadName) {
String str = "1. By default large buttons are displayed." + "\n" +
" But, I want buttons with a little small dimensions." + "\n\n" +
"2. On click of above button, above button expands to cover space used by this textArea." + "\n" +
" But, what I want, that button size does not changes onClick, only textArea length increases/decreases." ;
loggingArea = new JTextArea(getText() + " textArea." + "\n\n" + str + "\n\n" + "Type Here...") ;
}
public boolean isLoggingAreaVisible() {
return loggingAreaVisible;
}
public void setLoggingAreaVisible(boolean loggingAreaVisible) {
this.loggingAreaVisible = loggingAreaVisible;
}
public JTextArea getLoggingArea() {
return loggingArea;
}
}
謝謝, RITS :)
+1我曾經用你的頭像作爲我的桌面背景的情況下。 :D – mre 2012-01-18 12:45:58