簡體   English   中英

沒有得到java程序的輸出

[英]not getting output of java program

package com.gautam.notepad;

import javax.swing.*;    

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
public class main {

    public static void main(String[] args) {
        panel1 p =new panel1();  // This is the panel1 class object
        new App("NOTEPAD",p);    // i'm trying to pass panel1 object



    }
}


class App extends JFrame {

    public App(String title,panel1 panel)
    {
        this.setTitle(title);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setVisible(true);
        this.setLocationRelativeTo(null);
        this.setSize(800, 640);
        this.setLayout(new FlowLayout());
        this.add(panel);
        this.setResizable(false);
    }
}

class panel1 extends JPanel{

    public void paintComponent(Graphics g)
    {
        g.setColor(Color.green);
        g.fillRect(0, 0, this.getWidth(), this.getHeight());



    }
}

它可以正常工作,但在paintcomponent方法中是g.fillRect()方法不起作用,它不能繪制整個屏幕,只在屏幕中間繪制了一個小矩形。此代碼中的問題是什么

您在this.setLayout(new FlowLayout());this.setLayout(new FlowLayout());問題this.setLayout(new FlowLayout()); ,只需將其刪除即可。 默認情況下,它將使用您需要的BorderLayout。

這會起作用

import javax.swing.*;    
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
public class NotePad {

public static void main(String[] args) {

    App app = new App("NOTEPAD");  
    app.getContentPane().setBackground(Color.green);


}
}


class App extends JFrame {

public App(String title)
{
    this.setTitle(title);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setVisible(true);
    this.setLocationRelativeTo(null);
    this.setSize(800, 640);
    this.setLayout(new FlowLayout());
    //this.add(panel);
    this.setResizable(false);
}
}

問題與您選擇的布局有關。請查看此https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html#flow以查看不同的布局以及如何使用它們。

如果更改this.setLayout(new FlowLayout()); this.setLayout(new BorderLayout()); 例如,它應該工作

確定Flowlayout()得到它自己的規模和它發生小規模你從得到什么flowlayout()如果你想仍然能夠使用Flowlayout()和控制您的綠色矩形的尺寸比我建議在面板上使用setPreferredSize()方法,這將消除此問題並保留FlowLayout

public static void main(String[] args) {
        panel1 p =new panel1();  // This is the panel1 class object
        Dimension size= new Dimension(800, 640);//here you can add the size you want 
        p.setPreferredSize(size);
        new App("NOTEPAD",p);    // i'm trying to pass panel1 object



    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM