【发布时间】:2017-07-30 03:32:55
【问题描述】:
我是 java 新手,使用 java 创建 UI 小部件,并为此创建了以下类。但是为了给 textarea 添加边框,我知道我必须使用borderfactory 类。但是因为我有单独的 JFrame 和 JTextArea 类,所以我做不到。有什么帮助吗?
类
import javax.swing.*;
import java.awt.*;
import javax.swing.BorderFactory;
public class UIFactory {
//Border border = BorderFactory.createLineBorder(Color.BLACK);
public JButton newButton(int posx, int posy, int buttonWidth, int buttonHeight) {
JButton b = new JButton("Test");
b.setBounds(posx, posy, buttonWidth, buttonHeight);
return b;
}
public JFrame newFrame(int width, int height) {
JFrame f = new JFrame();
f.setSize(width, height);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
return f;
}
public JTextArea newTextArea(int xpos, int ypos, int twidth, int theight) {
JTextArea t = new JTextArea(300,300);
JScrollPane sp = new JScrollPane(t);
t.setBounds(xpos, ypos, twidth, theight);
t.setBackground(Color.orange);
t.setForeground(Color.black);
// t.setBorder(BorderFactory.createCompoundBorder(border,BorderFactory.createEmptyBorder(10, 10, 10, 10)));
return t;
}
}
还有我的主程序
import javax.swing.*;
import java.awt.*;
public class MyUI {
public static void main(String[] args) {
UIFactory ui = new UIFactory();
JFrame mainf = ui.newFrame(800, 800);
mainf.setLocation(400, 400);
JButton b2;
JButton b3;
mainf.add(b2 = ui.newButton(50, 50, 100, 50));
mainf.add(b3 = ui.newButton(50, 100, 100, 50));
JTextArea area;
mainf.add(area = ui.newTextArea(170,50,1600,300));
mainf.setVisible(true);
mainf.add(area = ui.newTextArea(170,400,1600,300));
mainf.setVisible(true);
}
}
【问题讨论】:
-
避免使用
null布局,像素完美的布局是现代用户界面设计中的一种错觉。影响组件单个尺寸的因素太多,您无法控制。 Swing 旨在与核心的布局管理器一起工作,丢弃这些将导致无穷无尽的问题和问题,您将花费越来越多的时间来尝试纠正。 -
我的“个人”建议是让
newTextArea接受Border的实例作为其参数之一