如果你只想通过访问其setText()方法来更改标签。你只需要按照以下步骤操作(保持其他所有内容不变):
public void makeFrames() {
CreateFrame frame = new CreateFrame("Label1");
frame.label.setText("new Label");
}
以下是一个快速的技巧,可以看到标签更改的效果:
public class Main {
JButton button;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Main object = new Main();
object.makeFrames();
}
});
}
public void makeFrames() {
final CreateFrame frame = new CreateFrame("Label1");
button = new JButton("Click");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.label.setText("new Label");
}
});
frame.frame.add(BorderLayout.NORTH, button);
}
}
当你点击按钮时,标签会改变为新的标签。
编辑2:(对main()进行更改,将按钮声明为静态变量,以便从main()中访问)
public class Main {
static JButton button;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final CreateFrame frameFromMain = new CreateFrame("Label1");
button = new JButton("Click");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frameFromMain.label.setText("new Label");
}
});
frameFromMain.frame.add(BorderLayout.NORTH, button);
}
});
}
}
请记住,您可以像访问类的其他成员一样访问CreateFrame类中的标签。如果您声明变量为静态变量,则可以直接访问它们,如下所示:
public class CreateFrame {
JFrame frame;
static JLabel label;
}
public class Main {
static JButton button;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
CreateFrame frameFromMain = new CreateFrame("Label1");
button = new JButton("Click");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CreateFrame.label.setText("new Label");
}
});
frameFromMain.frame.add(BorderLayout.NORTH, button);
}
});
}
}
编辑3:
如果你不想要按钮,删除按钮的代码并进行以下操作:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
CreateFrame frameFromMain = new CreateFrame("Label1");
CreateFrame.label.setText("new Label");
}
});
}
编辑4:使用原帖作者的代码:
public class TestFrame extends javax.swing.JFrame {
javax.swing.JLabel label;
public TestFrame() {
initComponents();
label=sampleLabel;
}
private void initComponents() {
sampleLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
sampleLabel.setText("anotherText");
add(sampleLabel);
pack();
}
private javax.swing.JLabel sampleLabel;
}
然后你的 main() 函数将如下所示:
public class Main {
public static void main(String[] args) {
final TestFrame frame = new TestFrame();
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
frame.setVisible(true);
}
});
frame.label.setText("Text From Main");
}
}
我进行了最小的更改。这段代码可以完美运行并实现你的要求。我去掉了你的“getContentPane”,因为在Java 6、7中不需要它。我还去掉了你的布局设置,因为我自己对它们不熟悉。你需要学会导入Java类。
看起来你正在学习Java的早期阶段。我建议你在移动到Swing之前坚持使用命令行程序,直到你弄清楚Java的工作原理。