- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我第一次在这里发布问题,所以请告诉我我是否不遵守规则或是否缺少某些内容。
我的问题如下。我有一个带有 JTable 的窗口。在这个表中我有不同的数据。两列使用 JComboBoxes 从一组数据中选择值。第二个 ComboBox 中的数据应基于第一个 ComboBox 的选择,但仅限于当前选定的行。
不幸的是,它没有按照预期的方式工作,并且它在第二个组合框中对该列中的所有组合框进行了更改。
为了简化问题,我从 Oracle Java 教程中获取了演示代码:[http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#combobox][1]并稍微调整了代码以完成我需要它做的事情。
我复制了我的整个小程序,以便您可以复制它并在您的计算机上运行它(如果您愿意/需要)。
package demoTraining;
/*
* Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle or the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* TableRenderDemo.java requires no other files.
*/
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/**
* TableRenderDemo is just like TableDemo, except that it explicitly initializes
* column sizes and it uses a combo box as an editor for the Sport column.
*/
public class TableRenderDemo extends JPanel implements ItemListener {
private boolean DEBUG = true;
JTable table;
public TableRenderDemo() {
super(new GridLayout(1, 0));
table = new JTable(new MyTableModel());
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
// Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
// Set up column sizes.
initColumnSizes(table);
// Fiddle with the Sport column's cell editors/renderers.
setUpSportColumn(table, table.getColumnModel().getColumn(2));
setUpCategoryColumn(table, table.getColumnModel().getColumn(5));
// Add the scroll pane to this panel.
add(scrollPane);
}
/*
* This method picks good column sizes. If all column heads are wider than
* the column's cells' contents, then you can just use
* column.sizeWidthToFit().
*/
private void initColumnSizes(JTable table) {
MyTableModel model = (MyTableModel) table.getModel();
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
Object[] longValues = model.longValues;
TableCellRenderer headerRenderer = table.getTableHeader()
.getDefaultRenderer();
for (int i = 0; i < 6; i++) {
column = table.getColumnModel().getColumn(i);
comp = headerRenderer.getTableCellRendererComponent(null,
column.getHeaderValue(), false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
comp = table.getDefaultRenderer(model.getColumnClass(i))
.getTableCellRendererComponent(table, longValues[i], false,
false, 0, i);
cellWidth = comp.getPreferredSize().width;
if (DEBUG) {
System.out.println("Initializing width of column " + i + ". "
+ "headerWidth = " + headerWidth + "; cellWidth = "
+ cellWidth);
}
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
}
}
public void setUpSportColumn(JTable table, TableColumn sportColumn) {
// Set up the editor for the sport cells.
JComboBox comboBox = new JComboBox();
comboBox.addItem("Snowboarding");
comboBox.addItem("Rowing");
comboBox.addItem("Knitting");
comboBox.addItem("Speed reading");
comboBox.addItem("Pool");
comboBox.addItem("None of the above");
comboBox.addItemListener(this);
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
// Set up tool tips for the sport cells.
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);
}
private void setUpCategoryColumn(JTable table, TableColumn categoryColumn) {
JComboBox categoryComboBox = new JComboBox();
categoryComboBox.addItem("Category1");
categoryComboBox.addItem("Category2");
categoryComboBox.addItem("Category3");
categoryColumn.setCellEditor(new DefaultCellEditor(categoryComboBox));
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
categoryColumn.setCellRenderer(renderer);
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.ItemListener#itemStateChanged(java.awt.event.ItemEvent)
*
* Catches the itemStateChange on the sport ComboBox and changes the values
* of the Category ComboBox.
*/
public void itemStateChanged(ItemEvent e) {
// Only does something on itemEven "SELECTED"
if (e.getStateChange() == ItemEvent.SELECTED) {
// Only does something if a row is selected as it needs the row
// number to make changes.
if (table.getSelectedRow() != -1) {
String currentSportSelection = e.getItem().toString();
System.out.println("1. Current selection: "
+ currentSportSelection);
// If the selection in the sports combobox is
// "None of the above" this change happens.
if (currentSportSelection == "None of the above") {
// Some Sysos to help with debugging.
System.out.println("2. Selected Row: "
+ table.getSelectedRow());
System.out.println("2.1. First Row Category: "
+ table.getModel().getValueAt(0, 5));
System.out.println("2.2. Second Row Category: "
+ table.getModel().getValueAt(1, 5));
System.out.println("3. Starting change of category column");
// Getting the tableCellEditor of the category cell in the
// selected row.
TableCellEditor categoryCellEditor = table.getCellEditor(
table.getSelectedRow(), 5);
// Getting the CellEditorComponent (ComboBox) of the
// category cell in the current row.
JComboBox currentCategoryComboBox = (JComboBox) categoryCellEditor
.getTableCellEditorComponent(table, null, true,
table.getSelectedRow(), 5);
// Refill the category combobox.
currentCategoryComboBox.removeAllItems();
currentCategoryComboBox.addItem("SuperCategory1");
currentCategoryComboBox.addItem("SuperCategory2");
currentCategoryComboBox.addItem("SuperCategory3");
currentCategoryComboBox.addItem("SuperCategory4");
// Set the new value in the cell.
table.getModel().setValueAt(
currentCategoryComboBox.getItemAt(0),
table.getSelectedRow(), 5);
// Some more Sysos
System.out.println("4. Selected Row: "
+ table.getSelectedRow());
System.out.println("5. Category of selected row: "
+ table.getValueAt(table.getSelectedRow(), 5));
System.out.println("6. Categorylist top item: "
+ currentCategoryComboBox.getItemAt(0));
System.out.println("7. Item deselected!");
table.getSelectionModel().clearSelection();
// Else clause does the same as if clause.
} else /*
* if (currentSportSelection == "Rowing" ||
* currentSportSelection == "Knitting" ||
* currentSportSelection == "Speed reading" ||
* currentSportSelection == "Pool" ||
* currentSportSelection == "None of the above")
*/{
System.out.println("8. Selected Row: "
+ table.getSelectedRow());
System.out.println("8.1. First Row Category: "
+ table.getModel().getValueAt(0, 5));
System.out.println("8.2. Second Row Category: "
+ table.getModel().getValueAt(1, 5));
TableCellEditor categoryCellEditor = table.getCellEditor(
table.getSelectedRow(), 5);
JComboBox categoryComboBox = (JComboBox) categoryCellEditor
.getTableCellEditorComponent(table, null, true,
table.getSelectedRow(), 5);
categoryComboBox.removeAllItems();
categoryComboBox.addItem("Category1");
categoryComboBox.addItem("Category2");
categoryComboBox.addItem("Category3");
table.getModel().setValueAt(categoryComboBox.getItemAt(0),
table.getSelectedRow(), 5);
// Some Sysos
System.out.println("9. Selected Row: "
+ table.getSelectedRow());
System.out.println("10. Category of selected row: "
+ table.getValueAt(table.getSelectedRow(), 5));
System.out.println("11. Categorylist top item: "
+ categoryComboBox.getItemAt(0));
System.out.println("12. Item deselected!");
table.getSelectionModel().clearSelection();
}
}
}
}
class MyTableModel extends AbstractTableModel {
private String[] columnNames = { "First Name", "Last Name", "Sport",
"# of Years", "Vegetarian", "Category" };
private Object[][] data = {
{ "Kathy", "Smith", "Snowboarding", new Integer(5),
new Boolean(false), "Category1" },
{ "John", "Doe", "Rowing", new Integer(3), new Boolean(true),
"Category2" }, };
public final Object[] longValues = { "Jane", "Kathy",
"None of the above", new Integer(20), Boolean.TRUE, "Category3" };
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
/*
* JTable uses this method to determine the default renderer/ editor for
* each cell. If we didn't implement this method, then the last column
* would contain text ("true"/"false"), rather than a check box.
*/
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
/*
* Don't need to implement this method unless your table's editable.
*/
public boolean isCellEditable(int row, int col) {
// Note that the data/cell address is constant,
// no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
}
}
/*
* Don't need to implement this method unless your table's data can
* change.
*/
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value + " (an instance of "
+ value.getClass() + ")");
}
data[row][col] = value;
fireTableCellUpdated(row, col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
}
}
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i = 0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j = 0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("TableRenderDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
TableRenderDemo newContentPane = new TableRenderDemo();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
我在其他一些问题中读到我需要使用“getTableCellRendererComponent()”,但我不能 100% 确定我正确使用了它。
此外,如果您需要更多信息,请随时询问。
预先感谢您针对此问题提供的任何帮助。
利奥·K.
最佳答案
您需要更改表中每一行的编辑器。
以下示例展示了如何为每行显示不同的编辑器:
import java.awt.*;
import java.util.List;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
public class TableComboBoxByRow extends JPanel
{
List<String[]> editorData = new ArrayList<String[]>(3);
public TableComboBoxByRow()
{
setLayout( new BorderLayout() );
// Create the editorData to be used for each row
editorData.add( new String[]{ "Red", "Blue", "Green" } );
editorData.add( new String[]{ "Circle", "Square", "Triangle" } );
editorData.add( new String[]{ "Apple", "Orange", "Banana" } );
// Create the table with default data
Object[][] data =
{
{"Color", "Red"},
{"Shape", "Square"},
{"Fruit", "Banana"},
{"Plain", "Text"}
};
String[] columnNames = {"Type","Value"};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model)
{
// Determine editor to be used by row
public TableCellEditor getCellEditor(int row, int column)
{
int modelColumn = convertColumnIndexToModel( column );
if (modelColumn == 1 && row < 3)
{
JComboBox<String> comboBox1 = new JComboBox<String>( editorData.get(row));
return new DefaultCellEditor( comboBox1 );
}
else
return super.getCellEditor(row, column);
}
};
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane );
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Table Combo Box by Row");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new TableComboBoxByRow() );
frame.setSize(200, 200);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
您显然需要自定义逻辑,因为您的编辑器将基于另一列(而不是行)中的值,但代码应该可以帮助您开始。
关于java - 使用 Java Swing 根据另一个 JComboBox 中的选择更改单个单元格中 JComboBox 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27987864/
我正在开发一个摆动程序以显示多张图片。并且可以旋转图片(每个图片都以JComponent实现)。 问题是,当图片旋转时,JComponent的边框不会改变,因此图片会被剪切。 有什么办法也可以旋转边框
我有一个 JPanel 和一个 JButton 向量,我想将每个按钮添加到面板。 我遇到的问题是我有一个代表按钮向量的变量 btns,但宏函数只是将它视为一个符号,而不是一个向量。有没有办法以某种方式
我有一个 swing 应用程序,它覆盖 javax.swing.text.Document 以将基础文档的内容限制为某些字符和文本长度。我想将我的应用程序移植到 Javafx,但我不知道此类是否有 J
我有一个带有面板的简单应用程序,我想在单击它时暂停并重新开始绘画。 object ModulusPatterns extends SimpleSwingApplication { var dela
我似乎无法在 Swing 中强制布局。我有一个 JComponent添加到 JLayeredPane我在 JComponent 上设置了边框.然后,我想立即重新绘制所有内容 - 而不是像 invali
我有一个 Swing 应用程序,我想通过将外部文件从 Windows 资源管理器拖到应用程序上来导入外部文件。我有这个基本功能工作。但是,我想将默认的拖放光标图标更改为应用程序适当的光标。当鼠标键被按
我想在我的 Scala 摆动应用程序中使用一棵树,但该组件在 API 中不可用。 是否包装了 JTree存在吗? 如果没有,你对制作有什么建议吗? 谢谢 最佳答案 即使您可以在 Scala 程序中直接
我目前正在努力使我的 Swing 应用程序看起来更好。我想在这些方面实现一些目标: 这个想法是让每个框都有一个漂亮的标题,背景类似于上图。使用基本的 Swing 组件,我能得到的最接近的东西是添加 T
这是我在 Scala 中使用 Swing 的第一次实验,并且对下面的代码有一些疑问。它所做的只是生成一个带有可改变颜色的彩色矩形的窗口。请随时回答一个或任何一个问题。 1) 我在下面使用了 Java
一个愚蠢的问题,但我真的无法让它起作用:我在 Swing 应用程序中有一些长时间运行的过程,可能需要几分钟。我想在此过程进行时向用户显示进度对话框。我还想阻止用户执行进一步的操作,例如在进程进行时按下
如何获取秋千组件的默认背景色?我的意思是JPanel的默认背景色? 最佳答案 要获取创建面板时将使用的 DEFAULT 颜色,请使用: Color color = UIManager.getColor
我想更改特定表头的背景颜色。在我的应用程序中,我必须将当前月份的标题颜色设置为红色。 我的代码在这里:: jTable1.getTableHeader(). setDefaultRe
我正在努力使在 Java3D Canvas 上显示 Java Swing 组件并与之交互成为可能。我通过将透明 JPanel 绘制到缓冲图像来显示组件,然后使用 J3DGraphics2D 在 Can
嗨 当我在 swing 中创建按钮时,它会在文本周围添加边框,从而使按钮变大一点。 现在,我确实需要那个屏幕空间,我通常做的是创建一个文本项(禁用),它创建更小的组件大小(文本周围更小的空间)并向其添
有scala.swing.BoxPanel,但它似乎没有捕获重点,因为没有与javax.swing.Box工厂方法createHorizontalStrut等效的东西、createHorizo
我的 scala swing 应用程序中有一个 BoxPanel 按钮,这对我来说很难看,因为按钮的大小各不相同。我已将其更改为 GridPanel,但随后它们也垂直填充了面板,我发现这更难看。我怎样
我刚开始学习 Scala,作为学习过程的一部分,我一直在尝试使用 Swing 编写一些简单的脚本。 这是一个非常精简的例子,它展示了我所看到的问题。 SimpleSwingApp: import sc
我刚刚开始使用 clojure 和跷跷板制作 GUI 应用程序。它只创建一个 JFrame 和几个组件。这是代码。 main 函数除了调用 start-gui 什么也不做并在返回后立即退出。 (ns
Scala 是一种很棒的语言,但不幸的是缺少库文档。如何更改组件的初始大小?我什么都没有(故意),但无论如何都希望它是一定的。我目前有 ... contents = new BoxPanel(Orie
基本设置是这样的:我有一个垂直的 JSplitPane,我希望它有一个固定大小的底部组件和一个调整大小的顶部组件,我通过调用 setResizeWeight(1.0) 来完成。在此应用程序中,有一个按
我是一名优秀的程序员,十分优秀!