相关疑难解决方法(0)

如何最好地定位Swing GUI?

另一个线程中,我说过我喜欢通过做这样的事情来集中我的GUI:

JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new HexagonGrid());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Run Code Online (Sandbox Code Playgroud)

但安德鲁汤普森有不同的意见,而是打电话

frame.pack();
frame.setLocationByPlatform(true);
Run Code Online (Sandbox Code Playgroud)

和询问的头脑想知道为什么?

java user-interface swing

124
推荐指数
2
解决办法
2万
查看次数

将鼠标侦听器添加到java中的矩形

正如标题所示,我试图在窗口上添加一个基本形状的动作监听器.我想知道这是否可能?我尝试添加监听器时遇到错误.

public static void main(String args[]) {
    JFrame frame = new Main();
    frame.setSize(300, 200);
    frame.setVisible(true);
    frame.setBackground(Color.BLUE);
}

Rectangle2D rect = new Rectangle2D.Double(60, 70, 120, 80);

public void paint(Graphics g) {
    Graphics2D g1 = (Graphics2D)g;
    g1.draw(rect);
    g1.setPaint(Color.yellow);
    g1.fill(rect);
}

Handlerclass handle = new Handlerclass();
rect.addMouseListener(handle);

public class Handlerclass implements MouseListener{
    public void mouseClicked (MouseEvent e){
    }
}
Run Code Online (Sandbox Code Playgroud)

java swing listener mouselistener

4
推荐指数
1
解决办法
1万
查看次数

将其他类的JPanel添加到cardLayout

我在3个单独的类中有3个窗口,我想使用cardLayout,这样当您单击下一个按钮时,将出现下一个窗口.如何将包含不同元素的JPanel添加到一个cardLayout?这是第一个窗口:(唯一不同的是背景 - 但它代表了我实际上是如何得到它的想法)

public class Window1 extends JPanel implements ActionListener {

static CardLayout cardLayout = new CardLayout();

public Window1() {
   init();
}

private void init() {
    JPanel jp = new JPanel(new BorderLayout());
    JPanel jp2 = new Window2();
    //JPanel jp3 = new Window3();
    JLabel textLabel = new JLabel("Window1");
    jp.setBackground(Color.GREEN);
    jp.add(textLabel, BorderLayout.CENTER);
    JButton nextButton = new JButton("NEXT");
    nextButton.setActionCommand("next");
    nextButton.addActionListener(this);
    jp.add(nextButton, BorderLayout.EAST);
    setLayout(cardLayout);
    add(jp, "string");
    add(jp2, "string");
    //add(jp3, "string");
}

public void actionPerformed(ActionEvent e) {            
    if (e.getActionCommand().equalsIgnoreCase("next")) {
    // go to the next …
Run Code Online (Sandbox Code Playgroud)

java user-interface swing jpanel cardlayout

3
推荐指数
1
解决办法
7941
查看次数