雖然每當調用repaint()時文本字段發生更改,但我有一個非常簡單的JFrame(它僅包含一個文本字段和大量繪製的東西)。我很確定它是repaint(),因爲即使當我將幀從一個顯示器拖到下一個以及每當我在代碼中調用它時都會發生。重新繪製文本字段變形
它精美開始了,當我運行程序:
但是,只要重繪()被調用時,發生這種情況:
如果我輸入的其餘部分立即彈出並工作正常。最終,我的最終目標是將大部分框架重新設置爲paintComponent()中的內容,同時仍然可以顯示文本字段。
我是比較新的圖形和繪畫,任何幫助非常感謝!
編輯
在創建SSCCE,我發現與文本字段的問題正在由Graphics2D的方法造成的旋轉,這是在我的paintComponent方法。我不知道爲什麼會發生這種情況,但我可以解決這個問題並考慮解決問題。
現在,我遇到了一個新問題:我的paintComponent方法被調用了太多次。下面是這個問題的SSCCE,我想事情發生的順序是:
- 電話的paintComponent()
- (按下按鈕時)調用重繪()
- (當按鈕被按下,但重繪後)調用paintStuff()
這一切都發生,但是之後paintComponent被某種方式調用,擦除paintStuff()所繪的所有東西。
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class tester extends JFrame {
private JPanel contentPane;
private JButton button;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
tester frame = new tester();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public tester() {
setBounds(100, 100, 450, 300);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel(){
public void paintComponent(Graphics g1) {
System.out.println("draw rectangle - should be first");
super.paintComponent(g1);
g1.drawRect(50,50,50,50);
}
};
contentPane.setLayout(null);
setContentPane(contentPane);
button = new JButton("Click me!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("repaint - should be second");
repaint();
paintStuff(contentPane.getGraphics());
}
});
button.setBounds(10, 11, 95, 20);
contentPane.add(button);
}
public void paintStuff(Graphics g){
System.out.println("draw circle - should be last");
g.drawOval(100,100,10,10);
}
}
確保你調用'super.paintComponent(...)'在paintComponent()方法的開始處。如果這沒有幫助,那就發佈一個證明問題的正確的[SSCCE](http://sscce.org/)。 – camickr
1)*「我有一個非常簡單的JFrame(它只包含一個文本字段..」*其中代碼顯示了一個'JButton',但沒有'JTextField'。2)將大小設置爲文本字段是設置它需要顯示的列數(字符)。調整其大小的另一種方法是更改它正在使用的「Font」的大小。但更普遍的是...... 3).. –
.. 3)Java GUI必須在不同的語言環境中使用不同的PLAF來處理不同的操作系統,屏幕大小,屏幕分辨率等。因此,它們不利於像素的完美佈局。請使用佈局管理器或[它們的組合](http://stackoverflow.com/a/5630271/418556)以及[white space]的佈局填充和邊框(http://stackoverflow.com/a/17874718/ 418556)。 –