You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Swing中JButton与JTextArea共存显示异常求助

解决Java Swing中JTextArea与JButton无法同时显示的问题

问题根源

你的代码中先执行TriangleSolution.add(...)添加组件,之后才设置TriangleSolution.setLayout(null)。JFrame默认使用BorderLayout,在设置null布局前的add操作会遵循BorderLayout规则——该布局的CENTER区域只能容纳一个组件,后添加的组件会直接覆盖之前的,所以无论调换添加顺序,都只会显示最后加入的那个组件。

修复方案

关键修改点

  1. 调整布局设置顺序:先设置JFrame的布局为null,再添加组件,确保组件按照你指定的bounds定位。
  2. 合理使用JScrollPane:将JTextArea放入滚动面板中,实现内容滚动(你已创建ScrollPane但未实际使用)。
  3. 规范代码细节:调整组件位置避免重叠,遵循Java变量命名规范,将setVisible(true)放在所有配置完成后调用。

修正后的完整代码

JScrollPane scrollPane = new JScrollPane();
JTextArea solutionTextArea;
JFrame triangleSolution = new JFrame();

String base = "Base = " + ValueOfBase.getText();
String height = "Height = " + ValueOfHeight.getText();    
String areaOfTriangle = "△ = Base * Height / 2";

solutionTextArea = new JTextArea();
solutionTextArea.setLineWrap(true);
solutionTextArea.setWrapStyleWord(true);
solutionTextArea.setEditable(false);
solutionTextArea.setText(areaOfTriangle + "\n\n" + base + "\n" + height);

// 将文本域绑定到滚动面板
scrollPane.setViewportView(solutionTextArea);
scrollPane.setBounds(0, 0, 400, 400);

JButton solutionExitButton = new JButton("Exit");
solutionExitButton.setBounds(500, 500, 100, 100);
solutionExitButton.setFocusable(false);
solutionExitButton.addActionListener(this);

// 先设置布局为null,再添加组件
triangleSolution.setLayout(null);
triangleSolution.add(scrollPane);
triangleSolution.add(solutionExitButton);

triangleSolution.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
triangleSolution.setSize(1000, 1000);
triangleSolution.setResizable(false);
// triangleSolution.setLocation(1200,100);
triangleSolution.setVisible(true);

额外建议

虽然null布局可以手动控制组件位置,但Swing更推荐使用内置布局管理器(如FlowLayout、BorderLayout、GridBagLayout等),这类管理器能自动适配不同系统的窗口大小和分辨率,减少手动调整位置的维护成本。

内容的提问来源于stack exchange,提问作者Bruce

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 06:54:32