Java 在JApplet中设置布局管理器?
我创建了一个包含三个组件的简单JApplet,但最后添加的组件总是覆盖其他两个组件,因此它们不可见。我相信这是因为它们被添加到默认BorderLayout中的同一区域(如果我错了,请纠正我!)。但是,当我尝试更改LayoutManager时,我不断收到一条错误消息。我对导致以下问题的行进行了评论Java 在JApplet中设置布局管理器?,java,Java,我创建了一个包含三个组件的简单JApplet,但最后添加的组件总是覆盖其他两个组件,因此它们不可见。我相信这是因为它们被添加到默认BorderLayout中的同一区域(如果我错了,请纠正我!)。但是,当我尝试更改LayoutManager时,我不断收到一条错误消息。我对导致以下问题的行进行了评论 import javax.swing.*; import java.awt.event.*; public class Vote extends JApplet { int candidat
import javax.swing.*;
import java.awt.event.*;
public class Vote extends JApplet {
int candidate1 = 50; // this int holds the votes for candidate 1
int candidate2 = 50; // this int holds the votes for candidate 2
public void init() {
JButton vote1 = new JButton("Vote for candidate 1");
JButton vote2 = new JButton("Vote for candidate 2");
JButton results = new JButton("See Results");
vote1.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent evt) {
++candidate1;
String message = "You voted for candidate 1. \n\nThe current results are: \nCandidate 1: " + candidate1 + "\nCandidate 2: " + candidate2;
String title = "Voting results";
JOptionPane.showMessageDialog(null, message, title, JOptionPane.INFORMATION_MESSAGE);
}
});
vote2.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent evt) {
++candidate2;
String message = "You voted for candidate 2. \n\nThe current results are: \nCandidate 1: " + candidate1 + "\nCandidate 2: " + candidate2;
String title = "Voting results";
JOptionPane.showMessageDialog(null, message, title, JOptionPane.INFORMATION_MESSAGE);
}
});
results.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String message = "The current results are: \nCandidate 1: " + candidate1 + "\nCandidate 2: " + candidate2;
String title = "Voting results";
JOptionPane.showMessageDialog(null, message, title, JOptionPane.INFORMATION_MESSAGE);
}
});
getContentPane().setLayout(new GridLayout(3, 1)); // this line is the one I can't get to work
getContentPane().add(vote1);
getContentPane().add(vote2);
getContentPane().add(results);
}
}
我经常做的是:创建一个新的
JPanel
,将其布局设置为我想要的任何布局,将所有组件添加到该JPanel,然后将该JPanel添加到frame/JApplet。“我相信这是因为它们被添加到默认BorderLayout中的同一区域(如果我错了,请纠正我!)”这一点你是对的,谢谢你的帮助,@Frakcool!事实证明,我忘记导入java.awt.*
,但您的解决方案也是一个很好的解决方案!我经常做的是:创建一个新的JPanel
,将其布局设置为我想要的任何布局,将所有组件添加到该JPanel,然后将该JPanel添加到frame/JApplet。“我相信这是因为它们被添加到默认BorderLayout中的同一区域(如果我错了,请纠正我!)”这一点你是对的,谢谢你的帮助,@Frakcool!事实证明,我忘记导入java.awt.*
,但您的解决方案也是一个很好的解决方案!