我添加了一个带有eclipse的jbutton,但它没有正确看到。我该如何解决?
public class GUITest // test class
{
// block the warnings
public static void main(String[] args) //main
{
System.out.println("start of main");
/* stackoverflow want to add more details */
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("Click here");
panel.add(button);
button.addActionListener(new Action());
System.out.println("end of main");
/ * stackoverflow想要添加更多细节* / }
public static class Action implements ActionListener //actionlistener
{
public void actionPerformed (ActionEvent e)
{ /* stackoverflow want to add more details */
JFrame frame2 = new JFrame("Clicked");
frame2.setVisible(true);
frame2.setSize(200,200);
JLabel label = new JLabel("You clicked me!");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label); // some more details
}
}
}
答案 0 :(得分:0)
我已经使用了它,它会正常工作。你可以检查你的图形驱动程序或其他东西。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Ashwin Parmar
*/
public class GUITest {
public static void main(String[] args) {
System.out.println("Start");
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("Click here");
panel.add(button);
button.addActionListener(new Action());
frame.setVisible(true);
System.out.println("End");
}
public static class Action implements ActionListener{
@Override
public void actionPerformed(ActionEvent ae) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
JFrame frame2 = new JFrame("Clicked");
frame2.setSize(200,200);
JLabel label = new JLabel("You have clicked me!");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label);
frame2.setVisible(true);
}
}
}
答案 1 :(得分:0)
setVisible
。如果您在窗口可见后添加组件,则需要致电revalidate
和repaint
。例如......
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("Click here");
panel.add(button);
button.addActionListener(new Action());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
在ActionListener
中执行相同的操作。
有关详细信息,请参阅Initial Threads