
import java.awt.*
public class Frame1 extends JFrame {
JScrollPane jScrollPane1 = new JScrollPane()
JList jList1 = new JList()
public Frame1() {
try {
jbInit()
}
catch(Exception e) {
e.printStackTrace()
}
}
private void jbInit() throws Exception {
this.setLocale(java.util.Locale.getDefault())
this.getContentPane().setLayout(null)
jScrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER)
jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
jScrollPane1.setBounds(new Rectangle(141, 62, 89, 132))
this.getContentPane().add(jScrollPane1, null)
jScrollPane1.getViewport().add(jList1, null)
}
}
以前有人问过这个问题,下面是答案:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Sub Form_Load()
For i = 1 To 20
List1.AddItem String(100, "0") &i
Next
SendMessage List1.hwnd, &H194, 999, ByVal 0 '999是滚动条的宽度范围,单位为象素
End Sub
=============================================================
更优的代码
'计算出列表框内最长的项目有多少象素的宽度,这样可以使列表框的滚动条调整到一个合适的范围,因为列表框的内容很可能是会变动的,如果生硬的加一个很大的滚动条,同样会使你的程序显得很不专业,所以这一段是更优的代码!
Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Private Declare Function DrawText Lib "user32" Alias "DrawTextA" (ByVal hdc As Long, ByVal lpStr As String, ByVal nCount As Long, lpRect As RECT, ByVal wFormat As Long) As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Const LB_SETHORIZONTALEXTENT = &H194
Const DT_CALCRECT = &H400
Public Function ListTextWidth(ByRef lstThis As ListBox) As Long
Dim i As Long
Dim tR As RECT
Dim lW As Long
Dim lWidth As Long
Dim lHDC As Long
With lstThis.Parent.Font
.Name = lstThis.Font.Name
.Size = lstThis.Font.Size
.Bold = lstThis.Font.Bold
.Italic = lstThis.Font.Italic
End With
lHDC = lstThis.Parent.hdc
'便历所有的列表项以找到最长的项
For i = 0 To lstThis.ListCount - 1
DrawText lHDC, lstThis.List(i), -1, tR, DT_CALCRECT
lW = tR.Right - tR.Left + 8
If (lW >lWidth) Then lWidth = lW
Next i
'返回最长列表项的长度(像素)
ListTextWidth = lWidth
End Function
'调用代码
Private Sub Command1_Click() '点击Command1会使列表框按当前内容中最长项目的宽度来设置滚动条的范围
'列表框内容有变化时,可以调用这行代码,随时改变滚动条的范围
SendMessage List1.hwnd, LB_SETHORIZONTALEXTENT, ListTextWidth(List1), 0
'写在这里是为了让你看清楚列表框滚动条的变化
End Sub
'测试数据
Private Sub Form_Load()
Command1.Caption = "点我"
For i = 1 To 100
'添加很长的项目给列表框
List1.AddItem String(i, "0")
Next
End Sub
列表框中的滚动条是随着列表项的增加自动出现的,不需要单独用代码控制。如果列表框画的小,但是添加的项目较多,运行程序时滚动条就自动出现了。如果涉及时列表框画的比较大,但是添加的项目比较少,那运行时就不会出现滚动条了
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)