我在這里需要幫助。我想為drawLine()從中獲得的方法提供一個引數getSize()。getSize()我想使用該方法在整個視窗中畫一條線。
package PROG2;
import java.awt.*;
import javax.swing.*;
class MyComponent extends JComponent {
@Override
public void paintComponent(Graphics g) {
g.drawLine(100, 100, 200, 200);
}
}
public class übung1 extends JFrame{
public static void berechnen() {
int height = frame.getHeight(); //Here it says it doesn't know "frame" variable but I don't know how to declare it here.
int width = frame.getWidth();
}
public static void main(String[] args){
JFrame frame = new JFrame("First window");
berechnen();
frame.add(new MyComponent());
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Graphics g = frame.getGraphics();
// int width = frame.getWidth();
// int height = frame.getHeight();
System.out.println("Gr??e:" frame.getSize());
//System.out.println(width);
}
}
uj5u.com熱心網友回復:
正如安德魯已經說過的那樣,
- 您不想獲取 JFrame 的尺寸或大小,而是獲取 JFrame 的 contentPane 中顯示的組件,這里是您的 MyComponent 實體。
- 獲取該資訊的最佳位置是在paintComponent 方法本身內部,就在繪制線條之前。
- 并且總是先呼叫super的畫法
我還推薦:
- 如果您想要不透明的影像,請在 JPanel 的 paintComponent 方法中繪制,而不是在 JComponent 中繪制
- 除非絕對需要,否則避免使用靜態方法和欄位
請注意,在下面的代碼中,紅線穿過 JPanel 的對角線,并繼續繪制對角線,即使手動調整 JFrame 的大小:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Stroke;
import javax.swing.*;
public class DrawLine extends JPanel {
private static final Stroke LINE_STROKE = new BasicStroke(15f);
private static final Dimension PREF_SIZE = new Dimension(800, 650);
public DrawLine() {
setPreferredSize(PREF_SIZE);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// code to make the line smooth (antialias the line to remove jaggies)
// and to make the line thick, using a wider "stroke"
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(LINE_STROKE);
// if we want a red line
g2.setColor(Color.RED);
// this is the key code here:
int width = getWidth();
int height = getHeight();
// draw along the main diagonal:
g2.drawLine(0, 0, width, height);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
DrawLine mainPanel = new DrawLine();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/468945.html
下一篇:按類jQuery選擇一個按鈕
