I'm trying to give JLabel
in next line, but nothing is happening even my output shows nothing but blank line when I run the code:
Main class:
import javax.swing.JFrame;
public class main {
public static void main(String[] args){
test piyu=new test();
piyu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
piyu.setSize(300,200);
piyu.setVisible(true);
}
}
Test class:
import java.awt.*;
import javax.swing.*;
public class test extends JFrame {
private JLabel item1,item2;
public test() {
super("First Java app");
JPanel panel=new JPanel();
panel.setLayout(new GridLayout());
item1=new JLabel("MY NAME IS XYZ");
item2=new JLabel("YO");
item1.setToolTipText("GAME ON");
panel.add(item1);
panel.add(item2);
}
}
You are just missing one line. You never add the JPanel
to the JFrame
.
class test extends JFrame {
private JLabel item1,item2;
public test(){
super("First Java app");
JPanel panel=new JPanel();
panel.setLayout(new GridLayout());
item1=new JLabel("MY NAME IS XYZ");
item2=new JLabel("YO");
item1.setToolTipText("GAME ON");
panel.add(item1);
panel.add(item2);
this.add(panel);
}
}
Also, note that there is no need to extend JFrame
in this case. You could have also written this:
import java.awt.*;
import javax.swing.*;
import javax.swing.JFrame;
public class main {
public static void main(String[] args){
JFrame piyu=new JFrame("First Java app");
JPanel panel=new JPanel();
JLabel item1,item2;
panel.setLayout(new GridLayout());
item1=new JLabel("MY NAME IS XYZ");
item2=new JLabel("YO");
item1.setToolTipText("GAME ON");
panel.add(item1);
panel.add(item2);
piyu.add(panel);
piyu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
piyu.setSize(300,200);
piyu.setVisible(true);
}
}
尝试将JPanel添加到JFrame,并观察其工作:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.