新手Java程序员在这里:
我讨厌每次遇到问题时都提出问题,但我不知道应该使用什么来让绿色的“Hello World”标签直接进入 JPanel 的中心。这是我的代码:
package game;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Javagame extends JPanel implements ActionListener{
protected JButton b1;
private JLabel label;
public Javagame() {
b1 = new JButton("Button!");
b1.setActionCommand("change");
b1.addActionListener(this);
add(b1);
label = new JLabel("Hello World!", SwingConstants.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 20));
label.setForeground(new Color(0x009900));
add(label, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
if ("change".equals(e.getActionCommand())) {
label.setText("Hello Universe!");
b1.setActionCommand("changeBack");
}
if ("changeBack".equals(e.getActionCommand())) {
label.setText("Hello World!");
b1.setActionCommand("change");
}
}
private static void createWindow(){
JFrame frame = new JFrame("Javagame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(500,500));
Javagame newContentPane = new Javagame();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createWindow();
}
}
BorderLayout.CENTER
似乎在add()
. 任何帮助将不胜感激,谢谢!