Java 在JButton背景中使用的两个视图之间传递颜色对象
我正在尝试制作一个三选项卡桌面应用程序,其中tab1:add/del按钮用于添加/删除0-20个JButtons,tab2:user Selective color(JColorChooser)和tab3用于显示统计信息,例如tab1中的按钮数和最新颜色。 我的问题是:我在这里收到了一个很好的提示(多亏气垫船上有很多鳗鱼!),我成功地添加了一个PropertyChangeListener,事实上,这个颜色现在是面板的可显示背景——而我想在新的JButton中使用它。同样的方式,它将需要为Tab3。。。最好同时显示完整的主颜色和主颜色。java:Java 在JButton背景中使用的两个视图之间传递颜色对象,java,swing,class,colors,instance,Java,Swing,Class,Colors,Instance,我正在尝试制作一个三选项卡桌面应用程序,其中tab1:add/del按钮用于添加/删除0-20个JButtons,tab2:user Selective color(JColorChooser)和tab3用于显示统计信息,例如tab1中的按钮数和最新颜色。 我的问题是:我在这里收到了一个很好的提示(多亏气垫船上有很多鳗鱼!),我成功地添加了一个PropertyChangeListener,事实上,这个颜色现在是面板的可显示背景——而我想在新的JButton中使用它。同样的方式,它将需要为Tab3
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class Main extends JComponent{
public Dimension getPreferredSize() {
return new Dimension(700, 500);
}
static int value = 0;
private static void showGUI() {
Colors colors = new Colors(); //a new instance of class (JColorchooser)
JButton[] jbn = new JButton[20]; //Array of 20 buttons (to be added/removed 1 by 1)
JFrame window = new JFrame("Panels JG");
window.add(new Main());
window.pack();
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null);
window.setVisible(true);
/* Creating the needed JPanels and their layouts */
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 10, 10));
JPanel bottom = new JPanel();
bottom.setLayout(new FlowLayout());
JPanel frontPg = new JPanel(new GridLayout(2, 1 , 25, 25));
JPanel stats = new JPanel();
/* Need to get two panels in the first view */
frontPg.add(panel, BorderLayout.NORTH);
frontPg.add(bottom, BorderLayout.SOUTH);
/* Adding tabs to JFrame */
JTabbedPane tabs = new JTabbedPane();
window.add(tabs);
tabs.addTab("Boxes", frontPg);
tabs.addTab("Color Select", colors);
tabs.addTab("Details", stats);
/* Add and del button for adding and removing boxes (JButtons) in the first tab */
JButton a = new JButton("Add");
JButton d = new JButton("Del");
// Alternative for placing the buttons to the right place:
a.setBounds(300, 650, 80, 25);
d.setBounds(400, 650, 80, 25);
bottom.add(a);
bottom.add(d);
window.setVisible(true);
a.setVisible(true);
d.setVisible(true);
// add a PropertyChangeListener to our Colors isntance.
colors.addPropertyChangeListener(Colors.NEW_COLOR,
new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
Color col = (Color) evt.getNewValue();
panel.setBackground(col);
System.out.println("BGcolor = " + col);
//this "test" above shows it is the right 'col' needed elsewhere too
}
});
// eof listener
JLabel label1 = new JLabel();
JLabel label2 = new JLabel();
JLabel label3 = new JLabel();
a.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Click add");
Color col = null; //how should this Color object be initiated really...
if (value < 20) {
jbn[value] = new JButton(String.valueOf(value));
col = Color.getColor(Colors.NEW_COLOR);
System.out.println("jb1 color = " + col);
// CAN IT BE RESIZED? YES IT CAN WHILE GENERALLY NOT RECOMMENDED...
Dimension d;
d = new Dimension(30, 50);
jbn[value].setMinimumSize(d);
d = new Dimension(100, 50);
jbn[value].setMaximumSize(d);
d = new Dimension(40, 50);
jbn[value].setPreferredSize(d);
jbn[value].setOpaque(true);
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
//HERE IS THE PROBLEM - col is always null... It just paints w/ WHITE.
if(col!=null){
jbn[value].setBackground(col);
jbn[value].addActionListener(this);
panel.add(jbn[value]);
panel.setVisible(true);
}
else {
jbn[value].setBackground(Color.WHITE);
panel.add(jbn[value]);
panel.setVisible(true);
}
window.pack();
d = new Dimension(700, 500);
window.setSize(d);
value++;
label1.setText(" Count of boxes ");
label2.setText(" " + (String.valueOf(value)));
label3.setText(" Current Color");
label1.setFont(label1.getFont().deriveFont(16.0f));
label2.setFont(label2.getFont().deriveFont(20.0f));
label3.setFont(label1.getFont().deriveFont(16.0f));
stats.setLayout(new GridLayout(4, 1, 10, 100));
stats.add(label1);
stats.add(label2);
stats.add(label3);
// ADDING FILLRECT OR SIMILAR TO LAST TAB for showing the latest color
label1.repaint();
label2.repaint();
label3.repaint();
}
else {
System.out.println("Max box count reached");
}
}
});
d.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Click del");
//HOW TO REMOVE THE LATEST ADDED PANEL?
value = value-1;
}
});
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(35, 45, 55));
g2d.fillRect(200, 500, 35, 35);
}
public static void main(String[] args) {
showGUI();
}
}
还有评论(开放性问题)内联。。。要指出有问题的地方(对我来说是!)在我看来,你的问题不在于如何获得颜色值,而在于何时获得颜色值。既然您希望用户在创建按钮时选择一种新颜色,那么在CreationActionListener中,为什么不在模式JDialog(如JOptionPane)中显示颜色面板,并以这种方式获得选择呢。例如
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
@SuppressWarnings("serial")
public class SelectButtonColor extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 400;
private static final int COLUMNS = 4;
private List<AbstractButton> buttonList = new ArrayList<>();
private JPanel buttonPanel = new JPanel(new GridLayout(0, COLUMNS, 5, 5));
private int buttonCount = 0;
private Colors colors = new Colors();
public SelectButtonColor() {
JButton addButton = new JButton(new AddAction("Add"));
JPanel southPanel = new JPanel();
southPanel.add(addButton);
JPanel innerBorderPanel = new JPanel(new BorderLayout());
innerBorderPanel.add(buttonPanel, BorderLayout.PAGE_START);
JScrollPane scrollPane = new JScrollPane(innerBorderPanel);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(southPanel, BorderLayout.PAGE_END);
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class AddAction extends AbstractAction {
public AddAction(String name) {
super(name);
int mnenonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnenonic);
}
@Override
public void actionPerformed(ActionEvent e) {
Component parent = SelectButtonColor.this;
Object message = colors;
String title = "Select a Button Color";
int optionType = JOptionPane.OK_CANCEL_OPTION;
int response = JOptionPane.showConfirmDialog(parent, message, title, optionType);
if (response == JOptionPane.OK_OPTION) {
Color color = colors.getNewCol();
String text = "" + buttonCount;
JButton button = new JButton(text);
button.setBackground(color);
buttonPanel.add(button);
buttonList.add(button);
buttonCount++;
buttonPanel.revalidate();
buttonPanel.repaint();
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("SelectButtonColor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SelectButtonColor());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
导入java.awt.BorderLayout;
导入java.awt.Color;
导入java.awt.Component;
导入java.awt.Dimension;
导入java.awt.GridLayout;
导入java.awt.event.ActionEvent;
导入java.util.ArrayList;
导入java.util.List;
导入javax.swing.*;
@抑制警告(“串行”)
公共类SelectButtonColor扩展了JPanel{
专用静态最终整型预调W=600;
私有静态最终整型参数H=400;
私有静态final int COLUMNS=4;
私有列表按钮列表=新的ArrayList();
private JPanel buttonPanel=新的JPanel(新的网格布局(0,列,5,5));
私有int按钮计数=0;
私有颜色=新颜色();
公共选择按钮颜色(){
JButton addButton=newjbutton(newaddaction(“Add”));
JPanel southPanel=新的JPanel();
添加(添加按钮);
JPanel innerBorderPanel=newJPanel(new BorderLayout());
innerBorderPanel.add(按钮面板,BorderLayout.PAGE_开始);
JScrollPane scrollPane=新的JScrollPane(innerBorderPanel);
setLayout(新的BorderLayout());
添加(滚动窗格,BorderLayout.CENTER);
添加(southPanel,BorderLayout.PAGE_END);
}
@凌驾
公共维度getPreferredSize(){
如果(isPreferredSizeSet()){
返回super.getPreferredSize();
}
返回新维度(PREF_W,PREF_H);
}
私有类AddAction扩展了AbstractAction{
公共AddAction(字符串名称){
超级(姓名);
int mnenonic=(int)name.charAt(0);
putValue(助记符键,助记符键);
}
@凌驾
已执行的公共无效操作(操作事件e){
组件父级=SelectButtonColor.this;
对象消息=颜色;
String title=“选择按钮颜色”;
int optionType=JOptionPane.OK\u CANCEL\u选项;
int response=JOptionPane.showConfirmDialog(父项、消息、标题、选项类型);
if(response==JOptionPane.OK\u选项){
Color=colors.getNewCol();
字符串文本=”“+按钮计数;
JButton按钮=新JButton(文本);
按钮。背景(颜色);
按钮面板。添加(按钮);
按钮列表。添加(按钮);
按钮计数++;
buttonPanel.revalidate();
buttonPanel.repaint();
}
}
}
私有静态void createAndShowGui(){
JFrame=newjframe(“SelectButtonColor”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(新建SelectButtonColor());
frame.pack();
frame.setLocationRelativeTo(空);
frame.setVisible(true);
}
公共静态void main(字符串[]args){
SwingUtilities.invokeLater(新的Runnable(){
公开募捐{
createAndShowGui();
}
});
}
}
顺便说一句,试着在这里发布的示例中使用更简洁的代码,因为这将使所有人都更容易理解和帮助。此外,您几乎从不希望覆盖绘制方法,而是希望覆盖绘制组件方法。..hello??
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
@SuppressWarnings("serial")
public class SelectButtonColor extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 400;
private static final int COLUMNS = 4;
private List<AbstractButton> buttonList = new ArrayList<>();
private JPanel buttonPanel = new JPanel(new GridLayout(0, COLUMNS, 5, 5));
private int buttonCount = 0;
private Colors colors = new Colors();
public SelectButtonColor() {
JButton addButton = new JButton(new AddAction("Add"));
JPanel southPanel = new JPanel();
southPanel.add(addButton);
JPanel innerBorderPanel = new JPanel(new BorderLayout());
innerBorderPanel.add(buttonPanel, BorderLayout.PAGE_START);
JScrollPane scrollPane = new JScrollPane(innerBorderPanel);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(southPanel, BorderLayout.PAGE_END);
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class AddAction extends AbstractAction {
public AddAction(String name) {
super(name);
int mnenonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnenonic);
}
@Override
public void actionPerformed(ActionEvent e) {
Component parent = SelectButtonColor.this;
Object message = colors;
String title = "Select a Button Color";
int optionType = JOptionPane.OK_CANCEL_OPTION;
int response = JOptionPane.showConfirmDialog(parent, message, title, optionType);
if (response == JOptionPane.OK_OPTION) {
Color color = colors.getNewCol();
String text = "" + buttonCount;
JButton button = new JButton(text);
button.setBackground(color);
buttonPanel.add(button);
buttonList.add(button);
buttonCount++;
buttonPanel.revalidate();
buttonPanel.repaint();
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("SelectButtonColor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SelectButtonColor());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}